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,
216                          SDValue Trunc, SDValue ExtLoad, 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, SDLoc DL, SDValue LHS, SDValue RHS);
333 
334     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
335 
336     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
337     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
338     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
339     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
340                              SDValue N3, ISD::CondCode CC,
341                              bool NotExtCompare = false);
342     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
343                           SDLoc DL, bool foldBooleans = true);
344 
345     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
346                            SDValue &CC) const;
347     bool isOneUseSetCC(SDValue N) const;
348 
349     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
350                                          unsigned HiOp);
351     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
352     SDValue CombineExtLoad(SDNode *N);
353     SDValue combineRepeatedFPDivisors(SDNode *N);
354     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
355     SDValue BuildSDIV(SDNode *N);
356     SDValue BuildSDIVPow2(SDNode *N);
357     SDValue BuildUDIV(SDNode *N);
358     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
359     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
360     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
361                                  SDNodeFlags *Flags);
362     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
363                                  SDNodeFlags *Flags);
364     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
365                                bool DemandHighBits = true);
366     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
367     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
368                               SDValue InnerPos, SDValue InnerNeg,
369                               unsigned PosOpcode, unsigned NegOpcode,
370                               SDLoc DL);
371     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
372     SDValue ReduceLoadWidth(SDNode *N);
373     SDValue ReduceLoadOpStoreWidth(SDNode *N);
374     SDValue TransformFPLoadStorePair(SDNode *N);
375     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
376     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
377 
378     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
379 
380     /// Walk up chain skipping non-aliasing memory nodes,
381     /// looking for aliasing nodes and adding them to the Aliases vector.
382     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
383                           SmallVectorImpl<SDValue> &Aliases);
384 
385     /// Return true if there is any possibility that the two addresses overlap.
386     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
387 
388     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
389     /// chain (aliasing node.)
390     SDValue FindBetterChain(SDNode *N, SDValue Chain);
391 
392     /// Do FindBetterChain for a store and any possibly adjacent stores on
393     /// consecutive chains.
394     bool findBetterNeighborChains(StoreSDNode *St);
395 
396     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
397     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
398 
399     /// Holds a pointer to an LSBaseSDNode as well as information on where it
400     /// is located in a sequence of memory operations connected by a chain.
401     struct MemOpLink {
402       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
403       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
404       // Ptr to the mem node.
405       LSBaseSDNode *MemNode;
406       // Offset from the base ptr.
407       int64_t OffsetFromBase;
408       // What is the sequence number of this mem node.
409       // Lowest mem operand in the DAG starts at zero.
410       unsigned SequenceNum;
411     };
412 
413     /// This is a helper function for visitMUL to check the profitability
414     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
415     /// MulNode is the original multiply, AddNode is (add x, c1),
416     /// and ConstNode is c2.
417     bool isMulAddWithConstProfitable(SDNode *MulNode,
418                                      SDValue &AddNode,
419                                      SDValue &ConstNode);
420 
421     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
422     /// constant build_vector of the stored constant values in Stores.
423     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
424                                          SDLoc SL,
425                                          ArrayRef<MemOpLink> Stores,
426                                          SmallVectorImpl<SDValue> &Chains,
427                                          EVT Ty) const;
428 
429     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
430     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
431     /// the type of the loaded value to be extended.  LoadedVT returns the type
432     /// of the original loaded value.  NarrowLoad returns whether the load would
433     /// need to be narrowed in order to match.
434     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
435                           EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
436                           bool &NarrowLoad);
437 
438     /// This is a helper function for MergeConsecutiveStores. When the source
439     /// elements of the consecutive stores are all constants or all extracted
440     /// vector elements, try to merge them into one larger store.
441     /// \return True if a merged store was created.
442     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
443                                          EVT MemVT, unsigned NumStores,
444                                          bool IsConstantSrc, bool UseVector);
445 
446     /// This is a helper function for MergeConsecutiveStores.
447     /// Stores that may be merged are placed in StoreNodes.
448     /// Loads that may alias with those stores are placed in AliasLoadNodes.
449     void getStoreMergeAndAliasCandidates(
450         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
451         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
452 
453     /// Helper function for MergeConsecutiveStores. Checks if
454     /// Candidate stores have indirect dependency through their
455     /// operands. \return True if safe to merge
456     bool checkMergeStoreCandidatesForDependencies(
457         SmallVectorImpl<MemOpLink> &StoreNodes);
458 
459     /// Merge consecutive store operations into a wide store.
460     /// This optimization uses wide integers or vectors when possible.
461     /// \return True if some memory operations were changed.
462     bool MergeConsecutiveStores(StoreSDNode *N);
463 
464     /// \brief Try to transform a truncation where C is a constant:
465     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
466     ///
467     /// \p N needs to be a truncation and its first operand an AND. Other
468     /// requirements are checked by the function (e.g. that trunc is
469     /// single-use) and if missed an empty SDValue is returned.
470     SDValue distributeTruncateThroughAnd(SDNode *N);
471 
472   public:
473     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
474         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
475           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
476       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
477     }
478 
479     /// Runs the dag combiner on all nodes in the work list
480     void Run(CombineLevel AtLevel);
481 
482     SelectionDAG &getDAG() const { return DAG; }
483 
484     /// Returns a type large enough to hold any valid shift amount - before type
485     /// legalization these can be huge.
486     EVT getShiftAmountTy(EVT LHSTy) {
487       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
488       if (LHSTy.isVector())
489         return LHSTy;
490       auto &DL = DAG.getDataLayout();
491       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
492                         : TLI.getPointerTy(DL);
493     }
494 
495     /// This method returns true if we are running before type legalization or
496     /// if the specified VT is legal.
497     bool isTypeLegal(const EVT &VT) {
498       if (!LegalTypes) return true;
499       return TLI.isTypeLegal(VT);
500     }
501 
502     /// Convenience wrapper around TargetLowering::getSetCCResultType
503     EVT getSetCCResultType(EVT VT) const {
504       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
505     }
506   };
507 }
508 
509 
510 namespace {
511 /// This class is a DAGUpdateListener that removes any deleted
512 /// nodes from the worklist.
513 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
514   DAGCombiner &DC;
515 public:
516   explicit WorklistRemover(DAGCombiner &dc)
517     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
518 
519   void NodeDeleted(SDNode *N, SDNode *E) override {
520     DC.removeFromWorklist(N);
521   }
522 };
523 }
524 
525 //===----------------------------------------------------------------------===//
526 //  TargetLowering::DAGCombinerInfo implementation
527 //===----------------------------------------------------------------------===//
528 
529 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
530   ((DAGCombiner*)DC)->AddToWorklist(N);
531 }
532 
533 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
534   ((DAGCombiner*)DC)->removeFromWorklist(N);
535 }
536 
537 SDValue TargetLowering::DAGCombinerInfo::
538 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
539   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
540 }
541 
542 SDValue TargetLowering::DAGCombinerInfo::
543 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
544   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
545 }
546 
547 
548 SDValue TargetLowering::DAGCombinerInfo::
549 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
550   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
551 }
552 
553 void TargetLowering::DAGCombinerInfo::
554 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
555   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
556 }
557 
558 //===----------------------------------------------------------------------===//
559 // Helper Functions
560 //===----------------------------------------------------------------------===//
561 
562 void DAGCombiner::deleteAndRecombine(SDNode *N) {
563   removeFromWorklist(N);
564 
565   // If the operands of this node are only used by the node, they will now be
566   // dead. Make sure to re-visit them and recursively delete dead nodes.
567   for (const SDValue &Op : N->ops())
568     // For an operand generating multiple values, one of the values may
569     // become dead allowing further simplification (e.g. split index
570     // arithmetic from an indexed load).
571     if (Op->hasOneUse() || Op->getNumValues() > 1)
572       AddToWorklist(Op.getNode());
573 
574   DAG.DeleteNode(N);
575 }
576 
577 /// Return 1 if we can compute the negated form of the specified expression for
578 /// the same cost as the expression itself, or 2 if we can compute the negated
579 /// form more cheaply than the expression itself.
580 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
581                                const TargetLowering &TLI,
582                                const TargetOptions *Options,
583                                unsigned Depth = 0) {
584   // fneg is removable even if it has multiple uses.
585   if (Op.getOpcode() == ISD::FNEG) return 2;
586 
587   // Don't allow anything with multiple uses.
588   if (!Op.hasOneUse()) return 0;
589 
590   // Don't recurse exponentially.
591   if (Depth > 6) return 0;
592 
593   switch (Op.getOpcode()) {
594   default: return false;
595   case ISD::ConstantFP:
596     // Don't invert constant FP values after legalize.  The negated constant
597     // isn't necessarily legal.
598     return LegalOperations ? 0 : 1;
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     if (!Options->UnsafeFPMath) return 0;
602 
603     // After operation legalization, it might not be legal to create new FSUBs.
604     if (LegalOperations &&
605         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
606       return 0;
607 
608     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
609     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
610                                     Options, Depth + 1))
611       return V;
612     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
613     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
614                               Depth + 1);
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     if (!Options->UnsafeFPMath) return 0;
618 
619     // fold (fneg (fsub A, B)) -> (fsub B, A)
620     return 1;
621 
622   case ISD::FMUL:
623   case ISD::FDIV:
624     if (Options->HonorSignDependentRoundingFPMath()) return 0;
625 
626     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
627     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
628                                     Options, Depth + 1))
629       return V;
630 
631     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
632                               Depth + 1);
633 
634   case ISD::FP_EXTEND:
635   case ISD::FP_ROUND:
636   case ISD::FSIN:
637     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
638                               Depth + 1);
639   }
640 }
641 
642 /// If isNegatibleForFree returns true, return the newly negated expression.
643 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
644                                     bool LegalOperations, unsigned Depth = 0) {
645   const TargetOptions &Options = DAG.getTarget().Options;
646   // fneg is removable even if it has multiple uses.
647   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
648 
649   // Don't allow anything with multiple uses.
650   assert(Op.hasOneUse() && "Unknown reuse!");
651 
652   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
653 
654   const SDNodeFlags *Flags = Op.getNode()->getFlags();
655 
656   switch (Op.getOpcode()) {
657   default: llvm_unreachable("Unknown code");
658   case ISD::ConstantFP: {
659     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
660     V.changeSign();
661     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
662   }
663   case ISD::FADD:
664     // FIXME: determine better conditions for this xform.
665     assert(Options.UnsafeFPMath);
666 
667     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
668     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
669                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
670       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
671                          GetNegatedExpression(Op.getOperand(0), DAG,
672                                               LegalOperations, Depth+1),
673                          Op.getOperand(1), Flags);
674     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
675     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
676                        GetNegatedExpression(Op.getOperand(1), DAG,
677                                             LegalOperations, Depth+1),
678                        Op.getOperand(0), Flags);
679   case ISD::FSUB:
680     // We can't turn -(A-B) into B-A when we honor signed zeros.
681     assert(Options.UnsafeFPMath);
682 
683     // fold (fneg (fsub 0, B)) -> B
684     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
685       if (N0CFP->isZero())
686         return Op.getOperand(1);
687 
688     // fold (fneg (fsub A, B)) -> (fsub B, A)
689     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
690                        Op.getOperand(1), Op.getOperand(0), Flags);
691 
692   case ISD::FMUL:
693   case ISD::FDIV:
694     assert(!Options.HonorSignDependentRoundingFPMath());
695 
696     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
697     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
698                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
699       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
700                          GetNegatedExpression(Op.getOperand(0), DAG,
701                                               LegalOperations, Depth+1),
702                          Op.getOperand(1), Flags);
703 
704     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
705     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
706                        Op.getOperand(0),
707                        GetNegatedExpression(Op.getOperand(1), DAG,
708                                             LegalOperations, Depth+1), Flags);
709 
710   case ISD::FP_EXTEND:
711   case ISD::FSIN:
712     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
713                        GetNegatedExpression(Op.getOperand(0), DAG,
714                                             LegalOperations, Depth+1));
715   case ISD::FP_ROUND:
716       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
717                          GetNegatedExpression(Op.getOperand(0), DAG,
718                                               LegalOperations, Depth+1),
719                          Op.getOperand(1));
720   }
721 }
722 
723 // Return true if this node is a setcc, or is a select_cc
724 // that selects between the target values used for true and false, making it
725 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
726 // the appropriate nodes based on the type of node we are checking. This
727 // simplifies life a bit for the callers.
728 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
729                                     SDValue &CC) const {
730   if (N.getOpcode() == ISD::SETCC) {
731     LHS = N.getOperand(0);
732     RHS = N.getOperand(1);
733     CC  = N.getOperand(2);
734     return true;
735   }
736 
737   if (N.getOpcode() != ISD::SELECT_CC ||
738       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
739       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
740     return false;
741 
742   if (TLI.getBooleanContents(N.getValueType()) ==
743       TargetLowering::UndefinedBooleanContent)
744     return false;
745 
746   LHS = N.getOperand(0);
747   RHS = N.getOperand(1);
748   CC  = N.getOperand(4);
749   return true;
750 }
751 
752 /// Return true if this is a SetCC-equivalent operation with only one use.
753 /// If this is true, it allows the users to invert the operation for free when
754 /// it is profitable to do so.
755 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
756   SDValue N0, N1, N2;
757   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
758     return true;
759   return false;
760 }
761 
762 /// Returns true if N is a BUILD_VECTOR node whose
763 /// elements are all the same constant or undefined.
764 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
765   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
766   if (!C)
767     return false;
768 
769   APInt SplatUndef;
770   unsigned SplatBitSize;
771   bool HasAnyUndefs;
772   EVT EltVT = N->getValueType(0).getVectorElementType();
773   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
774                              HasAnyUndefs) &&
775           EltVT.getSizeInBits() >= SplatBitSize);
776 }
777 
778 // \brief Returns the SDNode if it is a constant float BuildVector
779 // or constant float.
780 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
781   if (isa<ConstantFPSDNode>(N))
782     return N.getNode();
783   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
784     return N.getNode();
785   return nullptr;
786 }
787 
788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
789 // int.
790 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
791   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
792     return CN;
793 
794   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
795     BitVector UndefElements;
796     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
797 
798     // BuildVectors can truncate their operands. Ignore that case here.
799     // FIXME: We blindly ignore splats which include undef which is overly
800     // pessimistic.
801     if (CN && UndefElements.none() &&
802         CN->getValueType(0) == N.getValueType().getScalarType())
803       return CN;
804   }
805 
806   return nullptr;
807 }
808 
809 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
810 // float.
811 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
812   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
813     return CN;
814 
815   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
816     BitVector UndefElements;
817     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
818 
819     if (CN && UndefElements.none())
820       return CN;
821   }
822 
823   return nullptr;
824 }
825 
826 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
827                                     SDValue N0, SDValue N1) {
828   EVT VT = N0.getValueType();
829   if (N0.getOpcode() == Opc) {
830     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
831       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
832         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
833         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
834           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
835         return SDValue();
836       }
837       if (N0.hasOneUse()) {
838         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
839         // use
840         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
841         if (!OpNode.getNode())
842           return SDValue();
843         AddToWorklist(OpNode.getNode());
844         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
845       }
846     }
847   }
848 
849   if (N1.getOpcode() == Opc) {
850     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
851       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
852         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
853         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
854           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
855         return SDValue();
856       }
857       if (N1.hasOneUse()) {
858         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
859         // use
860         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
861         if (!OpNode.getNode())
862           return SDValue();
863         AddToWorklist(OpNode.getNode());
864         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
865       }
866     }
867   }
868 
869   return SDValue();
870 }
871 
872 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
873                                bool AddTo) {
874   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
875   ++NodesCombined;
876   DEBUG(dbgs() << "\nReplacing.1 ";
877         N->dump(&DAG);
878         dbgs() << "\nWith: ";
879         To[0].getNode()->dump(&DAG);
880         dbgs() << " and " << NumTo-1 << " other values\n");
881   for (unsigned i = 0, e = NumTo; i != e; ++i)
882     assert((!To[i].getNode() ||
883             N->getValueType(i) == To[i].getValueType()) &&
884            "Cannot combine value to value of different type!");
885 
886   WorklistRemover DeadNodes(*this);
887   DAG.ReplaceAllUsesWith(N, To);
888   if (AddTo) {
889     // Push the new nodes and any users onto the worklist
890     for (unsigned i = 0, e = NumTo; i != e; ++i) {
891       if (To[i].getNode()) {
892         AddToWorklist(To[i].getNode());
893         AddUsersToWorklist(To[i].getNode());
894       }
895     }
896   }
897 
898   // Finally, if the node is now dead, remove it from the graph.  The node
899   // may not be dead if the replacement process recursively simplified to
900   // something else needing this node.
901   if (N->use_empty())
902     deleteAndRecombine(N);
903   return SDValue(N, 0);
904 }
905 
906 void DAGCombiner::
907 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
908   // Replace all uses.  If any nodes become isomorphic to other nodes and
909   // are deleted, make sure to remove them from our worklist.
910   WorklistRemover DeadNodes(*this);
911   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
912 
913   // Push the new node and any (possibly new) users onto the worklist.
914   AddToWorklist(TLO.New.getNode());
915   AddUsersToWorklist(TLO.New.getNode());
916 
917   // Finally, if the node is now dead, remove it from the graph.  The node
918   // may not be dead if the replacement process recursively simplified to
919   // something else needing this node.
920   if (TLO.Old.getNode()->use_empty())
921     deleteAndRecombine(TLO.Old.getNode());
922 }
923 
924 /// Check the specified integer node value to see if it can be simplified or if
925 /// things it uses can be simplified by bit propagation. If so, return true.
926 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
927   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
928   APInt KnownZero, KnownOne;
929   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
930     return false;
931 
932   // Revisit the node.
933   AddToWorklist(Op.getNode());
934 
935   // Replace the old value with the new one.
936   ++NodesCombined;
937   DEBUG(dbgs() << "\nReplacing.2 ";
938         TLO.Old.getNode()->dump(&DAG);
939         dbgs() << "\nWith: ";
940         TLO.New.getNode()->dump(&DAG);
941         dbgs() << '\n');
942 
943   CommitTargetLoweringOpt(TLO);
944   return true;
945 }
946 
947 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
948   SDLoc dl(Load);
949   EVT VT = Load->getValueType(0);
950   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
951 
952   DEBUG(dbgs() << "\nReplacing.9 ";
953         Load->dump(&DAG);
954         dbgs() << "\nWith: ";
955         Trunc.getNode()->dump(&DAG);
956         dbgs() << '\n');
957   WorklistRemover DeadNodes(*this);
958   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
959   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
960   deleteAndRecombine(Load);
961   AddToWorklist(Trunc.getNode());
962 }
963 
964 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
965   Replace = false;
966   SDLoc dl(Op);
967   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
968     LoadSDNode *LD = cast<LoadSDNode>(Op);
969     EVT MemVT = LD->getMemoryVT();
970     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
971       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
972                                                        : ISD::EXTLOAD)
973       : LD->getExtensionType();
974     Replace = true;
975     return DAG.getExtLoad(ExtType, dl, PVT,
976                           LD->getChain(), LD->getBasePtr(),
977                           MemVT, LD->getMemOperand());
978   }
979 
980   unsigned Opc = Op.getOpcode();
981   switch (Opc) {
982   default: break;
983   case ISD::AssertSext:
984     return DAG.getNode(ISD::AssertSext, dl, PVT,
985                        SExtPromoteOperand(Op.getOperand(0), PVT),
986                        Op.getOperand(1));
987   case ISD::AssertZext:
988     return DAG.getNode(ISD::AssertZext, dl, PVT,
989                        ZExtPromoteOperand(Op.getOperand(0), PVT),
990                        Op.getOperand(1));
991   case ISD::Constant: {
992     unsigned ExtOpc =
993       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
994     return DAG.getNode(ExtOpc, dl, PVT, Op);
995   }
996   }
997 
998   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
999     return SDValue();
1000   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
1001 }
1002 
1003 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1004   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1005     return SDValue();
1006   EVT OldVT = Op.getValueType();
1007   SDLoc dl(Op);
1008   bool Replace = false;
1009   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1010   if (!NewOp.getNode())
1011     return SDValue();
1012   AddToWorklist(NewOp.getNode());
1013 
1014   if (Replace)
1015     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1016   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1017                      DAG.getValueType(OldVT));
1018 }
1019 
1020 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1021   EVT OldVT = Op.getValueType();
1022   SDLoc dl(Op);
1023   bool Replace = false;
1024   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1025   if (!NewOp.getNode())
1026     return SDValue();
1027   AddToWorklist(NewOp.getNode());
1028 
1029   if (Replace)
1030     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1031   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1032 }
1033 
1034 /// Promote the specified integer binary operation if the target indicates it is
1035 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1036 /// i32 since i16 instructions are longer.
1037 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1038   if (!LegalOperations)
1039     return SDValue();
1040 
1041   EVT VT = Op.getValueType();
1042   if (VT.isVector() || !VT.isInteger())
1043     return SDValue();
1044 
1045   // If operation type is 'undesirable', e.g. i16 on x86, consider
1046   // promoting it.
1047   unsigned Opc = Op.getOpcode();
1048   if (TLI.isTypeDesirableForOp(Opc, VT))
1049     return SDValue();
1050 
1051   EVT PVT = VT;
1052   // Consult target whether it is a good idea to promote this operation and
1053   // what's the right type to promote it to.
1054   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055     assert(PVT != VT && "Don't know what type to promote to!");
1056 
1057     bool Replace0 = false;
1058     SDValue N0 = Op.getOperand(0);
1059     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1060     if (!NN0.getNode())
1061       return SDValue();
1062 
1063     bool Replace1 = false;
1064     SDValue N1 = Op.getOperand(1);
1065     SDValue NN1;
1066     if (N0 == N1)
1067       NN1 = NN0;
1068     else {
1069       NN1 = PromoteOperand(N1, PVT, Replace1);
1070       if (!NN1.getNode())
1071         return SDValue();
1072     }
1073 
1074     AddToWorklist(NN0.getNode());
1075     if (NN1.getNode())
1076       AddToWorklist(NN1.getNode());
1077 
1078     if (Replace0)
1079       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1080     if (Replace1)
1081       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1082 
1083     DEBUG(dbgs() << "\nPromoting ";
1084           Op.getNode()->dump(&DAG));
1085     SDLoc dl(Op);
1086     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1087                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1088   }
1089   return SDValue();
1090 }
1091 
1092 /// Promote the specified integer shift operation if the target indicates it is
1093 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1094 /// i32 since i16 instructions are longer.
1095 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1096   if (!LegalOperations)
1097     return SDValue();
1098 
1099   EVT VT = Op.getValueType();
1100   if (VT.isVector() || !VT.isInteger())
1101     return SDValue();
1102 
1103   // If operation type is 'undesirable', e.g. i16 on x86, consider
1104   // promoting it.
1105   unsigned Opc = Op.getOpcode();
1106   if (TLI.isTypeDesirableForOp(Opc, VT))
1107     return SDValue();
1108 
1109   EVT PVT = VT;
1110   // Consult target whether it is a good idea to promote this operation and
1111   // what's the right type to promote it to.
1112   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1113     assert(PVT != VT && "Don't know what type to promote to!");
1114 
1115     bool Replace = false;
1116     SDValue N0 = Op.getOperand(0);
1117     if (Opc == ISD::SRA)
1118       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1119     else if (Opc == ISD::SRL)
1120       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1121     else
1122       N0 = PromoteOperand(N0, PVT, Replace);
1123     if (!N0.getNode())
1124       return SDValue();
1125 
1126     AddToWorklist(N0.getNode());
1127     if (Replace)
1128       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1129 
1130     DEBUG(dbgs() << "\nPromoting ";
1131           Op.getNode()->dump(&DAG));
1132     SDLoc dl(Op);
1133     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1134                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1135   }
1136   return SDValue();
1137 }
1138 
1139 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1140   if (!LegalOperations)
1141     return SDValue();
1142 
1143   EVT VT = Op.getValueType();
1144   if (VT.isVector() || !VT.isInteger())
1145     return SDValue();
1146 
1147   // If operation type is 'undesirable', e.g. i16 on x86, consider
1148   // promoting it.
1149   unsigned Opc = Op.getOpcode();
1150   if (TLI.isTypeDesirableForOp(Opc, VT))
1151     return SDValue();
1152 
1153   EVT PVT = VT;
1154   // Consult target whether it is a good idea to promote this operation and
1155   // what's the right type to promote it to.
1156   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1157     assert(PVT != VT && "Don't know what type to promote to!");
1158     // fold (aext (aext x)) -> (aext x)
1159     // fold (aext (zext x)) -> (zext x)
1160     // fold (aext (sext x)) -> (sext x)
1161     DEBUG(dbgs() << "\nPromoting ";
1162           Op.getNode()->dump(&DAG));
1163     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1164   }
1165   return SDValue();
1166 }
1167 
1168 bool DAGCombiner::PromoteLoad(SDValue Op) {
1169   if (!LegalOperations)
1170     return false;
1171 
1172   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1173     return false;
1174 
1175   EVT VT = Op.getValueType();
1176   if (VT.isVector() || !VT.isInteger())
1177     return false;
1178 
1179   // If operation type is 'undesirable', e.g. i16 on x86, consider
1180   // promoting it.
1181   unsigned Opc = Op.getOpcode();
1182   if (TLI.isTypeDesirableForOp(Opc, VT))
1183     return false;
1184 
1185   EVT PVT = VT;
1186   // Consult target whether it is a good idea to promote this operation and
1187   // what's the right type to promote it to.
1188   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1189     assert(PVT != VT && "Don't know what type to promote to!");
1190 
1191     SDLoc dl(Op);
1192     SDNode *N = Op.getNode();
1193     LoadSDNode *LD = cast<LoadSDNode>(N);
1194     EVT MemVT = LD->getMemoryVT();
1195     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1196       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1197                                                        : ISD::EXTLOAD)
1198       : LD->getExtensionType();
1199     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1200                                    LD->getChain(), LD->getBasePtr(),
1201                                    MemVT, LD->getMemOperand());
1202     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1203 
1204     DEBUG(dbgs() << "\nPromoting ";
1205           N->dump(&DAG);
1206           dbgs() << "\nTo: ";
1207           Result.getNode()->dump(&DAG);
1208           dbgs() << '\n');
1209     WorklistRemover DeadNodes(*this);
1210     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1212     deleteAndRecombine(N);
1213     AddToWorklist(Result.getNode());
1214     return true;
1215   }
1216   return false;
1217 }
1218 
1219 /// \brief Recursively delete a node which has no uses and any operands for
1220 /// which it is the only use.
1221 ///
1222 /// Note that this both deletes the nodes and removes them from the worklist.
1223 /// It also adds any nodes who have had a user deleted to the worklist as they
1224 /// may now have only one use and subject to other combines.
1225 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1226   if (!N->use_empty())
1227     return false;
1228 
1229   SmallSetVector<SDNode *, 16> Nodes;
1230   Nodes.insert(N);
1231   do {
1232     N = Nodes.pop_back_val();
1233     if (!N)
1234       continue;
1235 
1236     if (N->use_empty()) {
1237       for (const SDValue &ChildN : N->op_values())
1238         Nodes.insert(ChildN.getNode());
1239 
1240       removeFromWorklist(N);
1241       DAG.DeleteNode(N);
1242     } else {
1243       AddToWorklist(N);
1244     }
1245   } while (!Nodes.empty());
1246   return true;
1247 }
1248 
1249 //===----------------------------------------------------------------------===//
1250 //  Main DAG Combiner implementation
1251 //===----------------------------------------------------------------------===//
1252 
1253 void DAGCombiner::Run(CombineLevel AtLevel) {
1254   // set the instance variables, so that the various visit routines may use it.
1255   Level = AtLevel;
1256   LegalOperations = Level >= AfterLegalizeVectorOps;
1257   LegalTypes = Level >= AfterLegalizeTypes;
1258 
1259   // Add all the dag nodes to the worklist.
1260   for (SDNode &Node : DAG.allnodes())
1261     AddToWorklist(&Node);
1262 
1263   // Create a dummy node (which is not added to allnodes), that adds a reference
1264   // to the root node, preventing it from being deleted, and tracking any
1265   // changes of the root.
1266   HandleSDNode Dummy(DAG.getRoot());
1267 
1268   // While the worklist isn't empty, find a node and try to combine it.
1269   while (!WorklistMap.empty()) {
1270     SDNode *N;
1271     // The Worklist holds the SDNodes in order, but it may contain null entries.
1272     do {
1273       N = Worklist.pop_back_val();
1274     } while (!N);
1275 
1276     bool GoodWorklistEntry = WorklistMap.erase(N);
1277     (void)GoodWorklistEntry;
1278     assert(GoodWorklistEntry &&
1279            "Found a worklist entry without a corresponding map entry!");
1280 
1281     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1282     // N is deleted from the DAG, since they too may now be dead or may have a
1283     // reduced number of uses, allowing other xforms.
1284     if (recursivelyDeleteUnusedNodes(N))
1285       continue;
1286 
1287     WorklistRemover DeadNodes(*this);
1288 
1289     // If this combine is running after legalizing the DAG, re-legalize any
1290     // nodes pulled off the worklist.
1291     if (Level == AfterLegalizeDAG) {
1292       SmallSetVector<SDNode *, 16> UpdatedNodes;
1293       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1294 
1295       for (SDNode *LN : UpdatedNodes) {
1296         AddToWorklist(LN);
1297         AddUsersToWorklist(LN);
1298       }
1299       if (!NIsValid)
1300         continue;
1301     }
1302 
1303     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1304 
1305     // Add any operands of the new node which have not yet been combined to the
1306     // worklist as well. Because the worklist uniques things already, this
1307     // won't repeatedly process the same operand.
1308     CombinedNodes.insert(N);
1309     for (const SDValue &ChildN : N->op_values())
1310       if (!CombinedNodes.count(ChildN.getNode()))
1311         AddToWorklist(ChildN.getNode());
1312 
1313     SDValue RV = combine(N);
1314 
1315     if (!RV.getNode())
1316       continue;
1317 
1318     ++NodesCombined;
1319 
1320     // If we get back the same node we passed in, rather than a new node or
1321     // zero, we know that the node must have defined multiple values and
1322     // CombineTo was used.  Since CombineTo takes care of the worklist
1323     // mechanics for us, we have no work to do in this case.
1324     if (RV.getNode() == N)
1325       continue;
1326 
1327     assert(N->getOpcode() != ISD::DELETED_NODE &&
1328            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1329            "Node was deleted but visit returned new node!");
1330 
1331     DEBUG(dbgs() << " ... into: ";
1332           RV.getNode()->dump(&DAG));
1333 
1334     // Transfer debug value.
1335     DAG.TransferDbgValues(SDValue(N, 0), RV);
1336     if (N->getNumValues() == RV.getNode()->getNumValues())
1337       DAG.ReplaceAllUsesWith(N, RV.getNode());
1338     else {
1339       assert(N->getValueType(0) == RV.getValueType() &&
1340              N->getNumValues() == 1 && "Type mismatch");
1341       SDValue OpV = RV;
1342       DAG.ReplaceAllUsesWith(N, &OpV);
1343     }
1344 
1345     // Push the new node and any users onto the worklist
1346     AddToWorklist(RV.getNode());
1347     AddUsersToWorklist(RV.getNode());
1348 
1349     // Finally, if the node is now dead, remove it from the graph.  The node
1350     // may not be dead if the replacement process recursively simplified to
1351     // something else needing this node. This will also take care of adding any
1352     // operands which have lost a user to the worklist.
1353     recursivelyDeleteUnusedNodes(N);
1354   }
1355 
1356   // If the root changed (e.g. it was a dead load, update the root).
1357   DAG.setRoot(Dummy.getValue());
1358   DAG.RemoveDeadNodes();
1359 }
1360 
1361 SDValue DAGCombiner::visit(SDNode *N) {
1362   switch (N->getOpcode()) {
1363   default: break;
1364   case ISD::TokenFactor:        return visitTokenFactor(N);
1365   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1366   case ISD::ADD:                return visitADD(N);
1367   case ISD::SUB:                return visitSUB(N);
1368   case ISD::ADDC:               return visitADDC(N);
1369   case ISD::SUBC:               return visitSUBC(N);
1370   case ISD::ADDE:               return visitADDE(N);
1371   case ISD::SUBE:               return visitSUBE(N);
1372   case ISD::MUL:                return visitMUL(N);
1373   case ISD::SDIV:               return visitSDIV(N);
1374   case ISD::UDIV:               return visitUDIV(N);
1375   case ISD::SREM:
1376   case ISD::UREM:               return visitREM(N);
1377   case ISD::MULHU:              return visitMULHU(N);
1378   case ISD::MULHS:              return visitMULHS(N);
1379   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1380   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1381   case ISD::SMULO:              return visitSMULO(N);
1382   case ISD::UMULO:              return visitUMULO(N);
1383   case ISD::SMIN:
1384   case ISD::SMAX:
1385   case ISD::UMIN:
1386   case ISD::UMAX:               return visitIMINMAX(N);
1387   case ISD::AND:                return visitAND(N);
1388   case ISD::OR:                 return visitOR(N);
1389   case ISD::XOR:                return visitXOR(N);
1390   case ISD::SHL:                return visitSHL(N);
1391   case ISD::SRA:                return visitSRA(N);
1392   case ISD::SRL:                return visitSRL(N);
1393   case ISD::ROTR:
1394   case ISD::ROTL:               return visitRotate(N);
1395   case ISD::BSWAP:              return visitBSWAP(N);
1396   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1397   case ISD::CTLZ:               return visitCTLZ(N);
1398   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1399   case ISD::CTTZ:               return visitCTTZ(N);
1400   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1401   case ISD::CTPOP:              return visitCTPOP(N);
1402   case ISD::SELECT:             return visitSELECT(N);
1403   case ISD::VSELECT:            return visitVSELECT(N);
1404   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1405   case ISD::SETCC:              return visitSETCC(N);
1406   case ISD::SETCCE:             return visitSETCCE(N);
1407   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1408   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1409   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1410   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1411   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1412   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1413   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1414   case ISD::BITCAST:            return visitBITCAST(N);
1415   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1416   case ISD::FADD:               return visitFADD(N);
1417   case ISD::FSUB:               return visitFSUB(N);
1418   case ISD::FMUL:               return visitFMUL(N);
1419   case ISD::FMA:                return visitFMA(N);
1420   case ISD::FDIV:               return visitFDIV(N);
1421   case ISD::FREM:               return visitFREM(N);
1422   case ISD::FSQRT:              return visitFSQRT(N);
1423   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1424   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1425   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1426   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1427   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1428   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1429   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1430   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1431   case ISD::FNEG:               return visitFNEG(N);
1432   case ISD::FABS:               return visitFABS(N);
1433   case ISD::FFLOOR:             return visitFFLOOR(N);
1434   case ISD::FMINNUM:            return visitFMINNUM(N);
1435   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1436   case ISD::FCEIL:              return visitFCEIL(N);
1437   case ISD::FTRUNC:             return visitFTRUNC(N);
1438   case ISD::BRCOND:             return visitBRCOND(N);
1439   case ISD::BR_CC:              return visitBR_CC(N);
1440   case ISD::LOAD:               return visitLOAD(N);
1441   case ISD::STORE:              return visitSTORE(N);
1442   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1443   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1444   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1445   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1446   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1447   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1448   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1449   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1450   case ISD::MGATHER:            return visitMGATHER(N);
1451   case ISD::MLOAD:              return visitMLOAD(N);
1452   case ISD::MSCATTER:           return visitMSCATTER(N);
1453   case ISD::MSTORE:             return visitMSTORE(N);
1454   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1455   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1456   }
1457   return SDValue();
1458 }
1459 
1460 SDValue DAGCombiner::combine(SDNode *N) {
1461   SDValue RV = visit(N);
1462 
1463   // If nothing happened, try a target-specific DAG combine.
1464   if (!RV.getNode()) {
1465     assert(N->getOpcode() != ISD::DELETED_NODE &&
1466            "Node was deleted but visit returned NULL!");
1467 
1468     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1469         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1470 
1471       // Expose the DAG combiner to the target combiner impls.
1472       TargetLowering::DAGCombinerInfo
1473         DagCombineInfo(DAG, Level, false, this);
1474 
1475       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1476     }
1477   }
1478 
1479   // If nothing happened still, try promoting the operation.
1480   if (!RV.getNode()) {
1481     switch (N->getOpcode()) {
1482     default: break;
1483     case ISD::ADD:
1484     case ISD::SUB:
1485     case ISD::MUL:
1486     case ISD::AND:
1487     case ISD::OR:
1488     case ISD::XOR:
1489       RV = PromoteIntBinOp(SDValue(N, 0));
1490       break;
1491     case ISD::SHL:
1492     case ISD::SRA:
1493     case ISD::SRL:
1494       RV = PromoteIntShiftOp(SDValue(N, 0));
1495       break;
1496     case ISD::SIGN_EXTEND:
1497     case ISD::ZERO_EXTEND:
1498     case ISD::ANY_EXTEND:
1499       RV = PromoteExtend(SDValue(N, 0));
1500       break;
1501     case ISD::LOAD:
1502       if (PromoteLoad(SDValue(N, 0)))
1503         RV = SDValue(N, 0);
1504       break;
1505     }
1506   }
1507 
1508   // If N is a commutative binary node, try commuting it to enable more
1509   // sdisel CSE.
1510   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1511       N->getNumValues() == 1) {
1512     SDValue N0 = N->getOperand(0);
1513     SDValue N1 = N->getOperand(1);
1514 
1515     // Constant operands are canonicalized to RHS.
1516     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1517       SDValue Ops[] = {N1, N0};
1518       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1519                                             N->getFlags());
1520       if (CSENode)
1521         return SDValue(CSENode, 0);
1522     }
1523   }
1524 
1525   return RV;
1526 }
1527 
1528 /// Given a node, return its input chain if it has one, otherwise return a null
1529 /// sd operand.
1530 static SDValue getInputChainForNode(SDNode *N) {
1531   if (unsigned NumOps = N->getNumOperands()) {
1532     if (N->getOperand(0).getValueType() == MVT::Other)
1533       return N->getOperand(0);
1534     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1535       return N->getOperand(NumOps-1);
1536     for (unsigned i = 1; i < NumOps-1; ++i)
1537       if (N->getOperand(i).getValueType() == MVT::Other)
1538         return N->getOperand(i);
1539   }
1540   return SDValue();
1541 }
1542 
1543 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1544   // If N has two operands, where one has an input chain equal to the other,
1545   // the 'other' chain is redundant.
1546   if (N->getNumOperands() == 2) {
1547     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1548       return N->getOperand(0);
1549     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1550       return N->getOperand(1);
1551   }
1552 
1553   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1554   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1555   SmallPtrSet<SDNode*, 16> SeenOps;
1556   bool Changed = false;             // If we should replace this token factor.
1557 
1558   // Start out with this token factor.
1559   TFs.push_back(N);
1560 
1561   // Iterate through token factors.  The TFs grows when new token factors are
1562   // encountered.
1563   for (unsigned i = 0; i < TFs.size(); ++i) {
1564     SDNode *TF = TFs[i];
1565 
1566     // Check each of the operands.
1567     for (const SDValue &Op : TF->op_values()) {
1568 
1569       switch (Op.getOpcode()) {
1570       case ISD::EntryToken:
1571         // Entry tokens don't need to be added to the list. They are
1572         // redundant.
1573         Changed = true;
1574         break;
1575 
1576       case ISD::TokenFactor:
1577         if (Op.hasOneUse() &&
1578             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1579           // Queue up for processing.
1580           TFs.push_back(Op.getNode());
1581           // Clean up in case the token factor is removed.
1582           AddToWorklist(Op.getNode());
1583           Changed = true;
1584           break;
1585         }
1586         // Fall thru
1587 
1588       default:
1589         // Only add if it isn't already in the list.
1590         if (SeenOps.insert(Op.getNode()).second)
1591           Ops.push_back(Op);
1592         else
1593           Changed = true;
1594         break;
1595       }
1596     }
1597   }
1598 
1599   SDValue Result;
1600 
1601   // If we've changed things around then replace token factor.
1602   if (Changed) {
1603     if (Ops.empty()) {
1604       // The entry token is the only possible outcome.
1605       Result = DAG.getEntryNode();
1606     } else {
1607       // New and improved token factor.
1608       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1609     }
1610 
1611     // Add users to worklist if AA is enabled, since it may introduce
1612     // a lot of new chained token factors while removing memory deps.
1613     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1614       : DAG.getSubtarget().useAA();
1615     return CombineTo(N, Result, UseAA /*add to worklist*/);
1616   }
1617 
1618   return Result;
1619 }
1620 
1621 /// MERGE_VALUES can always be eliminated.
1622 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1623   WorklistRemover DeadNodes(*this);
1624   // Replacing results may cause a different MERGE_VALUES to suddenly
1625   // be CSE'd with N, and carry its uses with it. Iterate until no
1626   // uses remain, to ensure that the node can be safely deleted.
1627   // First add the users of this node to the work list so that they
1628   // can be tried again once they have new operands.
1629   AddUsersToWorklist(N);
1630   do {
1631     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1632       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1633   } while (!N->use_empty());
1634   deleteAndRecombine(N);
1635   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1636 }
1637 
1638 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1639 /// ConstantSDNode pointer else nullptr.
1640 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1641   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1642   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1643 }
1644 
1645 SDValue DAGCombiner::visitADD(SDNode *N) {
1646   SDValue N0 = N->getOperand(0);
1647   SDValue N1 = N->getOperand(1);
1648   EVT VT = N0.getValueType();
1649 
1650   // fold vector ops
1651   if (VT.isVector()) {
1652     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1653       return FoldedVOp;
1654 
1655     // fold (add x, 0) -> x, vector edition
1656     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1657       return N0;
1658     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1659       return N1;
1660   }
1661 
1662   // fold (add x, undef) -> undef
1663   if (N0.isUndef())
1664     return N0;
1665   if (N1.isUndef())
1666     return N1;
1667   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1668     // canonicalize constant to RHS
1669     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1670       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1671     // fold (add c1, c2) -> c1+c2
1672     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT,
1673                                       N0.getNode(), N1.getNode());
1674   }
1675   // fold (add x, 0) -> x
1676   if (isNullConstant(N1))
1677     return N0;
1678   // fold ((c1-A)+c2) -> (c1+c2)-A
1679   if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) {
1680     if (N0.getOpcode() == ISD::SUB)
1681       if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682         SDLoc DL(N);
1683         return DAG.getNode(ISD::SUB, DL, VT,
1684                            DAG.getConstant(N1C->getAPIntValue()+
1685                                            N0C->getAPIntValue(), DL, VT),
1686                            N0.getOperand(1));
1687       }
1688   }
1689   // reassociate add
1690   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1691     return RADD;
1692   // fold ((0-A) + B) -> B-A
1693   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695   // fold (A + (0-B)) -> A-B
1696   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698   // fold (A+(B-A)) -> B
1699   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700     return N1.getOperand(0);
1701   // fold ((B-A)+A) -> B
1702   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703     return N0.getOperand(0);
1704   // fold (A+(B-(A+C))) to (B-C)
1705   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0 == N1.getOperand(1).getOperand(0))
1707     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708                        N1.getOperand(1).getOperand(1));
1709   // fold (A+(B-(C+A))) to (B-C)
1710   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711       N0 == N1.getOperand(1).getOperand(1))
1712     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713                        N1.getOperand(1).getOperand(0));
1714   // fold (A+((B-A)+or-C)) to (B+or-C)
1715   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716       N1.getOperand(0).getOpcode() == ISD::SUB &&
1717       N0 == N1.getOperand(0).getOperand(1))
1718     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1720 
1721   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723     SDValue N00 = N0.getOperand(0);
1724     SDValue N01 = N0.getOperand(1);
1725     SDValue N10 = N1.getOperand(0);
1726     SDValue N11 = N1.getOperand(1);
1727 
1728     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732   }
1733 
1734   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735     return SDValue(N, 0);
1736 
1737   // fold (a+b) -> (a|b) iff a and b share no bits.
1738   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) &&
1739       VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1))
1740     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1741 
1742   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1743   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1744       isNullConstant(N1.getOperand(0).getOperand(0)))
1745     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1746                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1747                                    N1.getOperand(0).getOperand(1),
1748                                    N1.getOperand(1)));
1749   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1750       isNullConstant(N0.getOperand(0).getOperand(0)))
1751     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1752                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1753                                    N0.getOperand(0).getOperand(1),
1754                                    N0.getOperand(1)));
1755 
1756   if (N1.getOpcode() == ISD::AND) {
1757     SDValue AndOp0 = N1.getOperand(0);
1758     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1759     unsigned DestBits = VT.getScalarType().getSizeInBits();
1760 
1761     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1762     // and similar xforms where the inner op is either ~0 or 0.
1763     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1764       SDLoc DL(N);
1765       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1766     }
1767   }
1768 
1769   // add (sext i1), X -> sub X, (zext i1)
1770   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1771       N0.getOperand(0).getValueType() == MVT::i1 &&
1772       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1773     SDLoc DL(N);
1774     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1775     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1776   }
1777 
1778   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1779   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1780     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1781     if (TN->getVT() == MVT::i1) {
1782       SDLoc DL(N);
1783       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1784                                  DAG.getConstant(1, DL, VT));
1785       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1786     }
1787   }
1788 
1789   return SDValue();
1790 }
1791 
1792 SDValue DAGCombiner::visitADDC(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   EVT VT = N0.getValueType();
1796 
1797   // If the flag result is dead, turn this into an ADD.
1798   if (!N->hasAnyUseOfValue(1))
1799     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1800                      DAG.getNode(ISD::CARRY_FALSE,
1801                                  SDLoc(N), MVT::Glue));
1802 
1803   // canonicalize constant to RHS.
1804   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1805   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1806   if (N0C && !N1C)
1807     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1808 
1809   // fold (addc x, 0) -> x + no carry out
1810   if (isNullConstant(N1))
1811     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1812                                         SDLoc(N), MVT::Glue));
1813 
1814   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1815   APInt LHSZero, LHSOne;
1816   APInt RHSZero, RHSOne;
1817   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1818 
1819   if (LHSZero.getBoolValue()) {
1820     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1821 
1822     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1823     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1824     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1825       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1826                        DAG.getNode(ISD::CARRY_FALSE,
1827                                    SDLoc(N), MVT::Glue));
1828   }
1829 
1830   return SDValue();
1831 }
1832 
1833 SDValue DAGCombiner::visitADDE(SDNode *N) {
1834   SDValue N0 = N->getOperand(0);
1835   SDValue N1 = N->getOperand(1);
1836   SDValue CarryIn = N->getOperand(2);
1837 
1838   // canonicalize constant to RHS
1839   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1840   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1841   if (N0C && !N1C)
1842     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1843                        N1, N0, CarryIn);
1844 
1845   // fold (adde x, y, false) -> (addc x, y)
1846   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1847     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1848 
1849   return SDValue();
1850 }
1851 
1852 // Since it may not be valid to emit a fold to zero for vector initializers
1853 // check if we can before folding.
1854 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1855                              SelectionDAG &DAG,
1856                              bool LegalOperations, bool LegalTypes) {
1857   if (!VT.isVector())
1858     return DAG.getConstant(0, DL, VT);
1859   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1860     return DAG.getConstant(0, DL, VT);
1861   return SDValue();
1862 }
1863 
1864 SDValue DAGCombiner::visitSUB(SDNode *N) {
1865   SDValue N0 = N->getOperand(0);
1866   SDValue N1 = N->getOperand(1);
1867   EVT VT = N0.getValueType();
1868 
1869   // fold vector ops
1870   if (VT.isVector()) {
1871     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1872       return FoldedVOp;
1873 
1874     // fold (sub x, 0) -> x, vector edition
1875     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1876       return N0;
1877   }
1878 
1879   // fold (sub x, x) -> 0
1880   // FIXME: Refactor this and xor and other similar operations together.
1881   if (N0 == N1)
1882     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1883   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
1884       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
1885     // fold (sub c1, c2) -> c1-c2
1886     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT,
1887                                       N0.getNode(), N1.getNode());
1888   }
1889   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1890   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1891   // fold (sub x, c) -> (add x, -c)
1892   if (N1C) {
1893     SDLoc DL(N);
1894     return DAG.getNode(ISD::ADD, DL, VT, N0,
1895                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1896   }
1897   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1898   if (isAllOnesConstant(N0))
1899     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1900   // fold A-(A-B) -> B
1901   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1902     return N1.getOperand(1);
1903   // fold (A+B)-A -> B
1904   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1905     return N0.getOperand(1);
1906   // fold (A+B)-B -> A
1907   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1908     return N0.getOperand(0);
1909   // fold C2-(A+C1) -> (C2-C1)-A
1910   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1911     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1912   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1913     SDLoc DL(N);
1914     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1915                                    DL, VT);
1916     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1917                        N1.getOperand(0));
1918   }
1919   // fold ((A+(B+or-C))-B) -> A+or-C
1920   if (N0.getOpcode() == ISD::ADD &&
1921       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1922        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1923       N0.getOperand(1).getOperand(0) == N1)
1924     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1925                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1926   // fold ((A+(C+B))-B) -> A+C
1927   if (N0.getOpcode() == ISD::ADD &&
1928       N0.getOperand(1).getOpcode() == ISD::ADD &&
1929       N0.getOperand(1).getOperand(1) == N1)
1930     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1931                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1932   // fold ((A-(B-C))-C) -> A-B
1933   if (N0.getOpcode() == ISD::SUB &&
1934       N0.getOperand(1).getOpcode() == ISD::SUB &&
1935       N0.getOperand(1).getOperand(1) == N1)
1936     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1937                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1938 
1939   // If either operand of a sub is undef, the result is undef
1940   if (N0.isUndef())
1941     return N0;
1942   if (N1.isUndef())
1943     return N1;
1944 
1945   // If the relocation model supports it, consider symbol offsets.
1946   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1947     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1948       // fold (sub Sym, c) -> Sym-c
1949       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1950         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1951                                     GA->getOffset() -
1952                                       (uint64_t)N1C->getSExtValue());
1953       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1954       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1955         if (GA->getGlobal() == GB->getGlobal())
1956           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1957                                  SDLoc(N), VT);
1958     }
1959 
1960   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1961   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1962     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1963     if (TN->getVT() == MVT::i1) {
1964       SDLoc DL(N);
1965       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1966                                  DAG.getConstant(1, DL, VT));
1967       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1968     }
1969   }
1970 
1971   return SDValue();
1972 }
1973 
1974 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1975   SDValue N0 = N->getOperand(0);
1976   SDValue N1 = N->getOperand(1);
1977   EVT VT = N0.getValueType();
1978   SDLoc DL(N);
1979 
1980   // If the flag result is dead, turn this into an SUB.
1981   if (!N->hasAnyUseOfValue(1))
1982     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1983                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1984 
1985   // fold (subc x, x) -> 0 + no borrow
1986   if (N0 == N1)
1987     return CombineTo(N, DAG.getConstant(0, DL, VT),
1988                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1989 
1990   // fold (subc x, 0) -> x + no borrow
1991   if (isNullConstant(N1))
1992     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1993 
1994   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1995   if (isAllOnesConstant(N0))
1996     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
1997                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1998 
1999   return SDValue();
2000 }
2001 
2002 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2003   SDValue N0 = N->getOperand(0);
2004   SDValue N1 = N->getOperand(1);
2005   SDValue CarryIn = N->getOperand(2);
2006 
2007   // fold (sube x, y, false) -> (subc x, y)
2008   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2009     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2010 
2011   return SDValue();
2012 }
2013 
2014 SDValue DAGCombiner::visitMUL(SDNode *N) {
2015   SDValue N0 = N->getOperand(0);
2016   SDValue N1 = N->getOperand(1);
2017   EVT VT = N0.getValueType();
2018 
2019   // fold (mul x, undef) -> 0
2020   if (N0.isUndef() || N1.isUndef())
2021     return DAG.getConstant(0, SDLoc(N), VT);
2022 
2023   bool N0IsConst = false;
2024   bool N1IsConst = false;
2025   bool N1IsOpaqueConst = false;
2026   bool N0IsOpaqueConst = false;
2027   APInt ConstValue0, ConstValue1;
2028   // fold vector ops
2029   if (VT.isVector()) {
2030     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2031       return FoldedVOp;
2032 
2033     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2034     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2035   } else {
2036     N0IsConst = isa<ConstantSDNode>(N0);
2037     if (N0IsConst) {
2038       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2039       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2040     }
2041     N1IsConst = isa<ConstantSDNode>(N1);
2042     if (N1IsConst) {
2043       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2044       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2045     }
2046   }
2047 
2048   // fold (mul c1, c2) -> c1*c2
2049   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2050     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2051                                       N0.getNode(), N1.getNode());
2052 
2053   // canonicalize constant to RHS (vector doesn't have to splat)
2054   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2055      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2056     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2057   // fold (mul x, 0) -> 0
2058   if (N1IsConst && ConstValue1 == 0)
2059     return N1;
2060   // We require a splat of the entire scalar bit width for non-contiguous
2061   // bit patterns.
2062   bool IsFullSplat =
2063     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2064   // fold (mul x, 1) -> x
2065   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2066     return N0;
2067   // fold (mul x, -1) -> 0-x
2068   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2069     SDLoc DL(N);
2070     return DAG.getNode(ISD::SUB, DL, VT,
2071                        DAG.getConstant(0, DL, VT), N0);
2072   }
2073   // fold (mul x, (1 << c)) -> x << c
2074   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2075       IsFullSplat) {
2076     SDLoc DL(N);
2077     return DAG.getNode(ISD::SHL, DL, VT, N0,
2078                        DAG.getConstant(ConstValue1.logBase2(), DL,
2079                                        getShiftAmountTy(N0.getValueType())));
2080   }
2081   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2082   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2083       IsFullSplat) {
2084     unsigned Log2Val = (-ConstValue1).logBase2();
2085     SDLoc DL(N);
2086     // FIXME: If the input is something that is easily negated (e.g. a
2087     // single-use add), we should put the negate there.
2088     return DAG.getNode(ISD::SUB, DL, VT,
2089                        DAG.getConstant(0, DL, VT),
2090                        DAG.getNode(ISD::SHL, DL, VT, N0,
2091                             DAG.getConstant(Log2Val, DL,
2092                                       getShiftAmountTy(N0.getValueType()))));
2093   }
2094 
2095   APInt Val;
2096   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2097   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2098       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2099                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2100     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2101                              N1, N0.getOperand(1));
2102     AddToWorklist(C3.getNode());
2103     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2104                        N0.getOperand(0), C3);
2105   }
2106 
2107   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2108   // use.
2109   {
2110     SDValue Sh(nullptr,0), Y(nullptr,0);
2111     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2112     if (N0.getOpcode() == ISD::SHL &&
2113         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2115         N0.getNode()->hasOneUse()) {
2116       Sh = N0; Y = N1;
2117     } else if (N1.getOpcode() == ISD::SHL &&
2118                isa<ConstantSDNode>(N1.getOperand(1)) &&
2119                N1.getNode()->hasOneUse()) {
2120       Sh = N1; Y = N0;
2121     }
2122 
2123     if (Sh.getNode()) {
2124       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125                                 Sh.getOperand(0), Y);
2126       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2127                          Mul, Sh.getOperand(1));
2128     }
2129   }
2130 
2131   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2132   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2133       N0.getOpcode() == ISD::ADD &&
2134       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2135       isMulAddWithConstProfitable(N, N0, N1))
2136       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2137                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2138                                      N0.getOperand(0), N1),
2139                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2140                                      N0.getOperand(1), N1));
2141 
2142   // reassociate mul
2143   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2144     return RMUL;
2145 
2146   return SDValue();
2147 }
2148 
2149 /// Return true if divmod libcall is available.
2150 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2151                                      const TargetLowering &TLI) {
2152   RTLIB::Libcall LC;
2153   EVT NodeType = Node->getValueType(0);
2154   if (!NodeType.isSimple())
2155     return false;
2156   switch (NodeType.getSimpleVT().SimpleTy) {
2157   default: return false; // No libcall for vector types.
2158   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2159   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2160   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2161   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2162   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2163   }
2164 
2165   return TLI.getLibcallName(LC) != nullptr;
2166 }
2167 
2168 /// Issue divrem if both quotient and remainder are needed.
2169 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2170   if (Node->use_empty())
2171     return SDValue(); // This is a dead node, leave it alone.
2172 
2173   unsigned Opcode = Node->getOpcode();
2174   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2175   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2176 
2177   // DivMod lib calls can still work on non-legal types if using lib-calls.
2178   EVT VT = Node->getValueType(0);
2179   if (VT.isVector() || !VT.isInteger())
2180     return SDValue();
2181 
2182   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2183     return SDValue();
2184 
2185   // If DIVREM is going to get expanded into a libcall,
2186   // but there is no libcall available, then don't combine.
2187   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2188       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2189     return SDValue();
2190 
2191   // If div is legal, it's better to do the normal expansion
2192   unsigned OtherOpcode = 0;
2193   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2194     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2195     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2196       return SDValue();
2197   } else {
2198     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2199     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2200       return SDValue();
2201   }
2202 
2203   SDValue Op0 = Node->getOperand(0);
2204   SDValue Op1 = Node->getOperand(1);
2205   SDValue combined;
2206   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2207          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2208     SDNode *User = *UI;
2209     if (User == Node || User->use_empty())
2210       continue;
2211     // Convert the other matching node(s), too;
2212     // otherwise, the DIVREM may get target-legalized into something
2213     // target-specific that we won't be able to recognize.
2214     unsigned UserOpc = User->getOpcode();
2215     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2216         User->getOperand(0) == Op0 &&
2217         User->getOperand(1) == Op1) {
2218       if (!combined) {
2219         if (UserOpc == OtherOpcode) {
2220           SDVTList VTs = DAG.getVTList(VT, VT);
2221           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2222         } else if (UserOpc == DivRemOpc) {
2223           combined = SDValue(User, 0);
2224         } else {
2225           assert(UserOpc == Opcode);
2226           continue;
2227         }
2228       }
2229       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2230         CombineTo(User, combined);
2231       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2232         CombineTo(User, combined.getValue(1));
2233     }
2234   }
2235   return combined;
2236 }
2237 
2238 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2239   SDValue N0 = N->getOperand(0);
2240   SDValue N1 = N->getOperand(1);
2241   EVT VT = N->getValueType(0);
2242 
2243   // fold vector ops
2244   if (VT.isVector())
2245     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2246       return FoldedVOp;
2247 
2248   SDLoc DL(N);
2249 
2250   // fold (sdiv c1, c2) -> c1/c2
2251   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2252   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2253   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2254     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2255   // fold (sdiv X, 1) -> X
2256   if (N1C && N1C->isOne())
2257     return N0;
2258   // fold (sdiv X, -1) -> 0-X
2259   if (N1C && N1C->isAllOnesValue())
2260     return DAG.getNode(ISD::SUB, DL, VT,
2261                        DAG.getConstant(0, DL, VT), N0);
2262 
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2268   }
2269 
2270   // fold (sdiv X, pow2) -> simple ops after legalize
2271   // FIXME: We check for the exact bit here because the generic lowering gives
2272   // better results in that case. The target-specific lowering should learn how
2273   // to handle exact sdivs efficiently.
2274   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2275       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2276       (N1C->getAPIntValue().isPowerOf2() ||
2277        (-N1C->getAPIntValue()).isPowerOf2())) {
2278     // Target-specific implementation of sdiv x, pow2.
2279     if (SDValue Res = BuildSDIVPow2(N))
2280       return Res;
2281 
2282     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2283 
2284     // Splat the sign bit into the register
2285     SDValue SGN =
2286         DAG.getNode(ISD::SRA, DL, VT, N0,
2287                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2288                                     getShiftAmountTy(N0.getValueType())));
2289     AddToWorklist(SGN.getNode());
2290 
2291     // Add (N0 < 0) ? abs2 - 1 : 0;
2292     SDValue SRL =
2293         DAG.getNode(ISD::SRL, DL, VT, SGN,
2294                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2295                                     getShiftAmountTy(SGN.getValueType())));
2296     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2297     AddToWorklist(SRL.getNode());
2298     AddToWorklist(ADD.getNode());    // Divide by pow2
2299     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2300                   DAG.getConstant(lg2, DL,
2301                                   getShiftAmountTy(ADD.getValueType())));
2302 
2303     // If we're dividing by a positive value, we're done.  Otherwise, we must
2304     // negate the result.
2305     if (N1C->getAPIntValue().isNonNegative())
2306       return SRA;
2307 
2308     AddToWorklist(SRA.getNode());
2309     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2310   }
2311 
2312   // If integer divide is expensive and we satisfy the requirements, emit an
2313   // alternate sequence.  Targets may check function attributes for size/speed
2314   // trade-offs.
2315   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2316   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2317     if (SDValue Op = BuildSDIV(N))
2318       return Op;
2319 
2320   // sdiv, srem -> sdivrem
2321   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2322   // Otherwise, we break the simplification logic in visitREM().
2323   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2324     if (SDValue DivRem = useDivRem(N))
2325         return DivRem;
2326 
2327   // undef / X -> 0
2328   if (N0.isUndef())
2329     return DAG.getConstant(0, DL, VT);
2330   // X / undef -> undef
2331   if (N1.isUndef())
2332     return N1;
2333 
2334   return SDValue();
2335 }
2336 
2337 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2338   SDValue N0 = N->getOperand(0);
2339   SDValue N1 = N->getOperand(1);
2340   EVT VT = N->getValueType(0);
2341 
2342   // fold vector ops
2343   if (VT.isVector())
2344     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2345       return FoldedVOp;
2346 
2347   SDLoc DL(N);
2348 
2349   // fold (udiv c1, c2) -> c1/c2
2350   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2351   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352   if (N0C && N1C)
2353     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2354                                                     N0C, N1C))
2355       return Folded;
2356   // fold (udiv x, (1 << c)) -> x >>u c
2357   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2358     return DAG.getNode(ISD::SRL, DL, VT, N0,
2359                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2360                                        getShiftAmountTy(N0.getValueType())));
2361 
2362   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2363   if (N1.getOpcode() == ISD::SHL) {
2364     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2365       if (SHC->getAPIntValue().isPowerOf2()) {
2366         EVT ADDVT = N1.getOperand(1).getValueType();
2367         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2368                                   N1.getOperand(1),
2369                                   DAG.getConstant(SHC->getAPIntValue()
2370                                                                   .logBase2(),
2371                                                   DL, ADDVT));
2372         AddToWorklist(Add.getNode());
2373         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2374       }
2375     }
2376   }
2377 
2378   // fold (udiv x, c) -> alternate
2379   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2380   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2381     if (SDValue Op = BuildUDIV(N))
2382       return Op;
2383 
2384   // sdiv, srem -> sdivrem
2385   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2386   // Otherwise, we break the simplification logic in visitREM().
2387   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2388     if (SDValue DivRem = useDivRem(N))
2389         return DivRem;
2390 
2391   // undef / X -> 0
2392   if (N0.isUndef())
2393     return DAG.getConstant(0, DL, VT);
2394   // X / undef -> undef
2395   if (N1.isUndef())
2396     return N1;
2397 
2398   return SDValue();
2399 }
2400 
2401 // handles ISD::SREM and ISD::UREM
2402 SDValue DAGCombiner::visitREM(SDNode *N) {
2403   unsigned Opcode = N->getOpcode();
2404   SDValue N0 = N->getOperand(0);
2405   SDValue N1 = N->getOperand(1);
2406   EVT VT = N->getValueType(0);
2407   bool isSigned = (Opcode == ISD::SREM);
2408   SDLoc DL(N);
2409 
2410   // fold (rem c1, c2) -> c1%c2
2411   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2412   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2413   if (N0C && N1C)
2414     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2415       return Folded;
2416 
2417   if (isSigned) {
2418     // If we know the sign bits of both operands are zero, strength reduce to a
2419     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2420     if (!VT.isVector()) {
2421       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2422         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2423     }
2424   } else {
2425     // fold (urem x, pow2) -> (and x, pow2-1)
2426     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2427         N1C->getAPIntValue().isPowerOf2()) {
2428       return DAG.getNode(ISD::AND, DL, VT, N0,
2429                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2430     }
2431     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2432     if (N1.getOpcode() == ISD::SHL) {
2433       ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0));
2434       if (SHC && SHC->getAPIntValue().isPowerOf2()) {
2435         APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits());
2436         SDValue Add =
2437             DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT));
2438         AddToWorklist(Add.getNode());
2439         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2440       }
2441     }
2442   }
2443 
2444   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2445 
2446   // If X/C can be simplified by the division-by-constant logic, lower
2447   // X%C to the equivalent of X-X/C*C.
2448   // To avoid mangling nodes, this simplification requires that the combine()
2449   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2450   // against this by skipping the simplification if isIntDivCheap().  When
2451   // div is not cheap, combine will not return a DIVREM.  Regardless,
2452   // checking cheapness here makes sense since the simplification results in
2453   // fatter code.
2454   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2455     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2456     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2457     AddToWorklist(Div.getNode());
2458     SDValue OptimizedDiv = combine(Div.getNode());
2459     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2460       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2461              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2462       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2463       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2464       AddToWorklist(Mul.getNode());
2465       return Sub;
2466     }
2467   }
2468 
2469   // sdiv, srem -> sdivrem
2470   if (SDValue DivRem = useDivRem(N))
2471     return DivRem.getValue(1);
2472 
2473   // undef % X -> 0
2474   if (N0.isUndef())
2475     return DAG.getConstant(0, DL, VT);
2476   // X % undef -> undef
2477   if (N1.isUndef())
2478     return N1;
2479 
2480   return SDValue();
2481 }
2482 
2483 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2484   SDValue N0 = N->getOperand(0);
2485   SDValue N1 = N->getOperand(1);
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488 
2489   // fold (mulhs x, 0) -> 0
2490   if (isNullConstant(N1))
2491     return N1;
2492   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2493   if (isOneConstant(N1)) {
2494     SDLoc DL(N);
2495     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2496                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2497                                        DL,
2498                                        getShiftAmountTy(N0.getValueType())));
2499   }
2500   // fold (mulhs x, undef) -> 0
2501   if (N0.isUndef() || N1.isUndef())
2502     return DAG.getConstant(0, SDLoc(N), VT);
2503 
2504   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2505   // plus a shift.
2506   if (VT.isSimple() && !VT.isVector()) {
2507     MVT Simple = VT.getSimpleVT();
2508     unsigned SimpleSize = Simple.getSizeInBits();
2509     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2510     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2511       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2512       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2513       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2514       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2515             DAG.getConstant(SimpleSize, DL,
2516                             getShiftAmountTy(N1.getValueType())));
2517       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2518     }
2519   }
2520 
2521   return SDValue();
2522 }
2523 
2524 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2525   SDValue N0 = N->getOperand(0);
2526   SDValue N1 = N->getOperand(1);
2527   EVT VT = N->getValueType(0);
2528   SDLoc DL(N);
2529 
2530   // fold (mulhu x, 0) -> 0
2531   if (isNullConstant(N1))
2532     return N1;
2533   // fold (mulhu x, 1) -> 0
2534   if (isOneConstant(N1))
2535     return DAG.getConstant(0, DL, N0.getValueType());
2536   // fold (mulhu x, undef) -> 0
2537   if (N0.isUndef() || N1.isUndef())
2538     return DAG.getConstant(0, DL, VT);
2539 
2540   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2541   // plus a shift.
2542   if (VT.isSimple() && !VT.isVector()) {
2543     MVT Simple = VT.getSimpleVT();
2544     unsigned SimpleSize = Simple.getSizeInBits();
2545     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2546     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2547       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2548       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2549       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2550       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2551             DAG.getConstant(SimpleSize, DL,
2552                             getShiftAmountTy(N1.getValueType())));
2553       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2554     }
2555   }
2556 
2557   return SDValue();
2558 }
2559 
2560 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2561 /// give the opcodes for the two computations that are being performed. Return
2562 /// true if a simplification was made.
2563 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2564                                                 unsigned HiOp) {
2565   // If the high half is not needed, just compute the low half.
2566   bool HiExists = N->hasAnyUseOfValue(1);
2567   if (!HiExists &&
2568       (!LegalOperations ||
2569        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2570     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2571     return CombineTo(N, Res, Res);
2572   }
2573 
2574   // If the low half is not needed, just compute the high half.
2575   bool LoExists = N->hasAnyUseOfValue(0);
2576   if (!LoExists &&
2577       (!LegalOperations ||
2578        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2579     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2580     return CombineTo(N, Res, Res);
2581   }
2582 
2583   // If both halves are used, return as it is.
2584   if (LoExists && HiExists)
2585     return SDValue();
2586 
2587   // If the two computed results can be simplified separately, separate them.
2588   if (LoExists) {
2589     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2590     AddToWorklist(Lo.getNode());
2591     SDValue LoOpt = combine(Lo.getNode());
2592     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2593         (!LegalOperations ||
2594          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2595       return CombineTo(N, LoOpt, LoOpt);
2596   }
2597 
2598   if (HiExists) {
2599     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2600     AddToWorklist(Hi.getNode());
2601     SDValue HiOpt = combine(Hi.getNode());
2602     if (HiOpt.getNode() && HiOpt != Hi &&
2603         (!LegalOperations ||
2604          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2605       return CombineTo(N, HiOpt, HiOpt);
2606   }
2607 
2608   return SDValue();
2609 }
2610 
2611 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2612   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2613     return Res;
2614 
2615   EVT VT = N->getValueType(0);
2616   SDLoc DL(N);
2617 
2618   // If the type is twice as wide is legal, transform the mulhu to a wider
2619   // multiply plus a shift.
2620   if (VT.isSimple() && !VT.isVector()) {
2621     MVT Simple = VT.getSimpleVT();
2622     unsigned SimpleSize = Simple.getSizeInBits();
2623     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2624     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2625       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2626       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2627       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2628       // Compute the high part as N1.
2629       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2630             DAG.getConstant(SimpleSize, DL,
2631                             getShiftAmountTy(Lo.getValueType())));
2632       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2633       // Compute the low part as N0.
2634       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2635       return CombineTo(N, Lo, Hi);
2636     }
2637   }
2638 
2639   return SDValue();
2640 }
2641 
2642 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2643   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2644     return Res;
2645 
2646   EVT VT = N->getValueType(0);
2647   SDLoc DL(N);
2648 
2649   // If the type is twice as wide is legal, transform the mulhu to a wider
2650   // multiply plus a shift.
2651   if (VT.isSimple() && !VT.isVector()) {
2652     MVT Simple = VT.getSimpleVT();
2653     unsigned SimpleSize = Simple.getSizeInBits();
2654     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2655     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2656       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2657       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2658       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2659       // Compute the high part as N1.
2660       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2661             DAG.getConstant(SimpleSize, DL,
2662                             getShiftAmountTy(Lo.getValueType())));
2663       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2664       // Compute the low part as N0.
2665       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2666       return CombineTo(N, Lo, Hi);
2667     }
2668   }
2669 
2670   return SDValue();
2671 }
2672 
2673 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2674   // (smulo x, 2) -> (saddo x, x)
2675   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2676     if (C2->getAPIntValue() == 2)
2677       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2678                          N->getOperand(0), N->getOperand(0));
2679 
2680   return SDValue();
2681 }
2682 
2683 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2684   // (umulo x, 2) -> (uaddo x, x)
2685   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2686     if (C2->getAPIntValue() == 2)
2687       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2688                          N->getOperand(0), N->getOperand(0));
2689 
2690   return SDValue();
2691 }
2692 
2693 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2694   SDValue N0 = N->getOperand(0);
2695   SDValue N1 = N->getOperand(1);
2696   EVT VT = N0.getValueType();
2697 
2698   // fold vector ops
2699   if (VT.isVector())
2700     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2701       return FoldedVOp;
2702 
2703   // fold (add c1, c2) -> c1+c2
2704   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2705   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2708 
2709   // canonicalize constant to RHS
2710   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2711      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2712     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2713 
2714   return SDValue();
2715 }
2716 
2717 /// If this is a binary operator with two operands of the same opcode, try to
2718 /// simplify it.
2719 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2720   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2721   EVT VT = N0.getValueType();
2722   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2723 
2724   // Bail early if none of these transforms apply.
2725   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2726 
2727   // For each of OP in AND/OR/XOR:
2728   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2729   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2730   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2731   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2732   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2733   //
2734   // do not sink logical op inside of a vector extend, since it may combine
2735   // into a vsetcc.
2736   EVT Op0VT = N0.getOperand(0).getValueType();
2737   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2738        N0.getOpcode() == ISD::SIGN_EXTEND ||
2739        N0.getOpcode() == ISD::BSWAP ||
2740        // Avoid infinite looping with PromoteIntBinOp.
2741        (N0.getOpcode() == ISD::ANY_EXTEND &&
2742         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2743        (N0.getOpcode() == ISD::TRUNCATE &&
2744         (!TLI.isZExtFree(VT, Op0VT) ||
2745          !TLI.isTruncateFree(Op0VT, VT)) &&
2746         TLI.isTypeLegal(Op0VT))) &&
2747       !VT.isVector() &&
2748       Op0VT == N1.getOperand(0).getValueType() &&
2749       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2750     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2751                                  N0.getOperand(0).getValueType(),
2752                                  N0.getOperand(0), N1.getOperand(0));
2753     AddToWorklist(ORNode.getNode());
2754     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2755   }
2756 
2757   // For each of OP in SHL/SRL/SRA/AND...
2758   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2759   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2760   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2761   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2762        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2763       N0.getOperand(1) == N1.getOperand(1)) {
2764     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2765                                  N0.getOperand(0).getValueType(),
2766                                  N0.getOperand(0), N1.getOperand(0));
2767     AddToWorklist(ORNode.getNode());
2768     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2769                        ORNode, N0.getOperand(1));
2770   }
2771 
2772   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2773   // Only perform this optimization up until type legalization, before
2774   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2775   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2776   // we don't want to undo this promotion.
2777   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2778   // on scalars.
2779   if ((N0.getOpcode() == ISD::BITCAST ||
2780        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2781        Level <= AfterLegalizeTypes) {
2782     SDValue In0 = N0.getOperand(0);
2783     SDValue In1 = N1.getOperand(0);
2784     EVT In0Ty = In0.getValueType();
2785     EVT In1Ty = In1.getValueType();
2786     SDLoc DL(N);
2787     // If both incoming values are integers, and the original types are the
2788     // same.
2789     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2790       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2791       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2792       AddToWorklist(Op.getNode());
2793       return BC;
2794     }
2795   }
2796 
2797   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2798   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2799   // If both shuffles use the same mask, and both shuffle within a single
2800   // vector, then it is worthwhile to move the swizzle after the operation.
2801   // The type-legalizer generates this pattern when loading illegal
2802   // vector types from memory. In many cases this allows additional shuffle
2803   // optimizations.
2804   // There are other cases where moving the shuffle after the xor/and/or
2805   // is profitable even if shuffles don't perform a swizzle.
2806   // If both shuffles use the same mask, and both shuffles have the same first
2807   // or second operand, then it might still be profitable to move the shuffle
2808   // after the xor/and/or operation.
2809   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2810     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2811     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2812 
2813     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2814            "Inputs to shuffles are not the same type");
2815 
2816     // Check that both shuffles use the same mask. The masks are known to be of
2817     // the same length because the result vector type is the same.
2818     // Check also that shuffles have only one use to avoid introducing extra
2819     // instructions.
2820     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2821         SVN0->getMask().equals(SVN1->getMask())) {
2822       SDValue ShOp = N0->getOperand(1);
2823 
2824       // Don't try to fold this node if it requires introducing a
2825       // build vector of all zeros that might be illegal at this stage.
2826       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2827         if (!LegalTypes)
2828           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2829         else
2830           ShOp = SDValue();
2831       }
2832 
2833       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2834       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2835       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2836       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2837         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2838                                       N0->getOperand(0), N1->getOperand(0));
2839         AddToWorklist(NewNode.getNode());
2840         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2841                                     &SVN0->getMask()[0]);
2842       }
2843 
2844       // Don't try to fold this node if it requires introducing a
2845       // build vector of all zeros that might be illegal at this stage.
2846       ShOp = N0->getOperand(0);
2847       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
2848         if (!LegalTypes)
2849           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2850         else
2851           ShOp = SDValue();
2852       }
2853 
2854       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2855       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2856       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2857       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2858         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2859                                       N0->getOperand(1), N1->getOperand(1));
2860         AddToWorklist(NewNode.getNode());
2861         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2862                                     &SVN0->getMask()[0]);
2863       }
2864     }
2865   }
2866 
2867   return SDValue();
2868 }
2869 
2870 /// This contains all DAGCombine rules which reduce two values combined by
2871 /// an And operation to a single value. This makes them reusable in the context
2872 /// of visitSELECT(). Rules involving constants are not included as
2873 /// visitSELECT() already handles those cases.
2874 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2875                                   SDNode *LocReference) {
2876   EVT VT = N1.getValueType();
2877 
2878   // fold (and x, undef) -> 0
2879   if (N0.isUndef() || N1.isUndef())
2880     return DAG.getConstant(0, SDLoc(LocReference), VT);
2881   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2882   SDValue LL, LR, RL, RR, CC0, CC1;
2883   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2884     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2885     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2886 
2887     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2888         LL.getValueType().isInteger()) {
2889       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2890       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2891         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2892                                      LR.getValueType(), LL, RL);
2893         AddToWorklist(ORNode.getNode());
2894         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2895       }
2896       if (isAllOnesConstant(LR)) {
2897         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2898         if (Op1 == ISD::SETEQ) {
2899           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2900                                         LR.getValueType(), LL, RL);
2901           AddToWorklist(ANDNode.getNode());
2902           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2903         }
2904         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2905         if (Op1 == ISD::SETGT) {
2906           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2907                                        LR.getValueType(), LL, RL);
2908           AddToWorklist(ORNode.getNode());
2909           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2910         }
2911       }
2912     }
2913     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2914     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2915         Op0 == Op1 && LL.getValueType().isInteger() &&
2916       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2917                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2918       SDLoc DL(N0);
2919       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2920                                     LL, DAG.getConstant(1, DL,
2921                                                         LL.getValueType()));
2922       AddToWorklist(ADDNode.getNode());
2923       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2924                           DAG.getConstant(2, DL, LL.getValueType()),
2925                           ISD::SETUGE);
2926     }
2927     // canonicalize equivalent to ll == rl
2928     if (LL == RR && LR == RL) {
2929       Op1 = ISD::getSetCCSwappedOperands(Op1);
2930       std::swap(RL, RR);
2931     }
2932     if (LL == RL && LR == RR) {
2933       bool isInteger = LL.getValueType().isInteger();
2934       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2935       if (Result != ISD::SETCC_INVALID &&
2936           (!LegalOperations ||
2937            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2938             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2939         EVT CCVT = getSetCCResultType(LL.getValueType());
2940         if (N0.getValueType() == CCVT ||
2941             (!LegalOperations && N0.getValueType() == MVT::i1))
2942           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2943                               LL, LR, Result);
2944       }
2945     }
2946   }
2947 
2948   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2949       VT.getSizeInBits() <= 64) {
2950     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2951       APInt ADDC = ADDI->getAPIntValue();
2952       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2954         // immediate for an add, but it is legal if its top c2 bits are set,
2955         // transform the ADD so the immediate doesn't need to be materialized
2956         // in a register.
2957         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2958           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2959                                              SRLI->getZExtValue());
2960           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2961             ADDC |= Mask;
2962             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2963               SDLoc DL(N0);
2964               SDValue NewAdd =
2965                 DAG.getNode(ISD::ADD, DL, VT,
2966                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2967               CombineTo(N0.getNode(), NewAdd);
2968               // Return N so it doesn't get rechecked!
2969               return SDValue(LocReference, 0);
2970             }
2971           }
2972         }
2973       }
2974     }
2975   }
2976 
2977   // Reduce bit extract of low half of an integer to the narrower type.
2978   // (and (srl i64:x, K), KMask) ->
2979   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
2980   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
2981     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
2982       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2983         unsigned Size = VT.getSizeInBits();
2984         const APInt &AndMask = CAnd->getAPIntValue();
2985         unsigned ShiftBits = CShift->getZExtValue();
2986         unsigned MaskBits = AndMask.countTrailingOnes();
2987         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
2988 
2989         if (APIntOps::isMask(AndMask) &&
2990             // Required bits must not span the two halves of the integer and
2991             // must fit in the half size type.
2992             (ShiftBits + MaskBits <= Size / 2) &&
2993             TLI.isNarrowingProfitable(VT, HalfVT) &&
2994             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
2995             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2996             TLI.isTruncateFree(VT, HalfVT) &&
2997             TLI.isZExtFree(HalfVT, VT)) {
2998           // The isNarrowingProfitable is to avoid regressions on PPC and
2999           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3000           // on downstream users of this. Those patterns could probably be
3001           // extended to handle extensions mixed in.
3002 
3003           SDValue SL(N0);
3004           assert(ShiftBits != 0 && MaskBits <= Size);
3005 
3006           // Extracting the highest bit of the low half.
3007           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3008           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3009                                       N0.getOperand(0));
3010 
3011           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3012           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3013           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3014           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3015           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3016         }
3017       }
3018     }
3019   }
3020 
3021   return SDValue();
3022 }
3023 
3024 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3025                                    EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3026                                    bool &NarrowLoad) {
3027   uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3028 
3029   if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue()))
3030     return false;
3031 
3032   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3033   LoadedVT = LoadN->getMemoryVT();
3034 
3035   if (ExtVT == LoadedVT &&
3036       (!LegalOperations ||
3037        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3038     // ZEXTLOAD will match without needing to change the size of the value being
3039     // loaded.
3040     NarrowLoad = false;
3041     return true;
3042   }
3043 
3044   // Do not change the width of a volatile load.
3045   if (LoadN->isVolatile())
3046     return false;
3047 
3048   // Do not generate loads of non-round integer types since these can
3049   // be expensive (and would be wrong if the type is not byte sized).
3050   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3051     return false;
3052 
3053   if (LegalOperations &&
3054       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3055     return false;
3056 
3057   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3058     return false;
3059 
3060   NarrowLoad = true;
3061   return true;
3062 }
3063 
3064 SDValue DAGCombiner::visitAND(SDNode *N) {
3065   SDValue N0 = N->getOperand(0);
3066   SDValue N1 = N->getOperand(1);
3067   EVT VT = N1.getValueType();
3068 
3069   // fold vector ops
3070   if (VT.isVector()) {
3071     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3072       return FoldedVOp;
3073 
3074     // fold (and x, 0) -> 0, vector edition
3075     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3076       // do not return N0, because undef node may exist in N0
3077       return DAG.getConstant(
3078           APInt::getNullValue(
3079               N0.getValueType().getScalarType().getSizeInBits()),
3080           SDLoc(N), N0.getValueType());
3081     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3082       // do not return N1, because undef node may exist in N1
3083       return DAG.getConstant(
3084           APInt::getNullValue(
3085               N1.getValueType().getScalarType().getSizeInBits()),
3086           SDLoc(N), N1.getValueType());
3087 
3088     // fold (and x, -1) -> x, vector edition
3089     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3090       return N1;
3091     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3092       return N0;
3093   }
3094 
3095   // fold (and c1, c2) -> c1&c2
3096   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3098   if (N0C && N1C && !N1C->isOpaque())
3099     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3100   // canonicalize constant to RHS
3101   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3102      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3103     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3104   // fold (and x, -1) -> x
3105   if (isAllOnesConstant(N1))
3106     return N0;
3107   // if (and x, c) is known to be zero, return 0
3108   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3109   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3110                                    APInt::getAllOnesValue(BitWidth)))
3111     return DAG.getConstant(0, SDLoc(N), VT);
3112   // reassociate and
3113   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3114     return RAND;
3115   // fold (and (or x, C), D) -> D if (C & D) == D
3116   if (N1C && N0.getOpcode() == ISD::OR)
3117     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3118       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3119         return N1;
3120   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3121   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3122     SDValue N0Op0 = N0.getOperand(0);
3123     APInt Mask = ~N1C->getAPIntValue();
3124     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3125     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3126       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3127                                  N0.getValueType(), N0Op0);
3128 
3129       // Replace uses of the AND with uses of the Zero extend node.
3130       CombineTo(N, Zext);
3131 
3132       // We actually want to replace all uses of the any_extend with the
3133       // zero_extend, to avoid duplicating things.  This will later cause this
3134       // AND to be folded.
3135       CombineTo(N0.getNode(), Zext);
3136       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3137     }
3138   }
3139   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3140   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3141   // already be zero by virtue of the width of the base type of the load.
3142   //
3143   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3144   // more cases.
3145   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3146        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3147        N0.getOperand(0).getOpcode() == ISD::LOAD &&
3148        N0.getOperand(0).getResNo() == 0) ||
3149       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3150     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3151                                          N0 : N0.getOperand(0) );
3152 
3153     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3154     // This can be a pure constant or a vector splat, in which case we treat the
3155     // vector as a scalar and use the splat value.
3156     APInt Constant = APInt::getNullValue(1);
3157     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3158       Constant = C->getAPIntValue();
3159     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3160       APInt SplatValue, SplatUndef;
3161       unsigned SplatBitSize;
3162       bool HasAnyUndefs;
3163       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3164                                              SplatBitSize, HasAnyUndefs);
3165       if (IsSplat) {
3166         // Undef bits can contribute to a possible optimisation if set, so
3167         // set them.
3168         SplatValue |= SplatUndef;
3169 
3170         // The splat value may be something like "0x00FFFFFF", which means 0 for
3171         // the first vector value and FF for the rest, repeating. We need a mask
3172         // that will apply equally to all members of the vector, so AND all the
3173         // lanes of the constant together.
3174         EVT VT = Vector->getValueType(0);
3175         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3176 
3177         // If the splat value has been compressed to a bitlength lower
3178         // than the size of the vector lane, we need to re-expand it to
3179         // the lane size.
3180         if (BitWidth > SplatBitSize)
3181           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3182                SplatBitSize < BitWidth;
3183                SplatBitSize = SplatBitSize * 2)
3184             SplatValue |= SplatValue.shl(SplatBitSize);
3185 
3186         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3187         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3188         if (SplatBitSize % BitWidth == 0) {
3189           Constant = APInt::getAllOnesValue(BitWidth);
3190           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3191             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3192         }
3193       }
3194     }
3195 
3196     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3197     // actually legal and isn't going to get expanded, else this is a false
3198     // optimisation.
3199     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3200                                                     Load->getValueType(0),
3201                                                     Load->getMemoryVT());
3202 
3203     // Resize the constant to the same size as the original memory access before
3204     // extension. If it is still the AllOnesValue then this AND is completely
3205     // unneeded.
3206     Constant =
3207       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3208 
3209     bool B;
3210     switch (Load->getExtensionType()) {
3211     default: B = false; break;
3212     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3213     case ISD::ZEXTLOAD:
3214     case ISD::NON_EXTLOAD: B = true; break;
3215     }
3216 
3217     if (B && Constant.isAllOnesValue()) {
3218       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3219       // preserve semantics once we get rid of the AND.
3220       SDValue NewLoad(Load, 0);
3221       if (Load->getExtensionType() == ISD::EXTLOAD) {
3222         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3223                               Load->getValueType(0), SDLoc(Load),
3224                               Load->getChain(), Load->getBasePtr(),
3225                               Load->getOffset(), Load->getMemoryVT(),
3226                               Load->getMemOperand());
3227         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3228         if (Load->getNumValues() == 3) {
3229           // PRE/POST_INC loads have 3 values.
3230           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3231                            NewLoad.getValue(2) };
3232           CombineTo(Load, To, 3, true);
3233         } else {
3234           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3235         }
3236       }
3237 
3238       // Fold the AND away, taking care not to fold to the old load node if we
3239       // replaced it.
3240       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3241 
3242       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3243     }
3244   }
3245 
3246   // fold (and (load x), 255) -> (zextload x, i8)
3247   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3248   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3249   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3250               (N0.getOpcode() == ISD::ANY_EXTEND &&
3251                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3252     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3253     LoadSDNode *LN0 = HasAnyExt
3254       ? cast<LoadSDNode>(N0.getOperand(0))
3255       : cast<LoadSDNode>(N0);
3256     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3257         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3258       auto NarrowLoad = false;
3259       EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3260       EVT ExtVT, LoadedVT;
3261       if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3262                            NarrowLoad)) {
3263         if (!NarrowLoad) {
3264           SDValue NewLoad =
3265             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3266                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3267                            LN0->getMemOperand());
3268           AddToWorklist(N);
3269           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3270           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3271         } else {
3272           EVT PtrType = LN0->getOperand(1).getValueType();
3273 
3274           unsigned Alignment = LN0->getAlignment();
3275           SDValue NewPtr = LN0->getBasePtr();
3276 
3277           // For big endian targets, we need to add an offset to the pointer
3278           // to load the correct bytes.  For little endian systems, we merely
3279           // need to read fewer bytes from the same pointer.
3280           if (DAG.getDataLayout().isBigEndian()) {
3281             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3282             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3283             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3284             SDLoc DL(LN0);
3285             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3286                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3287             Alignment = MinAlign(Alignment, PtrOff);
3288           }
3289 
3290           AddToWorklist(NewPtr.getNode());
3291 
3292           SDValue Load =
3293             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3294                            LN0->getChain(), NewPtr,
3295                            LN0->getPointerInfo(),
3296                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3297                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3298           AddToWorklist(N);
3299           CombineTo(LN0, Load, Load.getValue(1));
3300           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3301         }
3302       }
3303     }
3304   }
3305 
3306   if (SDValue Combined = visitANDLike(N0, N1, N))
3307     return Combined;
3308 
3309   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3310   if (N0.getOpcode() == N1.getOpcode())
3311     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3312       return Tmp;
3313 
3314   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3315   // fold (and (sra)) -> (and (srl)) when possible.
3316   if (!VT.isVector() &&
3317       SimplifyDemandedBits(SDValue(N, 0)))
3318     return SDValue(N, 0);
3319 
3320   // fold (zext_inreg (extload x)) -> (zextload x)
3321   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3322     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3323     EVT MemVT = LN0->getMemoryVT();
3324     // If we zero all the possible extended bits, then we can turn this into
3325     // a zextload if we are running before legalize or the operation is legal.
3326     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3327     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3328                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3329         ((!LegalOperations && !LN0->isVolatile()) ||
3330          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3331       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3332                                        LN0->getChain(), LN0->getBasePtr(),
3333                                        MemVT, LN0->getMemOperand());
3334       AddToWorklist(N);
3335       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3336       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3337     }
3338   }
3339   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3340   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3341       N0.hasOneUse()) {
3342     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3343     EVT MemVT = LN0->getMemoryVT();
3344     // If we zero all the possible extended bits, then we can turn this into
3345     // a zextload if we are running before legalize or the operation is legal.
3346     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3347     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3348                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3349         ((!LegalOperations && !LN0->isVolatile()) ||
3350          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3351       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3352                                        LN0->getChain(), LN0->getBasePtr(),
3353                                        MemVT, LN0->getMemOperand());
3354       AddToWorklist(N);
3355       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3356       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3357     }
3358   }
3359   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3360   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3361     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3362                                            N0.getOperand(1), false))
3363       return BSwap;
3364   }
3365 
3366   return SDValue();
3367 }
3368 
3369 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3370 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3371                                         bool DemandHighBits) {
3372   if (!LegalOperations)
3373     return SDValue();
3374 
3375   EVT VT = N->getValueType(0);
3376   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3377     return SDValue();
3378   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3379     return SDValue();
3380 
3381   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3382   bool LookPassAnd0 = false;
3383   bool LookPassAnd1 = false;
3384   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3385       std::swap(N0, N1);
3386   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3387       std::swap(N0, N1);
3388   if (N0.getOpcode() == ISD::AND) {
3389     if (!N0.getNode()->hasOneUse())
3390       return SDValue();
3391     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3392     if (!N01C || N01C->getZExtValue() != 0xFF00)
3393       return SDValue();
3394     N0 = N0.getOperand(0);
3395     LookPassAnd0 = true;
3396   }
3397 
3398   if (N1.getOpcode() == ISD::AND) {
3399     if (!N1.getNode()->hasOneUse())
3400       return SDValue();
3401     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3402     if (!N11C || N11C->getZExtValue() != 0xFF)
3403       return SDValue();
3404     N1 = N1.getOperand(0);
3405     LookPassAnd1 = true;
3406   }
3407 
3408   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3409     std::swap(N0, N1);
3410   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3411     return SDValue();
3412   if (!N0.getNode()->hasOneUse() ||
3413       !N1.getNode()->hasOneUse())
3414     return SDValue();
3415 
3416   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3417   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3418   if (!N01C || !N11C)
3419     return SDValue();
3420   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3421     return SDValue();
3422 
3423   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3424   SDValue N00 = N0->getOperand(0);
3425   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3426     if (!N00.getNode()->hasOneUse())
3427       return SDValue();
3428     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3429     if (!N001C || N001C->getZExtValue() != 0xFF)
3430       return SDValue();
3431     N00 = N00.getOperand(0);
3432     LookPassAnd0 = true;
3433   }
3434 
3435   SDValue N10 = N1->getOperand(0);
3436   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3437     if (!N10.getNode()->hasOneUse())
3438       return SDValue();
3439     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3440     if (!N101C || N101C->getZExtValue() != 0xFF00)
3441       return SDValue();
3442     N10 = N10.getOperand(0);
3443     LookPassAnd1 = true;
3444   }
3445 
3446   if (N00 != N10)
3447     return SDValue();
3448 
3449   // Make sure everything beyond the low halfword gets set to zero since the SRL
3450   // 16 will clear the top bits.
3451   unsigned OpSizeInBits = VT.getSizeInBits();
3452   if (DemandHighBits && OpSizeInBits > 16) {
3453     // If the left-shift isn't masked out then the only way this is a bswap is
3454     // if all bits beyond the low 8 are 0. In that case the entire pattern
3455     // reduces to a left shift anyway: leave it for other parts of the combiner.
3456     if (!LookPassAnd0)
3457       return SDValue();
3458 
3459     // However, if the right shift isn't masked out then it might be because
3460     // it's not needed. See if we can spot that too.
3461     if (!LookPassAnd1 &&
3462         !DAG.MaskedValueIsZero(
3463             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3464       return SDValue();
3465   }
3466 
3467   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3468   if (OpSizeInBits > 16) {
3469     SDLoc DL(N);
3470     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3471                       DAG.getConstant(OpSizeInBits - 16, DL,
3472                                       getShiftAmountTy(VT)));
3473   }
3474   return Res;
3475 }
3476 
3477 /// Return true if the specified node is an element that makes up a 32-bit
3478 /// packed halfword byteswap.
3479 /// ((x & 0x000000ff) << 8) |
3480 /// ((x & 0x0000ff00) >> 8) |
3481 /// ((x & 0x00ff0000) << 8) |
3482 /// ((x & 0xff000000) >> 8)
3483 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3484   if (!N.getNode()->hasOneUse())
3485     return false;
3486 
3487   unsigned Opc = N.getOpcode();
3488   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3489     return false;
3490 
3491   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3492   if (!N1C)
3493     return false;
3494 
3495   unsigned Num;
3496   switch (N1C->getZExtValue()) {
3497   default:
3498     return false;
3499   case 0xFF:       Num = 0; break;
3500   case 0xFF00:     Num = 1; break;
3501   case 0xFF0000:   Num = 2; break;
3502   case 0xFF000000: Num = 3; break;
3503   }
3504 
3505   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3506   SDValue N0 = N.getOperand(0);
3507   if (Opc == ISD::AND) {
3508     if (Num == 0 || Num == 2) {
3509       // (x >> 8) & 0xff
3510       // (x >> 8) & 0xff0000
3511       if (N0.getOpcode() != ISD::SRL)
3512         return false;
3513       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3514       if (!C || C->getZExtValue() != 8)
3515         return false;
3516     } else {
3517       // (x << 8) & 0xff00
3518       // (x << 8) & 0xff000000
3519       if (N0.getOpcode() != ISD::SHL)
3520         return false;
3521       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3522       if (!C || C->getZExtValue() != 8)
3523         return false;
3524     }
3525   } else if (Opc == ISD::SHL) {
3526     // (x & 0xff) << 8
3527     // (x & 0xff0000) << 8
3528     if (Num != 0 && Num != 2)
3529       return false;
3530     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3531     if (!C || C->getZExtValue() != 8)
3532       return false;
3533   } else { // Opc == ISD::SRL
3534     // (x & 0xff00) >> 8
3535     // (x & 0xff000000) >> 8
3536     if (Num != 1 && Num != 3)
3537       return false;
3538     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3539     if (!C || C->getZExtValue() != 8)
3540       return false;
3541   }
3542 
3543   if (Parts[Num])
3544     return false;
3545 
3546   Parts[Num] = N0.getOperand(0).getNode();
3547   return true;
3548 }
3549 
3550 /// Match a 32-bit packed halfword bswap. That is
3551 /// ((x & 0x000000ff) << 8) |
3552 /// ((x & 0x0000ff00) >> 8) |
3553 /// ((x & 0x00ff0000) << 8) |
3554 /// ((x & 0xff000000) >> 8)
3555 /// => (rotl (bswap x), 16)
3556 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3557   if (!LegalOperations)
3558     return SDValue();
3559 
3560   EVT VT = N->getValueType(0);
3561   if (VT != MVT::i32)
3562     return SDValue();
3563   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3564     return SDValue();
3565 
3566   // Look for either
3567   // (or (or (and), (and)), (or (and), (and)))
3568   // (or (or (or (and), (and)), (and)), (and))
3569   if (N0.getOpcode() != ISD::OR)
3570     return SDValue();
3571   SDValue N00 = N0.getOperand(0);
3572   SDValue N01 = N0.getOperand(1);
3573   SDNode *Parts[4] = {};
3574 
3575   if (N1.getOpcode() == ISD::OR &&
3576       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3577     // (or (or (and), (and)), (or (and), (and)))
3578     SDValue N000 = N00.getOperand(0);
3579     if (!isBSwapHWordElement(N000, Parts))
3580       return SDValue();
3581 
3582     SDValue N001 = N00.getOperand(1);
3583     if (!isBSwapHWordElement(N001, Parts))
3584       return SDValue();
3585     SDValue N010 = N01.getOperand(0);
3586     if (!isBSwapHWordElement(N010, Parts))
3587       return SDValue();
3588     SDValue N011 = N01.getOperand(1);
3589     if (!isBSwapHWordElement(N011, Parts))
3590       return SDValue();
3591   } else {
3592     // (or (or (or (and), (and)), (and)), (and))
3593     if (!isBSwapHWordElement(N1, Parts))
3594       return SDValue();
3595     if (!isBSwapHWordElement(N01, Parts))
3596       return SDValue();
3597     if (N00.getOpcode() != ISD::OR)
3598       return SDValue();
3599     SDValue N000 = N00.getOperand(0);
3600     if (!isBSwapHWordElement(N000, Parts))
3601       return SDValue();
3602     SDValue N001 = N00.getOperand(1);
3603     if (!isBSwapHWordElement(N001, Parts))
3604       return SDValue();
3605   }
3606 
3607   // Make sure the parts are all coming from the same node.
3608   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3609     return SDValue();
3610 
3611   SDLoc DL(N);
3612   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3613                               SDValue(Parts[0], 0));
3614 
3615   // Result of the bswap should be rotated by 16. If it's not legal, then
3616   // do  (x << 16) | (x >> 16).
3617   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3618   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3619     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3620   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3621     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3622   return DAG.getNode(ISD::OR, DL, VT,
3623                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3624                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3625 }
3626 
3627 /// This contains all DAGCombine rules which reduce two values combined by
3628 /// an Or operation to a single value \see visitANDLike().
3629 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3630   EVT VT = N1.getValueType();
3631   // fold (or x, undef) -> -1
3632   if (!LegalOperations &&
3633       (N0.isUndef() || N1.isUndef())) {
3634     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3635     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3636                            SDLoc(LocReference), VT);
3637   }
3638   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3639   SDValue LL, LR, RL, RR, CC0, CC1;
3640   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3641     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3642     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3643 
3644     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3645       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3646       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3647       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3648         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3649                                      LR.getValueType(), LL, RL);
3650         AddToWorklist(ORNode.getNode());
3651         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3652       }
3653       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3654       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3655       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3656         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3657                                       LR.getValueType(), LL, RL);
3658         AddToWorklist(ANDNode.getNode());
3659         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3660       }
3661     }
3662     // canonicalize equivalent to ll == rl
3663     if (LL == RR && LR == RL) {
3664       Op1 = ISD::getSetCCSwappedOperands(Op1);
3665       std::swap(RL, RR);
3666     }
3667     if (LL == RL && LR == RR) {
3668       bool isInteger = LL.getValueType().isInteger();
3669       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3670       if (Result != ISD::SETCC_INVALID &&
3671           (!LegalOperations ||
3672            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3673             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3674         EVT CCVT = getSetCCResultType(LL.getValueType());
3675         if (N0.getValueType() == CCVT ||
3676             (!LegalOperations && N0.getValueType() == MVT::i1))
3677           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3678                               LL, LR, Result);
3679       }
3680     }
3681   }
3682 
3683   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3684   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3685       // Don't increase # computations.
3686       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3687     // We can only do this xform if we know that bits from X that are set in C2
3688     // but not in C1 are already zero.  Likewise for Y.
3689     if (const ConstantSDNode *N0O1C =
3690         getAsNonOpaqueConstant(N0.getOperand(1))) {
3691       if (const ConstantSDNode *N1O1C =
3692           getAsNonOpaqueConstant(N1.getOperand(1))) {
3693         // We can only do this xform if we know that bits from X that are set in
3694         // C2 but not in C1 are already zero.  Likewise for Y.
3695         const APInt &LHSMask = N0O1C->getAPIntValue();
3696         const APInt &RHSMask = N1O1C->getAPIntValue();
3697 
3698         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3699             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3700           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3701                                   N0.getOperand(0), N1.getOperand(0));
3702           SDLoc DL(LocReference);
3703           return DAG.getNode(ISD::AND, DL, VT, X,
3704                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3705         }
3706       }
3707     }
3708   }
3709 
3710   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3711   if (N0.getOpcode() == ISD::AND &&
3712       N1.getOpcode() == ISD::AND &&
3713       N0.getOperand(0) == N1.getOperand(0) &&
3714       // Don't increase # computations.
3715       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3716     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3717                             N0.getOperand(1), N1.getOperand(1));
3718     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3719   }
3720 
3721   return SDValue();
3722 }
3723 
3724 SDValue DAGCombiner::visitOR(SDNode *N) {
3725   SDValue N0 = N->getOperand(0);
3726   SDValue N1 = N->getOperand(1);
3727   EVT VT = N1.getValueType();
3728 
3729   // fold vector ops
3730   if (VT.isVector()) {
3731     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3732       return FoldedVOp;
3733 
3734     // fold (or x, 0) -> x, vector edition
3735     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3736       return N1;
3737     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3738       return N0;
3739 
3740     // fold (or x, -1) -> -1, vector edition
3741     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3742       // do not return N0, because undef node may exist in N0
3743       return DAG.getConstant(
3744           APInt::getAllOnesValue(
3745               N0.getValueType().getScalarType().getSizeInBits()),
3746           SDLoc(N), N0.getValueType());
3747     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3748       // do not return N1, because undef node may exist in N1
3749       return DAG.getConstant(
3750           APInt::getAllOnesValue(
3751               N1.getValueType().getScalarType().getSizeInBits()),
3752           SDLoc(N), N1.getValueType());
3753 
3754     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3755     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3756     // Do this only if the resulting shuffle is legal.
3757     if (isa<ShuffleVectorSDNode>(N0) &&
3758         isa<ShuffleVectorSDNode>(N1) &&
3759         // Avoid folding a node with illegal type.
3760         TLI.isTypeLegal(VT) &&
3761         N0->getOperand(1) == N1->getOperand(1) &&
3762         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3763       bool CanFold = true;
3764       unsigned NumElts = VT.getVectorNumElements();
3765       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3766       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3767       // We construct two shuffle masks:
3768       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3769       // and N1 as the second operand.
3770       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3771       // and N0 as the second operand.
3772       // We do this because OR is commutable and therefore there might be
3773       // two ways to fold this node into a shuffle.
3774       SmallVector<int,4> Mask1;
3775       SmallVector<int,4> Mask2;
3776 
3777       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3778         int M0 = SV0->getMaskElt(i);
3779         int M1 = SV1->getMaskElt(i);
3780 
3781         // Both shuffle indexes are undef. Propagate Undef.
3782         if (M0 < 0 && M1 < 0) {
3783           Mask1.push_back(M0);
3784           Mask2.push_back(M0);
3785           continue;
3786         }
3787 
3788         if (M0 < 0 || M1 < 0 ||
3789             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3790             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3791           CanFold = false;
3792           break;
3793         }
3794 
3795         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3796         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3797       }
3798 
3799       if (CanFold) {
3800         // Fold this sequence only if the resulting shuffle is 'legal'.
3801         if (TLI.isShuffleMaskLegal(Mask1, VT))
3802           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3803                                       N1->getOperand(0), &Mask1[0]);
3804         if (TLI.isShuffleMaskLegal(Mask2, VT))
3805           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3806                                       N0->getOperand(0), &Mask2[0]);
3807       }
3808     }
3809   }
3810 
3811   // fold (or c1, c2) -> c1|c2
3812   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3813   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3814   if (N0C && N1C && !N1C->isOpaque())
3815     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3816   // canonicalize constant to RHS
3817   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3818      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3819     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3820   // fold (or x, 0) -> x
3821   if (isNullConstant(N1))
3822     return N0;
3823   // fold (or x, -1) -> -1
3824   if (isAllOnesConstant(N1))
3825     return N1;
3826   // fold (or x, c) -> c iff (x & ~c) == 0
3827   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3828     return N1;
3829 
3830   if (SDValue Combined = visitORLike(N0, N1, N))
3831     return Combined;
3832 
3833   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3834   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3835     return BSwap;
3836   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3837     return BSwap;
3838 
3839   // reassociate or
3840   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3841     return ROR;
3842   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3843   // iff (c1 & c2) == 0.
3844   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3845              isa<ConstantSDNode>(N0.getOperand(1))) {
3846     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3847     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3848       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3849                                                    N1C, C1))
3850         return DAG.getNode(
3851             ISD::AND, SDLoc(N), VT,
3852             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3853       return SDValue();
3854     }
3855   }
3856   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3857   if (N0.getOpcode() == N1.getOpcode())
3858     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3859       return Tmp;
3860 
3861   // See if this is some rotate idiom.
3862   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3863     return SDValue(Rot, 0);
3864 
3865   // Simplify the operands using demanded-bits information.
3866   if (!VT.isVector() &&
3867       SimplifyDemandedBits(SDValue(N, 0)))
3868     return SDValue(N, 0);
3869 
3870   return SDValue();
3871 }
3872 
3873 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3874 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3875   if (Op.getOpcode() == ISD::AND) {
3876     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3877       Mask = Op.getOperand(1);
3878       Op = Op.getOperand(0);
3879     } else {
3880       return false;
3881     }
3882   }
3883 
3884   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3885     Shift = Op;
3886     return true;
3887   }
3888 
3889   return false;
3890 }
3891 
3892 // Return true if we can prove that, whenever Neg and Pos are both in the
3893 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3894 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3895 //
3896 //     (or (shift1 X, Neg), (shift2 X, Pos))
3897 //
3898 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3899 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3900 // to consider shift amounts with defined behavior.
3901 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3902   // If EltSize is a power of 2 then:
3903   //
3904   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3905   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3906   //
3907   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3908   // for the stronger condition:
3909   //
3910   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3911   //
3912   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3913   // we can just replace Neg with Neg' for the rest of the function.
3914   //
3915   // In other cases we check for the even stronger condition:
3916   //
3917   //     Neg == EltSize - Pos                                    [B]
3918   //
3919   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3920   // behavior if Pos == 0 (and consequently Neg == EltSize).
3921   //
3922   // We could actually use [A] whenever EltSize is a power of 2, but the
3923   // only extra cases that it would match are those uninteresting ones
3924   // where Neg and Pos are never in range at the same time.  E.g. for
3925   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3926   // as well as (sub 32, Pos), but:
3927   //
3928   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3929   //
3930   // always invokes undefined behavior for 32-bit X.
3931   //
3932   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3933   unsigned MaskLoBits = 0;
3934   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3935     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3936       if (NegC->getAPIntValue() == EltSize - 1) {
3937         Neg = Neg.getOperand(0);
3938         MaskLoBits = Log2_64(EltSize);
3939       }
3940     }
3941   }
3942 
3943   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3944   if (Neg.getOpcode() != ISD::SUB)
3945     return false;
3946   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3947   if (!NegC)
3948     return false;
3949   SDValue NegOp1 = Neg.getOperand(1);
3950 
3951   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3952   // Pos'.  The truncation is redundant for the purpose of the equality.
3953   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3954     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3955       if (PosC->getAPIntValue() == EltSize - 1)
3956         Pos = Pos.getOperand(0);
3957 
3958   // The condition we need is now:
3959   //
3960   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3961   //
3962   // If NegOp1 == Pos then we need:
3963   //
3964   //              EltSize & Mask == NegC & Mask
3965   //
3966   // (because "x & Mask" is a truncation and distributes through subtraction).
3967   APInt Width;
3968   if (Pos == NegOp1)
3969     Width = NegC->getAPIntValue();
3970 
3971   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3972   // Then the condition we want to prove becomes:
3973   //
3974   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3975   //
3976   // which, again because "x & Mask" is a truncation, becomes:
3977   //
3978   //                NegC & Mask == (EltSize - PosC) & Mask
3979   //             EltSize & Mask == (NegC + PosC) & Mask
3980   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3981     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3982       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3983     else
3984       return false;
3985   } else
3986     return false;
3987 
3988   // Now we just need to check that EltSize & Mask == Width & Mask.
3989   if (MaskLoBits)
3990     // EltSize & Mask is 0 since Mask is EltSize - 1.
3991     return Width.getLoBits(MaskLoBits) == 0;
3992   return Width == EltSize;
3993 }
3994 
3995 // A subroutine of MatchRotate used once we have found an OR of two opposite
3996 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3997 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3998 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3999 // Neg with outer conversions stripped away.
4000 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4001                                        SDValue Neg, SDValue InnerPos,
4002                                        SDValue InnerNeg, unsigned PosOpcode,
4003                                        unsigned NegOpcode, SDLoc DL) {
4004   // fold (or (shl x, (*ext y)),
4005   //          (srl x, (*ext (sub 32, y)))) ->
4006   //   (rotl x, y) or (rotr x, (sub 32, y))
4007   //
4008   // fold (or (shl x, (*ext (sub 32, y))),
4009   //          (srl x, (*ext y))) ->
4010   //   (rotr x, y) or (rotl x, (sub 32, y))
4011   EVT VT = Shifted.getValueType();
4012   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4013     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4014     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4015                        HasPos ? Pos : Neg).getNode();
4016   }
4017 
4018   return nullptr;
4019 }
4020 
4021 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4022 // idioms for rotate, and if the target supports rotation instructions, generate
4023 // a rot[lr].
4024 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
4025   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4026   EVT VT = LHS.getValueType();
4027   if (!TLI.isTypeLegal(VT)) return nullptr;
4028 
4029   // The target must have at least one rotate flavor.
4030   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4031   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4032   if (!HasROTL && !HasROTR) return nullptr;
4033 
4034   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4035   SDValue LHSShift;   // The shift.
4036   SDValue LHSMask;    // AND value if any.
4037   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4038     return nullptr; // Not part of a rotate.
4039 
4040   SDValue RHSShift;   // The shift.
4041   SDValue RHSMask;    // AND value if any.
4042   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4043     return nullptr; // Not part of a rotate.
4044 
4045   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4046     return nullptr;   // Not shifting the same value.
4047 
4048   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4049     return nullptr;   // Shifts must disagree.
4050 
4051   // Canonicalize shl to left side in a shl/srl pair.
4052   if (RHSShift.getOpcode() == ISD::SHL) {
4053     std::swap(LHS, RHS);
4054     std::swap(LHSShift, RHSShift);
4055     std::swap(LHSMask, RHSMask);
4056   }
4057 
4058   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4059   SDValue LHSShiftArg = LHSShift.getOperand(0);
4060   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4061   SDValue RHSShiftArg = RHSShift.getOperand(0);
4062   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4063 
4064   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4065   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4066   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4067     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4068     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4069     if ((LShVal + RShVal) != EltSizeInBits)
4070       return nullptr;
4071 
4072     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4073                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4074 
4075     // If there is an AND of either shifted operand, apply it to the result.
4076     if (LHSMask.getNode() || RHSMask.getNode()) {
4077       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4078       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4079 
4080       if (LHSMask.getNode()) {
4081         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4082         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4083                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4084                                        DAG.getConstant(RHSBits, DL, VT)));
4085       }
4086       if (RHSMask.getNode()) {
4087         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4088         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4089                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4090                                        DAG.getConstant(LHSBits, DL, VT)));
4091       }
4092 
4093       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4094     }
4095 
4096     return Rot.getNode();
4097   }
4098 
4099   // If there is a mask here, and we have a variable shift, we can't be sure
4100   // that we're masking out the right stuff.
4101   if (LHSMask.getNode() || RHSMask.getNode())
4102     return nullptr;
4103 
4104   // If the shift amount is sign/zext/any-extended just peel it off.
4105   SDValue LExtOp0 = LHSShiftAmt;
4106   SDValue RExtOp0 = RHSShiftAmt;
4107   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4108        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4109        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4110        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4111       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4112        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4113        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4114        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4115     LExtOp0 = LHSShiftAmt.getOperand(0);
4116     RExtOp0 = RHSShiftAmt.getOperand(0);
4117   }
4118 
4119   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4120                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4121   if (TryL)
4122     return TryL;
4123 
4124   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4125                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4126   if (TryR)
4127     return TryR;
4128 
4129   return nullptr;
4130 }
4131 
4132 SDValue DAGCombiner::visitXOR(SDNode *N) {
4133   SDValue N0 = N->getOperand(0);
4134   SDValue N1 = N->getOperand(1);
4135   EVT VT = N0.getValueType();
4136 
4137   // fold vector ops
4138   if (VT.isVector()) {
4139     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4140       return FoldedVOp;
4141 
4142     // fold (xor x, 0) -> x, vector edition
4143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4144       return N1;
4145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4146       return N0;
4147   }
4148 
4149   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4150   if (N0.isUndef() && N1.isUndef())
4151     return DAG.getConstant(0, SDLoc(N), VT);
4152   // fold (xor x, undef) -> undef
4153   if (N0.isUndef())
4154     return N0;
4155   if (N1.isUndef())
4156     return N1;
4157   // fold (xor c1, c2) -> c1^c2
4158   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4159   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4160   if (N0C && N1C)
4161     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4162   // canonicalize constant to RHS
4163   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4164      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4165     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4166   // fold (xor x, 0) -> x
4167   if (isNullConstant(N1))
4168     return N0;
4169   // reassociate xor
4170   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4171     return RXOR;
4172 
4173   // fold !(x cc y) -> (x !cc y)
4174   SDValue LHS, RHS, CC;
4175   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4176     bool isInt = LHS.getValueType().isInteger();
4177     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4178                                                isInt);
4179 
4180     if (!LegalOperations ||
4181         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4182       switch (N0.getOpcode()) {
4183       default:
4184         llvm_unreachable("Unhandled SetCC Equivalent!");
4185       case ISD::SETCC:
4186         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4187       case ISD::SELECT_CC:
4188         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4189                                N0.getOperand(3), NotCC);
4190       }
4191     }
4192   }
4193 
4194   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4195   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4196       N0.getNode()->hasOneUse() &&
4197       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4198     SDValue V = N0.getOperand(0);
4199     SDLoc DL(N0);
4200     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4201                     DAG.getConstant(1, DL, V.getValueType()));
4202     AddToWorklist(V.getNode());
4203     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4204   }
4205 
4206   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4207   if (isOneConstant(N1) && VT == MVT::i1 &&
4208       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4209     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4210     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4211       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4212       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4213       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4214       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4215       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4216     }
4217   }
4218   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4219   if (isAllOnesConstant(N1) &&
4220       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4221     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4222     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4223       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4224       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4225       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4226       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4227       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4228     }
4229   }
4230   // fold (xor (and x, y), y) -> (and (not x), y)
4231   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4232       N0->getOperand(1) == N1) {
4233     SDValue X = N0->getOperand(0);
4234     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4235     AddToWorklist(NotX.getNode());
4236     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4237   }
4238   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4239   if (N1C && N0.getOpcode() == ISD::XOR) {
4240     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4241       SDLoc DL(N);
4242       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4243                          DAG.getConstant(N1C->getAPIntValue() ^
4244                                          N00C->getAPIntValue(), DL, VT));
4245     }
4246     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4247       SDLoc DL(N);
4248       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4249                          DAG.getConstant(N1C->getAPIntValue() ^
4250                                          N01C->getAPIntValue(), DL, VT));
4251     }
4252   }
4253   // fold (xor x, x) -> 0
4254   if (N0 == N1)
4255     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4256 
4257   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4258   // Here is a concrete example of this equivalence:
4259   // i16   x ==  14
4260   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4261   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4262   //
4263   // =>
4264   //
4265   // i16     ~1      == 0b1111111111111110
4266   // i16 rol(~1, 14) == 0b1011111111111111
4267   //
4268   // Some additional tips to help conceptualize this transform:
4269   // - Try to see the operation as placing a single zero in a value of all ones.
4270   // - There exists no value for x which would allow the result to contain zero.
4271   // - Values of x larger than the bitwidth are undefined and do not require a
4272   //   consistent result.
4273   // - Pushing the zero left requires shifting one bits in from the right.
4274   // A rotate left of ~1 is a nice way of achieving the desired result.
4275   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4276       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4277     SDLoc DL(N);
4278     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4279                        N0.getOperand(1));
4280   }
4281 
4282   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4283   if (N0.getOpcode() == N1.getOpcode())
4284     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4285       return Tmp;
4286 
4287   // Simplify the expression using non-local knowledge.
4288   if (!VT.isVector() &&
4289       SimplifyDemandedBits(SDValue(N, 0)))
4290     return SDValue(N, 0);
4291 
4292   return SDValue();
4293 }
4294 
4295 /// Handle transforms common to the three shifts, when the shift amount is a
4296 /// constant.
4297 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4298   SDNode *LHS = N->getOperand(0).getNode();
4299   if (!LHS->hasOneUse()) return SDValue();
4300 
4301   // We want to pull some binops through shifts, so that we have (and (shift))
4302   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4303   // thing happens with address calculations, so it's important to canonicalize
4304   // it.
4305   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4306 
4307   switch (LHS->getOpcode()) {
4308   default: return SDValue();
4309   case ISD::OR:
4310   case ISD::XOR:
4311     HighBitSet = false; // We can only transform sra if the high bit is clear.
4312     break;
4313   case ISD::AND:
4314     HighBitSet = true;  // We can only transform sra if the high bit is set.
4315     break;
4316   case ISD::ADD:
4317     if (N->getOpcode() != ISD::SHL)
4318       return SDValue(); // only shl(add) not sr[al](add).
4319     HighBitSet = false; // We can only transform sra if the high bit is clear.
4320     break;
4321   }
4322 
4323   // We require the RHS of the binop to be a constant and not opaque as well.
4324   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4325   if (!BinOpCst) return SDValue();
4326 
4327   // FIXME: disable this unless the input to the binop is a shift by a constant.
4328   // If it is not a shift, it pessimizes some common cases like:
4329   //
4330   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4331   //    int bar(int *X, int i) { return X[i & 255]; }
4332   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4333   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4334        BinOpLHSVal->getOpcode() != ISD::SRA &&
4335        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4336       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4337     return SDValue();
4338 
4339   EVT VT = N->getValueType(0);
4340 
4341   // If this is a signed shift right, and the high bit is modified by the
4342   // logical operation, do not perform the transformation. The highBitSet
4343   // boolean indicates the value of the high bit of the constant which would
4344   // cause it to be modified for this operation.
4345   if (N->getOpcode() == ISD::SRA) {
4346     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4347     if (BinOpRHSSignSet != HighBitSet)
4348       return SDValue();
4349   }
4350 
4351   if (!TLI.isDesirableToCommuteWithShift(LHS))
4352     return SDValue();
4353 
4354   // Fold the constants, shifting the binop RHS by the shift amount.
4355   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4356                                N->getValueType(0),
4357                                LHS->getOperand(1), N->getOperand(1));
4358   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4359 
4360   // Create the new shift.
4361   SDValue NewShift = DAG.getNode(N->getOpcode(),
4362                                  SDLoc(LHS->getOperand(0)),
4363                                  VT, LHS->getOperand(0), N->getOperand(1));
4364 
4365   // Create the new binop.
4366   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4367 }
4368 
4369 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4370   assert(N->getOpcode() == ISD::TRUNCATE);
4371   assert(N->getOperand(0).getOpcode() == ISD::AND);
4372 
4373   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4374   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4375     SDValue N01 = N->getOperand(0).getOperand(1);
4376 
4377     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4378       if (!N01C->isOpaque()) {
4379         EVT TruncVT = N->getValueType(0);
4380         SDValue N00 = N->getOperand(0).getOperand(0);
4381         APInt TruncC = N01C->getAPIntValue();
4382         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4383         SDLoc DL(N);
4384 
4385         return DAG.getNode(ISD::AND, DL, TruncVT,
4386                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4387                            DAG.getConstant(TruncC, DL, TruncVT));
4388       }
4389     }
4390   }
4391 
4392   return SDValue();
4393 }
4394 
4395 SDValue DAGCombiner::visitRotate(SDNode *N) {
4396   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4397   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4398       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4399     if (SDValue NewOp1 =
4400             distributeTruncateThroughAnd(N->getOperand(1).getNode()))
4401       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4402                          N->getOperand(0), NewOp1);
4403   }
4404   return SDValue();
4405 }
4406 
4407 SDValue DAGCombiner::visitSHL(SDNode *N) {
4408   SDValue N0 = N->getOperand(0);
4409   SDValue N1 = N->getOperand(1);
4410   EVT VT = N0.getValueType();
4411   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4412 
4413   // fold vector ops
4414   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4415   if (VT.isVector()) {
4416     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4417       return FoldedVOp;
4418 
4419     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4420     // If setcc produces all-one true value then:
4421     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4422     if (N1CV && N1CV->isConstant()) {
4423       if (N0.getOpcode() == ISD::AND) {
4424         SDValue N00 = N0->getOperand(0);
4425         SDValue N01 = N0->getOperand(1);
4426         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4427 
4428         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4429             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4430                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4431           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4432                                                      N01CV, N1CV))
4433             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4434         }
4435       } else {
4436         N1C = isConstOrConstSplat(N1);
4437       }
4438     }
4439   }
4440 
4441   // fold (shl c1, c2) -> c1<<c2
4442   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4443   if (N0C && N1C && !N1C->isOpaque())
4444     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4445   // fold (shl 0, x) -> 0
4446   if (isNullConstant(N0))
4447     return N0;
4448   // fold (shl x, c >= size(x)) -> undef
4449   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4450     return DAG.getUNDEF(VT);
4451   // fold (shl x, 0) -> x
4452   if (N1C && N1C->isNullValue())
4453     return N0;
4454   // fold (shl undef, x) -> 0
4455   if (N0.isUndef())
4456     return DAG.getConstant(0, SDLoc(N), VT);
4457   // if (shl x, c) is known to be zero, return 0
4458   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4459                             APInt::getAllOnesValue(OpSizeInBits)))
4460     return DAG.getConstant(0, SDLoc(N), VT);
4461   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4462   if (N1.getOpcode() == ISD::TRUNCATE &&
4463       N1.getOperand(0).getOpcode() == ISD::AND) {
4464     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4465       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4466   }
4467 
4468   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4469     return SDValue(N, 0);
4470 
4471   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4472   if (N1C && N0.getOpcode() == ISD::SHL) {
4473     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4474       uint64_t c1 = N0C1->getZExtValue();
4475       uint64_t c2 = N1C->getZExtValue();
4476       SDLoc DL(N);
4477       if (c1 + c2 >= OpSizeInBits)
4478         return DAG.getConstant(0, DL, VT);
4479       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4480                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4481     }
4482   }
4483 
4484   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4485   // For this to be valid, the second form must not preserve any of the bits
4486   // that are shifted out by the inner shift in the first form.  This means
4487   // the outer shift size must be >= the number of bits added by the ext.
4488   // As a corollary, we don't care what kind of ext it is.
4489   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4490               N0.getOpcode() == ISD::ANY_EXTEND ||
4491               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4492       N0.getOperand(0).getOpcode() == ISD::SHL) {
4493     SDValue N0Op0 = N0.getOperand(0);
4494     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4495       uint64_t c1 = N0Op0C1->getZExtValue();
4496       uint64_t c2 = N1C->getZExtValue();
4497       EVT InnerShiftVT = N0Op0.getValueType();
4498       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4499       if (c2 >= OpSizeInBits - InnerShiftSize) {
4500         SDLoc DL(N0);
4501         if (c1 + c2 >= OpSizeInBits)
4502           return DAG.getConstant(0, DL, VT);
4503         return DAG.getNode(ISD::SHL, DL, VT,
4504                            DAG.getNode(N0.getOpcode(), DL, VT,
4505                                        N0Op0->getOperand(0)),
4506                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4507       }
4508     }
4509   }
4510 
4511   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4512   // Only fold this if the inner zext has no other uses to avoid increasing
4513   // the total number of instructions.
4514   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4515       N0.getOperand(0).getOpcode() == ISD::SRL) {
4516     SDValue N0Op0 = N0.getOperand(0);
4517     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4518       uint64_t c1 = N0Op0C1->getZExtValue();
4519       if (c1 < VT.getScalarSizeInBits()) {
4520         uint64_t c2 = N1C->getZExtValue();
4521         if (c1 == c2) {
4522           SDValue NewOp0 = N0.getOperand(0);
4523           EVT CountVT = NewOp0.getOperand(1).getValueType();
4524           SDLoc DL(N);
4525           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4526                                        NewOp0,
4527                                        DAG.getConstant(c2, DL, CountVT));
4528           AddToWorklist(NewSHL.getNode());
4529           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4530         }
4531       }
4532     }
4533   }
4534 
4535   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4536   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4537   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4538       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4539     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4540       uint64_t C1 = N0C1->getZExtValue();
4541       uint64_t C2 = N1C->getZExtValue();
4542       SDLoc DL(N);
4543       if (C1 <= C2)
4544         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4545                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4546       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4547                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4548     }
4549   }
4550 
4551   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4552   //                               (and (srl x, (sub c1, c2), MASK)
4553   // Only fold this if the inner shift has no other uses -- if it does, folding
4554   // this will increase the total number of instructions.
4555   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4556     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4557       uint64_t c1 = N0C1->getZExtValue();
4558       if (c1 < OpSizeInBits) {
4559         uint64_t c2 = N1C->getZExtValue();
4560         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4561         SDValue Shift;
4562         if (c2 > c1) {
4563           Mask = Mask.shl(c2 - c1);
4564           SDLoc DL(N);
4565           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4566                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4567         } else {
4568           Mask = Mask.lshr(c1 - c2);
4569           SDLoc DL(N);
4570           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4571                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4572         }
4573         SDLoc DL(N0);
4574         return DAG.getNode(ISD::AND, DL, VT, Shift,
4575                            DAG.getConstant(Mask, DL, VT));
4576       }
4577     }
4578   }
4579   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4580   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4581     unsigned BitSize = VT.getScalarSizeInBits();
4582     SDLoc DL(N);
4583     SDValue HiBitsMask =
4584       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4585                                             BitSize - N1C->getZExtValue()),
4586                       DL, VT);
4587     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4588                        HiBitsMask);
4589   }
4590 
4591   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4592   // Variant of version done on multiply, except mul by a power of 2 is turned
4593   // into a shift.
4594   APInt Val;
4595   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4596       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4597        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4598     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4599     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4600     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4601   }
4602 
4603   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4604   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4605     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4606       if (SDValue Folded =
4607               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4608         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4609     }
4610   }
4611 
4612   if (N1C && !N1C->isOpaque())
4613     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4614       return NewSHL;
4615 
4616   return SDValue();
4617 }
4618 
4619 SDValue DAGCombiner::visitSRA(SDNode *N) {
4620   SDValue N0 = N->getOperand(0);
4621   SDValue N1 = N->getOperand(1);
4622   EVT VT = N0.getValueType();
4623   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4624 
4625   // fold vector ops
4626   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4627   if (VT.isVector()) {
4628     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4629       return FoldedVOp;
4630 
4631     N1C = isConstOrConstSplat(N1);
4632   }
4633 
4634   // fold (sra c1, c2) -> (sra c1, c2)
4635   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4636   if (N0C && N1C && !N1C->isOpaque())
4637     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4638   // fold (sra 0, x) -> 0
4639   if (isNullConstant(N0))
4640     return N0;
4641   // fold (sra -1, x) -> -1
4642   if (isAllOnesConstant(N0))
4643     return N0;
4644   // fold (sra x, (setge c, size(x))) -> undef
4645   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4646     return DAG.getUNDEF(VT);
4647   // fold (sra x, 0) -> x
4648   if (N1C && N1C->isNullValue())
4649     return N0;
4650   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4651   // sext_inreg.
4652   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4653     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4654     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4655     if (VT.isVector())
4656       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4657                                ExtVT, VT.getVectorNumElements());
4658     if ((!LegalOperations ||
4659          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4660       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4661                          N0.getOperand(0), DAG.getValueType(ExtVT));
4662   }
4663 
4664   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4665   if (N1C && N0.getOpcode() == ISD::SRA) {
4666     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4667       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4668       if (Sum >= OpSizeInBits)
4669         Sum = OpSizeInBits - 1;
4670       SDLoc DL(N);
4671       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4672                          DAG.getConstant(Sum, DL, N1.getValueType()));
4673     }
4674   }
4675 
4676   // fold (sra (shl X, m), (sub result_size, n))
4677   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4678   // result_size - n != m.
4679   // If truncate is free for the target sext(shl) is likely to result in better
4680   // code.
4681   if (N0.getOpcode() == ISD::SHL && N1C) {
4682     // Get the two constanst of the shifts, CN0 = m, CN = n.
4683     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4684     if (N01C) {
4685       LLVMContext &Ctx = *DAG.getContext();
4686       // Determine what the truncate's result bitsize and type would be.
4687       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4688 
4689       if (VT.isVector())
4690         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4691 
4692       // Determine the residual right-shift amount.
4693       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4694 
4695       // If the shift is not a no-op (in which case this should be just a sign
4696       // extend already), the truncated to type is legal, sign_extend is legal
4697       // on that type, and the truncate to that type is both legal and free,
4698       // perform the transform.
4699       if ((ShiftAmt > 0) &&
4700           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4701           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4702           TLI.isTruncateFree(VT, TruncVT)) {
4703 
4704         SDLoc DL(N);
4705         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4706             getShiftAmountTy(N0.getOperand(0).getValueType()));
4707         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4708                                     N0.getOperand(0), Amt);
4709         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4710                                     Shift);
4711         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4712                            N->getValueType(0), Trunc);
4713       }
4714     }
4715   }
4716 
4717   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4718   if (N1.getOpcode() == ISD::TRUNCATE &&
4719       N1.getOperand(0).getOpcode() == ISD::AND) {
4720     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4721       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4722   }
4723 
4724   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4725   //      if c1 is equal to the number of bits the trunc removes
4726   if (N0.getOpcode() == ISD::TRUNCATE &&
4727       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4728        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4729       N0.getOperand(0).hasOneUse() &&
4730       N0.getOperand(0).getOperand(1).hasOneUse() &&
4731       N1C) {
4732     SDValue N0Op0 = N0.getOperand(0);
4733     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4734       unsigned LargeShiftVal = LargeShift->getZExtValue();
4735       EVT LargeVT = N0Op0.getValueType();
4736 
4737       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4738         SDLoc DL(N);
4739         SDValue Amt =
4740           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4741                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4742         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4743                                   N0Op0.getOperand(0), Amt);
4744         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4745       }
4746     }
4747   }
4748 
4749   // Simplify, based on bits shifted out of the LHS.
4750   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4751     return SDValue(N, 0);
4752 
4753 
4754   // If the sign bit is known to be zero, switch this to a SRL.
4755   if (DAG.SignBitIsZero(N0))
4756     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4757 
4758   if (N1C && !N1C->isOpaque())
4759     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4760       return NewSRA;
4761 
4762   return SDValue();
4763 }
4764 
4765 SDValue DAGCombiner::visitSRL(SDNode *N) {
4766   SDValue N0 = N->getOperand(0);
4767   SDValue N1 = N->getOperand(1);
4768   EVT VT = N0.getValueType();
4769   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4770 
4771   // fold vector ops
4772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4773   if (VT.isVector()) {
4774     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4775       return FoldedVOp;
4776 
4777     N1C = isConstOrConstSplat(N1);
4778   }
4779 
4780   // fold (srl c1, c2) -> c1 >>u c2
4781   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4782   if (N0C && N1C && !N1C->isOpaque())
4783     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4784   // fold (srl 0, x) -> 0
4785   if (isNullConstant(N0))
4786     return N0;
4787   // fold (srl x, c >= size(x)) -> undef
4788   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4789     return DAG.getUNDEF(VT);
4790   // fold (srl x, 0) -> x
4791   if (N1C && N1C->isNullValue())
4792     return N0;
4793   // if (srl x, c) is known to be zero, return 0
4794   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4795                                    APInt::getAllOnesValue(OpSizeInBits)))
4796     return DAG.getConstant(0, SDLoc(N), VT);
4797 
4798   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4799   if (N1C && N0.getOpcode() == ISD::SRL) {
4800     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4801       uint64_t c1 = N01C->getZExtValue();
4802       uint64_t c2 = N1C->getZExtValue();
4803       SDLoc DL(N);
4804       if (c1 + c2 >= OpSizeInBits)
4805         return DAG.getConstant(0, DL, VT);
4806       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4807                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4808     }
4809   }
4810 
4811   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4812   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4813       N0.getOperand(0).getOpcode() == ISD::SRL &&
4814       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4815     uint64_t c1 =
4816       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4817     uint64_t c2 = N1C->getZExtValue();
4818     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4819     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4820     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4821     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4822     if (c1 + OpSizeInBits == InnerShiftSize) {
4823       SDLoc DL(N0);
4824       if (c1 + c2 >= InnerShiftSize)
4825         return DAG.getConstant(0, DL, VT);
4826       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4827                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4828                                      N0.getOperand(0)->getOperand(0),
4829                                      DAG.getConstant(c1 + c2, DL,
4830                                                      ShiftCountVT)));
4831     }
4832   }
4833 
4834   // fold (srl (shl x, c), c) -> (and x, cst2)
4835   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4836     unsigned BitSize = N0.getScalarValueSizeInBits();
4837     if (BitSize <= 64) {
4838       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4839       SDLoc DL(N);
4840       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4841                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4842     }
4843   }
4844 
4845   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4846   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4847     // Shifting in all undef bits?
4848     EVT SmallVT = N0.getOperand(0).getValueType();
4849     unsigned BitSize = SmallVT.getScalarSizeInBits();
4850     if (N1C->getZExtValue() >= BitSize)
4851       return DAG.getUNDEF(VT);
4852 
4853     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4854       uint64_t ShiftAmt = N1C->getZExtValue();
4855       SDLoc DL0(N0);
4856       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4857                                        N0.getOperand(0),
4858                           DAG.getConstant(ShiftAmt, DL0,
4859                                           getShiftAmountTy(SmallVT)));
4860       AddToWorklist(SmallShift.getNode());
4861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4862       SDLoc DL(N);
4863       return DAG.getNode(ISD::AND, DL, VT,
4864                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4865                          DAG.getConstant(Mask, DL, VT));
4866     }
4867   }
4868 
4869   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4870   // bit, which is unmodified by sra.
4871   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4872     if (N0.getOpcode() == ISD::SRA)
4873       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4874   }
4875 
4876   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4877   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4878       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4879     APInt KnownZero, KnownOne;
4880     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4881 
4882     // If any of the input bits are KnownOne, then the input couldn't be all
4883     // zeros, thus the result of the srl will always be zero.
4884     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4885 
4886     // If all of the bits input the to ctlz node are known to be zero, then
4887     // the result of the ctlz is "32" and the result of the shift is one.
4888     APInt UnknownBits = ~KnownZero;
4889     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4890 
4891     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4892     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4893       // Okay, we know that only that the single bit specified by UnknownBits
4894       // could be set on input to the CTLZ node. If this bit is set, the SRL
4895       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4896       // to an SRL/XOR pair, which is likely to simplify more.
4897       unsigned ShAmt = UnknownBits.countTrailingZeros();
4898       SDValue Op = N0.getOperand(0);
4899 
4900       if (ShAmt) {
4901         SDLoc DL(N0);
4902         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4903                   DAG.getConstant(ShAmt, DL,
4904                                   getShiftAmountTy(Op.getValueType())));
4905         AddToWorklist(Op.getNode());
4906       }
4907 
4908       SDLoc DL(N);
4909       return DAG.getNode(ISD::XOR, DL, VT,
4910                          Op, DAG.getConstant(1, DL, VT));
4911     }
4912   }
4913 
4914   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4915   if (N1.getOpcode() == ISD::TRUNCATE &&
4916       N1.getOperand(0).getOpcode() == ISD::AND) {
4917     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4918       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4919   }
4920 
4921   // fold operands of srl based on knowledge that the low bits are not
4922   // demanded.
4923   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4924     return SDValue(N, 0);
4925 
4926   if (N1C && !N1C->isOpaque())
4927     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4928       return NewSRL;
4929 
4930   // Attempt to convert a srl of a load into a narrower zero-extending load.
4931   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4932     return NarrowLoad;
4933 
4934   // Here is a common situation. We want to optimize:
4935   //
4936   //   %a = ...
4937   //   %b = and i32 %a, 2
4938   //   %c = srl i32 %b, 1
4939   //   brcond i32 %c ...
4940   //
4941   // into
4942   //
4943   //   %a = ...
4944   //   %b = and %a, 2
4945   //   %c = setcc eq %b, 0
4946   //   brcond %c ...
4947   //
4948   // However when after the source operand of SRL is optimized into AND, the SRL
4949   // itself may not be optimized further. Look for it and add the BRCOND into
4950   // the worklist.
4951   if (N->hasOneUse()) {
4952     SDNode *Use = *N->use_begin();
4953     if (Use->getOpcode() == ISD::BRCOND)
4954       AddToWorklist(Use);
4955     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4956       // Also look pass the truncate.
4957       Use = *Use->use_begin();
4958       if (Use->getOpcode() == ISD::BRCOND)
4959         AddToWorklist(Use);
4960     }
4961   }
4962 
4963   return SDValue();
4964 }
4965 
4966 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4967   SDValue N0 = N->getOperand(0);
4968   EVT VT = N->getValueType(0);
4969 
4970   // fold (bswap c1) -> c2
4971   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4972     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4973   // fold (bswap (bswap x)) -> x
4974   if (N0.getOpcode() == ISD::BSWAP)
4975     return N0->getOperand(0);
4976   return SDValue();
4977 }
4978 
4979 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
4980   SDValue N0 = N->getOperand(0);
4981 
4982   // fold (bitreverse (bitreverse x)) -> x
4983   if (N0.getOpcode() == ISD::BITREVERSE)
4984     return N0.getOperand(0);
4985   return SDValue();
4986 }
4987 
4988 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4989   SDValue N0 = N->getOperand(0);
4990   EVT VT = N->getValueType(0);
4991 
4992   // fold (ctlz c1) -> c2
4993   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
4994     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4995   return SDValue();
4996 }
4997 
4998 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4999   SDValue N0 = N->getOperand(0);
5000   EVT VT = N->getValueType(0);
5001 
5002   // fold (ctlz_zero_undef c1) -> c2
5003   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5004     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5005   return SDValue();
5006 }
5007 
5008 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5009   SDValue N0 = N->getOperand(0);
5010   EVT VT = N->getValueType(0);
5011 
5012   // fold (cttz c1) -> c2
5013   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5014     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5015   return SDValue();
5016 }
5017 
5018 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5019   SDValue N0 = N->getOperand(0);
5020   EVT VT = N->getValueType(0);
5021 
5022   // fold (cttz_zero_undef c1) -> c2
5023   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5024     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5025   return SDValue();
5026 }
5027 
5028 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5029   SDValue N0 = N->getOperand(0);
5030   EVT VT = N->getValueType(0);
5031 
5032   // fold (ctpop c1) -> c2
5033   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5034     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5035   return SDValue();
5036 }
5037 
5038 
5039 /// \brief Generate Min/Max node
5040 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
5041                                    SDValue True, SDValue False,
5042                                    ISD::CondCode CC, const TargetLowering &TLI,
5043                                    SelectionDAG &DAG) {
5044   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5045     return SDValue();
5046 
5047   switch (CC) {
5048   case ISD::SETOLT:
5049   case ISD::SETOLE:
5050   case ISD::SETLT:
5051   case ISD::SETLE:
5052   case ISD::SETULT:
5053   case ISD::SETULE: {
5054     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5055     if (TLI.isOperationLegal(Opcode, VT))
5056       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5057     return SDValue();
5058   }
5059   case ISD::SETOGT:
5060   case ISD::SETOGE:
5061   case ISD::SETGT:
5062   case ISD::SETGE:
5063   case ISD::SETUGT:
5064   case ISD::SETUGE: {
5065     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5066     if (TLI.isOperationLegal(Opcode, VT))
5067       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5068     return SDValue();
5069   }
5070   default:
5071     return SDValue();
5072   }
5073 }
5074 
5075 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5076   SDValue N0 = N->getOperand(0);
5077   SDValue N1 = N->getOperand(1);
5078   SDValue N2 = N->getOperand(2);
5079   EVT VT = N->getValueType(0);
5080   EVT VT0 = N0.getValueType();
5081 
5082   // fold (select C, X, X) -> X
5083   if (N1 == N2)
5084     return N1;
5085   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5086     // fold (select true, X, Y) -> X
5087     // fold (select false, X, Y) -> Y
5088     return !N0C->isNullValue() ? N1 : N2;
5089   }
5090   // fold (select C, 1, X) -> (or C, X)
5091   if (VT == MVT::i1 && isOneConstant(N1))
5092     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5093   // fold (select C, 0, 1) -> (xor C, 1)
5094   // We can't do this reliably if integer based booleans have different contents
5095   // to floating point based booleans. This is because we can't tell whether we
5096   // have an integer-based boolean or a floating-point-based boolean unless we
5097   // can find the SETCC that produced it and inspect its operands. This is
5098   // fairly easy if C is the SETCC node, but it can potentially be
5099   // undiscoverable (or not reasonably discoverable). For example, it could be
5100   // in another basic block or it could require searching a complicated
5101   // expression.
5102   if (VT.isInteger() &&
5103       (VT0 == MVT::i1 || (VT0.isInteger() &&
5104                           TLI.getBooleanContents(false, false) ==
5105                               TLI.getBooleanContents(false, true) &&
5106                           TLI.getBooleanContents(false, false) ==
5107                               TargetLowering::ZeroOrOneBooleanContent)) &&
5108       isNullConstant(N1) && isOneConstant(N2)) {
5109     SDValue XORNode;
5110     if (VT == VT0) {
5111       SDLoc DL(N);
5112       return DAG.getNode(ISD::XOR, DL, VT0,
5113                          N0, DAG.getConstant(1, DL, VT0));
5114     }
5115     SDLoc DL0(N0);
5116     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5117                           N0, DAG.getConstant(1, DL0, VT0));
5118     AddToWorklist(XORNode.getNode());
5119     if (VT.bitsGT(VT0))
5120       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5121     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5122   }
5123   // fold (select C, 0, X) -> (and (not C), X)
5124   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5125     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5126     AddToWorklist(NOTNode.getNode());
5127     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5128   }
5129   // fold (select C, X, 1) -> (or (not C), X)
5130   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5131     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5132     AddToWorklist(NOTNode.getNode());
5133     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5134   }
5135   // fold (select C, X, 0) -> (and C, X)
5136   if (VT == MVT::i1 && isNullConstant(N2))
5137     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5138   // fold (select X, X, Y) -> (or X, Y)
5139   // fold (select X, 1, Y) -> (or X, Y)
5140   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5141     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5142   // fold (select X, Y, X) -> (and X, Y)
5143   // fold (select X, Y, 0) -> (and X, Y)
5144   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5145     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5146 
5147   // If we can fold this based on the true/false value, do so.
5148   if (SimplifySelectOps(N, N1, N2))
5149     return SDValue(N, 0);  // Don't revisit N.
5150 
5151   if (VT0 == MVT::i1) {
5152     // The code in this block deals with the following 2 equivalences:
5153     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5154     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5155     // The target can specify its prefered form with the
5156     // shouldNormalizeToSelectSequence() callback. However we always transform
5157     // to the right anyway if we find the inner select exists in the DAG anyway
5158     // and we always transform to the left side if we know that we can further
5159     // optimize the combination of the conditions.
5160     bool normalizeToSequence
5161       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5162     // select (and Cond0, Cond1), X, Y
5163     //   -> select Cond0, (select Cond1, X, Y), Y
5164     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5165       SDValue Cond0 = N0->getOperand(0);
5166       SDValue Cond1 = N0->getOperand(1);
5167       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5168                                         N1.getValueType(), Cond1, N1, N2);
5169       if (normalizeToSequence || !InnerSelect.use_empty())
5170         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5171                            InnerSelect, N2);
5172     }
5173     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5174     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5175       SDValue Cond0 = N0->getOperand(0);
5176       SDValue Cond1 = N0->getOperand(1);
5177       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5178                                         N1.getValueType(), Cond1, N1, N2);
5179       if (normalizeToSequence || !InnerSelect.use_empty())
5180         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5181                            InnerSelect);
5182     }
5183 
5184     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5185     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5186       SDValue N1_0 = N1->getOperand(0);
5187       SDValue N1_1 = N1->getOperand(1);
5188       SDValue N1_2 = N1->getOperand(2);
5189       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5190         // Create the actual and node if we can generate good code for it.
5191         if (!normalizeToSequence) {
5192           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5193                                     N0, N1_0);
5194           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5195                              N1_1, N2);
5196         }
5197         // Otherwise see if we can optimize the "and" to a better pattern.
5198         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5199           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5200                              N1_1, N2);
5201       }
5202     }
5203     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5204     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5205       SDValue N2_0 = N2->getOperand(0);
5206       SDValue N2_1 = N2->getOperand(1);
5207       SDValue N2_2 = N2->getOperand(2);
5208       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5209         // Create the actual or node if we can generate good code for it.
5210         if (!normalizeToSequence) {
5211           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5212                                    N0, N2_0);
5213           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5214                              N1, N2_2);
5215         }
5216         // Otherwise see if we can optimize to a better pattern.
5217         if (SDValue Combined = visitORLike(N0, N2_0, N))
5218           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5219                              N1, N2_2);
5220       }
5221     }
5222   }
5223 
5224   // fold selects based on a setcc into other things, such as min/max/abs
5225   if (N0.getOpcode() == ISD::SETCC) {
5226     // select x, y (fcmp lt x, y) -> fminnum x, y
5227     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5228     //
5229     // This is OK if we don't care about what happens if either operand is a
5230     // NaN.
5231     //
5232 
5233     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5234     // no signed zeros as well as no nans.
5235     const TargetOptions &Options = DAG.getTarget().Options;
5236     if (Options.UnsafeFPMath &&
5237         VT.isFloatingPoint() && N0.hasOneUse() &&
5238         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5239       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5240 
5241       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5242                                                 N0.getOperand(1), N1, N2, CC,
5243                                                 TLI, DAG))
5244         return FMinMax;
5245     }
5246 
5247     if ((!LegalOperations &&
5248          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5249         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5250       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5251                          N0.getOperand(0), N0.getOperand(1),
5252                          N1, N2, N0.getOperand(2));
5253     return SimplifySelect(SDLoc(N), N0, N1, N2);
5254   }
5255 
5256   return SDValue();
5257 }
5258 
5259 static
5260 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5261   SDLoc DL(N);
5262   EVT LoVT, HiVT;
5263   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5264 
5265   // Split the inputs.
5266   SDValue Lo, Hi, LL, LH, RL, RH;
5267   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5268   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5269 
5270   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5271   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5272 
5273   return std::make_pair(Lo, Hi);
5274 }
5275 
5276 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5277 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5278 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5279   SDLoc dl(N);
5280   SDValue Cond = N->getOperand(0);
5281   SDValue LHS = N->getOperand(1);
5282   SDValue RHS = N->getOperand(2);
5283   EVT VT = N->getValueType(0);
5284   int NumElems = VT.getVectorNumElements();
5285   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5286          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5287          Cond.getOpcode() == ISD::BUILD_VECTOR);
5288 
5289   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5290   // binary ones here.
5291   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5292     return SDValue();
5293 
5294   // We're sure we have an even number of elements due to the
5295   // concat_vectors we have as arguments to vselect.
5296   // Skip BV elements until we find one that's not an UNDEF
5297   // After we find an UNDEF element, keep looping until we get to half the
5298   // length of the BV and see if all the non-undef nodes are the same.
5299   ConstantSDNode *BottomHalf = nullptr;
5300   for (int i = 0; i < NumElems / 2; ++i) {
5301     if (Cond->getOperand(i)->isUndef())
5302       continue;
5303 
5304     if (BottomHalf == nullptr)
5305       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5306     else if (Cond->getOperand(i).getNode() != BottomHalf)
5307       return SDValue();
5308   }
5309 
5310   // Do the same for the second half of the BuildVector
5311   ConstantSDNode *TopHalf = nullptr;
5312   for (int i = NumElems / 2; i < NumElems; ++i) {
5313     if (Cond->getOperand(i)->isUndef())
5314       continue;
5315 
5316     if (TopHalf == nullptr)
5317       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5318     else if (Cond->getOperand(i).getNode() != TopHalf)
5319       return SDValue();
5320   }
5321 
5322   assert(TopHalf && BottomHalf &&
5323          "One half of the selector was all UNDEFs and the other was all the "
5324          "same value. This should have been addressed before this function.");
5325   return DAG.getNode(
5326       ISD::CONCAT_VECTORS, dl, VT,
5327       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5328       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5329 }
5330 
5331 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5332 
5333   if (Level >= AfterLegalizeTypes)
5334     return SDValue();
5335 
5336   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5337   SDValue Mask = MSC->getMask();
5338   SDValue Data  = MSC->getValue();
5339   SDLoc DL(N);
5340 
5341   // If the MSCATTER data type requires splitting and the mask is provided by a
5342   // SETCC, then split both nodes and its operands before legalization. This
5343   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5344   // and enables future optimizations (e.g. min/max pattern matching on X86).
5345   if (Mask.getOpcode() != ISD::SETCC)
5346     return SDValue();
5347 
5348   // Check if any splitting is required.
5349   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5350       TargetLowering::TypeSplitVector)
5351     return SDValue();
5352   SDValue MaskLo, MaskHi, Lo, Hi;
5353   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5354 
5355   EVT LoVT, HiVT;
5356   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5357 
5358   SDValue Chain = MSC->getChain();
5359 
5360   EVT MemoryVT = MSC->getMemoryVT();
5361   unsigned Alignment = MSC->getOriginalAlignment();
5362 
5363   EVT LoMemVT, HiMemVT;
5364   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5365 
5366   SDValue DataLo, DataHi;
5367   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5368 
5369   SDValue BasePtr = MSC->getBasePtr();
5370   SDValue IndexLo, IndexHi;
5371   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5372 
5373   MachineMemOperand *MMO = DAG.getMachineFunction().
5374     getMachineMemOperand(MSC->getPointerInfo(),
5375                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5376                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5377 
5378   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5379   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5380                             DL, OpsLo, MMO);
5381 
5382   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5383   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5384                             DL, OpsHi, MMO);
5385 
5386   AddToWorklist(Lo.getNode());
5387   AddToWorklist(Hi.getNode());
5388 
5389   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5390 }
5391 
5392 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5393 
5394   if (Level >= AfterLegalizeTypes)
5395     return SDValue();
5396 
5397   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5398   SDValue Mask = MST->getMask();
5399   SDValue Data  = MST->getValue();
5400   SDLoc DL(N);
5401 
5402   // If the MSTORE data type requires splitting and the mask is provided by a
5403   // SETCC, then split both nodes and its operands before legalization. This
5404   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5405   // and enables future optimizations (e.g. min/max pattern matching on X86).
5406   if (Mask.getOpcode() == ISD::SETCC) {
5407 
5408     // Check if any splitting is required.
5409     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5410         TargetLowering::TypeSplitVector)
5411       return SDValue();
5412 
5413     SDValue MaskLo, MaskHi, Lo, Hi;
5414     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5415 
5416     EVT LoVT, HiVT;
5417     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5418 
5419     SDValue Chain = MST->getChain();
5420     SDValue Ptr   = MST->getBasePtr();
5421 
5422     EVT MemoryVT = MST->getMemoryVT();
5423     unsigned Alignment = MST->getOriginalAlignment();
5424 
5425     // if Alignment is equal to the vector size,
5426     // take the half of it for the second part
5427     unsigned SecondHalfAlignment =
5428       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5429          Alignment/2 : Alignment;
5430 
5431     EVT LoMemVT, HiMemVT;
5432     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5433 
5434     SDValue DataLo, DataHi;
5435     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5436 
5437     MachineMemOperand *MMO = DAG.getMachineFunction().
5438       getMachineMemOperand(MST->getPointerInfo(),
5439                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5440                            Alignment, MST->getAAInfo(), MST->getRanges());
5441 
5442     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5443                             MST->isTruncatingStore());
5444 
5445     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5446     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5447                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5448 
5449     MMO = DAG.getMachineFunction().
5450       getMachineMemOperand(MST->getPointerInfo(),
5451                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5452                            SecondHalfAlignment, MST->getAAInfo(),
5453                            MST->getRanges());
5454 
5455     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5456                             MST->isTruncatingStore());
5457 
5458     AddToWorklist(Lo.getNode());
5459     AddToWorklist(Hi.getNode());
5460 
5461     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5462   }
5463   return SDValue();
5464 }
5465 
5466 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5467 
5468   if (Level >= AfterLegalizeTypes)
5469     return SDValue();
5470 
5471   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5472   SDValue Mask = MGT->getMask();
5473   SDLoc DL(N);
5474 
5475   // If the MGATHER result requires splitting and the mask is provided by a
5476   // SETCC, then split both nodes and its operands before legalization. This
5477   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5478   // and enables future optimizations (e.g. min/max pattern matching on X86).
5479 
5480   if (Mask.getOpcode() != ISD::SETCC)
5481     return SDValue();
5482 
5483   EVT VT = N->getValueType(0);
5484 
5485   // Check if any splitting is required.
5486   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5487       TargetLowering::TypeSplitVector)
5488     return SDValue();
5489 
5490   SDValue MaskLo, MaskHi, Lo, Hi;
5491   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5492 
5493   SDValue Src0 = MGT->getValue();
5494   SDValue Src0Lo, Src0Hi;
5495   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5496 
5497   EVT LoVT, HiVT;
5498   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5499 
5500   SDValue Chain = MGT->getChain();
5501   EVT MemoryVT = MGT->getMemoryVT();
5502   unsigned Alignment = MGT->getOriginalAlignment();
5503 
5504   EVT LoMemVT, HiMemVT;
5505   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5506 
5507   SDValue BasePtr = MGT->getBasePtr();
5508   SDValue Index = MGT->getIndex();
5509   SDValue IndexLo, IndexHi;
5510   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5511 
5512   MachineMemOperand *MMO = DAG.getMachineFunction().
5513     getMachineMemOperand(MGT->getPointerInfo(),
5514                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5515                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5516 
5517   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5518   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5519                             MMO);
5520 
5521   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5522   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5523                             MMO);
5524 
5525   AddToWorklist(Lo.getNode());
5526   AddToWorklist(Hi.getNode());
5527 
5528   // Build a factor node to remember that this load is independent of the
5529   // other one.
5530   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5531                       Hi.getValue(1));
5532 
5533   // Legalized the chain result - switch anything that used the old chain to
5534   // use the new one.
5535   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5536 
5537   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5538 
5539   SDValue RetOps[] = { GatherRes, Chain };
5540   return DAG.getMergeValues(RetOps, DL);
5541 }
5542 
5543 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5544 
5545   if (Level >= AfterLegalizeTypes)
5546     return SDValue();
5547 
5548   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5549   SDValue Mask = MLD->getMask();
5550   SDLoc DL(N);
5551 
5552   // If the MLOAD result requires splitting and the mask is provided by a
5553   // SETCC, then split both nodes and its operands before legalization. This
5554   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5555   // and enables future optimizations (e.g. min/max pattern matching on X86).
5556 
5557   if (Mask.getOpcode() == ISD::SETCC) {
5558     EVT VT = N->getValueType(0);
5559 
5560     // Check if any splitting is required.
5561     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5562         TargetLowering::TypeSplitVector)
5563       return SDValue();
5564 
5565     SDValue MaskLo, MaskHi, Lo, Hi;
5566     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5567 
5568     SDValue Src0 = MLD->getSrc0();
5569     SDValue Src0Lo, Src0Hi;
5570     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5571 
5572     EVT LoVT, HiVT;
5573     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5574 
5575     SDValue Chain = MLD->getChain();
5576     SDValue Ptr   = MLD->getBasePtr();
5577     EVT MemoryVT = MLD->getMemoryVT();
5578     unsigned Alignment = MLD->getOriginalAlignment();
5579 
5580     // if Alignment is equal to the vector size,
5581     // take the half of it for the second part
5582     unsigned SecondHalfAlignment =
5583       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5584          Alignment/2 : Alignment;
5585 
5586     EVT LoMemVT, HiMemVT;
5587     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5588 
5589     MachineMemOperand *MMO = DAG.getMachineFunction().
5590     getMachineMemOperand(MLD->getPointerInfo(),
5591                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5592                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5593 
5594     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5595                            ISD::NON_EXTLOAD);
5596 
5597     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5598     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5599                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5600 
5601     MMO = DAG.getMachineFunction().
5602     getMachineMemOperand(MLD->getPointerInfo(),
5603                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5604                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5605 
5606     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5607                            ISD::NON_EXTLOAD);
5608 
5609     AddToWorklist(Lo.getNode());
5610     AddToWorklist(Hi.getNode());
5611 
5612     // Build a factor node to remember that this load is independent of the
5613     // other one.
5614     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5615                         Hi.getValue(1));
5616 
5617     // Legalized the chain result - switch anything that used the old chain to
5618     // use the new one.
5619     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5620 
5621     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5622 
5623     SDValue RetOps[] = { LoadRes, Chain };
5624     return DAG.getMergeValues(RetOps, DL);
5625   }
5626   return SDValue();
5627 }
5628 
5629 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5630   SDValue N0 = N->getOperand(0);
5631   SDValue N1 = N->getOperand(1);
5632   SDValue N2 = N->getOperand(2);
5633   SDLoc DL(N);
5634 
5635   // Canonicalize integer abs.
5636   // vselect (setg[te] X,  0),  X, -X ->
5637   // vselect (setgt    X, -1),  X, -X ->
5638   // vselect (setl[te] X,  0), -X,  X ->
5639   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5640   if (N0.getOpcode() == ISD::SETCC) {
5641     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5642     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5643     bool isAbs = false;
5644     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5645 
5646     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5647          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5648         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5649       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5650     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5651              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5652       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5653 
5654     if (isAbs) {
5655       EVT VT = LHS.getValueType();
5656       SDValue Shift = DAG.getNode(
5657           ISD::SRA, DL, VT, LHS,
5658           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5659       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5660       AddToWorklist(Shift.getNode());
5661       AddToWorklist(Add.getNode());
5662       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5663     }
5664   }
5665 
5666   if (SimplifySelectOps(N, N1, N2))
5667     return SDValue(N, 0);  // Don't revisit N.
5668 
5669   // If the VSELECT result requires splitting and the mask is provided by a
5670   // SETCC, then split both nodes and its operands before legalization. This
5671   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5672   // and enables future optimizations (e.g. min/max pattern matching on X86).
5673   if (N0.getOpcode() == ISD::SETCC) {
5674     EVT VT = N->getValueType(0);
5675 
5676     // Check if any splitting is required.
5677     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5678         TargetLowering::TypeSplitVector)
5679       return SDValue();
5680 
5681     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5682     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5683     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5684     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5685 
5686     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5687     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5688 
5689     // Add the new VSELECT nodes to the work list in case they need to be split
5690     // again.
5691     AddToWorklist(Lo.getNode());
5692     AddToWorklist(Hi.getNode());
5693 
5694     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5695   }
5696 
5697   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5698   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5699     return N1;
5700   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5701   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5702     return N2;
5703 
5704   // The ConvertSelectToConcatVector function is assuming both the above
5705   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5706   // and addressed.
5707   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5708       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5709       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5710     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5711       return CV;
5712   }
5713 
5714   return SDValue();
5715 }
5716 
5717 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5718   SDValue N0 = N->getOperand(0);
5719   SDValue N1 = N->getOperand(1);
5720   SDValue N2 = N->getOperand(2);
5721   SDValue N3 = N->getOperand(3);
5722   SDValue N4 = N->getOperand(4);
5723   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5724 
5725   // fold select_cc lhs, rhs, x, x, cc -> x
5726   if (N2 == N3)
5727     return N2;
5728 
5729   // Determine if the condition we're dealing with is constant
5730   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
5731                                   CC, SDLoc(N), false)) {
5732     AddToWorklist(SCC.getNode());
5733 
5734     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5735       if (!SCCC->isNullValue())
5736         return N2;    // cond always true -> true val
5737       else
5738         return N3;    // cond always false -> false val
5739     } else if (SCC->isUndef()) {
5740       // When the condition is UNDEF, just return the first operand. This is
5741       // coherent the DAG creation, no setcc node is created in this case
5742       return N2;
5743     } else if (SCC.getOpcode() == ISD::SETCC) {
5744       // Fold to a simpler select_cc
5745       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5746                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5747                          SCC.getOperand(2));
5748     }
5749   }
5750 
5751   // If we can fold this based on the true/false value, do so.
5752   if (SimplifySelectOps(N, N2, N3))
5753     return SDValue(N, 0);  // Don't revisit N.
5754 
5755   // fold select_cc into other things, such as min/max/abs
5756   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5757 }
5758 
5759 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5760   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5761                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5762                        SDLoc(N));
5763 }
5764 
5765 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
5766   SDValue LHS = N->getOperand(0);
5767   SDValue RHS = N->getOperand(1);
5768   SDValue Carry = N->getOperand(2);
5769   SDValue Cond = N->getOperand(3);
5770 
5771   // If Carry is false, fold to a regular SETCC.
5772   if (Carry.getOpcode() == ISD::CARRY_FALSE)
5773     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
5774 
5775   return SDValue();
5776 }
5777 
5778 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5779 /// a build_vector of constants.
5780 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5781 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5782 /// Vector extends are not folded if operations are legal; this is to
5783 /// avoid introducing illegal build_vector dag nodes.
5784 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5785                                          SelectionDAG &DAG, bool LegalTypes,
5786                                          bool LegalOperations) {
5787   unsigned Opcode = N->getOpcode();
5788   SDValue N0 = N->getOperand(0);
5789   EVT VT = N->getValueType(0);
5790 
5791   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5792          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5793          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
5794          && "Expected EXTEND dag node in input!");
5795 
5796   // fold (sext c1) -> c1
5797   // fold (zext c1) -> c1
5798   // fold (aext c1) -> c1
5799   if (isa<ConstantSDNode>(N0))
5800     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5801 
5802   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5803   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5804   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5805   EVT SVT = VT.getScalarType();
5806   if (!(VT.isVector() &&
5807       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5808       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5809     return nullptr;
5810 
5811   // We can fold this node into a build_vector.
5812   unsigned VTBits = SVT.getSizeInBits();
5813   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5814   SmallVector<SDValue, 8> Elts;
5815   unsigned NumElts = VT.getVectorNumElements();
5816   SDLoc DL(N);
5817 
5818   for (unsigned i=0; i != NumElts; ++i) {
5819     SDValue Op = N0->getOperand(i);
5820     if (Op->isUndef()) {
5821       Elts.push_back(DAG.getUNDEF(SVT));
5822       continue;
5823     }
5824 
5825     SDLoc DL(Op);
5826     // Get the constant value and if needed trunc it to the size of the type.
5827     // Nodes like build_vector might have constants wider than the scalar type.
5828     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5829     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5830       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5831     else
5832       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5833   }
5834 
5835   return DAG.getBuildVector(VT, DL, Elts).getNode();
5836 }
5837 
5838 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5839 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5840 // transformation. Returns true if extension are possible and the above
5841 // mentioned transformation is profitable.
5842 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5843                                     unsigned ExtOpc,
5844                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5845                                     const TargetLowering &TLI) {
5846   bool HasCopyToRegUses = false;
5847   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5848   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5849                             UE = N0.getNode()->use_end();
5850        UI != UE; ++UI) {
5851     SDNode *User = *UI;
5852     if (User == N)
5853       continue;
5854     if (UI.getUse().getResNo() != N0.getResNo())
5855       continue;
5856     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5857     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5858       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5859       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5860         // Sign bits will be lost after a zext.
5861         return false;
5862       bool Add = false;
5863       for (unsigned i = 0; i != 2; ++i) {
5864         SDValue UseOp = User->getOperand(i);
5865         if (UseOp == N0)
5866           continue;
5867         if (!isa<ConstantSDNode>(UseOp))
5868           return false;
5869         Add = true;
5870       }
5871       if (Add)
5872         ExtendNodes.push_back(User);
5873       continue;
5874     }
5875     // If truncates aren't free and there are users we can't
5876     // extend, it isn't worthwhile.
5877     if (!isTruncFree)
5878       return false;
5879     // Remember if this value is live-out.
5880     if (User->getOpcode() == ISD::CopyToReg)
5881       HasCopyToRegUses = true;
5882   }
5883 
5884   if (HasCopyToRegUses) {
5885     bool BothLiveOut = false;
5886     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5887          UI != UE; ++UI) {
5888       SDUse &Use = UI.getUse();
5889       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5890         BothLiveOut = true;
5891         break;
5892       }
5893     }
5894     if (BothLiveOut)
5895       // Both unextended and extended values are live out. There had better be
5896       // a good reason for the transformation.
5897       return ExtendNodes.size();
5898   }
5899   return true;
5900 }
5901 
5902 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5903                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5904                                   ISD::NodeType ExtType) {
5905   // Extend SetCC uses if necessary.
5906   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5907     SDNode *SetCC = SetCCs[i];
5908     SmallVector<SDValue, 4> Ops;
5909 
5910     for (unsigned j = 0; j != 2; ++j) {
5911       SDValue SOp = SetCC->getOperand(j);
5912       if (SOp == Trunc)
5913         Ops.push_back(ExtLoad);
5914       else
5915         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5916     }
5917 
5918     Ops.push_back(SetCC->getOperand(2));
5919     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5920   }
5921 }
5922 
5923 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5924 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5925   SDValue N0 = N->getOperand(0);
5926   EVT DstVT = N->getValueType(0);
5927   EVT SrcVT = N0.getValueType();
5928 
5929   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5930           N->getOpcode() == ISD::ZERO_EXTEND) &&
5931          "Unexpected node type (not an extend)!");
5932 
5933   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5934   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5935   //   (v8i32 (sext (v8i16 (load x))))
5936   // into:
5937   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5938   //                          (v4i32 (sextload (x + 16)))))
5939   // Where uses of the original load, i.e.:
5940   //   (v8i16 (load x))
5941   // are replaced with:
5942   //   (v8i16 (truncate
5943   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5944   //                            (v4i32 (sextload (x + 16)))))))
5945   //
5946   // This combine is only applicable to illegal, but splittable, vectors.
5947   // All legal types, and illegal non-vector types, are handled elsewhere.
5948   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5949   //
5950   if (N0->getOpcode() != ISD::LOAD)
5951     return SDValue();
5952 
5953   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5954 
5955   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5956       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5957       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5958     return SDValue();
5959 
5960   SmallVector<SDNode *, 4> SetCCs;
5961   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5962     return SDValue();
5963 
5964   ISD::LoadExtType ExtType =
5965       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5966 
5967   // Try to split the vector types to get down to legal types.
5968   EVT SplitSrcVT = SrcVT;
5969   EVT SplitDstVT = DstVT;
5970   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5971          SplitSrcVT.getVectorNumElements() > 1) {
5972     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5973     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5974   }
5975 
5976   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5977     return SDValue();
5978 
5979   SDLoc DL(N);
5980   const unsigned NumSplits =
5981       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5982   const unsigned Stride = SplitSrcVT.getStoreSize();
5983   SmallVector<SDValue, 4> Loads;
5984   SmallVector<SDValue, 4> Chains;
5985 
5986   SDValue BasePtr = LN0->getBasePtr();
5987   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5988     const unsigned Offset = Idx * Stride;
5989     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5990 
5991     SDValue SplitLoad = DAG.getExtLoad(
5992         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5993         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5994         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5995         Align, LN0->getAAInfo());
5996 
5997     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5998                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5999 
6000     Loads.push_back(SplitLoad.getValue(0));
6001     Chains.push_back(SplitLoad.getValue(1));
6002   }
6003 
6004   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6005   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6006 
6007   CombineTo(N, NewValue);
6008 
6009   // Replace uses of the original load (before extension)
6010   // with a truncate of the concatenated sextloaded vectors.
6011   SDValue Trunc =
6012       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6013   CombineTo(N0.getNode(), Trunc, NewChain);
6014   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6015                   (ISD::NodeType)N->getOpcode());
6016   return SDValue(N, 0); // Return N so it doesn't get rechecked!
6017 }
6018 
6019 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6020   SDValue N0 = N->getOperand(0);
6021   EVT VT = N->getValueType(0);
6022 
6023   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6024                                               LegalOperations))
6025     return SDValue(Res, 0);
6026 
6027   // fold (sext (sext x)) -> (sext x)
6028   // fold (sext (aext x)) -> (sext x)
6029   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6030     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
6031                        N0.getOperand(0));
6032 
6033   if (N0.getOpcode() == ISD::TRUNCATE) {
6034     // fold (sext (truncate (load x))) -> (sext (smaller load x))
6035     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6036     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6037       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6038       if (NarrowLoad.getNode() != N0.getNode()) {
6039         CombineTo(N0.getNode(), NarrowLoad);
6040         // CombineTo deleted the truncate, if needed, but not what's under it.
6041         AddToWorklist(oye);
6042       }
6043       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6044     }
6045 
6046     // See if the value being truncated is already sign extended.  If so, just
6047     // eliminate the trunc/sext pair.
6048     SDValue Op = N0.getOperand(0);
6049     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
6050     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
6051     unsigned DestBits = VT.getScalarType().getSizeInBits();
6052     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6053 
6054     if (OpBits == DestBits) {
6055       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
6056       // bits, it is already ready.
6057       if (NumSignBits > DestBits-MidBits)
6058         return Op;
6059     } else if (OpBits < DestBits) {
6060       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
6061       // bits, just sext from i32.
6062       if (NumSignBits > OpBits-MidBits)
6063         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
6064     } else {
6065       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
6066       // bits, just truncate to i32.
6067       if (NumSignBits > OpBits-MidBits)
6068         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6069     }
6070 
6071     // fold (sext (truncate x)) -> (sextinreg x).
6072     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6073                                                  N0.getValueType())) {
6074       if (OpBits < DestBits)
6075         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6076       else if (OpBits > DestBits)
6077         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6078       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
6079                          DAG.getValueType(N0.getValueType()));
6080     }
6081   }
6082 
6083   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6084   // Only generate vector extloads when 1) they're legal, and 2) they are
6085   // deemed desirable by the target.
6086   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6087       ((!LegalOperations && !VT.isVector() &&
6088         !cast<LoadSDNode>(N0)->isVolatile()) ||
6089        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6090     bool DoXform = true;
6091     SmallVector<SDNode*, 4> SetCCs;
6092     if (!N0.hasOneUse())
6093       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6094     if (VT.isVector())
6095       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6096     if (DoXform) {
6097       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6098       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6099                                        LN0->getChain(),
6100                                        LN0->getBasePtr(), N0.getValueType(),
6101                                        LN0->getMemOperand());
6102       CombineTo(N, ExtLoad);
6103       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6104                                   N0.getValueType(), ExtLoad);
6105       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6106       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6107                       ISD::SIGN_EXTEND);
6108       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6109     }
6110   }
6111 
6112   // fold (sext (load x)) to multiple smaller sextloads.
6113   // Only on illegal but splittable vectors.
6114   if (SDValue ExtLoad = CombineExtLoad(N))
6115     return ExtLoad;
6116 
6117   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6118   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6119   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6120       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6121     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6122     EVT MemVT = LN0->getMemoryVT();
6123     if ((!LegalOperations && !LN0->isVolatile()) ||
6124         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6125       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6126                                        LN0->getChain(),
6127                                        LN0->getBasePtr(), MemVT,
6128                                        LN0->getMemOperand());
6129       CombineTo(N, ExtLoad);
6130       CombineTo(N0.getNode(),
6131                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6132                             N0.getValueType(), ExtLoad),
6133                 ExtLoad.getValue(1));
6134       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6135     }
6136   }
6137 
6138   // fold (sext (and/or/xor (load x), cst)) ->
6139   //      (and/or/xor (sextload x), (sext cst))
6140   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6141        N0.getOpcode() == ISD::XOR) &&
6142       isa<LoadSDNode>(N0.getOperand(0)) &&
6143       N0.getOperand(1).getOpcode() == ISD::Constant &&
6144       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6145       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6146     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6147     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6148       bool DoXform = true;
6149       SmallVector<SDNode*, 4> SetCCs;
6150       if (!N0.hasOneUse())
6151         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6152                                           SetCCs, TLI);
6153       if (DoXform) {
6154         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6155                                          LN0->getChain(), LN0->getBasePtr(),
6156                                          LN0->getMemoryVT(),
6157                                          LN0->getMemOperand());
6158         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6159         Mask = Mask.sext(VT.getSizeInBits());
6160         SDLoc DL(N);
6161         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6162                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6163         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6164                                     SDLoc(N0.getOperand(0)),
6165                                     N0.getOperand(0).getValueType(), ExtLoad);
6166         CombineTo(N, And);
6167         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6168         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6169                         ISD::SIGN_EXTEND);
6170         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6171       }
6172     }
6173   }
6174 
6175   if (N0.getOpcode() == ISD::SETCC) {
6176     EVT N0VT = N0.getOperand(0).getValueType();
6177     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6178     // Only do this before legalize for now.
6179     if (VT.isVector() && !LegalOperations &&
6180         TLI.getBooleanContents(N0VT) ==
6181             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6182       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6183       // of the same size as the compared operands. Only optimize sext(setcc())
6184       // if this is the case.
6185       EVT SVT = getSetCCResultType(N0VT);
6186 
6187       // We know that the # elements of the results is the same as the
6188       // # elements of the compare (and the # elements of the compare result
6189       // for that matter).  Check to see that they are the same size.  If so,
6190       // we know that the element size of the sext'd result matches the
6191       // element size of the compare operands.
6192       if (VT.getSizeInBits() == SVT.getSizeInBits())
6193         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6194                              N0.getOperand(1),
6195                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6196 
6197       // If the desired elements are smaller or larger than the source
6198       // elements we can use a matching integer vector type and then
6199       // truncate/sign extend
6200       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6201       if (SVT == MatchingVectorType) {
6202         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6203                                N0.getOperand(0), N0.getOperand(1),
6204                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6205         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6206       }
6207     }
6208 
6209     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6210     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6211     SDLoc DL(N);
6212     SDValue NegOne =
6213       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6214     if (SDValue SCC = SimplifySelectCC(
6215             DL, N0.getOperand(0), N0.getOperand(1), NegOne,
6216             DAG.getConstant(0, DL, VT),
6217             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6218       return SCC;
6219 
6220     if (!VT.isVector()) {
6221       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6222       if (!LegalOperations ||
6223           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6224         SDLoc DL(N);
6225         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6226         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6227                                      N0.getOperand(0), N0.getOperand(1), CC);
6228         return DAG.getSelect(DL, VT, SetCC,
6229                              NegOne, DAG.getConstant(0, DL, VT));
6230       }
6231     }
6232   }
6233 
6234   // fold (sext x) -> (zext x) if the sign bit is known zero.
6235   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6236       DAG.SignBitIsZero(N0))
6237     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6238 
6239   return SDValue();
6240 }
6241 
6242 // isTruncateOf - If N is a truncate of some other value, return true, record
6243 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6244 // This function computes KnownZero to avoid a duplicated call to
6245 // computeKnownBits in the caller.
6246 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6247                          APInt &KnownZero) {
6248   APInt KnownOne;
6249   if (N->getOpcode() == ISD::TRUNCATE) {
6250     Op = N->getOperand(0);
6251     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6252     return true;
6253   }
6254 
6255   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6256       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6257     return false;
6258 
6259   SDValue Op0 = N->getOperand(0);
6260   SDValue Op1 = N->getOperand(1);
6261   assert(Op0.getValueType() == Op1.getValueType());
6262 
6263   if (isNullConstant(Op0))
6264     Op = Op1;
6265   else if (isNullConstant(Op1))
6266     Op = Op0;
6267   else
6268     return false;
6269 
6270   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6271 
6272   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6273     return false;
6274 
6275   return true;
6276 }
6277 
6278 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6279   SDValue N0 = N->getOperand(0);
6280   EVT VT = N->getValueType(0);
6281 
6282   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6283                                               LegalOperations))
6284     return SDValue(Res, 0);
6285 
6286   // fold (zext (zext x)) -> (zext x)
6287   // fold (zext (aext x)) -> (zext x)
6288   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6289     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6290                        N0.getOperand(0));
6291 
6292   // fold (zext (truncate x)) -> (zext x) or
6293   //      (zext (truncate x)) -> (truncate x)
6294   // This is valid when the truncated bits of x are already zero.
6295   // FIXME: We should extend this to work for vectors too.
6296   SDValue Op;
6297   APInt KnownZero;
6298   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6299     APInt TruncatedBits =
6300       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6301       APInt(Op.getValueSizeInBits(), 0) :
6302       APInt::getBitsSet(Op.getValueSizeInBits(),
6303                         N0.getValueSizeInBits(),
6304                         std::min(Op.getValueSizeInBits(),
6305                                  VT.getSizeInBits()));
6306     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6307       if (VT.bitsGT(Op.getValueType()))
6308         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6309       if (VT.bitsLT(Op.getValueType()))
6310         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6311 
6312       return Op;
6313     }
6314   }
6315 
6316   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6317   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6318   if (N0.getOpcode() == ISD::TRUNCATE) {
6319     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6320       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6321       if (NarrowLoad.getNode() != N0.getNode()) {
6322         CombineTo(N0.getNode(), NarrowLoad);
6323         // CombineTo deleted the truncate, if needed, but not what's under it.
6324         AddToWorklist(oye);
6325       }
6326       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6327     }
6328   }
6329 
6330   // fold (zext (truncate x)) -> (and x, mask)
6331   if (N0.getOpcode() == ISD::TRUNCATE) {
6332     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6333     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6334     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6335       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6336       if (NarrowLoad.getNode() != N0.getNode()) {
6337         CombineTo(N0.getNode(), NarrowLoad);
6338         // CombineTo deleted the truncate, if needed, but not what's under it.
6339         AddToWorklist(oye);
6340       }
6341       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6342     }
6343 
6344     EVT SrcVT = N0.getOperand(0).getValueType();
6345     EVT MinVT = N0.getValueType();
6346 
6347     // Try to mask before the extension to avoid having to generate a larger mask,
6348     // possibly over several sub-vectors.
6349     if (SrcVT.bitsLT(VT)) {
6350       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6351                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6352         SDValue Op = N0.getOperand(0);
6353         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6354         AddToWorklist(Op.getNode());
6355         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6356       }
6357     }
6358 
6359     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6360       SDValue Op = N0.getOperand(0);
6361       if (SrcVT.bitsLT(VT)) {
6362         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6363         AddToWorklist(Op.getNode());
6364       } else if (SrcVT.bitsGT(VT)) {
6365         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6366         AddToWorklist(Op.getNode());
6367       }
6368       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6369     }
6370   }
6371 
6372   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6373   // if either of the casts is not free.
6374   if (N0.getOpcode() == ISD::AND &&
6375       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6376       N0.getOperand(1).getOpcode() == ISD::Constant &&
6377       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6378                            N0.getValueType()) ||
6379        !TLI.isZExtFree(N0.getValueType(), VT))) {
6380     SDValue X = N0.getOperand(0).getOperand(0);
6381     if (X.getValueType().bitsLT(VT)) {
6382       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6383     } else if (X.getValueType().bitsGT(VT)) {
6384       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6385     }
6386     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6387     Mask = Mask.zext(VT.getSizeInBits());
6388     SDLoc DL(N);
6389     return DAG.getNode(ISD::AND, DL, VT,
6390                        X, DAG.getConstant(Mask, DL, VT));
6391   }
6392 
6393   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6394   // Only generate vector extloads when 1) they're legal, and 2) they are
6395   // deemed desirable by the target.
6396   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6397       ((!LegalOperations && !VT.isVector() &&
6398         !cast<LoadSDNode>(N0)->isVolatile()) ||
6399        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6400     bool DoXform = true;
6401     SmallVector<SDNode*, 4> SetCCs;
6402     if (!N0.hasOneUse())
6403       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6404     if (VT.isVector())
6405       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6406     if (DoXform) {
6407       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6408       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6409                                        LN0->getChain(),
6410                                        LN0->getBasePtr(), N0.getValueType(),
6411                                        LN0->getMemOperand());
6412       CombineTo(N, ExtLoad);
6413       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6414                                   N0.getValueType(), ExtLoad);
6415       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6416 
6417       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6418                       ISD::ZERO_EXTEND);
6419       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6420     }
6421   }
6422 
6423   // fold (zext (load x)) to multiple smaller zextloads.
6424   // Only on illegal but splittable vectors.
6425   if (SDValue ExtLoad = CombineExtLoad(N))
6426     return ExtLoad;
6427 
6428   // fold (zext (and/or/xor (load x), cst)) ->
6429   //      (and/or/xor (zextload x), (zext cst))
6430   // Unless (and (load x) cst) will match as a zextload already and has
6431   // additional users.
6432   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6433        N0.getOpcode() == ISD::XOR) &&
6434       isa<LoadSDNode>(N0.getOperand(0)) &&
6435       N0.getOperand(1).getOpcode() == ISD::Constant &&
6436       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6437       (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) {
6438     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6439     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6440       bool DoXform = true;
6441       SmallVector<SDNode*, 4> SetCCs;
6442       if (!N0.hasOneUse()) {
6443         if (N0.getOpcode() == ISD::AND) {
6444           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
6445           auto NarrowLoad = false;
6446           EVT LoadResultTy = AndC->getValueType(0);
6447           EVT ExtVT, LoadedVT;
6448           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
6449                                NarrowLoad))
6450             DoXform = false;
6451         }
6452         if (DoXform)
6453           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
6454                                             ISD::ZERO_EXTEND, SetCCs, TLI);
6455       }
6456       if (DoXform) {
6457         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6458                                          LN0->getChain(), LN0->getBasePtr(),
6459                                          LN0->getMemoryVT(),
6460                                          LN0->getMemOperand());
6461         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6462         Mask = Mask.zext(VT.getSizeInBits());
6463         SDLoc DL(N);
6464         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6465                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6466         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6467                                     SDLoc(N0.getOperand(0)),
6468                                     N0.getOperand(0).getValueType(), ExtLoad);
6469         CombineTo(N, And);
6470         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6471         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6472                         ISD::ZERO_EXTEND);
6473         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6474       }
6475     }
6476   }
6477 
6478   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6479   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6480   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6481       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6482     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6483     EVT MemVT = LN0->getMemoryVT();
6484     if ((!LegalOperations && !LN0->isVolatile()) ||
6485         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6486       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6487                                        LN0->getChain(),
6488                                        LN0->getBasePtr(), MemVT,
6489                                        LN0->getMemOperand());
6490       CombineTo(N, ExtLoad);
6491       CombineTo(N0.getNode(),
6492                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6493                             ExtLoad),
6494                 ExtLoad.getValue(1));
6495       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6496     }
6497   }
6498 
6499   if (N0.getOpcode() == ISD::SETCC) {
6500     if (!LegalOperations && VT.isVector() &&
6501         N0.getValueType().getVectorElementType() == MVT::i1) {
6502       EVT N0VT = N0.getOperand(0).getValueType();
6503       if (getSetCCResultType(N0VT) == N0.getValueType())
6504         return SDValue();
6505 
6506       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6507       // Only do this before legalize for now.
6508       SDLoc DL(N);
6509       SDValue VecOnes = DAG.getConstant(1, DL, VT);
6510       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6511         // We know that the # elements of the results is the same as the
6512         // # elements of the compare (and the # elements of the compare result
6513         // for that matter).  Check to see that they are the same size.  If so,
6514         // we know that the element size of the sext'd result matches the
6515         // element size of the compare operands.
6516         return DAG.getNode(ISD::AND, DL, VT,
6517                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6518                                          N0.getOperand(1),
6519                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6520                            VecOnes);
6521 
6522       // If the desired elements are smaller or larger than the source
6523       // elements we can use a matching integer vector type and then
6524       // truncate/sign extend
6525       EVT MatchingElementType =
6526         EVT::getIntegerVT(*DAG.getContext(),
6527                           N0VT.getScalarType().getSizeInBits());
6528       EVT MatchingVectorType =
6529         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6530                          N0VT.getVectorNumElements());
6531       SDValue VsetCC =
6532         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6533                       N0.getOperand(1),
6534                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6535       return DAG.getNode(ISD::AND, DL, VT,
6536                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6537                          VecOnes);
6538     }
6539 
6540     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6541     SDLoc DL(N);
6542     if (SDValue SCC = SimplifySelectCC(
6543             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6544             DAG.getConstant(0, DL, VT),
6545             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6546       return SCC;
6547   }
6548 
6549   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6550   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6551       isa<ConstantSDNode>(N0.getOperand(1)) &&
6552       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6553       N0.hasOneUse()) {
6554     SDValue ShAmt = N0.getOperand(1);
6555     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6556     if (N0.getOpcode() == ISD::SHL) {
6557       SDValue InnerZExt = N0.getOperand(0);
6558       // If the original shl may be shifting out bits, do not perform this
6559       // transformation.
6560       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6561         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6562       if (ShAmtVal > KnownZeroBits)
6563         return SDValue();
6564     }
6565 
6566     SDLoc DL(N);
6567 
6568     // Ensure that the shift amount is wide enough for the shifted value.
6569     if (VT.getSizeInBits() >= 256)
6570       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6571 
6572     return DAG.getNode(N0.getOpcode(), DL, VT,
6573                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6574                        ShAmt);
6575   }
6576 
6577   return SDValue();
6578 }
6579 
6580 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6581   SDValue N0 = N->getOperand(0);
6582   EVT VT = N->getValueType(0);
6583 
6584   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6585                                               LegalOperations))
6586     return SDValue(Res, 0);
6587 
6588   // fold (aext (aext x)) -> (aext x)
6589   // fold (aext (zext x)) -> (zext x)
6590   // fold (aext (sext x)) -> (sext x)
6591   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6592       N0.getOpcode() == ISD::ZERO_EXTEND ||
6593       N0.getOpcode() == ISD::SIGN_EXTEND)
6594     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6595 
6596   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6597   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6598   if (N0.getOpcode() == ISD::TRUNCATE) {
6599     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6600       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6601       if (NarrowLoad.getNode() != N0.getNode()) {
6602         CombineTo(N0.getNode(), NarrowLoad);
6603         // CombineTo deleted the truncate, if needed, but not what's under it.
6604         AddToWorklist(oye);
6605       }
6606       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6607     }
6608   }
6609 
6610   // fold (aext (truncate x))
6611   if (N0.getOpcode() == ISD::TRUNCATE) {
6612     SDValue TruncOp = N0.getOperand(0);
6613     if (TruncOp.getValueType() == VT)
6614       return TruncOp; // x iff x size == zext size.
6615     if (TruncOp.getValueType().bitsGT(VT))
6616       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6617     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6618   }
6619 
6620   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6621   // if the trunc is not free.
6622   if (N0.getOpcode() == ISD::AND &&
6623       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6624       N0.getOperand(1).getOpcode() == ISD::Constant &&
6625       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6626                           N0.getValueType())) {
6627     SDValue X = N0.getOperand(0).getOperand(0);
6628     if (X.getValueType().bitsLT(VT)) {
6629       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6630     } else if (X.getValueType().bitsGT(VT)) {
6631       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6632     }
6633     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6634     Mask = Mask.zext(VT.getSizeInBits());
6635     SDLoc DL(N);
6636     return DAG.getNode(ISD::AND, DL, VT,
6637                        X, DAG.getConstant(Mask, DL, VT));
6638   }
6639 
6640   // fold (aext (load x)) -> (aext (truncate (extload x)))
6641   // None of the supported targets knows how to perform load and any_ext
6642   // on vectors in one instruction.  We only perform this transformation on
6643   // scalars.
6644   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6645       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6646       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6647     bool DoXform = true;
6648     SmallVector<SDNode*, 4> SetCCs;
6649     if (!N0.hasOneUse())
6650       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6651     if (DoXform) {
6652       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6653       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6654                                        LN0->getChain(),
6655                                        LN0->getBasePtr(), N0.getValueType(),
6656                                        LN0->getMemOperand());
6657       CombineTo(N, ExtLoad);
6658       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6659                                   N0.getValueType(), ExtLoad);
6660       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6661       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6662                       ISD::ANY_EXTEND);
6663       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6664     }
6665   }
6666 
6667   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6668   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6669   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6670   if (N0.getOpcode() == ISD::LOAD &&
6671       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6672       N0.hasOneUse()) {
6673     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6674     ISD::LoadExtType ExtType = LN0->getExtensionType();
6675     EVT MemVT = LN0->getMemoryVT();
6676     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6677       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6678                                        VT, LN0->getChain(), LN0->getBasePtr(),
6679                                        MemVT, LN0->getMemOperand());
6680       CombineTo(N, ExtLoad);
6681       CombineTo(N0.getNode(),
6682                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6683                             N0.getValueType(), ExtLoad),
6684                 ExtLoad.getValue(1));
6685       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6686     }
6687   }
6688 
6689   if (N0.getOpcode() == ISD::SETCC) {
6690     // For vectors:
6691     // aext(setcc) -> vsetcc
6692     // aext(setcc) -> truncate(vsetcc)
6693     // aext(setcc) -> aext(vsetcc)
6694     // Only do this before legalize for now.
6695     if (VT.isVector() && !LegalOperations) {
6696       EVT N0VT = N0.getOperand(0).getValueType();
6697         // We know that the # elements of the results is the same as the
6698         // # elements of the compare (and the # elements of the compare result
6699         // for that matter).  Check to see that they are the same size.  If so,
6700         // we know that the element size of the sext'd result matches the
6701         // element size of the compare operands.
6702       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6703         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6704                              N0.getOperand(1),
6705                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6706       // If the desired elements are smaller or larger than the source
6707       // elements we can use a matching integer vector type and then
6708       // truncate/any extend
6709       else {
6710         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6711         SDValue VsetCC =
6712           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6713                         N0.getOperand(1),
6714                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6715         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6716       }
6717     }
6718 
6719     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6720     SDLoc DL(N);
6721     if (SDValue SCC = SimplifySelectCC(
6722             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
6723             DAG.getConstant(0, DL, VT),
6724             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
6725       return SCC;
6726   }
6727 
6728   return SDValue();
6729 }
6730 
6731 /// See if the specified operand can be simplified with the knowledge that only
6732 /// the bits specified by Mask are used.  If so, return the simpler operand,
6733 /// otherwise return a null SDValue.
6734 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6735   switch (V.getOpcode()) {
6736   default: break;
6737   case ISD::Constant: {
6738     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6739     assert(CV && "Const value should be ConstSDNode.");
6740     const APInt &CVal = CV->getAPIntValue();
6741     APInt NewVal = CVal & Mask;
6742     if (NewVal != CVal)
6743       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6744     break;
6745   }
6746   case ISD::OR:
6747   case ISD::XOR:
6748     // If the LHS or RHS don't contribute bits to the or, drop them.
6749     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6750       return V.getOperand(1);
6751     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6752       return V.getOperand(0);
6753     break;
6754   case ISD::SRL:
6755     // Only look at single-use SRLs.
6756     if (!V.getNode()->hasOneUse())
6757       break;
6758     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6759       // See if we can recursively simplify the LHS.
6760       unsigned Amt = RHSC->getZExtValue();
6761 
6762       // Watch out for shift count overflow though.
6763       if (Amt >= Mask.getBitWidth()) break;
6764       APInt NewMask = Mask << Amt;
6765       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6766         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6767                            SimplifyLHS, V.getOperand(1));
6768     }
6769   }
6770   return SDValue();
6771 }
6772 
6773 /// If the result of a wider load is shifted to right of N  bits and then
6774 /// truncated to a narrower type and where N is a multiple of number of bits of
6775 /// the narrower type, transform it to a narrower load from address + N / num of
6776 /// bits of new type. If the result is to be extended, also fold the extension
6777 /// to form a extending load.
6778 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6779   unsigned Opc = N->getOpcode();
6780 
6781   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6782   SDValue N0 = N->getOperand(0);
6783   EVT VT = N->getValueType(0);
6784   EVT ExtVT = VT;
6785 
6786   // This transformation isn't valid for vector loads.
6787   if (VT.isVector())
6788     return SDValue();
6789 
6790   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6791   // extended to VT.
6792   if (Opc == ISD::SIGN_EXTEND_INREG) {
6793     ExtType = ISD::SEXTLOAD;
6794     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6795   } else if (Opc == ISD::SRL) {
6796     // Another special-case: SRL is basically zero-extending a narrower value.
6797     ExtType = ISD::ZEXTLOAD;
6798     N0 = SDValue(N, 0);
6799     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6800     if (!N01) return SDValue();
6801     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6802                               VT.getSizeInBits() - N01->getZExtValue());
6803   }
6804   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6805     return SDValue();
6806 
6807   unsigned EVTBits = ExtVT.getSizeInBits();
6808 
6809   // Do not generate loads of non-round integer types since these can
6810   // be expensive (and would be wrong if the type is not byte sized).
6811   if (!ExtVT.isRound())
6812     return SDValue();
6813 
6814   unsigned ShAmt = 0;
6815   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6816     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6817       ShAmt = N01->getZExtValue();
6818       // Is the shift amount a multiple of size of VT?
6819       if ((ShAmt & (EVTBits-1)) == 0) {
6820         N0 = N0.getOperand(0);
6821         // Is the load width a multiple of size of VT?
6822         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6823           return SDValue();
6824       }
6825 
6826       // At this point, we must have a load or else we can't do the transform.
6827       if (!isa<LoadSDNode>(N0)) return SDValue();
6828 
6829       // Because a SRL must be assumed to *need* to zero-extend the high bits
6830       // (as opposed to anyext the high bits), we can't combine the zextload
6831       // lowering of SRL and an sextload.
6832       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6833         return SDValue();
6834 
6835       // If the shift amount is larger than the input type then we're not
6836       // accessing any of the loaded bytes.  If the load was a zextload/extload
6837       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6838       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6839         return SDValue();
6840     }
6841   }
6842 
6843   // If the load is shifted left (and the result isn't shifted back right),
6844   // we can fold the truncate through the shift.
6845   unsigned ShLeftAmt = 0;
6846   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6847       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6848     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6849       ShLeftAmt = N01->getZExtValue();
6850       N0 = N0.getOperand(0);
6851     }
6852   }
6853 
6854   // If we haven't found a load, we can't narrow it.  Don't transform one with
6855   // multiple uses, this would require adding a new load.
6856   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6857     return SDValue();
6858 
6859   // Don't change the width of a volatile load.
6860   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6861   if (LN0->isVolatile())
6862     return SDValue();
6863 
6864   // Verify that we are actually reducing a load width here.
6865   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6866     return SDValue();
6867 
6868   // For the transform to be legal, the load must produce only two values
6869   // (the value loaded and the chain).  Don't transform a pre-increment
6870   // load, for example, which produces an extra value.  Otherwise the
6871   // transformation is not equivalent, and the downstream logic to replace
6872   // uses gets things wrong.
6873   if (LN0->getNumValues() > 2)
6874     return SDValue();
6875 
6876   // If the load that we're shrinking is an extload and we're not just
6877   // discarding the extension we can't simply shrink the load. Bail.
6878   // TODO: It would be possible to merge the extensions in some cases.
6879   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6880       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6881     return SDValue();
6882 
6883   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6884     return SDValue();
6885 
6886   EVT PtrType = N0.getOperand(1).getValueType();
6887 
6888   if (PtrType == MVT::Untyped || PtrType.isExtended())
6889     // It's not possible to generate a constant of extended or untyped type.
6890     return SDValue();
6891 
6892   // For big endian targets, we need to adjust the offset to the pointer to
6893   // load the correct bytes.
6894   if (DAG.getDataLayout().isBigEndian()) {
6895     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6896     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6897     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6898   }
6899 
6900   uint64_t PtrOff = ShAmt / 8;
6901   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6902   SDLoc DL(LN0);
6903   // The original load itself didn't wrap, so an offset within it doesn't.
6904   SDNodeFlags Flags;
6905   Flags.setNoUnsignedWrap(true);
6906   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6907                                PtrType, LN0->getBasePtr(),
6908                                DAG.getConstant(PtrOff, DL, PtrType),
6909                                &Flags);
6910   AddToWorklist(NewPtr.getNode());
6911 
6912   SDValue Load;
6913   if (ExtType == ISD::NON_EXTLOAD)
6914     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6915                         LN0->getPointerInfo().getWithOffset(PtrOff),
6916                         LN0->isVolatile(), LN0->isNonTemporal(),
6917                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6918   else
6919     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6920                           LN0->getPointerInfo().getWithOffset(PtrOff),
6921                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6922                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6923 
6924   // Replace the old load's chain with the new load's chain.
6925   WorklistRemover DeadNodes(*this);
6926   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6927 
6928   // Shift the result left, if we've swallowed a left shift.
6929   SDValue Result = Load;
6930   if (ShLeftAmt != 0) {
6931     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6932     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6933       ShImmTy = VT;
6934     // If the shift amount is as large as the result size (but, presumably,
6935     // no larger than the source) then the useful bits of the result are
6936     // zero; we can't simply return the shortened shift, because the result
6937     // of that operation is undefined.
6938     SDLoc DL(N0);
6939     if (ShLeftAmt >= VT.getSizeInBits())
6940       Result = DAG.getConstant(0, DL, VT);
6941     else
6942       Result = DAG.getNode(ISD::SHL, DL, VT,
6943                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6944   }
6945 
6946   // Return the new loaded value.
6947   return Result;
6948 }
6949 
6950 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6951   SDValue N0 = N->getOperand(0);
6952   SDValue N1 = N->getOperand(1);
6953   EVT VT = N->getValueType(0);
6954   EVT EVT = cast<VTSDNode>(N1)->getVT();
6955   unsigned VTBits = VT.getScalarType().getSizeInBits();
6956   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6957 
6958   if (N0.isUndef())
6959     return DAG.getUNDEF(VT);
6960 
6961   // fold (sext_in_reg c1) -> c1
6962   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6963     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6964 
6965   // If the input is already sign extended, just drop the extension.
6966   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6967     return N0;
6968 
6969   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6970   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6971       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6972     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6973                        N0.getOperand(0), N1);
6974 
6975   // fold (sext_in_reg (sext x)) -> (sext x)
6976   // fold (sext_in_reg (aext x)) -> (sext x)
6977   // if x is small enough.
6978   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6979     SDValue N00 = N0.getOperand(0);
6980     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6981         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6982       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6983   }
6984 
6985   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6986   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6987     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6988 
6989   // fold operands of sext_in_reg based on knowledge that the top bits are not
6990   // demanded.
6991   if (SimplifyDemandedBits(SDValue(N, 0)))
6992     return SDValue(N, 0);
6993 
6994   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6995   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6996   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6997     return NarrowLoad;
6998 
6999   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7000   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7001   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7002   if (N0.getOpcode() == ISD::SRL) {
7003     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7004       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7005         // We can turn this into an SRA iff the input to the SRL is already sign
7006         // extended enough.
7007         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7008         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7009           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7010                              N0.getOperand(0), N0.getOperand(1));
7011       }
7012   }
7013 
7014   // fold (sext_inreg (extload x)) -> (sextload x)
7015   if (ISD::isEXTLoad(N0.getNode()) &&
7016       ISD::isUNINDEXEDLoad(N0.getNode()) &&
7017       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7018       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7019        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7020     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7021     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7022                                      LN0->getChain(),
7023                                      LN0->getBasePtr(), EVT,
7024                                      LN0->getMemOperand());
7025     CombineTo(N, ExtLoad);
7026     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7027     AddToWorklist(ExtLoad.getNode());
7028     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7029   }
7030   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7031   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7032       N0.hasOneUse() &&
7033       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7034       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7035        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7036     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7037     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7038                                      LN0->getChain(),
7039                                      LN0->getBasePtr(), EVT,
7040                                      LN0->getMemOperand());
7041     CombineTo(N, ExtLoad);
7042     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7043     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7044   }
7045 
7046   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7047   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7048     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7049                                            N0.getOperand(1), false))
7050       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7051                          BSwap, N1);
7052   }
7053 
7054   return SDValue();
7055 }
7056 
7057 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7058   SDValue N0 = N->getOperand(0);
7059   EVT VT = N->getValueType(0);
7060 
7061   if (N0.isUndef())
7062     return DAG.getUNDEF(VT);
7063 
7064   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7065                                               LegalOperations))
7066     return SDValue(Res, 0);
7067 
7068   return SDValue();
7069 }
7070 
7071 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7072   SDValue N0 = N->getOperand(0);
7073   EVT VT = N->getValueType(0);
7074 
7075   if (N0.isUndef())
7076     return DAG.getUNDEF(VT);
7077 
7078   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7079                                               LegalOperations))
7080     return SDValue(Res, 0);
7081 
7082   return SDValue();
7083 }
7084 
7085 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7086   SDValue N0 = N->getOperand(0);
7087   EVT VT = N->getValueType(0);
7088   bool isLE = DAG.getDataLayout().isLittleEndian();
7089 
7090   // noop truncate
7091   if (N0.getValueType() == N->getValueType(0))
7092     return N0;
7093   // fold (truncate c1) -> c1
7094   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7095     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
7096   // fold (truncate (truncate x)) -> (truncate x)
7097   if (N0.getOpcode() == ISD::TRUNCATE)
7098     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7099   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
7100   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
7101       N0.getOpcode() == ISD::SIGN_EXTEND ||
7102       N0.getOpcode() == ISD::ANY_EXTEND) {
7103     // if the source is smaller than the dest, we still need an extend.
7104     if (N0.getOperand(0).getValueType().bitsLT(VT))
7105       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7106     // if the source is larger than the dest, than we just need the truncate.
7107     if (N0.getOperand(0).getValueType().bitsGT(VT))
7108       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7109     // if the source and dest are the same type, we can drop both the extend
7110     // and the truncate.
7111     return N0.getOperand(0);
7112   }
7113 
7114   // Fold extract-and-trunc into a narrow extract. For example:
7115   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7116   //   i32 y = TRUNCATE(i64 x)
7117   //        -- becomes --
7118   //   v16i8 b = BITCAST (v2i64 val)
7119   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7120   //
7121   // Note: We only run this optimization after type legalization (which often
7122   // creates this pattern) and before operation legalization after which
7123   // we need to be more careful about the vector instructions that we generate.
7124   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7125       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7126 
7127     EVT VecTy = N0.getOperand(0).getValueType();
7128     EVT ExTy = N0.getValueType();
7129     EVT TrTy = N->getValueType(0);
7130 
7131     unsigned NumElem = VecTy.getVectorNumElements();
7132     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7133 
7134     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7135     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7136 
7137     SDValue EltNo = N0->getOperand(1);
7138     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7139       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7140       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7141       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7142 
7143       SDLoc DL(N);
7144       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
7145                          DAG.getBitcast(NVT, N0.getOperand(0)),
7146                          DAG.getConstant(Index, DL, IndexTy));
7147     }
7148   }
7149 
7150   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7151   if (N0.getOpcode() == ISD::SELECT) {
7152     EVT SrcVT = N0.getValueType();
7153     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7154         TLI.isTruncateFree(SrcVT, VT)) {
7155       SDLoc SL(N0);
7156       SDValue Cond = N0.getOperand(0);
7157       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7158       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7159       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7160     }
7161   }
7162 
7163   // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2
7164   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7165       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
7166       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
7167     if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
7168       uint64_t Amt = CAmt->getZExtValue();
7169       unsigned Size = VT.getSizeInBits();
7170 
7171       if (Amt < Size / 2) {
7172         SDLoc SL(N);
7173         EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
7174 
7175         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
7176         return DAG.getNode(ISD::SHL, SL, VT, Trunc,
7177                            DAG.getConstant(Amt, SL, AmtVT));
7178       }
7179     }
7180   }
7181 
7182   // Fold a series of buildvector, bitcast, and truncate if possible.
7183   // For example fold
7184   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7185   //   (2xi32 (buildvector x, y)).
7186   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7187       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7188       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7189       N0.getOperand(0).hasOneUse()) {
7190 
7191     SDValue BuildVect = N0.getOperand(0);
7192     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7193     EVT TruncVecEltTy = VT.getVectorElementType();
7194 
7195     // Check that the element types match.
7196     if (BuildVectEltTy == TruncVecEltTy) {
7197       // Now we only need to compute the offset of the truncated elements.
7198       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7199       unsigned TruncVecNumElts = VT.getVectorNumElements();
7200       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7201 
7202       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7203              "Invalid number of elements");
7204 
7205       SmallVector<SDValue, 8> Opnds;
7206       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7207         Opnds.push_back(BuildVect.getOperand(i));
7208 
7209       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
7210     }
7211   }
7212 
7213   // See if we can simplify the input to this truncate through knowledge that
7214   // only the low bits are being used.
7215   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7216   // Currently we only perform this optimization on scalars because vectors
7217   // may have different active low bits.
7218   if (!VT.isVector()) {
7219     if (SDValue Shorter =
7220             GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7221                                                      VT.getSizeInBits())))
7222       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7223   }
7224   // fold (truncate (load x)) -> (smaller load x)
7225   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7226   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7227     if (SDValue Reduced = ReduceLoadWidth(N))
7228       return Reduced;
7229 
7230     // Handle the case where the load remains an extending load even
7231     // after truncation.
7232     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7233       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7234       if (!LN0->isVolatile() &&
7235           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7236         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7237                                          VT, LN0->getChain(), LN0->getBasePtr(),
7238                                          LN0->getMemoryVT(),
7239                                          LN0->getMemOperand());
7240         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7241         return NewLoad;
7242       }
7243     }
7244   }
7245   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7246   // where ... are all 'undef'.
7247   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7248     SmallVector<EVT, 8> VTs;
7249     SDValue V;
7250     unsigned Idx = 0;
7251     unsigned NumDefs = 0;
7252 
7253     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7254       SDValue X = N0.getOperand(i);
7255       if (!X.isUndef()) {
7256         V = X;
7257         Idx = i;
7258         NumDefs++;
7259       }
7260       // Stop if more than one members are non-undef.
7261       if (NumDefs > 1)
7262         break;
7263       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7264                                      VT.getVectorElementType(),
7265                                      X.getValueType().getVectorNumElements()));
7266     }
7267 
7268     if (NumDefs == 0)
7269       return DAG.getUNDEF(VT);
7270 
7271     if (NumDefs == 1) {
7272       assert(V.getNode() && "The single defined operand is empty!");
7273       SmallVector<SDValue, 8> Opnds;
7274       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7275         if (i != Idx) {
7276           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7277           continue;
7278         }
7279         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7280         AddToWorklist(NV.getNode());
7281         Opnds.push_back(NV);
7282       }
7283       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7284     }
7285   }
7286 
7287   // Fold truncate of a bitcast of a vector to an extract of the low vector
7288   // element.
7289   //
7290   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
7291   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
7292     SDValue VecSrc = N0.getOperand(0);
7293     EVT SrcVT = VecSrc.getValueType();
7294     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
7295         (!LegalOperations ||
7296          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
7297       SDLoc SL(N);
7298 
7299       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
7300       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
7301                          VecSrc, DAG.getConstant(0, SL, IdxVT));
7302     }
7303   }
7304 
7305   // Simplify the operands using demanded-bits information.
7306   if (!VT.isVector() &&
7307       SimplifyDemandedBits(SDValue(N, 0)))
7308     return SDValue(N, 0);
7309 
7310   return SDValue();
7311 }
7312 
7313 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7314   SDValue Elt = N->getOperand(i);
7315   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7316     return Elt.getNode();
7317   return Elt.getOperand(Elt.getResNo()).getNode();
7318 }
7319 
7320 /// build_pair (load, load) -> load
7321 /// if load locations are consecutive.
7322 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7323   assert(N->getOpcode() == ISD::BUILD_PAIR);
7324 
7325   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7326   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7327   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7328       LD1->getAddressSpace() != LD2->getAddressSpace())
7329     return SDValue();
7330   EVT LD1VT = LD1->getValueType(0);
7331   unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
7332   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
7333       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
7334     unsigned Align = LD1->getAlignment();
7335     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7336         VT.getTypeForEVT(*DAG.getContext()));
7337 
7338     if (NewAlign <= Align &&
7339         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7340       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7341                          LD1->getBasePtr(), LD1->getPointerInfo(),
7342                          false, false, false, Align);
7343   }
7344 
7345   return SDValue();
7346 }
7347 
7348 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
7349   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
7350   // and Lo parts; on big-endian machines it doesn't.
7351   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
7352 }
7353 
7354 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
7355                                     const TargetLowering &TLI) {
7356   // If this is not a bitcast to an FP type or if the target doesn't have
7357   // IEEE754-compliant FP logic, we're done.
7358   EVT VT = N->getValueType(0);
7359   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
7360     return SDValue();
7361 
7362   // TODO: Use splat values for the constant-checking below and remove this
7363   // restriction.
7364   SDValue N0 = N->getOperand(0);
7365   EVT SourceVT = N0.getValueType();
7366   if (SourceVT.isVector())
7367     return SDValue();
7368 
7369   unsigned FPOpcode;
7370   APInt SignMask;
7371   switch (N0.getOpcode()) {
7372   case ISD::AND:
7373     FPOpcode = ISD::FABS;
7374     SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
7375     break;
7376   case ISD::XOR:
7377     FPOpcode = ISD::FNEG;
7378     SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
7379     break;
7380   // TODO: ISD::OR --> ISD::FNABS?
7381   default:
7382     return SDValue();
7383   }
7384 
7385   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
7386   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
7387   SDValue LogicOp0 = N0.getOperand(0);
7388   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7389   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
7390       LogicOp0.getOpcode() == ISD::BITCAST &&
7391       LogicOp0->getOperand(0).getValueType() == VT)
7392     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
7393 
7394   return SDValue();
7395 }
7396 
7397 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7398   SDValue N0 = N->getOperand(0);
7399   EVT VT = N->getValueType(0);
7400 
7401   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7402   // Only do this before legalize, since afterward the target may be depending
7403   // on the bitconvert.
7404   // First check to see if this is all constant.
7405   if (!LegalTypes &&
7406       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7407       VT.isVector()) {
7408     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7409 
7410     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7411     assert(!DestEltVT.isVector() &&
7412            "Element type of vector ValueType must not be vector!");
7413     if (isSimple)
7414       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7415   }
7416 
7417   // If the input is a constant, let getNode fold it.
7418   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7419     // If we can't allow illegal operations, we need to check that this is just
7420     // a fp -> int or int -> conversion and that the resulting operation will
7421     // be legal.
7422     if (!LegalOperations ||
7423         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7424          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7425         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7426          TLI.isOperationLegal(ISD::Constant, VT)))
7427       return DAG.getBitcast(VT, N0);
7428   }
7429 
7430   // (conv (conv x, t1), t2) -> (conv x, t2)
7431   if (N0.getOpcode() == ISD::BITCAST)
7432     return DAG.getBitcast(VT, N0.getOperand(0));
7433 
7434   // fold (conv (load x)) -> (load (conv*)x)
7435   // If the resultant load doesn't need a higher alignment than the original!
7436   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7437       // Do not change the width of a volatile load.
7438       !cast<LoadSDNode>(N0)->isVolatile() &&
7439       // Do not remove the cast if the types differ in endian layout.
7440       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7441           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7442       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7443       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7444     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7445     unsigned OrigAlign = LN0->getAlignment();
7446 
7447     bool Fast = false;
7448     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7449                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
7450         Fast) {
7451       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7452                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7453                                  LN0->isVolatile(), LN0->isNonTemporal(),
7454                                  LN0->isInvariant(), OrigAlign,
7455                                  LN0->getAAInfo());
7456       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7457       return Load;
7458     }
7459   }
7460 
7461   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
7462     return V;
7463 
7464   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7465   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7466   //
7467   // For ppc_fp128:
7468   // fold (bitcast (fneg x)) ->
7469   //     flipbit = signbit
7470   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7471   //
7472   // fold (bitcast (fabs x)) ->
7473   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
7474   //     (xor (bitcast x) (build_pair flipbit, flipbit))
7475   // This often reduces constant pool loads.
7476   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7477        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7478       N0.getNode()->hasOneUse() && VT.isInteger() &&
7479       !VT.isVector() && !N0.getValueType().isVector()) {
7480     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
7481     AddToWorklist(NewConv.getNode());
7482 
7483     SDLoc DL(N);
7484     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7485       assert(VT.getSizeInBits() == 128);
7486       SDValue SignBit = DAG.getConstant(
7487           APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
7488       SDValue FlipBit;
7489       if (N0.getOpcode() == ISD::FNEG) {
7490         FlipBit = SignBit;
7491         AddToWorklist(FlipBit.getNode());
7492       } else {
7493         assert(N0.getOpcode() == ISD::FABS);
7494         SDValue Hi =
7495             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
7496                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7497                                               SDLoc(NewConv)));
7498         AddToWorklist(Hi.getNode());
7499         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
7500         AddToWorklist(FlipBit.getNode());
7501       }
7502       SDValue FlipBits =
7503           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7504       AddToWorklist(FlipBits.getNode());
7505       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
7506     }
7507     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7508     if (N0.getOpcode() == ISD::FNEG)
7509       return DAG.getNode(ISD::XOR, DL, VT,
7510                          NewConv, DAG.getConstant(SignBit, DL, VT));
7511     assert(N0.getOpcode() == ISD::FABS);
7512     return DAG.getNode(ISD::AND, DL, VT,
7513                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7514   }
7515 
7516   // fold (bitconvert (fcopysign cst, x)) ->
7517   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7518   // Note that we don't handle (copysign x, cst) because this can always be
7519   // folded to an fneg or fabs.
7520   //
7521   // For ppc_fp128:
7522   // fold (bitcast (fcopysign cst, x)) ->
7523   //     flipbit = (and (extract_element
7524   //                     (xor (bitcast cst), (bitcast x)), 0),
7525   //                    signbit)
7526   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
7527   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7528       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7529       VT.isInteger() && !VT.isVector()) {
7530     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7531     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7532     if (isTypeLegal(IntXVT)) {
7533       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
7534       AddToWorklist(X.getNode());
7535 
7536       // If X has a different width than the result/lhs, sext it or truncate it.
7537       unsigned VTWidth = VT.getSizeInBits();
7538       if (OrigXWidth < VTWidth) {
7539         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7540         AddToWorklist(X.getNode());
7541       } else if (OrigXWidth > VTWidth) {
7542         // To get the sign bit in the right place, we have to shift it right
7543         // before truncating.
7544         SDLoc DL(X);
7545         X = DAG.getNode(ISD::SRL, DL,
7546                         X.getValueType(), X,
7547                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7548                                         X.getValueType()));
7549         AddToWorklist(X.getNode());
7550         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7551         AddToWorklist(X.getNode());
7552       }
7553 
7554       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
7555         APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
7556         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7557         AddToWorklist(Cst.getNode());
7558         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
7559         AddToWorklist(X.getNode());
7560         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
7561         AddToWorklist(XorResult.getNode());
7562         SDValue XorResult64 = DAG.getNode(
7563             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
7564             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
7565                                   SDLoc(XorResult)));
7566         AddToWorklist(XorResult64.getNode());
7567         SDValue FlipBit =
7568             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
7569                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
7570         AddToWorklist(FlipBit.getNode());
7571         SDValue FlipBits =
7572             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
7573         AddToWorklist(FlipBits.getNode());
7574         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
7575       }
7576       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7577       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7578                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7579       AddToWorklist(X.getNode());
7580 
7581       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
7582       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7583                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7584       AddToWorklist(Cst.getNode());
7585 
7586       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7587     }
7588   }
7589 
7590   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7591   if (N0.getOpcode() == ISD::BUILD_PAIR)
7592     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7593       return CombineLD;
7594 
7595   // Remove double bitcasts from shuffles - this is often a legacy of
7596   // XformToShuffleWithZero being used to combine bitmaskings (of
7597   // float vectors bitcast to integer vectors) into shuffles.
7598   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7599   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7600       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7601       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7602       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7603     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7604 
7605     // If operands are a bitcast, peek through if it casts the original VT.
7606     // If operands are a constant, just bitcast back to original VT.
7607     auto PeekThroughBitcast = [&](SDValue Op) {
7608       if (Op.getOpcode() == ISD::BITCAST &&
7609           Op.getOperand(0).getValueType() == VT)
7610         return SDValue(Op.getOperand(0));
7611       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7612           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7613         return DAG.getBitcast(VT, Op);
7614       return SDValue();
7615     };
7616 
7617     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7618     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7619     if (!(SV0 && SV1))
7620       return SDValue();
7621 
7622     int MaskScale =
7623         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7624     SmallVector<int, 8> NewMask;
7625     for (int M : SVN->getMask())
7626       for (int i = 0; i != MaskScale; ++i)
7627         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7628 
7629     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7630     if (!LegalMask) {
7631       std::swap(SV0, SV1);
7632       ShuffleVectorSDNode::commuteMask(NewMask);
7633       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7634     }
7635 
7636     if (LegalMask)
7637       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7638   }
7639 
7640   return SDValue();
7641 }
7642 
7643 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7644   EVT VT = N->getValueType(0);
7645   return CombineConsecutiveLoads(N, VT);
7646 }
7647 
7648 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7649 /// operands. DstEltVT indicates the destination element value type.
7650 SDValue DAGCombiner::
7651 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7652   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7653 
7654   // If this is already the right type, we're done.
7655   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7656 
7657   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7658   unsigned DstBitSize = DstEltVT.getSizeInBits();
7659 
7660   // If this is a conversion of N elements of one type to N elements of another
7661   // type, convert each element.  This handles FP<->INT cases.
7662   if (SrcBitSize == DstBitSize) {
7663     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7664                               BV->getValueType(0).getVectorNumElements());
7665 
7666     // Due to the FP element handling below calling this routine recursively,
7667     // we can end up with a scalar-to-vector node here.
7668     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7669       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7670                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
7671 
7672     SmallVector<SDValue, 8> Ops;
7673     for (SDValue Op : BV->op_values()) {
7674       // If the vector element type is not legal, the BUILD_VECTOR operands
7675       // are promoted and implicitly truncated.  Make that explicit here.
7676       if (Op.getValueType() != SrcEltVT)
7677         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7678       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
7679       AddToWorklist(Ops.back().getNode());
7680     }
7681     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
7682   }
7683 
7684   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7685   // handle annoying details of growing/shrinking FP values, we convert them to
7686   // int first.
7687   if (SrcEltVT.isFloatingPoint()) {
7688     // Convert the input float vector to a int vector where the elements are the
7689     // same sizes.
7690     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7691     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7692     SrcEltVT = IntVT;
7693   }
7694 
7695   // Now we know the input is an integer vector.  If the output is a FP type,
7696   // convert to integer first, then to FP of the right size.
7697   if (DstEltVT.isFloatingPoint()) {
7698     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7699     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7700 
7701     // Next, convert to FP elements of the same size.
7702     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7703   }
7704 
7705   SDLoc DL(BV);
7706 
7707   // Okay, we know the src/dst types are both integers of differing types.
7708   // Handling growing first.
7709   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7710   if (SrcBitSize < DstBitSize) {
7711     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7712 
7713     SmallVector<SDValue, 8> Ops;
7714     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7715          i += NumInputsPerOutput) {
7716       bool isLE = DAG.getDataLayout().isLittleEndian();
7717       APInt NewBits = APInt(DstBitSize, 0);
7718       bool EltIsUndef = true;
7719       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7720         // Shift the previously computed bits over.
7721         NewBits <<= SrcBitSize;
7722         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7723         if (Op.isUndef()) continue;
7724         EltIsUndef = false;
7725 
7726         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7727                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7728       }
7729 
7730       if (EltIsUndef)
7731         Ops.push_back(DAG.getUNDEF(DstEltVT));
7732       else
7733         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7734     }
7735 
7736     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7737     return DAG.getBuildVector(VT, DL, Ops);
7738   }
7739 
7740   // Finally, this must be the case where we are shrinking elements: each input
7741   // turns into multiple outputs.
7742   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7743   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7744                             NumOutputsPerInput*BV->getNumOperands());
7745   SmallVector<SDValue, 8> Ops;
7746 
7747   for (const SDValue &Op : BV->op_values()) {
7748     if (Op.isUndef()) {
7749       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7750       continue;
7751     }
7752 
7753     APInt OpVal = cast<ConstantSDNode>(Op)->
7754                   getAPIntValue().zextOrTrunc(SrcBitSize);
7755 
7756     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7757       APInt ThisVal = OpVal.trunc(DstBitSize);
7758       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7759       OpVal = OpVal.lshr(DstBitSize);
7760     }
7761 
7762     // For big endian targets, swap the order of the pieces of each element.
7763     if (DAG.getDataLayout().isBigEndian())
7764       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7765   }
7766 
7767   return DAG.getBuildVector(VT, DL, Ops);
7768 }
7769 
7770 /// Try to perform FMA combining on a given FADD node.
7771 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7772   SDValue N0 = N->getOperand(0);
7773   SDValue N1 = N->getOperand(1);
7774   EVT VT = N->getValueType(0);
7775   SDLoc SL(N);
7776 
7777   const TargetOptions &Options = DAG.getTarget().Options;
7778   bool AllowFusion =
7779       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7780 
7781   // Floating-point multiply-add with intermediate rounding.
7782   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7783 
7784   // Floating-point multiply-add without intermediate rounding.
7785   bool HasFMA =
7786       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7787       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7788 
7789   // No valid opcode, do not combine.
7790   if (!HasFMAD && !HasFMA)
7791     return SDValue();
7792 
7793   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7794   ;
7795   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7796     return SDValue();
7797 
7798   // Always prefer FMAD to FMA for precision.
7799   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7800   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7801   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7802 
7803   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7804   // prefer to fold the multiply with fewer uses.
7805   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7806       N1.getOpcode() == ISD::FMUL) {
7807     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7808       std::swap(N0, N1);
7809   }
7810 
7811   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7812   if (N0.getOpcode() == ISD::FMUL &&
7813       (Aggressive || N0->hasOneUse())) {
7814     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7815                        N0.getOperand(0), N0.getOperand(1), N1);
7816   }
7817 
7818   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7819   // Note: Commutes FADD operands.
7820   if (N1.getOpcode() == ISD::FMUL &&
7821       (Aggressive || N1->hasOneUse())) {
7822     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7823                        N1.getOperand(0), N1.getOperand(1), N0);
7824   }
7825 
7826   // Look through FP_EXTEND nodes to do more combining.
7827   if (AllowFusion && LookThroughFPExt) {
7828     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7829     if (N0.getOpcode() == ISD::FP_EXTEND) {
7830       SDValue N00 = N0.getOperand(0);
7831       if (N00.getOpcode() == ISD::FMUL)
7832         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7833                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7834                                        N00.getOperand(0)),
7835                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7836                                        N00.getOperand(1)), N1);
7837     }
7838 
7839     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7840     // Note: Commutes FADD operands.
7841     if (N1.getOpcode() == ISD::FP_EXTEND) {
7842       SDValue N10 = N1.getOperand(0);
7843       if (N10.getOpcode() == ISD::FMUL)
7844         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7845                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7846                                        N10.getOperand(0)),
7847                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7848                                        N10.getOperand(1)), N0);
7849     }
7850   }
7851 
7852   // More folding opportunities when target permits.
7853   if ((AllowFusion || HasFMAD)  && Aggressive) {
7854     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7855     if (N0.getOpcode() == PreferredFusedOpcode &&
7856         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7857       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7858                          N0.getOperand(0), N0.getOperand(1),
7859                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7860                                      N0.getOperand(2).getOperand(0),
7861                                      N0.getOperand(2).getOperand(1),
7862                                      N1));
7863     }
7864 
7865     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7866     if (N1->getOpcode() == PreferredFusedOpcode &&
7867         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7868       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                          N1.getOperand(0), N1.getOperand(1),
7870                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7871                                      N1.getOperand(2).getOperand(0),
7872                                      N1.getOperand(2).getOperand(1),
7873                                      N0));
7874     }
7875 
7876     if (AllowFusion && LookThroughFPExt) {
7877       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7878       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7879       auto FoldFAddFMAFPExtFMul = [&] (
7880           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7881         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7882                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7883                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7884                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7885                                        Z));
7886       };
7887       if (N0.getOpcode() == PreferredFusedOpcode) {
7888         SDValue N02 = N0.getOperand(2);
7889         if (N02.getOpcode() == ISD::FP_EXTEND) {
7890           SDValue N020 = N02.getOperand(0);
7891           if (N020.getOpcode() == ISD::FMUL)
7892             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7893                                         N020.getOperand(0), N020.getOperand(1),
7894                                         N1);
7895         }
7896       }
7897 
7898       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7899       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7900       // FIXME: This turns two single-precision and one double-precision
7901       // operation into two double-precision operations, which might not be
7902       // interesting for all targets, especially GPUs.
7903       auto FoldFAddFPExtFMAFMul = [&] (
7904           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7905         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7906                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7907                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7908                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7909                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7910                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7911                                        Z));
7912       };
7913       if (N0.getOpcode() == ISD::FP_EXTEND) {
7914         SDValue N00 = N0.getOperand(0);
7915         if (N00.getOpcode() == PreferredFusedOpcode) {
7916           SDValue N002 = N00.getOperand(2);
7917           if (N002.getOpcode() == ISD::FMUL)
7918             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7919                                         N002.getOperand(0), N002.getOperand(1),
7920                                         N1);
7921         }
7922       }
7923 
7924       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7925       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7926       if (N1.getOpcode() == PreferredFusedOpcode) {
7927         SDValue N12 = N1.getOperand(2);
7928         if (N12.getOpcode() == ISD::FP_EXTEND) {
7929           SDValue N120 = N12.getOperand(0);
7930           if (N120.getOpcode() == ISD::FMUL)
7931             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7932                                         N120.getOperand(0), N120.getOperand(1),
7933                                         N0);
7934         }
7935       }
7936 
7937       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7938       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7939       // FIXME: This turns two single-precision and one double-precision
7940       // operation into two double-precision operations, which might not be
7941       // interesting for all targets, especially GPUs.
7942       if (N1.getOpcode() == ISD::FP_EXTEND) {
7943         SDValue N10 = N1.getOperand(0);
7944         if (N10.getOpcode() == PreferredFusedOpcode) {
7945           SDValue N102 = N10.getOperand(2);
7946           if (N102.getOpcode() == ISD::FMUL)
7947             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7948                                         N102.getOperand(0), N102.getOperand(1),
7949                                         N0);
7950         }
7951       }
7952     }
7953   }
7954 
7955   return SDValue();
7956 }
7957 
7958 /// Try to perform FMA combining on a given FSUB node.
7959 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7960   SDValue N0 = N->getOperand(0);
7961   SDValue N1 = N->getOperand(1);
7962   EVT VT = N->getValueType(0);
7963   SDLoc SL(N);
7964 
7965   const TargetOptions &Options = DAG.getTarget().Options;
7966   bool AllowFusion =
7967       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7968 
7969   // Floating-point multiply-add with intermediate rounding.
7970   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7971 
7972   // Floating-point multiply-add without intermediate rounding.
7973   bool HasFMA =
7974       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7975       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7976 
7977   // No valid opcode, do not combine.
7978   if (!HasFMAD && !HasFMA)
7979     return SDValue();
7980 
7981   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
7982   if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel))
7983     return SDValue();
7984 
7985   // Always prefer FMAD to FMA for precision.
7986   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7987   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7988   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7989 
7990   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7991   if (N0.getOpcode() == ISD::FMUL &&
7992       (Aggressive || N0->hasOneUse())) {
7993     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7994                        N0.getOperand(0), N0.getOperand(1),
7995                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7996   }
7997 
7998   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7999   // Note: Commutes FSUB operands.
8000   if (N1.getOpcode() == ISD::FMUL &&
8001       (Aggressive || N1->hasOneUse()))
8002     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8003                        DAG.getNode(ISD::FNEG, SL, VT,
8004                                    N1.getOperand(0)),
8005                        N1.getOperand(1), N0);
8006 
8007   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8008   if (N0.getOpcode() == ISD::FNEG &&
8009       N0.getOperand(0).getOpcode() == ISD::FMUL &&
8010       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8011     SDValue N00 = N0.getOperand(0).getOperand(0);
8012     SDValue N01 = N0.getOperand(0).getOperand(1);
8013     return DAG.getNode(PreferredFusedOpcode, SL, VT,
8014                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8015                        DAG.getNode(ISD::FNEG, SL, VT, N1));
8016   }
8017 
8018   // Look through FP_EXTEND nodes to do more combining.
8019   if (AllowFusion && LookThroughFPExt) {
8020     // fold (fsub (fpext (fmul x, y)), z)
8021     //   -> (fma (fpext x), (fpext y), (fneg z))
8022     if (N0.getOpcode() == ISD::FP_EXTEND) {
8023       SDValue N00 = N0.getOperand(0);
8024       if (N00.getOpcode() == ISD::FMUL)
8025         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8026                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8027                                        N00.getOperand(0)),
8028                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8029                                        N00.getOperand(1)),
8030                            DAG.getNode(ISD::FNEG, SL, VT, N1));
8031     }
8032 
8033     // fold (fsub x, (fpext (fmul y, z)))
8034     //   -> (fma (fneg (fpext y)), (fpext z), x)
8035     // Note: Commutes FSUB operands.
8036     if (N1.getOpcode() == ISD::FP_EXTEND) {
8037       SDValue N10 = N1.getOperand(0);
8038       if (N10.getOpcode() == ISD::FMUL)
8039         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8040                            DAG.getNode(ISD::FNEG, SL, VT,
8041                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
8042                                                    N10.getOperand(0))),
8043                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8044                                        N10.getOperand(1)),
8045                            N0);
8046     }
8047 
8048     // fold (fsub (fpext (fneg (fmul, x, y))), z)
8049     //   -> (fneg (fma (fpext x), (fpext y), z))
8050     // Note: This could be removed with appropriate canonicalization of the
8051     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8052     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8053     // from implementing the canonicalization in visitFSUB.
8054     if (N0.getOpcode() == ISD::FP_EXTEND) {
8055       SDValue N00 = N0.getOperand(0);
8056       if (N00.getOpcode() == ISD::FNEG) {
8057         SDValue N000 = N00.getOperand(0);
8058         if (N000.getOpcode() == ISD::FMUL) {
8059           return DAG.getNode(ISD::FNEG, SL, VT,
8060                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8061                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8062                                                      N000.getOperand(0)),
8063                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8064                                                      N000.getOperand(1)),
8065                                          N1));
8066         }
8067       }
8068     }
8069 
8070     // fold (fsub (fneg (fpext (fmul, x, y))), z)
8071     //   -> (fneg (fma (fpext x)), (fpext y), z)
8072     // Note: This could be removed with appropriate canonicalization of the
8073     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
8074     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
8075     // from implementing the canonicalization in visitFSUB.
8076     if (N0.getOpcode() == ISD::FNEG) {
8077       SDValue N00 = N0.getOperand(0);
8078       if (N00.getOpcode() == ISD::FP_EXTEND) {
8079         SDValue N000 = N00.getOperand(0);
8080         if (N000.getOpcode() == ISD::FMUL) {
8081           return DAG.getNode(ISD::FNEG, SL, VT,
8082                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8083                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8084                                                      N000.getOperand(0)),
8085                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8086                                                      N000.getOperand(1)),
8087                                          N1));
8088         }
8089       }
8090     }
8091 
8092   }
8093 
8094   // More folding opportunities when target permits.
8095   if ((AllowFusion || HasFMAD) && Aggressive) {
8096     // fold (fsub (fma x, y, (fmul u, v)), z)
8097     //   -> (fma x, y (fma u, v, (fneg z)))
8098     if (N0.getOpcode() == PreferredFusedOpcode &&
8099         N0.getOperand(2).getOpcode() == ISD::FMUL) {
8100       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8101                          N0.getOperand(0), N0.getOperand(1),
8102                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8103                                      N0.getOperand(2).getOperand(0),
8104                                      N0.getOperand(2).getOperand(1),
8105                                      DAG.getNode(ISD::FNEG, SL, VT,
8106                                                  N1)));
8107     }
8108 
8109     // fold (fsub x, (fma y, z, (fmul u, v)))
8110     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
8111     if (N1.getOpcode() == PreferredFusedOpcode &&
8112         N1.getOperand(2).getOpcode() == ISD::FMUL) {
8113       SDValue N20 = N1.getOperand(2).getOperand(0);
8114       SDValue N21 = N1.getOperand(2).getOperand(1);
8115       return DAG.getNode(PreferredFusedOpcode, SL, VT,
8116                          DAG.getNode(ISD::FNEG, SL, VT,
8117                                      N1.getOperand(0)),
8118                          N1.getOperand(1),
8119                          DAG.getNode(PreferredFusedOpcode, SL, VT,
8120                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
8121 
8122                                      N21, N0));
8123     }
8124 
8125     if (AllowFusion && LookThroughFPExt) {
8126       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
8127       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
8128       if (N0.getOpcode() == PreferredFusedOpcode) {
8129         SDValue N02 = N0.getOperand(2);
8130         if (N02.getOpcode() == ISD::FP_EXTEND) {
8131           SDValue N020 = N02.getOperand(0);
8132           if (N020.getOpcode() == ISD::FMUL)
8133             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8134                                N0.getOperand(0), N0.getOperand(1),
8135                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8136                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8137                                                        N020.getOperand(0)),
8138                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8139                                                        N020.getOperand(1)),
8140                                            DAG.getNode(ISD::FNEG, SL, VT,
8141                                                        N1)));
8142         }
8143       }
8144 
8145       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
8146       //   -> (fma (fpext x), (fpext y),
8147       //           (fma (fpext u), (fpext v), (fneg z)))
8148       // FIXME: This turns two single-precision and one double-precision
8149       // operation into two double-precision operations, which might not be
8150       // interesting for all targets, especially GPUs.
8151       if (N0.getOpcode() == ISD::FP_EXTEND) {
8152         SDValue N00 = N0.getOperand(0);
8153         if (N00.getOpcode() == PreferredFusedOpcode) {
8154           SDValue N002 = N00.getOperand(2);
8155           if (N002.getOpcode() == ISD::FMUL)
8156             return DAG.getNode(PreferredFusedOpcode, SL, VT,
8157                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8158                                            N00.getOperand(0)),
8159                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
8160                                            N00.getOperand(1)),
8161                                DAG.getNode(PreferredFusedOpcode, SL, VT,
8162                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8163                                                        N002.getOperand(0)),
8164                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
8165                                                        N002.getOperand(1)),
8166                                            DAG.getNode(ISD::FNEG, SL, VT,
8167                                                        N1)));
8168         }
8169       }
8170 
8171       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
8172       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
8173       if (N1.getOpcode() == PreferredFusedOpcode &&
8174         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
8175         SDValue N120 = N1.getOperand(2).getOperand(0);
8176         if (N120.getOpcode() == ISD::FMUL) {
8177           SDValue N1200 = N120.getOperand(0);
8178           SDValue N1201 = N120.getOperand(1);
8179           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8180                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
8181                              N1.getOperand(1),
8182                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8183                                          DAG.getNode(ISD::FNEG, SL, VT,
8184                                              DAG.getNode(ISD::FP_EXTEND, SL,
8185                                                          VT, N1200)),
8186                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8187                                                      N1201),
8188                                          N0));
8189         }
8190       }
8191 
8192       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
8193       //   -> (fma (fneg (fpext y)), (fpext z),
8194       //           (fma (fneg (fpext u)), (fpext v), x))
8195       // FIXME: This turns two single-precision and one double-precision
8196       // operation into two double-precision operations, which might not be
8197       // interesting for all targets, especially GPUs.
8198       if (N1.getOpcode() == ISD::FP_EXTEND &&
8199         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
8200         SDValue N100 = N1.getOperand(0).getOperand(0);
8201         SDValue N101 = N1.getOperand(0).getOperand(1);
8202         SDValue N102 = N1.getOperand(0).getOperand(2);
8203         if (N102.getOpcode() == ISD::FMUL) {
8204           SDValue N1020 = N102.getOperand(0);
8205           SDValue N1021 = N102.getOperand(1);
8206           return DAG.getNode(PreferredFusedOpcode, SL, VT,
8207                              DAG.getNode(ISD::FNEG, SL, VT,
8208                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8209                                                      N100)),
8210                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
8211                              DAG.getNode(PreferredFusedOpcode, SL, VT,
8212                                          DAG.getNode(ISD::FNEG, SL, VT,
8213                                              DAG.getNode(ISD::FP_EXTEND, SL,
8214                                                          VT, N1020)),
8215                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
8216                                                      N1021),
8217                                          N0));
8218         }
8219       }
8220     }
8221   }
8222 
8223   return SDValue();
8224 }
8225 
8226 /// Try to perform FMA combining on a given FMUL node.
8227 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
8228   SDValue N0 = N->getOperand(0);
8229   SDValue N1 = N->getOperand(1);
8230   EVT VT = N->getValueType(0);
8231   SDLoc SL(N);
8232 
8233   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
8234 
8235   const TargetOptions &Options = DAG.getTarget().Options;
8236   bool AllowFusion =
8237       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8238 
8239   // Floating-point multiply-add with intermediate rounding.
8240   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8241 
8242   // Floating-point multiply-add without intermediate rounding.
8243   bool HasFMA =
8244       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8245       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8246 
8247   // No valid opcode, do not combine.
8248   if (!HasFMAD && !HasFMA)
8249     return SDValue();
8250 
8251   // Always prefer FMAD to FMA for precision.
8252   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8253   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8254 
8255   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8256   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8257   auto FuseFADD = [&](SDValue X, SDValue Y) {
8258     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8259       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8260       if (XC1 && XC1->isExactlyValue(+1.0))
8261         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8262       if (XC1 && XC1->isExactlyValue(-1.0))
8263         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8264                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8265     }
8266     return SDValue();
8267   };
8268 
8269   if (SDValue FMA = FuseFADD(N0, N1))
8270     return FMA;
8271   if (SDValue FMA = FuseFADD(N1, N0))
8272     return FMA;
8273 
8274   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8275   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8276   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8277   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8278   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8279     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8280       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8281       if (XC0 && XC0->isExactlyValue(+1.0))
8282         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8283                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8284                            Y);
8285       if (XC0 && XC0->isExactlyValue(-1.0))
8286         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8287                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8288                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8289 
8290       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8291       if (XC1 && XC1->isExactlyValue(+1.0))
8292         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8293                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8294       if (XC1 && XC1->isExactlyValue(-1.0))
8295         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8296     }
8297     return SDValue();
8298   };
8299 
8300   if (SDValue FMA = FuseFSUB(N0, N1))
8301     return FMA;
8302   if (SDValue FMA = FuseFSUB(N1, N0))
8303     return FMA;
8304 
8305   return SDValue();
8306 }
8307 
8308 SDValue DAGCombiner::visitFADD(SDNode *N) {
8309   SDValue N0 = N->getOperand(0);
8310   SDValue N1 = N->getOperand(1);
8311   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8312   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8313   EVT VT = N->getValueType(0);
8314   SDLoc DL(N);
8315   const TargetOptions &Options = DAG.getTarget().Options;
8316   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8317 
8318   // fold vector ops
8319   if (VT.isVector())
8320     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8321       return FoldedVOp;
8322 
8323   // fold (fadd c1, c2) -> c1 + c2
8324   if (N0CFP && N1CFP)
8325     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8326 
8327   // canonicalize constant to RHS
8328   if (N0CFP && !N1CFP)
8329     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8330 
8331   // fold (fadd A, (fneg B)) -> (fsub A, B)
8332   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8333       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8334     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8335                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8336 
8337   // fold (fadd (fneg A), B) -> (fsub B, A)
8338   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8339       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8340     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8341                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8342 
8343   // If 'unsafe math' is enabled, fold lots of things.
8344   if (Options.UnsafeFPMath) {
8345     // No FP constant should be created after legalization as Instruction
8346     // Selection pass has a hard time dealing with FP constants.
8347     bool AllowNewConst = (Level < AfterLegalizeDAG);
8348 
8349     // fold (fadd A, 0) -> A
8350     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8351       if (N1C->isZero())
8352         return N0;
8353 
8354     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8355     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8356         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8357       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8358                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8359                                      Flags),
8360                          Flags);
8361 
8362     // If allowed, fold (fadd (fneg x), x) -> 0.0
8363     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8364       return DAG.getConstantFP(0.0, DL, VT);
8365 
8366     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8367     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8368       return DAG.getConstantFP(0.0, DL, VT);
8369 
8370     // We can fold chains of FADD's of the same value into multiplications.
8371     // This transform is not safe in general because we are reducing the number
8372     // of rounding steps.
8373     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8374       if (N0.getOpcode() == ISD::FMUL) {
8375         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8376         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8377 
8378         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8379         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8380           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8381                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8382           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8383         }
8384 
8385         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8386         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8387             N1.getOperand(0) == N1.getOperand(1) &&
8388             N0.getOperand(0) == N1.getOperand(0)) {
8389           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8390                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8391           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8392         }
8393       }
8394 
8395       if (N1.getOpcode() == ISD::FMUL) {
8396         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8397         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8398 
8399         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8400         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8401           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8402                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8403           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8404         }
8405 
8406         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8407         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8408             N0.getOperand(0) == N0.getOperand(1) &&
8409             N1.getOperand(0) == N0.getOperand(0)) {
8410           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8411                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8412           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8413         }
8414       }
8415 
8416       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8417         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8418         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8419         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8420             (N0.getOperand(0) == N1)) {
8421           return DAG.getNode(ISD::FMUL, DL, VT,
8422                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8423         }
8424       }
8425 
8426       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8427         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8428         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8429         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8430             N1.getOperand(0) == N0) {
8431           return DAG.getNode(ISD::FMUL, DL, VT,
8432                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8433         }
8434       }
8435 
8436       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8437       if (AllowNewConst &&
8438           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8439           N0.getOperand(0) == N0.getOperand(1) &&
8440           N1.getOperand(0) == N1.getOperand(1) &&
8441           N0.getOperand(0) == N1.getOperand(0)) {
8442         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8443                            DAG.getConstantFP(4.0, DL, VT), Flags);
8444       }
8445     }
8446   } // enable-unsafe-fp-math
8447 
8448   // FADD -> FMA combines:
8449   if (SDValue Fused = visitFADDForFMACombine(N)) {
8450     AddToWorklist(Fused.getNode());
8451     return Fused;
8452   }
8453   return SDValue();
8454 }
8455 
8456 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8457   SDValue N0 = N->getOperand(0);
8458   SDValue N1 = N->getOperand(1);
8459   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8460   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8461   EVT VT = N->getValueType(0);
8462   SDLoc dl(N);
8463   const TargetOptions &Options = DAG.getTarget().Options;
8464   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8465 
8466   // fold vector ops
8467   if (VT.isVector())
8468     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8469       return FoldedVOp;
8470 
8471   // fold (fsub c1, c2) -> c1-c2
8472   if (N0CFP && N1CFP)
8473     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8474 
8475   // fold (fsub A, (fneg B)) -> (fadd A, B)
8476   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8477     return DAG.getNode(ISD::FADD, dl, VT, N0,
8478                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8479 
8480   // If 'unsafe math' is enabled, fold lots of things.
8481   if (Options.UnsafeFPMath) {
8482     // (fsub A, 0) -> A
8483     if (N1CFP && N1CFP->isZero())
8484       return N0;
8485 
8486     // (fsub 0, B) -> -B
8487     if (N0CFP && N0CFP->isZero()) {
8488       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8489         return GetNegatedExpression(N1, DAG, LegalOperations);
8490       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8491         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8492     }
8493 
8494     // (fsub x, x) -> 0.0
8495     if (N0 == N1)
8496       return DAG.getConstantFP(0.0f, dl, VT);
8497 
8498     // (fsub x, (fadd x, y)) -> (fneg y)
8499     // (fsub x, (fadd y, x)) -> (fneg y)
8500     if (N1.getOpcode() == ISD::FADD) {
8501       SDValue N10 = N1->getOperand(0);
8502       SDValue N11 = N1->getOperand(1);
8503 
8504       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8505         return GetNegatedExpression(N11, DAG, LegalOperations);
8506 
8507       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8508         return GetNegatedExpression(N10, DAG, LegalOperations);
8509     }
8510   }
8511 
8512   // FSUB -> FMA combines:
8513   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8514     AddToWorklist(Fused.getNode());
8515     return Fused;
8516   }
8517 
8518   return SDValue();
8519 }
8520 
8521 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8522   SDValue N0 = N->getOperand(0);
8523   SDValue N1 = N->getOperand(1);
8524   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8525   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8526   EVT VT = N->getValueType(0);
8527   SDLoc DL(N);
8528   const TargetOptions &Options = DAG.getTarget().Options;
8529   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8530 
8531   // fold vector ops
8532   if (VT.isVector()) {
8533     // This just handles C1 * C2 for vectors. Other vector folds are below.
8534     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8535       return FoldedVOp;
8536   }
8537 
8538   // fold (fmul c1, c2) -> c1*c2
8539   if (N0CFP && N1CFP)
8540     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8541 
8542   // canonicalize constant to RHS
8543   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8544      !isConstantFPBuildVectorOrConstantFP(N1))
8545     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8546 
8547   // fold (fmul A, 1.0) -> A
8548   if (N1CFP && N1CFP->isExactlyValue(1.0))
8549     return N0;
8550 
8551   if (Options.UnsafeFPMath) {
8552     // fold (fmul A, 0) -> 0
8553     if (N1CFP && N1CFP->isZero())
8554       return N1;
8555 
8556     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8557     if (N0.getOpcode() == ISD::FMUL) {
8558       // Fold scalars or any vector constants (not just splats).
8559       // This fold is done in general by InstCombine, but extra fmul insts
8560       // may have been generated during lowering.
8561       SDValue N00 = N0.getOperand(0);
8562       SDValue N01 = N0.getOperand(1);
8563       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8564       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8565       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8566 
8567       // Check 1: Make sure that the first operand of the inner multiply is NOT
8568       // a constant. Otherwise, we may induce infinite looping.
8569       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8570         // Check 2: Make sure that the second operand of the inner multiply and
8571         // the second operand of the outer multiply are constants.
8572         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8573             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8574           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8575           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8576         }
8577       }
8578     }
8579 
8580     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8581     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8582     // during an early run of DAGCombiner can prevent folding with fmuls
8583     // inserted during lowering.
8584     if (N0.getOpcode() == ISD::FADD &&
8585         (N0.getOperand(0) == N0.getOperand(1)) &&
8586         N0.hasOneUse()) {
8587       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8588       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8589       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8590     }
8591   }
8592 
8593   // fold (fmul X, 2.0) -> (fadd X, X)
8594   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8595     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8596 
8597   // fold (fmul X, -1.0) -> (fneg X)
8598   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8599     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8600       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8601 
8602   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8603   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8604     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8605       // Both can be negated for free, check to see if at least one is cheaper
8606       // negated.
8607       if (LHSNeg == 2 || RHSNeg == 2)
8608         return DAG.getNode(ISD::FMUL, DL, VT,
8609                            GetNegatedExpression(N0, DAG, LegalOperations),
8610                            GetNegatedExpression(N1, DAG, LegalOperations),
8611                            Flags);
8612     }
8613   }
8614 
8615   // FMUL -> FMA combines:
8616   if (SDValue Fused = visitFMULForFMACombine(N)) {
8617     AddToWorklist(Fused.getNode());
8618     return Fused;
8619   }
8620 
8621   return SDValue();
8622 }
8623 
8624 SDValue DAGCombiner::visitFMA(SDNode *N) {
8625   SDValue N0 = N->getOperand(0);
8626   SDValue N1 = N->getOperand(1);
8627   SDValue N2 = N->getOperand(2);
8628   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8629   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8630   EVT VT = N->getValueType(0);
8631   SDLoc dl(N);
8632   const TargetOptions &Options = DAG.getTarget().Options;
8633 
8634   // Constant fold FMA.
8635   if (isa<ConstantFPSDNode>(N0) &&
8636       isa<ConstantFPSDNode>(N1) &&
8637       isa<ConstantFPSDNode>(N2)) {
8638     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8639   }
8640 
8641   if (Options.UnsafeFPMath) {
8642     if (N0CFP && N0CFP->isZero())
8643       return N2;
8644     if (N1CFP && N1CFP->isZero())
8645       return N2;
8646   }
8647   // TODO: The FMA node should have flags that propagate to these nodes.
8648   if (N0CFP && N0CFP->isExactlyValue(1.0))
8649     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8650   if (N1CFP && N1CFP->isExactlyValue(1.0))
8651     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8652 
8653   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8654   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8655      !isConstantFPBuildVectorOrConstantFP(N1))
8656     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8657 
8658   // TODO: FMA nodes should have flags that propagate to the created nodes.
8659   // For now, create a Flags object for use with all unsafe math transforms.
8660   SDNodeFlags Flags;
8661   Flags.setUnsafeAlgebra(true);
8662 
8663   if (Options.UnsafeFPMath) {
8664     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8665     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8666         isConstantFPBuildVectorOrConstantFP(N1) &&
8667         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8668       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8669                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8670                                      &Flags), &Flags);
8671     }
8672 
8673     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8674     if (N0.getOpcode() == ISD::FMUL &&
8675         isConstantFPBuildVectorOrConstantFP(N1) &&
8676         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8677       return DAG.getNode(ISD::FMA, dl, VT,
8678                          N0.getOperand(0),
8679                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8680                                      &Flags),
8681                          N2);
8682     }
8683   }
8684 
8685   // (fma x, 1, y) -> (fadd x, y)
8686   // (fma x, -1, y) -> (fadd (fneg x), y)
8687   if (N1CFP) {
8688     if (N1CFP->isExactlyValue(1.0))
8689       // TODO: The FMA node should have flags that propagate to this node.
8690       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8691 
8692     if (N1CFP->isExactlyValue(-1.0) &&
8693         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8694       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8695       AddToWorklist(RHSNeg.getNode());
8696       // TODO: The FMA node should have flags that propagate to this node.
8697       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8698     }
8699   }
8700 
8701   if (Options.UnsafeFPMath) {
8702     // (fma x, c, x) -> (fmul x, (c+1))
8703     if (N1CFP && N0 == N2) {
8704     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8705                          DAG.getNode(ISD::FADD, dl, VT,
8706                                      N1, DAG.getConstantFP(1.0, dl, VT),
8707                                      &Flags), &Flags);
8708     }
8709 
8710     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8711     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8712       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8713                          DAG.getNode(ISD::FADD, dl, VT,
8714                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8715                                      &Flags), &Flags);
8716     }
8717   }
8718 
8719   return SDValue();
8720 }
8721 
8722 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8723 // reciprocal.
8724 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8725 // Notice that this is not always beneficial. One reason is different target
8726 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8727 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8728 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8729 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8730   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8731   const SDNodeFlags *Flags = N->getFlags();
8732   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8733     return SDValue();
8734 
8735   // Skip if current node is a reciprocal.
8736   SDValue N0 = N->getOperand(0);
8737   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8738   if (N0CFP && N0CFP->isExactlyValue(1.0))
8739     return SDValue();
8740 
8741   // Exit early if the target does not want this transform or if there can't
8742   // possibly be enough uses of the divisor to make the transform worthwhile.
8743   SDValue N1 = N->getOperand(1);
8744   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8745   if (!MinUses || N1->use_size() < MinUses)
8746     return SDValue();
8747 
8748   // Find all FDIV users of the same divisor.
8749   // Use a set because duplicates may be present in the user list.
8750   SetVector<SDNode *> Users;
8751   for (auto *U : N1->uses()) {
8752     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8753       // This division is eligible for optimization only if global unsafe math
8754       // is enabled or if this division allows reciprocal formation.
8755       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8756         Users.insert(U);
8757     }
8758   }
8759 
8760   // Now that we have the actual number of divisor uses, make sure it meets
8761   // the minimum threshold specified by the target.
8762   if (Users.size() < MinUses)
8763     return SDValue();
8764 
8765   EVT VT = N->getValueType(0);
8766   SDLoc DL(N);
8767   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8768   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8769 
8770   // Dividend / Divisor -> Dividend * Reciprocal
8771   for (auto *U : Users) {
8772     SDValue Dividend = U->getOperand(0);
8773     if (Dividend != FPOne) {
8774       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8775                                     Reciprocal, Flags);
8776       CombineTo(U, NewNode);
8777     } else if (U != Reciprocal.getNode()) {
8778       // In the absence of fast-math-flags, this user node is always the
8779       // same node as Reciprocal, but with FMF they may be different nodes.
8780       CombineTo(U, Reciprocal);
8781     }
8782   }
8783   return SDValue(N, 0);  // N was replaced.
8784 }
8785 
8786 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8787   SDValue N0 = N->getOperand(0);
8788   SDValue N1 = N->getOperand(1);
8789   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8790   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8791   EVT VT = N->getValueType(0);
8792   SDLoc DL(N);
8793   const TargetOptions &Options = DAG.getTarget().Options;
8794   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8795 
8796   // fold vector ops
8797   if (VT.isVector())
8798     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8799       return FoldedVOp;
8800 
8801   // fold (fdiv c1, c2) -> c1/c2
8802   if (N0CFP && N1CFP)
8803     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8804 
8805   if (Options.UnsafeFPMath) {
8806     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8807     if (N1CFP) {
8808       // Compute the reciprocal 1.0 / c2.
8809       APFloat N1APF = N1CFP->getValueAPF();
8810       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8811       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8812       // Only do the transform if the reciprocal is a legal fp immediate that
8813       // isn't too nasty (eg NaN, denormal, ...).
8814       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8815           (!LegalOperations ||
8816            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8817            // backend)... we should handle this gracefully after Legalize.
8818            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8819            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8820            TLI.isFPImmLegal(Recip, VT)))
8821         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8822                            DAG.getConstantFP(Recip, DL, VT), Flags);
8823     }
8824 
8825     // If this FDIV is part of a reciprocal square root, it may be folded
8826     // into a target-specific square root estimate instruction.
8827     if (N1.getOpcode() == ISD::FSQRT) {
8828       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8829         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8830       }
8831     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8832                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8833       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8834                                           Flags)) {
8835         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8836         AddToWorklist(RV.getNode());
8837         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8838       }
8839     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8840                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8841       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8842                                           Flags)) {
8843         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8844         AddToWorklist(RV.getNode());
8845         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8846       }
8847     } else if (N1.getOpcode() == ISD::FMUL) {
8848       // Look through an FMUL. Even though this won't remove the FDIV directly,
8849       // it's still worthwhile to get rid of the FSQRT if possible.
8850       SDValue SqrtOp;
8851       SDValue OtherOp;
8852       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8853         SqrtOp = N1.getOperand(0);
8854         OtherOp = N1.getOperand(1);
8855       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8856         SqrtOp = N1.getOperand(1);
8857         OtherOp = N1.getOperand(0);
8858       }
8859       if (SqrtOp.getNode()) {
8860         // We found a FSQRT, so try to make this fold:
8861         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8862         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8863           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8864           AddToWorklist(RV.getNode());
8865           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8866         }
8867       }
8868     }
8869 
8870     // Fold into a reciprocal estimate and multiply instead of a real divide.
8871     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8872       AddToWorklist(RV.getNode());
8873       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8874     }
8875   }
8876 
8877   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8878   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8879     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8880       // Both can be negated for free, check to see if at least one is cheaper
8881       // negated.
8882       if (LHSNeg == 2 || RHSNeg == 2)
8883         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8884                            GetNegatedExpression(N0, DAG, LegalOperations),
8885                            GetNegatedExpression(N1, DAG, LegalOperations),
8886                            Flags);
8887     }
8888   }
8889 
8890   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8891     return CombineRepeatedDivisors;
8892 
8893   return SDValue();
8894 }
8895 
8896 SDValue DAGCombiner::visitFREM(SDNode *N) {
8897   SDValue N0 = N->getOperand(0);
8898   SDValue N1 = N->getOperand(1);
8899   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8900   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8901   EVT VT = N->getValueType(0);
8902 
8903   // fold (frem c1, c2) -> fmod(c1,c2)
8904   if (N0CFP && N1CFP)
8905     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8906                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8907 
8908   return SDValue();
8909 }
8910 
8911 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8912   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8913     return SDValue();
8914 
8915   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8916   // For now, create a Flags object for use with all unsafe math transforms.
8917   SDNodeFlags Flags;
8918   Flags.setUnsafeAlgebra(true);
8919 
8920   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8921   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8922   if (!RV)
8923     return SDValue();
8924 
8925   EVT VT = RV.getValueType();
8926   SDLoc DL(N);
8927   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8928   AddToWorklist(RV.getNode());
8929 
8930   // Unfortunately, RV is now NaN if the input was exactly 0.
8931   // Select out this case and force the answer to 0.
8932   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8933   EVT CCVT = getSetCCResultType(VT);
8934   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8935   AddToWorklist(ZeroCmp.getNode());
8936   AddToWorklist(RV.getNode());
8937 
8938   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8939                      ZeroCmp, Zero, RV);
8940 }
8941 
8942 /// copysign(x, fp_extend(y)) -> copysign(x, y)
8943 /// copysign(x, fp_round(y)) -> copysign(x, y)
8944 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
8945   SDValue N1 = N->getOperand(1);
8946   if ((N1.getOpcode() == ISD::FP_EXTEND ||
8947        N1.getOpcode() == ISD::FP_ROUND)) {
8948     // Do not optimize out type conversion of f128 type yet.
8949     // For some targets like x86_64, configuration is changed to keep one f128
8950     // value in one SSE register, but instruction selection cannot handle
8951     // FCOPYSIGN on SSE registers yet.
8952     EVT N1VT = N1->getValueType(0);
8953     EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
8954     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
8955   }
8956   return false;
8957 }
8958 
8959 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8960   SDValue N0 = N->getOperand(0);
8961   SDValue N1 = N->getOperand(1);
8962   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8963   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8964   EVT VT = N->getValueType(0);
8965 
8966   if (N0CFP && N1CFP)  // Constant fold
8967     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8968 
8969   if (N1CFP) {
8970     const APFloat& V = N1CFP->getValueAPF();
8971     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8972     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8973     if (!V.isNegative()) {
8974       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8975         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8976     } else {
8977       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8978         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8979                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8980     }
8981   }
8982 
8983   // copysign(fabs(x), y) -> copysign(x, y)
8984   // copysign(fneg(x), y) -> copysign(x, y)
8985   // copysign(copysign(x,z), y) -> copysign(x, y)
8986   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8987       N0.getOpcode() == ISD::FCOPYSIGN)
8988     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8989                        N0.getOperand(0), N1);
8990 
8991   // copysign(x, abs(y)) -> abs(x)
8992   if (N1.getOpcode() == ISD::FABS)
8993     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8994 
8995   // copysign(x, copysign(y,z)) -> copysign(x, z)
8996   if (N1.getOpcode() == ISD::FCOPYSIGN)
8997     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8998                        N0, N1.getOperand(1));
8999 
9000   // copysign(x, fp_extend(y)) -> copysign(x, y)
9001   // copysign(x, fp_round(y)) -> copysign(x, y)
9002   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9003     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9004                        N0, N1.getOperand(0));
9005 
9006   return SDValue();
9007 }
9008 
9009 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9010   SDValue N0 = N->getOperand(0);
9011   EVT VT = N->getValueType(0);
9012   EVT OpVT = N0.getValueType();
9013 
9014   // fold (sint_to_fp c1) -> c1fp
9015   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9016       // ...but only if the target supports immediate floating-point values
9017       (!LegalOperations ||
9018        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9019     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9020 
9021   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9022   // but UINT_TO_FP is legal on this target, try to convert.
9023   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9024       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9025     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9026     if (DAG.SignBitIsZero(N0))
9027       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9028   }
9029 
9030   // The next optimizations are desirable only if SELECT_CC can be lowered.
9031   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9032     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9033     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
9034         !VT.isVector() &&
9035         (!LegalOperations ||
9036          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9037       SDLoc DL(N);
9038       SDValue Ops[] =
9039         { N0.getOperand(0), N0.getOperand(1),
9040           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9041           N0.getOperand(2) };
9042       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9043     }
9044 
9045     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
9046     //      (select_cc x, y, 1.0, 0.0,, cc)
9047     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
9048         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
9049         (!LegalOperations ||
9050          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9051       SDLoc DL(N);
9052       SDValue Ops[] =
9053         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
9054           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9055           N0.getOperand(0).getOperand(2) };
9056       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9057     }
9058   }
9059 
9060   return SDValue();
9061 }
9062 
9063 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
9064   SDValue N0 = N->getOperand(0);
9065   EVT VT = N->getValueType(0);
9066   EVT OpVT = N0.getValueType();
9067 
9068   // fold (uint_to_fp c1) -> c1fp
9069   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9070       // ...but only if the target supports immediate floating-point values
9071       (!LegalOperations ||
9072        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9073     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
9074 
9075   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
9076   // but SINT_TO_FP is legal on this target, try to convert.
9077   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
9078       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
9079     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
9080     if (DAG.SignBitIsZero(N0))
9081       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9082   }
9083 
9084   // The next optimizations are desirable only if SELECT_CC can be lowered.
9085   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
9086     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
9087 
9088     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
9089         (!LegalOperations ||
9090          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
9091       SDLoc DL(N);
9092       SDValue Ops[] =
9093         { N0.getOperand(0), N0.getOperand(1),
9094           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
9095           N0.getOperand(2) };
9096       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
9097     }
9098   }
9099 
9100   return SDValue();
9101 }
9102 
9103 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
9104 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
9105   SDValue N0 = N->getOperand(0);
9106   EVT VT = N->getValueType(0);
9107 
9108   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
9109     return SDValue();
9110 
9111   SDValue Src = N0.getOperand(0);
9112   EVT SrcVT = Src.getValueType();
9113   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
9114   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
9115 
9116   // We can safely assume the conversion won't overflow the output range,
9117   // because (for example) (uint8_t)18293.f is undefined behavior.
9118 
9119   // Since we can assume the conversion won't overflow, our decision as to
9120   // whether the input will fit in the float should depend on the minimum
9121   // of the input range and output range.
9122 
9123   // This means this is also safe for a signed input and unsigned output, since
9124   // a negative input would lead to undefined behavior.
9125   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
9126   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
9127   unsigned ActualSize = std::min(InputSize, OutputSize);
9128   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
9129 
9130   // We can only fold away the float conversion if the input range can be
9131   // represented exactly in the float range.
9132   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
9133     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
9134       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
9135                                                        : ISD::ZERO_EXTEND;
9136       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
9137     }
9138     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
9139       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
9140     return DAG.getBitcast(VT, Src);
9141   }
9142   return SDValue();
9143 }
9144 
9145 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
9146   SDValue N0 = N->getOperand(0);
9147   EVT VT = N->getValueType(0);
9148 
9149   // fold (fp_to_sint c1fp) -> c1
9150   if (isConstantFPBuildVectorOrConstantFP(N0))
9151     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
9152 
9153   return FoldIntToFPToInt(N, DAG);
9154 }
9155 
9156 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
9157   SDValue N0 = N->getOperand(0);
9158   EVT VT = N->getValueType(0);
9159 
9160   // fold (fp_to_uint c1fp) -> c1
9161   if (isConstantFPBuildVectorOrConstantFP(N0))
9162     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
9163 
9164   return FoldIntToFPToInt(N, DAG);
9165 }
9166 
9167 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
9168   SDValue N0 = N->getOperand(0);
9169   SDValue N1 = N->getOperand(1);
9170   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9171   EVT VT = N->getValueType(0);
9172 
9173   // fold (fp_round c1fp) -> c1fp
9174   if (N0CFP)
9175     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
9176 
9177   // fold (fp_round (fp_extend x)) -> x
9178   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
9179     return N0.getOperand(0);
9180 
9181   // fold (fp_round (fp_round x)) -> (fp_round x)
9182   if (N0.getOpcode() == ISD::FP_ROUND) {
9183     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
9184     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
9185 
9186     // Skip this folding if it results in an fp_round from f80 to f16.
9187     //
9188     // f80 to f16 always generates an expensive (and as yet, unimplemented)
9189     // libcall to __truncxfhf2 instead of selecting native f16 conversion
9190     // instructions from f32 or f64.  Moreover, the first (value-preserving)
9191     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
9192     // x86.
9193     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
9194       return SDValue();
9195 
9196     // If the first fp_round isn't a value preserving truncation, it might
9197     // introduce a tie in the second fp_round, that wouldn't occur in the
9198     // single-step fp_round we want to fold to.
9199     // In other words, double rounding isn't the same as rounding.
9200     // Also, this is a value preserving truncation iff both fp_round's are.
9201     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
9202       SDLoc DL(N);
9203       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
9204                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
9205     }
9206   }
9207 
9208   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
9209   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
9210     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
9211                               N0.getOperand(0), N1);
9212     AddToWorklist(Tmp.getNode());
9213     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
9214                        Tmp, N0.getOperand(1));
9215   }
9216 
9217   return SDValue();
9218 }
9219 
9220 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
9221   SDValue N0 = N->getOperand(0);
9222   EVT VT = N->getValueType(0);
9223   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
9224   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9225 
9226   // fold (fp_round_inreg c1fp) -> c1fp
9227   if (N0CFP && isTypeLegal(EVT)) {
9228     SDLoc DL(N);
9229     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
9230     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
9231   }
9232 
9233   return SDValue();
9234 }
9235 
9236 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
9237   SDValue N0 = N->getOperand(0);
9238   EVT VT = N->getValueType(0);
9239 
9240   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
9241   if (N->hasOneUse() &&
9242       N->use_begin()->getOpcode() == ISD::FP_ROUND)
9243     return SDValue();
9244 
9245   // fold (fp_extend c1fp) -> c1fp
9246   if (isConstantFPBuildVectorOrConstantFP(N0))
9247     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
9248 
9249   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
9250   if (N0.getOpcode() == ISD::FP16_TO_FP &&
9251       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
9252     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
9253 
9254   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
9255   // value of X.
9256   if (N0.getOpcode() == ISD::FP_ROUND
9257       && N0.getNode()->getConstantOperandVal(1) == 1) {
9258     SDValue In = N0.getOperand(0);
9259     if (In.getValueType() == VT) return In;
9260     if (VT.bitsLT(In.getValueType()))
9261       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
9262                          In, N0.getOperand(1));
9263     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
9264   }
9265 
9266   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
9267   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9268        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
9269     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9270     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
9271                                      LN0->getChain(),
9272                                      LN0->getBasePtr(), N0.getValueType(),
9273                                      LN0->getMemOperand());
9274     CombineTo(N, ExtLoad);
9275     CombineTo(N0.getNode(),
9276               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9277                           N0.getValueType(), ExtLoad,
9278                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9279               ExtLoad.getValue(1));
9280     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9281   }
9282 
9283   return SDValue();
9284 }
9285 
9286 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9287   SDValue N0 = N->getOperand(0);
9288   EVT VT = N->getValueType(0);
9289 
9290   // fold (fceil c1) -> fceil(c1)
9291   if (isConstantFPBuildVectorOrConstantFP(N0))
9292     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9293 
9294   return SDValue();
9295 }
9296 
9297 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9298   SDValue N0 = N->getOperand(0);
9299   EVT VT = N->getValueType(0);
9300 
9301   // fold (ftrunc c1) -> ftrunc(c1)
9302   if (isConstantFPBuildVectorOrConstantFP(N0))
9303     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9304 
9305   return SDValue();
9306 }
9307 
9308 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9309   SDValue N0 = N->getOperand(0);
9310   EVT VT = N->getValueType(0);
9311 
9312   // fold (ffloor c1) -> ffloor(c1)
9313   if (isConstantFPBuildVectorOrConstantFP(N0))
9314     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9315 
9316   return SDValue();
9317 }
9318 
9319 // FIXME: FNEG and FABS have a lot in common; refactor.
9320 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9321   SDValue N0 = N->getOperand(0);
9322   EVT VT = N->getValueType(0);
9323 
9324   // Constant fold FNEG.
9325   if (isConstantFPBuildVectorOrConstantFP(N0))
9326     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9327 
9328   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9329                          &DAG.getTarget().Options))
9330     return GetNegatedExpression(N0, DAG, LegalOperations);
9331 
9332   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9333   // constant pool values.
9334   if (!TLI.isFNegFree(VT) &&
9335       N0.getOpcode() == ISD::BITCAST &&
9336       N0.getNode()->hasOneUse()) {
9337     SDValue Int = N0.getOperand(0);
9338     EVT IntVT = Int.getValueType();
9339     if (IntVT.isInteger() && !IntVT.isVector()) {
9340       APInt SignMask;
9341       if (N0.getValueType().isVector()) {
9342         // For a vector, get a mask such as 0x80... per scalar element
9343         // and splat it.
9344         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9345         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9346       } else {
9347         // For a scalar, just generate 0x80...
9348         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9349       }
9350       SDLoc DL0(N0);
9351       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9352                         DAG.getConstant(SignMask, DL0, IntVT));
9353       AddToWorklist(Int.getNode());
9354       return DAG.getBitcast(VT, Int);
9355     }
9356   }
9357 
9358   // (fneg (fmul c, x)) -> (fmul -c, x)
9359   if (N0.getOpcode() == ISD::FMUL &&
9360       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9361     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9362     if (CFP1) {
9363       APFloat CVal = CFP1->getValueAPF();
9364       CVal.changeSign();
9365       if (Level >= AfterLegalizeDAG &&
9366           (TLI.isFPImmLegal(CVal, VT) ||
9367            TLI.isOperationLegal(ISD::ConstantFP, VT)))
9368         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9369                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9370                                        N0.getOperand(1)),
9371                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9372     }
9373   }
9374 
9375   return SDValue();
9376 }
9377 
9378 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9379   SDValue N0 = N->getOperand(0);
9380   SDValue N1 = N->getOperand(1);
9381   EVT VT = N->getValueType(0);
9382   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9383   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9384 
9385   if (N0CFP && N1CFP) {
9386     const APFloat &C0 = N0CFP->getValueAPF();
9387     const APFloat &C1 = N1CFP->getValueAPF();
9388     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9389   }
9390 
9391   // Canonicalize to constant on RHS.
9392   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9393      !isConstantFPBuildVectorOrConstantFP(N1))
9394     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9395 
9396   return SDValue();
9397 }
9398 
9399 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9400   SDValue N0 = N->getOperand(0);
9401   SDValue N1 = N->getOperand(1);
9402   EVT VT = N->getValueType(0);
9403   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9404   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9405 
9406   if (N0CFP && N1CFP) {
9407     const APFloat &C0 = N0CFP->getValueAPF();
9408     const APFloat &C1 = N1CFP->getValueAPF();
9409     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9410   }
9411 
9412   // Canonicalize to constant on RHS.
9413   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9414      !isConstantFPBuildVectorOrConstantFP(N1))
9415     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9416 
9417   return SDValue();
9418 }
9419 
9420 SDValue DAGCombiner::visitFABS(SDNode *N) {
9421   SDValue N0 = N->getOperand(0);
9422   EVT VT = N->getValueType(0);
9423 
9424   // fold (fabs c1) -> fabs(c1)
9425   if (isConstantFPBuildVectorOrConstantFP(N0))
9426     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9427 
9428   // fold (fabs (fabs x)) -> (fabs x)
9429   if (N0.getOpcode() == ISD::FABS)
9430     return N->getOperand(0);
9431 
9432   // fold (fabs (fneg x)) -> (fabs x)
9433   // fold (fabs (fcopysign x, y)) -> (fabs x)
9434   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9435     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9436 
9437   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9438   // constant pool values.
9439   if (!TLI.isFAbsFree(VT) &&
9440       N0.getOpcode() == ISD::BITCAST &&
9441       N0.getNode()->hasOneUse()) {
9442     SDValue Int = N0.getOperand(0);
9443     EVT IntVT = Int.getValueType();
9444     if (IntVT.isInteger() && !IntVT.isVector()) {
9445       APInt SignMask;
9446       if (N0.getValueType().isVector()) {
9447         // For a vector, get a mask such as 0x7f... per scalar element
9448         // and splat it.
9449         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9450         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9451       } else {
9452         // For a scalar, just generate 0x7f...
9453         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9454       }
9455       SDLoc DL(N0);
9456       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9457                         DAG.getConstant(SignMask, DL, IntVT));
9458       AddToWorklist(Int.getNode());
9459       return DAG.getBitcast(N->getValueType(0), Int);
9460     }
9461   }
9462 
9463   return SDValue();
9464 }
9465 
9466 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9467   SDValue Chain = N->getOperand(0);
9468   SDValue N1 = N->getOperand(1);
9469   SDValue N2 = N->getOperand(2);
9470 
9471   // If N is a constant we could fold this into a fallthrough or unconditional
9472   // branch. However that doesn't happen very often in normal code, because
9473   // Instcombine/SimplifyCFG should have handled the available opportunities.
9474   // If we did this folding here, it would be necessary to update the
9475   // MachineBasicBlock CFG, which is awkward.
9476 
9477   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9478   // on the target.
9479   if (N1.getOpcode() == ISD::SETCC &&
9480       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9481                                    N1.getOperand(0).getValueType())) {
9482     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9483                        Chain, N1.getOperand(2),
9484                        N1.getOperand(0), N1.getOperand(1), N2);
9485   }
9486 
9487   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9488       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9489        (N1.getOperand(0).hasOneUse() &&
9490         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9491     SDNode *Trunc = nullptr;
9492     if (N1.getOpcode() == ISD::TRUNCATE) {
9493       // Look pass the truncate.
9494       Trunc = N1.getNode();
9495       N1 = N1.getOperand(0);
9496     }
9497 
9498     // Match this pattern so that we can generate simpler code:
9499     //
9500     //   %a = ...
9501     //   %b = and i32 %a, 2
9502     //   %c = srl i32 %b, 1
9503     //   brcond i32 %c ...
9504     //
9505     // into
9506     //
9507     //   %a = ...
9508     //   %b = and i32 %a, 2
9509     //   %c = setcc eq %b, 0
9510     //   brcond %c ...
9511     //
9512     // This applies only when the AND constant value has one bit set and the
9513     // SRL constant is equal to the log2 of the AND constant. The back-end is
9514     // smart enough to convert the result into a TEST/JMP sequence.
9515     SDValue Op0 = N1.getOperand(0);
9516     SDValue Op1 = N1.getOperand(1);
9517 
9518     if (Op0.getOpcode() == ISD::AND &&
9519         Op1.getOpcode() == ISD::Constant) {
9520       SDValue AndOp1 = Op0.getOperand(1);
9521 
9522       if (AndOp1.getOpcode() == ISD::Constant) {
9523         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9524 
9525         if (AndConst.isPowerOf2() &&
9526             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9527           SDLoc DL(N);
9528           SDValue SetCC =
9529             DAG.getSetCC(DL,
9530                          getSetCCResultType(Op0.getValueType()),
9531                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9532                          ISD::SETNE);
9533 
9534           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9535                                           MVT::Other, Chain, SetCC, N2);
9536           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9537           // will convert it back to (X & C1) >> C2.
9538           CombineTo(N, NewBRCond, false);
9539           // Truncate is dead.
9540           if (Trunc)
9541             deleteAndRecombine(Trunc);
9542           // Replace the uses of SRL with SETCC
9543           WorklistRemover DeadNodes(*this);
9544           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9545           deleteAndRecombine(N1.getNode());
9546           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9547         }
9548       }
9549     }
9550 
9551     if (Trunc)
9552       // Restore N1 if the above transformation doesn't match.
9553       N1 = N->getOperand(1);
9554   }
9555 
9556   // Transform br(xor(x, y)) -> br(x != y)
9557   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9558   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9559     SDNode *TheXor = N1.getNode();
9560     SDValue Op0 = TheXor->getOperand(0);
9561     SDValue Op1 = TheXor->getOperand(1);
9562     if (Op0.getOpcode() == Op1.getOpcode()) {
9563       // Avoid missing important xor optimizations.
9564       if (SDValue Tmp = visitXOR(TheXor)) {
9565         if (Tmp.getNode() != TheXor) {
9566           DEBUG(dbgs() << "\nReplacing.8 ";
9567                 TheXor->dump(&DAG);
9568                 dbgs() << "\nWith: ";
9569                 Tmp.getNode()->dump(&DAG);
9570                 dbgs() << '\n');
9571           WorklistRemover DeadNodes(*this);
9572           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9573           deleteAndRecombine(TheXor);
9574           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9575                              MVT::Other, Chain, Tmp, N2);
9576         }
9577 
9578         // visitXOR has changed XOR's operands or replaced the XOR completely,
9579         // bail out.
9580         return SDValue(N, 0);
9581       }
9582     }
9583 
9584     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9585       bool Equal = false;
9586       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9587           Op0.getOpcode() == ISD::XOR) {
9588         TheXor = Op0.getNode();
9589         Equal = true;
9590       }
9591 
9592       EVT SetCCVT = N1.getValueType();
9593       if (LegalTypes)
9594         SetCCVT = getSetCCResultType(SetCCVT);
9595       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9596                                    SetCCVT,
9597                                    Op0, Op1,
9598                                    Equal ? ISD::SETEQ : ISD::SETNE);
9599       // Replace the uses of XOR with SETCC
9600       WorklistRemover DeadNodes(*this);
9601       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9602       deleteAndRecombine(N1.getNode());
9603       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9604                          MVT::Other, Chain, SetCC, N2);
9605     }
9606   }
9607 
9608   return SDValue();
9609 }
9610 
9611 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9612 //
9613 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9614   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9615   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9616 
9617   // If N is a constant we could fold this into a fallthrough or unconditional
9618   // branch. However that doesn't happen very often in normal code, because
9619   // Instcombine/SimplifyCFG should have handled the available opportunities.
9620   // If we did this folding here, it would be necessary to update the
9621   // MachineBasicBlock CFG, which is awkward.
9622 
9623   // Use SimplifySetCC to simplify SETCC's.
9624   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9625                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9626                                false);
9627   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9628 
9629   // fold to a simpler setcc
9630   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9631     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9632                        N->getOperand(0), Simp.getOperand(2),
9633                        Simp.getOperand(0), Simp.getOperand(1),
9634                        N->getOperand(4));
9635 
9636   return SDValue();
9637 }
9638 
9639 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9640 /// and that N may be folded in the load / store addressing mode.
9641 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9642                                     SelectionDAG &DAG,
9643                                     const TargetLowering &TLI) {
9644   EVT VT;
9645   unsigned AS;
9646 
9647   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9648     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9649       return false;
9650     VT = LD->getMemoryVT();
9651     AS = LD->getAddressSpace();
9652   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9653     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9654       return false;
9655     VT = ST->getMemoryVT();
9656     AS = ST->getAddressSpace();
9657   } else
9658     return false;
9659 
9660   TargetLowering::AddrMode AM;
9661   if (N->getOpcode() == ISD::ADD) {
9662     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9663     if (Offset)
9664       // [reg +/- imm]
9665       AM.BaseOffs = Offset->getSExtValue();
9666     else
9667       // [reg +/- reg]
9668       AM.Scale = 1;
9669   } else if (N->getOpcode() == ISD::SUB) {
9670     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9671     if (Offset)
9672       // [reg +/- imm]
9673       AM.BaseOffs = -Offset->getSExtValue();
9674     else
9675       // [reg +/- reg]
9676       AM.Scale = 1;
9677   } else
9678     return false;
9679 
9680   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9681                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9682 }
9683 
9684 /// Try turning a load/store into a pre-indexed load/store when the base
9685 /// pointer is an add or subtract and it has other uses besides the load/store.
9686 /// After the transformation, the new indexed load/store has effectively folded
9687 /// the add/subtract in and all of its other uses are redirected to the
9688 /// new load/store.
9689 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9690   if (Level < AfterLegalizeDAG)
9691     return false;
9692 
9693   bool isLoad = true;
9694   SDValue Ptr;
9695   EVT VT;
9696   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9697     if (LD->isIndexed())
9698       return false;
9699     VT = LD->getMemoryVT();
9700     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9701         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9702       return false;
9703     Ptr = LD->getBasePtr();
9704   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9705     if (ST->isIndexed())
9706       return false;
9707     VT = ST->getMemoryVT();
9708     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9709         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9710       return false;
9711     Ptr = ST->getBasePtr();
9712     isLoad = false;
9713   } else {
9714     return false;
9715   }
9716 
9717   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9718   // out.  There is no reason to make this a preinc/predec.
9719   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9720       Ptr.getNode()->hasOneUse())
9721     return false;
9722 
9723   // Ask the target to do addressing mode selection.
9724   SDValue BasePtr;
9725   SDValue Offset;
9726   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9727   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9728     return false;
9729 
9730   // Backends without true r+i pre-indexed forms may need to pass a
9731   // constant base with a variable offset so that constant coercion
9732   // will work with the patterns in canonical form.
9733   bool Swapped = false;
9734   if (isa<ConstantSDNode>(BasePtr)) {
9735     std::swap(BasePtr, Offset);
9736     Swapped = true;
9737   }
9738 
9739   // Don't create a indexed load / store with zero offset.
9740   if (isNullConstant(Offset))
9741     return false;
9742 
9743   // Try turning it into a pre-indexed load / store except when:
9744   // 1) The new base ptr is a frame index.
9745   // 2) If N is a store and the new base ptr is either the same as or is a
9746   //    predecessor of the value being stored.
9747   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9748   //    that would create a cycle.
9749   // 4) All uses are load / store ops that use it as old base ptr.
9750 
9751   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9752   // (plus the implicit offset) to a register to preinc anyway.
9753   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9754     return false;
9755 
9756   // Check #2.
9757   if (!isLoad) {
9758     SDValue Val = cast<StoreSDNode>(N)->getValue();
9759     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9760       return false;
9761   }
9762 
9763   // Caches for hasPredecessorHelper.
9764   SmallPtrSet<const SDNode *, 32> Visited;
9765   SmallVector<const SDNode *, 16> Worklist;
9766   Worklist.push_back(N);
9767 
9768   // If the offset is a constant, there may be other adds of constants that
9769   // can be folded with this one. We should do this to avoid having to keep
9770   // a copy of the original base pointer.
9771   SmallVector<SDNode *, 16> OtherUses;
9772   if (isa<ConstantSDNode>(Offset))
9773     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9774                               UE = BasePtr.getNode()->use_end();
9775          UI != UE; ++UI) {
9776       SDUse &Use = UI.getUse();
9777       // Skip the use that is Ptr and uses of other results from BasePtr's
9778       // node (important for nodes that return multiple results).
9779       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9780         continue;
9781 
9782       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
9783         continue;
9784 
9785       if (Use.getUser()->getOpcode() != ISD::ADD &&
9786           Use.getUser()->getOpcode() != ISD::SUB) {
9787         OtherUses.clear();
9788         break;
9789       }
9790 
9791       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9792       if (!isa<ConstantSDNode>(Op1)) {
9793         OtherUses.clear();
9794         break;
9795       }
9796 
9797       // FIXME: In some cases, we can be smarter about this.
9798       if (Op1.getValueType() != Offset.getValueType()) {
9799         OtherUses.clear();
9800         break;
9801       }
9802 
9803       OtherUses.push_back(Use.getUser());
9804     }
9805 
9806   if (Swapped)
9807     std::swap(BasePtr, Offset);
9808 
9809   // Now check for #3 and #4.
9810   bool RealUse = false;
9811 
9812   for (SDNode *Use : Ptr.getNode()->uses()) {
9813     if (Use == N)
9814       continue;
9815     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
9816       return false;
9817 
9818     // If Ptr may be folded in addressing mode of other use, then it's
9819     // not profitable to do this transformation.
9820     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9821       RealUse = true;
9822   }
9823 
9824   if (!RealUse)
9825     return false;
9826 
9827   SDValue Result;
9828   if (isLoad)
9829     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9830                                 BasePtr, Offset, AM);
9831   else
9832     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9833                                  BasePtr, Offset, AM);
9834   ++PreIndexedNodes;
9835   ++NodesCombined;
9836   DEBUG(dbgs() << "\nReplacing.4 ";
9837         N->dump(&DAG);
9838         dbgs() << "\nWith: ";
9839         Result.getNode()->dump(&DAG);
9840         dbgs() << '\n');
9841   WorklistRemover DeadNodes(*this);
9842   if (isLoad) {
9843     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9844     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9845   } else {
9846     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9847   }
9848 
9849   // Finally, since the node is now dead, remove it from the graph.
9850   deleteAndRecombine(N);
9851 
9852   if (Swapped)
9853     std::swap(BasePtr, Offset);
9854 
9855   // Replace other uses of BasePtr that can be updated to use Ptr
9856   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9857     unsigned OffsetIdx = 1;
9858     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9859       OffsetIdx = 0;
9860     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9861            BasePtr.getNode() && "Expected BasePtr operand");
9862 
9863     // We need to replace ptr0 in the following expression:
9864     //   x0 * offset0 + y0 * ptr0 = t0
9865     // knowing that
9866     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9867     //
9868     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9869     // indexed load/store and the expresion that needs to be re-written.
9870     //
9871     // Therefore, we have:
9872     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9873 
9874     ConstantSDNode *CN =
9875       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9876     int X0, X1, Y0, Y1;
9877     APInt Offset0 = CN->getAPIntValue();
9878     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9879 
9880     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9881     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9882     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9883     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9884 
9885     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9886 
9887     APInt CNV = Offset0;
9888     if (X0 < 0) CNV = -CNV;
9889     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9890     else CNV = CNV - Offset1;
9891 
9892     SDLoc DL(OtherUses[i]);
9893 
9894     // We can now generate the new expression.
9895     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9896     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9897 
9898     SDValue NewUse = DAG.getNode(Opcode,
9899                                  DL,
9900                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9901     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9902     deleteAndRecombine(OtherUses[i]);
9903   }
9904 
9905   // Replace the uses of Ptr with uses of the updated base value.
9906   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9907   deleteAndRecombine(Ptr.getNode());
9908 
9909   return true;
9910 }
9911 
9912 /// Try to combine a load/store with a add/sub of the base pointer node into a
9913 /// post-indexed load/store. The transformation folded the add/subtract into the
9914 /// new indexed load/store effectively and all of its uses are redirected to the
9915 /// new load/store.
9916 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9917   if (Level < AfterLegalizeDAG)
9918     return false;
9919 
9920   bool isLoad = true;
9921   SDValue Ptr;
9922   EVT VT;
9923   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9924     if (LD->isIndexed())
9925       return false;
9926     VT = LD->getMemoryVT();
9927     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9928         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9929       return false;
9930     Ptr = LD->getBasePtr();
9931   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9932     if (ST->isIndexed())
9933       return false;
9934     VT = ST->getMemoryVT();
9935     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9936         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9937       return false;
9938     Ptr = ST->getBasePtr();
9939     isLoad = false;
9940   } else {
9941     return false;
9942   }
9943 
9944   if (Ptr.getNode()->hasOneUse())
9945     return false;
9946 
9947   for (SDNode *Op : Ptr.getNode()->uses()) {
9948     if (Op == N ||
9949         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9950       continue;
9951 
9952     SDValue BasePtr;
9953     SDValue Offset;
9954     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9955     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9956       // Don't create a indexed load / store with zero offset.
9957       if (isNullConstant(Offset))
9958         continue;
9959 
9960       // Try turning it into a post-indexed load / store except when
9961       // 1) All uses are load / store ops that use it as base ptr (and
9962       //    it may be folded as addressing mmode).
9963       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9964       //    nor a successor of N. Otherwise, if Op is folded that would
9965       //    create a cycle.
9966 
9967       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9968         continue;
9969 
9970       // Check for #1.
9971       bool TryNext = false;
9972       for (SDNode *Use : BasePtr.getNode()->uses()) {
9973         if (Use == Ptr.getNode())
9974           continue;
9975 
9976         // If all the uses are load / store addresses, then don't do the
9977         // transformation.
9978         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9979           bool RealUse = false;
9980           for (SDNode *UseUse : Use->uses()) {
9981             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9982               RealUse = true;
9983           }
9984 
9985           if (!RealUse) {
9986             TryNext = true;
9987             break;
9988           }
9989         }
9990       }
9991 
9992       if (TryNext)
9993         continue;
9994 
9995       // Check for #2
9996       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9997         SDValue Result = isLoad
9998           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9999                                BasePtr, Offset, AM)
10000           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10001                                 BasePtr, Offset, AM);
10002         ++PostIndexedNodes;
10003         ++NodesCombined;
10004         DEBUG(dbgs() << "\nReplacing.5 ";
10005               N->dump(&DAG);
10006               dbgs() << "\nWith: ";
10007               Result.getNode()->dump(&DAG);
10008               dbgs() << '\n');
10009         WorklistRemover DeadNodes(*this);
10010         if (isLoad) {
10011           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10012           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10013         } else {
10014           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10015         }
10016 
10017         // Finally, since the node is now dead, remove it from the graph.
10018         deleteAndRecombine(N);
10019 
10020         // Replace the uses of Use with uses of the updated base value.
10021         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10022                                       Result.getValue(isLoad ? 1 : 0));
10023         deleteAndRecombine(Op);
10024         return true;
10025       }
10026     }
10027   }
10028 
10029   return false;
10030 }
10031 
10032 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
10033 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
10034   ISD::MemIndexedMode AM = LD->getAddressingMode();
10035   assert(AM != ISD::UNINDEXED);
10036   SDValue BP = LD->getOperand(1);
10037   SDValue Inc = LD->getOperand(2);
10038 
10039   // Some backends use TargetConstants for load offsets, but don't expect
10040   // TargetConstants in general ADD nodes. We can convert these constants into
10041   // regular Constants (if the constant is not opaque).
10042   assert((Inc.getOpcode() != ISD::TargetConstant ||
10043           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
10044          "Cannot split out indexing using opaque target constants");
10045   if (Inc.getOpcode() == ISD::TargetConstant) {
10046     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
10047     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
10048                           ConstInc->getValueType(0));
10049   }
10050 
10051   unsigned Opc =
10052       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
10053   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
10054 }
10055 
10056 SDValue DAGCombiner::visitLOAD(SDNode *N) {
10057   LoadSDNode *LD  = cast<LoadSDNode>(N);
10058   SDValue Chain = LD->getChain();
10059   SDValue Ptr   = LD->getBasePtr();
10060 
10061   // If load is not volatile and there are no uses of the loaded value (and
10062   // the updated indexed value in case of indexed loads), change uses of the
10063   // chain value into uses of the chain input (i.e. delete the dead load).
10064   if (!LD->isVolatile()) {
10065     if (N->getValueType(1) == MVT::Other) {
10066       // Unindexed loads.
10067       if (!N->hasAnyUseOfValue(0)) {
10068         // It's not safe to use the two value CombineTo variant here. e.g.
10069         // v1, chain2 = load chain1, loc
10070         // v2, chain3 = load chain2, loc
10071         // v3         = add v2, c
10072         // Now we replace use of chain2 with chain1.  This makes the second load
10073         // isomorphic to the one we are deleting, and thus makes this load live.
10074         DEBUG(dbgs() << "\nReplacing.6 ";
10075               N->dump(&DAG);
10076               dbgs() << "\nWith chain: ";
10077               Chain.getNode()->dump(&DAG);
10078               dbgs() << "\n");
10079         WorklistRemover DeadNodes(*this);
10080         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10081 
10082         if (N->use_empty())
10083           deleteAndRecombine(N);
10084 
10085         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10086       }
10087     } else {
10088       // Indexed loads.
10089       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
10090 
10091       // If this load has an opaque TargetConstant offset, then we cannot split
10092       // the indexing into an add/sub directly (that TargetConstant may not be
10093       // valid for a different type of node, and we cannot convert an opaque
10094       // target constant into a regular constant).
10095       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
10096                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
10097 
10098       if (!N->hasAnyUseOfValue(0) &&
10099           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
10100         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
10101         SDValue Index;
10102         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
10103           Index = SplitIndexingFromLoad(LD);
10104           // Try to fold the base pointer arithmetic into subsequent loads and
10105           // stores.
10106           AddUsersToWorklist(N);
10107         } else
10108           Index = DAG.getUNDEF(N->getValueType(1));
10109         DEBUG(dbgs() << "\nReplacing.7 ";
10110               N->dump(&DAG);
10111               dbgs() << "\nWith: ";
10112               Undef.getNode()->dump(&DAG);
10113               dbgs() << " and 2 other values\n");
10114         WorklistRemover DeadNodes(*this);
10115         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
10116         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
10117         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
10118         deleteAndRecombine(N);
10119         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10120       }
10121     }
10122   }
10123 
10124   // If this load is directly stored, replace the load value with the stored
10125   // value.
10126   // TODO: Handle store large -> read small portion.
10127   // TODO: Handle TRUNCSTORE/LOADEXT
10128   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
10129     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
10130       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
10131       if (PrevST->getBasePtr() == Ptr &&
10132           PrevST->getValue().getValueType() == N->getValueType(0))
10133       return CombineTo(N, Chain.getOperand(1), Chain);
10134     }
10135   }
10136 
10137   // Try to infer better alignment information than the load already has.
10138   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
10139     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10140       if (Align > LD->getMemOperand()->getBaseAlignment()) {
10141         SDValue NewLoad =
10142                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
10143                               LD->getValueType(0),
10144                               Chain, Ptr, LD->getPointerInfo(),
10145                               LD->getMemoryVT(),
10146                               LD->isVolatile(), LD->isNonTemporal(),
10147                               LD->isInvariant(), Align, LD->getAAInfo());
10148         if (NewLoad.getNode() != N)
10149           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
10150       }
10151     }
10152   }
10153 
10154   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10155                                                   : DAG.getSubtarget().useAA();
10156 #ifndef NDEBUG
10157   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10158       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10159     UseAA = false;
10160 #endif
10161   if (UseAA && LD->isUnindexed()) {
10162     // Walk up chain skipping non-aliasing memory nodes.
10163     SDValue BetterChain = FindBetterChain(N, Chain);
10164 
10165     // If there is a better chain.
10166     if (Chain != BetterChain) {
10167       SDValue ReplLoad;
10168 
10169       // Replace the chain to void dependency.
10170       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
10171         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
10172                                BetterChain, Ptr, LD->getMemOperand());
10173       } else {
10174         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
10175                                   LD->getValueType(0),
10176                                   BetterChain, Ptr, LD->getMemoryVT(),
10177                                   LD->getMemOperand());
10178       }
10179 
10180       // Create token factor to keep old chain connected.
10181       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10182                                   MVT::Other, Chain, ReplLoad.getValue(1));
10183 
10184       // Make sure the new and old chains are cleaned up.
10185       AddToWorklist(Token.getNode());
10186 
10187       // Replace uses with load result and token factor. Don't add users
10188       // to work list.
10189       return CombineTo(N, ReplLoad.getValue(0), Token, false);
10190     }
10191   }
10192 
10193   // Try transforming N to an indexed load.
10194   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10195     return SDValue(N, 0);
10196 
10197   // Try to slice up N to more direct loads if the slices are mapped to
10198   // different register banks or pairing can take place.
10199   if (SliceUpLoad(N))
10200     return SDValue(N, 0);
10201 
10202   return SDValue();
10203 }
10204 
10205 namespace {
10206 /// \brief Helper structure used to slice a load in smaller loads.
10207 /// Basically a slice is obtained from the following sequence:
10208 /// Origin = load Ty1, Base
10209 /// Shift = srl Ty1 Origin, CstTy Amount
10210 /// Inst = trunc Shift to Ty2
10211 ///
10212 /// Then, it will be rewriten into:
10213 /// Slice = load SliceTy, Base + SliceOffset
10214 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
10215 ///
10216 /// SliceTy is deduced from the number of bits that are actually used to
10217 /// build Inst.
10218 struct LoadedSlice {
10219   /// \brief Helper structure used to compute the cost of a slice.
10220   struct Cost {
10221     /// Are we optimizing for code size.
10222     bool ForCodeSize;
10223     /// Various cost.
10224     unsigned Loads;
10225     unsigned Truncates;
10226     unsigned CrossRegisterBanksCopies;
10227     unsigned ZExts;
10228     unsigned Shift;
10229 
10230     Cost(bool ForCodeSize = false)
10231         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
10232           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
10233 
10234     /// \brief Get the cost of one isolated slice.
10235     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
10236         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
10237           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
10238       EVT TruncType = LS.Inst->getValueType(0);
10239       EVT LoadedType = LS.getLoadedType();
10240       if (TruncType != LoadedType &&
10241           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
10242         ZExts = 1;
10243     }
10244 
10245     /// \brief Account for slicing gain in the current cost.
10246     /// Slicing provide a few gains like removing a shift or a
10247     /// truncate. This method allows to grow the cost of the original
10248     /// load with the gain from this slice.
10249     void addSliceGain(const LoadedSlice &LS) {
10250       // Each slice saves a truncate.
10251       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
10252       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
10253                               LS.Inst->getValueType(0)))
10254         ++Truncates;
10255       // If there is a shift amount, this slice gets rid of it.
10256       if (LS.Shift)
10257         ++Shift;
10258       // If this slice can merge a cross register bank copy, account for it.
10259       if (LS.canMergeExpensiveCrossRegisterBankCopy())
10260         ++CrossRegisterBanksCopies;
10261     }
10262 
10263     Cost &operator+=(const Cost &RHS) {
10264       Loads += RHS.Loads;
10265       Truncates += RHS.Truncates;
10266       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
10267       ZExts += RHS.ZExts;
10268       Shift += RHS.Shift;
10269       return *this;
10270     }
10271 
10272     bool operator==(const Cost &RHS) const {
10273       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
10274              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
10275              ZExts == RHS.ZExts && Shift == RHS.Shift;
10276     }
10277 
10278     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10279 
10280     bool operator<(const Cost &RHS) const {
10281       // Assume cross register banks copies are as expensive as loads.
10282       // FIXME: Do we want some more target hooks?
10283       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10284       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10285       // Unless we are optimizing for code size, consider the
10286       // expensive operation first.
10287       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10288         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10289       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10290              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10291     }
10292 
10293     bool operator>(const Cost &RHS) const { return RHS < *this; }
10294 
10295     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10296 
10297     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10298   };
10299   // The last instruction that represent the slice. This should be a
10300   // truncate instruction.
10301   SDNode *Inst;
10302   // The original load instruction.
10303   LoadSDNode *Origin;
10304   // The right shift amount in bits from the original load.
10305   unsigned Shift;
10306   // The DAG from which Origin came from.
10307   // This is used to get some contextual information about legal types, etc.
10308   SelectionDAG *DAG;
10309 
10310   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10311               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10312       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10313 
10314   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10315   /// \return Result is \p BitWidth and has used bits set to 1 and
10316   ///         not used bits set to 0.
10317   APInt getUsedBits() const {
10318     // Reproduce the trunc(lshr) sequence:
10319     // - Start from the truncated value.
10320     // - Zero extend to the desired bit width.
10321     // - Shift left.
10322     assert(Origin && "No original load to compare against.");
10323     unsigned BitWidth = Origin->getValueSizeInBits(0);
10324     assert(Inst && "This slice is not bound to an instruction");
10325     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10326            "Extracted slice is bigger than the whole type!");
10327     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10328     UsedBits.setAllBits();
10329     UsedBits = UsedBits.zext(BitWidth);
10330     UsedBits <<= Shift;
10331     return UsedBits;
10332   }
10333 
10334   /// \brief Get the size of the slice to be loaded in bytes.
10335   unsigned getLoadedSize() const {
10336     unsigned SliceSize = getUsedBits().countPopulation();
10337     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10338     return SliceSize / 8;
10339   }
10340 
10341   /// \brief Get the type that will be loaded for this slice.
10342   /// Note: This may not be the final type for the slice.
10343   EVT getLoadedType() const {
10344     assert(DAG && "Missing context");
10345     LLVMContext &Ctxt = *DAG->getContext();
10346     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10347   }
10348 
10349   /// \brief Get the alignment of the load used for this slice.
10350   unsigned getAlignment() const {
10351     unsigned Alignment = Origin->getAlignment();
10352     unsigned Offset = getOffsetFromBase();
10353     if (Offset != 0)
10354       Alignment = MinAlign(Alignment, Alignment + Offset);
10355     return Alignment;
10356   }
10357 
10358   /// \brief Check if this slice can be rewritten with legal operations.
10359   bool isLegal() const {
10360     // An invalid slice is not legal.
10361     if (!Origin || !Inst || !DAG)
10362       return false;
10363 
10364     // Offsets are for indexed load only, we do not handle that.
10365     if (!Origin->getOffset().isUndef())
10366       return false;
10367 
10368     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10369 
10370     // Check that the type is legal.
10371     EVT SliceType = getLoadedType();
10372     if (!TLI.isTypeLegal(SliceType))
10373       return false;
10374 
10375     // Check that the load is legal for this type.
10376     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10377       return false;
10378 
10379     // Check that the offset can be computed.
10380     // 1. Check its type.
10381     EVT PtrType = Origin->getBasePtr().getValueType();
10382     if (PtrType == MVT::Untyped || PtrType.isExtended())
10383       return false;
10384 
10385     // 2. Check that it fits in the immediate.
10386     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10387       return false;
10388 
10389     // 3. Check that the computation is legal.
10390     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10391       return false;
10392 
10393     // Check that the zext is legal if it needs one.
10394     EVT TruncateType = Inst->getValueType(0);
10395     if (TruncateType != SliceType &&
10396         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10397       return false;
10398 
10399     return true;
10400   }
10401 
10402   /// \brief Get the offset in bytes of this slice in the original chunk of
10403   /// bits.
10404   /// \pre DAG != nullptr.
10405   uint64_t getOffsetFromBase() const {
10406     assert(DAG && "Missing context.");
10407     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10408     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10409     uint64_t Offset = Shift / 8;
10410     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10411     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10412            "The size of the original loaded type is not a multiple of a"
10413            " byte.");
10414     // If Offset is bigger than TySizeInBytes, it means we are loading all
10415     // zeros. This should have been optimized before in the process.
10416     assert(TySizeInBytes > Offset &&
10417            "Invalid shift amount for given loaded size");
10418     if (IsBigEndian)
10419       Offset = TySizeInBytes - Offset - getLoadedSize();
10420     return Offset;
10421   }
10422 
10423   /// \brief Generate the sequence of instructions to load the slice
10424   /// represented by this object and redirect the uses of this slice to
10425   /// this new sequence of instructions.
10426   /// \pre this->Inst && this->Origin are valid Instructions and this
10427   /// object passed the legal check: LoadedSlice::isLegal returned true.
10428   /// \return The last instruction of the sequence used to load the slice.
10429   SDValue loadSlice() const {
10430     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10431     const SDValue &OldBaseAddr = Origin->getBasePtr();
10432     SDValue BaseAddr = OldBaseAddr;
10433     // Get the offset in that chunk of bytes w.r.t. the endianess.
10434     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10435     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10436     if (Offset) {
10437       // BaseAddr = BaseAddr + Offset.
10438       EVT ArithType = BaseAddr.getValueType();
10439       SDLoc DL(Origin);
10440       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10441                               DAG->getConstant(Offset, DL, ArithType));
10442     }
10443 
10444     // Create the type of the loaded slice according to its size.
10445     EVT SliceType = getLoadedType();
10446 
10447     // Create the load for the slice.
10448     SDValue LastInst = DAG->getLoad(
10449         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10450         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10451         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10452     // If the final type is not the same as the loaded type, this means that
10453     // we have to pad with zero. Create a zero extend for that.
10454     EVT FinalType = Inst->getValueType(0);
10455     if (SliceType != FinalType)
10456       LastInst =
10457           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10458     return LastInst;
10459   }
10460 
10461   /// \brief Check if this slice can be merged with an expensive cross register
10462   /// bank copy. E.g.,
10463   /// i = load i32
10464   /// f = bitcast i32 i to float
10465   bool canMergeExpensiveCrossRegisterBankCopy() const {
10466     if (!Inst || !Inst->hasOneUse())
10467       return false;
10468     SDNode *Use = *Inst->use_begin();
10469     if (Use->getOpcode() != ISD::BITCAST)
10470       return false;
10471     assert(DAG && "Missing context");
10472     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10473     EVT ResVT = Use->getValueType(0);
10474     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10475     const TargetRegisterClass *ArgRC =
10476         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10477     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10478       return false;
10479 
10480     // At this point, we know that we perform a cross-register-bank copy.
10481     // Check if it is expensive.
10482     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10483     // Assume bitcasts are cheap, unless both register classes do not
10484     // explicitly share a common sub class.
10485     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10486       return false;
10487 
10488     // Check if it will be merged with the load.
10489     // 1. Check the alignment constraint.
10490     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10491         ResVT.getTypeForEVT(*DAG->getContext()));
10492 
10493     if (RequiredAlignment > getAlignment())
10494       return false;
10495 
10496     // 2. Check that the load is a legal operation for that type.
10497     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10498       return false;
10499 
10500     // 3. Check that we do not have a zext in the way.
10501     if (Inst->getValueType(0) != getLoadedType())
10502       return false;
10503 
10504     return true;
10505   }
10506 };
10507 }
10508 
10509 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10510 /// \p UsedBits looks like 0..0 1..1 0..0.
10511 static bool areUsedBitsDense(const APInt &UsedBits) {
10512   // If all the bits are one, this is dense!
10513   if (UsedBits.isAllOnesValue())
10514     return true;
10515 
10516   // Get rid of the unused bits on the right.
10517   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10518   // Get rid of the unused bits on the left.
10519   if (NarrowedUsedBits.countLeadingZeros())
10520     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10521   // Check that the chunk of bits is completely used.
10522   return NarrowedUsedBits.isAllOnesValue();
10523 }
10524 
10525 /// \brief Check whether or not \p First and \p Second are next to each other
10526 /// in memory. This means that there is no hole between the bits loaded
10527 /// by \p First and the bits loaded by \p Second.
10528 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10529                                      const LoadedSlice &Second) {
10530   assert(First.Origin == Second.Origin && First.Origin &&
10531          "Unable to match different memory origins.");
10532   APInt UsedBits = First.getUsedBits();
10533   assert((UsedBits & Second.getUsedBits()) == 0 &&
10534          "Slices are not supposed to overlap.");
10535   UsedBits |= Second.getUsedBits();
10536   return areUsedBitsDense(UsedBits);
10537 }
10538 
10539 /// \brief Adjust the \p GlobalLSCost according to the target
10540 /// paring capabilities and the layout of the slices.
10541 /// \pre \p GlobalLSCost should account for at least as many loads as
10542 /// there is in the slices in \p LoadedSlices.
10543 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10544                                  LoadedSlice::Cost &GlobalLSCost) {
10545   unsigned NumberOfSlices = LoadedSlices.size();
10546   // If there is less than 2 elements, no pairing is possible.
10547   if (NumberOfSlices < 2)
10548     return;
10549 
10550   // Sort the slices so that elements that are likely to be next to each
10551   // other in memory are next to each other in the list.
10552   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10553             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10554     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10555     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10556   });
10557   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10558   // First (resp. Second) is the first (resp. Second) potentially candidate
10559   // to be placed in a paired load.
10560   const LoadedSlice *First = nullptr;
10561   const LoadedSlice *Second = nullptr;
10562   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10563                 // Set the beginning of the pair.
10564                                                            First = Second) {
10565 
10566     Second = &LoadedSlices[CurrSlice];
10567 
10568     // If First is NULL, it means we start a new pair.
10569     // Get to the next slice.
10570     if (!First)
10571       continue;
10572 
10573     EVT LoadedType = First->getLoadedType();
10574 
10575     // If the types of the slices are different, we cannot pair them.
10576     if (LoadedType != Second->getLoadedType())
10577       continue;
10578 
10579     // Check if the target supplies paired loads for this type.
10580     unsigned RequiredAlignment = 0;
10581     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10582       // move to the next pair, this type is hopeless.
10583       Second = nullptr;
10584       continue;
10585     }
10586     // Check if we meet the alignment requirement.
10587     if (RequiredAlignment > First->getAlignment())
10588       continue;
10589 
10590     // Check that both loads are next to each other in memory.
10591     if (!areSlicesNextToEachOther(*First, *Second))
10592       continue;
10593 
10594     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10595     --GlobalLSCost.Loads;
10596     // Move to the next pair.
10597     Second = nullptr;
10598   }
10599 }
10600 
10601 /// \brief Check the profitability of all involved LoadedSlice.
10602 /// Currently, it is considered profitable if there is exactly two
10603 /// involved slices (1) which are (2) next to each other in memory, and
10604 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10605 ///
10606 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10607 /// the elements themselves.
10608 ///
10609 /// FIXME: When the cost model will be mature enough, we can relax
10610 /// constraints (1) and (2).
10611 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10612                                 const APInt &UsedBits, bool ForCodeSize) {
10613   unsigned NumberOfSlices = LoadedSlices.size();
10614   if (StressLoadSlicing)
10615     return NumberOfSlices > 1;
10616 
10617   // Check (1).
10618   if (NumberOfSlices != 2)
10619     return false;
10620 
10621   // Check (2).
10622   if (!areUsedBitsDense(UsedBits))
10623     return false;
10624 
10625   // Check (3).
10626   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10627   // The original code has one big load.
10628   OrigCost.Loads = 1;
10629   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10630     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10631     // Accumulate the cost of all the slices.
10632     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10633     GlobalSlicingCost += SliceCost;
10634 
10635     // Account as cost in the original configuration the gain obtained
10636     // with the current slices.
10637     OrigCost.addSliceGain(LS);
10638   }
10639 
10640   // If the target supports paired load, adjust the cost accordingly.
10641   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10642   return OrigCost > GlobalSlicingCost;
10643 }
10644 
10645 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10646 /// operations, split it in the various pieces being extracted.
10647 ///
10648 /// This sort of thing is introduced by SROA.
10649 /// This slicing takes care not to insert overlapping loads.
10650 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10651 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10652   if (Level < AfterLegalizeDAG)
10653     return false;
10654 
10655   LoadSDNode *LD = cast<LoadSDNode>(N);
10656   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10657       !LD->getValueType(0).isInteger())
10658     return false;
10659 
10660   // Keep track of already used bits to detect overlapping values.
10661   // In that case, we will just abort the transformation.
10662   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10663 
10664   SmallVector<LoadedSlice, 4> LoadedSlices;
10665 
10666   // Check if this load is used as several smaller chunks of bits.
10667   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10668   // of computation for each trunc.
10669   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10670        UI != UIEnd; ++UI) {
10671     // Skip the uses of the chain.
10672     if (UI.getUse().getResNo() != 0)
10673       continue;
10674 
10675     SDNode *User = *UI;
10676     unsigned Shift = 0;
10677 
10678     // Check if this is a trunc(lshr).
10679     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10680         isa<ConstantSDNode>(User->getOperand(1))) {
10681       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10682       User = *User->use_begin();
10683     }
10684 
10685     // At this point, User is a Truncate, iff we encountered, trunc or
10686     // trunc(lshr).
10687     if (User->getOpcode() != ISD::TRUNCATE)
10688       return false;
10689 
10690     // The width of the type must be a power of 2 and greater than 8-bits.
10691     // Otherwise the load cannot be represented in LLVM IR.
10692     // Moreover, if we shifted with a non-8-bits multiple, the slice
10693     // will be across several bytes. We do not support that.
10694     unsigned Width = User->getValueSizeInBits(0);
10695     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10696       return 0;
10697 
10698     // Build the slice for this chain of computations.
10699     LoadedSlice LS(User, LD, Shift, &DAG);
10700     APInt CurrentUsedBits = LS.getUsedBits();
10701 
10702     // Check if this slice overlaps with another.
10703     if ((CurrentUsedBits & UsedBits) != 0)
10704       return false;
10705     // Update the bits used globally.
10706     UsedBits |= CurrentUsedBits;
10707 
10708     // Check if the new slice would be legal.
10709     if (!LS.isLegal())
10710       return false;
10711 
10712     // Record the slice.
10713     LoadedSlices.push_back(LS);
10714   }
10715 
10716   // Abort slicing if it does not seem to be profitable.
10717   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10718     return false;
10719 
10720   ++SlicedLoads;
10721 
10722   // Rewrite each chain to use an independent load.
10723   // By construction, each chain can be represented by a unique load.
10724 
10725   // Prepare the argument for the new token factor for all the slices.
10726   SmallVector<SDValue, 8> ArgChains;
10727   for (SmallVectorImpl<LoadedSlice>::const_iterator
10728            LSIt = LoadedSlices.begin(),
10729            LSItEnd = LoadedSlices.end();
10730        LSIt != LSItEnd; ++LSIt) {
10731     SDValue SliceInst = LSIt->loadSlice();
10732     CombineTo(LSIt->Inst, SliceInst, true);
10733     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10734       SliceInst = SliceInst.getOperand(0);
10735     assert(SliceInst->getOpcode() == ISD::LOAD &&
10736            "It takes more than a zext to get to the loaded slice!!");
10737     ArgChains.push_back(SliceInst.getValue(1));
10738   }
10739 
10740   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10741                               ArgChains);
10742   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10743   return true;
10744 }
10745 
10746 /// Check to see if V is (and load (ptr), imm), where the load is having
10747 /// specific bytes cleared out.  If so, return the byte size being masked out
10748 /// and the shift amount.
10749 static std::pair<unsigned, unsigned>
10750 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10751   std::pair<unsigned, unsigned> Result(0, 0);
10752 
10753   // Check for the structure we're looking for.
10754   if (V->getOpcode() != ISD::AND ||
10755       !isa<ConstantSDNode>(V->getOperand(1)) ||
10756       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10757     return Result;
10758 
10759   // Check the chain and pointer.
10760   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10761   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10762 
10763   // The store should be chained directly to the load or be an operand of a
10764   // tokenfactor.
10765   if (LD == Chain.getNode())
10766     ; // ok.
10767   else if (Chain->getOpcode() != ISD::TokenFactor)
10768     return Result; // Fail.
10769   else {
10770     bool isOk = false;
10771     for (const SDValue &ChainOp : Chain->op_values())
10772       if (ChainOp.getNode() == LD) {
10773         isOk = true;
10774         break;
10775       }
10776     if (!isOk) return Result;
10777   }
10778 
10779   // This only handles simple types.
10780   if (V.getValueType() != MVT::i16 &&
10781       V.getValueType() != MVT::i32 &&
10782       V.getValueType() != MVT::i64)
10783     return Result;
10784 
10785   // Check the constant mask.  Invert it so that the bits being masked out are
10786   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10787   // follow the sign bit for uniformity.
10788   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10789   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10790   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10791   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10792   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10793   if (NotMaskLZ == 64) return Result;  // All zero mask.
10794 
10795   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10796   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10797     return Result;
10798 
10799   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10800   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10801     NotMaskLZ -= 64-V.getValueSizeInBits();
10802 
10803   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10804   switch (MaskedBytes) {
10805   case 1:
10806   case 2:
10807   case 4: break;
10808   default: return Result; // All one mask, or 5-byte mask.
10809   }
10810 
10811   // Verify that the first bit starts at a multiple of mask so that the access
10812   // is aligned the same as the access width.
10813   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10814 
10815   Result.first = MaskedBytes;
10816   Result.second = NotMaskTZ/8;
10817   return Result;
10818 }
10819 
10820 
10821 /// Check to see if IVal is something that provides a value as specified by
10822 /// MaskInfo. If so, replace the specified store with a narrower store of
10823 /// truncated IVal.
10824 static SDNode *
10825 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10826                                 SDValue IVal, StoreSDNode *St,
10827                                 DAGCombiner *DC) {
10828   unsigned NumBytes = MaskInfo.first;
10829   unsigned ByteShift = MaskInfo.second;
10830   SelectionDAG &DAG = DC->getDAG();
10831 
10832   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10833   // that uses this.  If not, this is not a replacement.
10834   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10835                                   ByteShift*8, (ByteShift+NumBytes)*8);
10836   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10837 
10838   // Check that it is legal on the target to do this.  It is legal if the new
10839   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10840   // legalization.
10841   MVT VT = MVT::getIntegerVT(NumBytes*8);
10842   if (!DC->isTypeLegal(VT))
10843     return nullptr;
10844 
10845   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10846   // shifted by ByteShift and truncated down to NumBytes.
10847   if (ByteShift) {
10848     SDLoc DL(IVal);
10849     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10850                        DAG.getConstant(ByteShift*8, DL,
10851                                     DC->getShiftAmountTy(IVal.getValueType())));
10852   }
10853 
10854   // Figure out the offset for the store and the alignment of the access.
10855   unsigned StOffset;
10856   unsigned NewAlign = St->getAlignment();
10857 
10858   if (DAG.getDataLayout().isLittleEndian())
10859     StOffset = ByteShift;
10860   else
10861     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10862 
10863   SDValue Ptr = St->getBasePtr();
10864   if (StOffset) {
10865     SDLoc DL(IVal);
10866     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10867                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10868     NewAlign = MinAlign(NewAlign, StOffset);
10869   }
10870 
10871   // Truncate down to the new size.
10872   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10873 
10874   ++OpsNarrowed;
10875   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10876                       St->getPointerInfo().getWithOffset(StOffset),
10877                       false, false, NewAlign).getNode();
10878 }
10879 
10880 
10881 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10882 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10883 /// narrowing the load and store if it would end up being a win for performance
10884 /// or code size.
10885 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10886   StoreSDNode *ST  = cast<StoreSDNode>(N);
10887   if (ST->isVolatile())
10888     return SDValue();
10889 
10890   SDValue Chain = ST->getChain();
10891   SDValue Value = ST->getValue();
10892   SDValue Ptr   = ST->getBasePtr();
10893   EVT VT = Value.getValueType();
10894 
10895   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10896     return SDValue();
10897 
10898   unsigned Opc = Value.getOpcode();
10899 
10900   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10901   // is a byte mask indicating a consecutive number of bytes, check to see if
10902   // Y is known to provide just those bytes.  If so, we try to replace the
10903   // load + replace + store sequence with a single (narrower) store, which makes
10904   // the load dead.
10905   if (Opc == ISD::OR) {
10906     std::pair<unsigned, unsigned> MaskedLoad;
10907     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10908     if (MaskedLoad.first)
10909       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10910                                                   Value.getOperand(1), ST,this))
10911         return SDValue(NewST, 0);
10912 
10913     // Or is commutative, so try swapping X and Y.
10914     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10915     if (MaskedLoad.first)
10916       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10917                                                   Value.getOperand(0), ST,this))
10918         return SDValue(NewST, 0);
10919   }
10920 
10921   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10922       Value.getOperand(1).getOpcode() != ISD::Constant)
10923     return SDValue();
10924 
10925   SDValue N0 = Value.getOperand(0);
10926   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10927       Chain == SDValue(N0.getNode(), 1)) {
10928     LoadSDNode *LD = cast<LoadSDNode>(N0);
10929     if (LD->getBasePtr() != Ptr ||
10930         LD->getPointerInfo().getAddrSpace() !=
10931         ST->getPointerInfo().getAddrSpace())
10932       return SDValue();
10933 
10934     // Find the type to narrow it the load / op / store to.
10935     SDValue N1 = Value.getOperand(1);
10936     unsigned BitWidth = N1.getValueSizeInBits();
10937     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10938     if (Opc == ISD::AND)
10939       Imm ^= APInt::getAllOnesValue(BitWidth);
10940     if (Imm == 0 || Imm.isAllOnesValue())
10941       return SDValue();
10942     unsigned ShAmt = Imm.countTrailingZeros();
10943     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10944     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10945     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10946     // The narrowing should be profitable, the load/store operation should be
10947     // legal (or custom) and the store size should be equal to the NewVT width.
10948     while (NewBW < BitWidth &&
10949            (NewVT.getStoreSizeInBits() != NewBW ||
10950             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10951             !TLI.isNarrowingProfitable(VT, NewVT))) {
10952       NewBW = NextPowerOf2(NewBW);
10953       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10954     }
10955     if (NewBW >= BitWidth)
10956       return SDValue();
10957 
10958     // If the lsb changed does not start at the type bitwidth boundary,
10959     // start at the previous one.
10960     if (ShAmt % NewBW)
10961       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10962     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10963                                    std::min(BitWidth, ShAmt + NewBW));
10964     if ((Imm & Mask) == Imm) {
10965       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10966       if (Opc == ISD::AND)
10967         NewImm ^= APInt::getAllOnesValue(NewBW);
10968       uint64_t PtrOff = ShAmt / 8;
10969       // For big endian targets, we need to adjust the offset to the pointer to
10970       // load the correct bytes.
10971       if (DAG.getDataLayout().isBigEndian())
10972         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10973 
10974       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10975       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10976       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10977         return SDValue();
10978 
10979       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10980                                    Ptr.getValueType(), Ptr,
10981                                    DAG.getConstant(PtrOff, SDLoc(LD),
10982                                                    Ptr.getValueType()));
10983       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10984                                   LD->getChain(), NewPtr,
10985                                   LD->getPointerInfo().getWithOffset(PtrOff),
10986                                   LD->isVolatile(), LD->isNonTemporal(),
10987                                   LD->isInvariant(), NewAlign,
10988                                   LD->getAAInfo());
10989       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10990                                    DAG.getConstant(NewImm, SDLoc(Value),
10991                                                    NewVT));
10992       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10993                                    NewVal, NewPtr,
10994                                    ST->getPointerInfo().getWithOffset(PtrOff),
10995                                    false, false, NewAlign);
10996 
10997       AddToWorklist(NewPtr.getNode());
10998       AddToWorklist(NewLD.getNode());
10999       AddToWorklist(NewVal.getNode());
11000       WorklistRemover DeadNodes(*this);
11001       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11002       ++OpsNarrowed;
11003       return NewST;
11004     }
11005   }
11006 
11007   return SDValue();
11008 }
11009 
11010 /// For a given floating point load / store pair, if the load value isn't used
11011 /// by any other operations, then consider transforming the pair to integer
11012 /// load / store operations if the target deems the transformation profitable.
11013 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11014   StoreSDNode *ST  = cast<StoreSDNode>(N);
11015   SDValue Chain = ST->getChain();
11016   SDValue Value = ST->getValue();
11017   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11018       Value.hasOneUse() &&
11019       Chain == SDValue(Value.getNode(), 1)) {
11020     LoadSDNode *LD = cast<LoadSDNode>(Value);
11021     EVT VT = LD->getMemoryVT();
11022     if (!VT.isFloatingPoint() ||
11023         VT != ST->getMemoryVT() ||
11024         LD->isNonTemporal() ||
11025         ST->isNonTemporal() ||
11026         LD->getPointerInfo().getAddrSpace() != 0 ||
11027         ST->getPointerInfo().getAddrSpace() != 0)
11028       return SDValue();
11029 
11030     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11031     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11032         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11033         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11034         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11035       return SDValue();
11036 
11037     unsigned LDAlign = LD->getAlignment();
11038     unsigned STAlign = ST->getAlignment();
11039     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
11040     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
11041     if (LDAlign < ABIAlign || STAlign < ABIAlign)
11042       return SDValue();
11043 
11044     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
11045                                 LD->getChain(), LD->getBasePtr(),
11046                                 LD->getPointerInfo(),
11047                                 false, false, false, LDAlign);
11048 
11049     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
11050                                  NewLD, ST->getBasePtr(),
11051                                  ST->getPointerInfo(),
11052                                  false, false, STAlign);
11053 
11054     AddToWorklist(NewLD.getNode());
11055     AddToWorklist(NewST.getNode());
11056     WorklistRemover DeadNodes(*this);
11057     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
11058     ++LdStFP2Int;
11059     return NewST;
11060   }
11061 
11062   return SDValue();
11063 }
11064 
11065 namespace {
11066 /// Helper struct to parse and store a memory address as base + index + offset.
11067 /// We ignore sign extensions when it is safe to do so.
11068 /// The following two expressions are not equivalent. To differentiate we need
11069 /// to store whether there was a sign extension involved in the index
11070 /// computation.
11071 ///  (load (i64 add (i64 copyfromreg %c)
11072 ///                 (i64 signextend (add (i8 load %index)
11073 ///                                      (i8 1))))
11074 /// vs
11075 ///
11076 /// (load (i64 add (i64 copyfromreg %c)
11077 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
11078 ///                                         (i32 1)))))
11079 struct BaseIndexOffset {
11080   SDValue Base;
11081   SDValue Index;
11082   int64_t Offset;
11083   bool IsIndexSignExt;
11084 
11085   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
11086 
11087   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
11088                   bool IsIndexSignExt) :
11089     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
11090 
11091   bool equalBaseIndex(const BaseIndexOffset &Other) {
11092     return Other.Base == Base && Other.Index == Index &&
11093       Other.IsIndexSignExt == IsIndexSignExt;
11094   }
11095 
11096   /// Parses tree in Ptr for base, index, offset addresses.
11097   static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) {
11098     bool IsIndexSignExt = false;
11099 
11100     // Split up a folded GlobalAddress+Offset into its component parts.
11101     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
11102       if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
11103         return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
11104                                                     SDLoc(GA),
11105                                                     GA->getValueType(0),
11106                                                     /*Offset=*/0,
11107                                                     /*isTargetGA=*/false,
11108                                                     GA->getTargetFlags()),
11109                                SDValue(),
11110                                GA->getOffset(),
11111                                IsIndexSignExt);
11112       }
11113 
11114     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
11115     // instruction, then it could be just the BASE or everything else we don't
11116     // know how to handle. Just use Ptr as BASE and give up.
11117     if (Ptr->getOpcode() != ISD::ADD)
11118       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11119 
11120     // We know that we have at least an ADD instruction. Try to pattern match
11121     // the simple case of BASE + OFFSET.
11122     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
11123       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
11124       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
11125                               IsIndexSignExt);
11126     }
11127 
11128     // Inside a loop the current BASE pointer is calculated using an ADD and a
11129     // MUL instruction. In this case Ptr is the actual BASE pointer.
11130     // (i64 add (i64 %array_ptr)
11131     //          (i64 mul (i64 %induction_var)
11132     //                   (i64 %element_size)))
11133     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
11134       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11135 
11136     // Look at Base + Index + Offset cases.
11137     SDValue Base = Ptr->getOperand(0);
11138     SDValue IndexOffset = Ptr->getOperand(1);
11139 
11140     // Skip signextends.
11141     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
11142       IndexOffset = IndexOffset->getOperand(0);
11143       IsIndexSignExt = true;
11144     }
11145 
11146     // Either the case of Base + Index (no offset) or something else.
11147     if (IndexOffset->getOpcode() != ISD::ADD)
11148       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
11149 
11150     // Now we have the case of Base + Index + offset.
11151     SDValue Index = IndexOffset->getOperand(0);
11152     SDValue Offset = IndexOffset->getOperand(1);
11153 
11154     if (!isa<ConstantSDNode>(Offset))
11155       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
11156 
11157     // Ignore signextends.
11158     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
11159       Index = Index->getOperand(0);
11160       IsIndexSignExt = true;
11161     } else IsIndexSignExt = false;
11162 
11163     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
11164     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
11165   }
11166 };
11167 } // namespace
11168 
11169 // This is a helper function for visitMUL to check the profitability
11170 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
11171 // MulNode is the original multiply, AddNode is (add x, c1),
11172 // and ConstNode is c2.
11173 //
11174 // If the (add x, c1) has multiple uses, we could increase
11175 // the number of adds if we make this transformation.
11176 // It would only be worth doing this if we can remove a
11177 // multiply in the process. Check for that here.
11178 // To illustrate:
11179 //     (A + c1) * c3
11180 //     (A + c2) * c3
11181 // We're checking for cases where we have common "c3 * A" expressions.
11182 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
11183                                               SDValue &AddNode,
11184                                               SDValue &ConstNode) {
11185   APInt Val;
11186 
11187   // If the add only has one use, this would be OK to do.
11188   if (AddNode.getNode()->hasOneUse())
11189     return true;
11190 
11191   // Walk all the users of the constant with which we're multiplying.
11192   for (SDNode *Use : ConstNode->uses()) {
11193 
11194     if (Use == MulNode) // This use is the one we're on right now. Skip it.
11195       continue;
11196 
11197     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
11198       SDNode *OtherOp;
11199       SDNode *MulVar = AddNode.getOperand(0).getNode();
11200 
11201       // OtherOp is what we're multiplying against the constant.
11202       if (Use->getOperand(0) == ConstNode)
11203         OtherOp = Use->getOperand(1).getNode();
11204       else
11205         OtherOp = Use->getOperand(0).getNode();
11206 
11207       // Check to see if multiply is with the same operand of our "add".
11208       //
11209       //     ConstNode  = CONST
11210       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
11211       //     ...
11212       //     AddNode  = (A + c1)  <-- MulVar is A.
11213       //         = AddNode * ConstNode   <-- current visiting instruction.
11214       //
11215       // If we make this transformation, we will have a common
11216       // multiply (ConstNode * A) that we can save.
11217       if (OtherOp == MulVar)
11218         return true;
11219 
11220       // Now check to see if a future expansion will give us a common
11221       // multiply.
11222       //
11223       //     ConstNode  = CONST
11224       //     AddNode    = (A + c1)
11225       //     ...   = AddNode * ConstNode <-- current visiting instruction.
11226       //     ...
11227       //     OtherOp = (A + c2)
11228       //     Use     = OtherOp * ConstNode <-- visiting Use.
11229       //
11230       // If we make this transformation, we will have a common
11231       // multiply (CONST * A) after we also do the same transformation
11232       // to the "t2" instruction.
11233       if (OtherOp->getOpcode() == ISD::ADD &&
11234           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
11235           OtherOp->getOperand(0).getNode() == MulVar)
11236         return true;
11237     }
11238   }
11239 
11240   // Didn't find a case where this would be profitable.
11241   return false;
11242 }
11243 
11244 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
11245                                                   SDLoc SL,
11246                                                   ArrayRef<MemOpLink> Stores,
11247                                                   SmallVectorImpl<SDValue> &Chains,
11248                                                   EVT Ty) const {
11249   SmallVector<SDValue, 8> BuildVector;
11250 
11251   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
11252     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
11253     Chains.push_back(St->getChain());
11254     BuildVector.push_back(St->getValue());
11255   }
11256 
11257   return DAG.getBuildVector(Ty, SL, BuildVector);
11258 }
11259 
11260 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
11261                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
11262                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
11263   // Make sure we have something to merge.
11264   if (NumStores < 2)
11265     return false;
11266 
11267   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11268   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11269   unsigned LatestNodeUsed = 0;
11270 
11271   for (unsigned i=0; i < NumStores; ++i) {
11272     // Find a chain for the new wide-store operand. Notice that some
11273     // of the store nodes that we found may not be selected for inclusion
11274     // in the wide store. The chain we use needs to be the chain of the
11275     // latest store node which is *used* and replaced by the wide store.
11276     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11277       LatestNodeUsed = i;
11278   }
11279 
11280   SmallVector<SDValue, 8> Chains;
11281 
11282   // The latest Node in the DAG.
11283   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11284   SDLoc DL(StoreNodes[0].MemNode);
11285 
11286   SDValue StoredVal;
11287   if (UseVector) {
11288     bool IsVec = MemVT.isVector();
11289     unsigned Elts = NumStores;
11290     if (IsVec) {
11291       // When merging vector stores, get the total number of elements.
11292       Elts *= MemVT.getVectorNumElements();
11293     }
11294     // Get the type for the merged vector store.
11295     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11296     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11297 
11298     if (IsConstantSrc) {
11299       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11300     } else {
11301       SmallVector<SDValue, 8> Ops;
11302       for (unsigned i = 0; i < NumStores; ++i) {
11303         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11304         SDValue Val = St->getValue();
11305         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11306         if (Val.getValueType() != MemVT)
11307           return false;
11308         Ops.push_back(Val);
11309         Chains.push_back(St->getChain());
11310       }
11311 
11312       // Build the extracted vector elements back into a vector.
11313       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11314                               DL, Ty, Ops);    }
11315   } else {
11316     // We should always use a vector store when merging extracted vector
11317     // elements, so this path implies a store of constants.
11318     assert(IsConstantSrc && "Merged vector elements should use vector store");
11319 
11320     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11321     APInt StoreInt(SizeInBits, 0);
11322 
11323     // Construct a single integer constant which is made of the smaller
11324     // constant inputs.
11325     bool IsLE = DAG.getDataLayout().isLittleEndian();
11326     for (unsigned i = 0; i < NumStores; ++i) {
11327       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11328       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11329       Chains.push_back(St->getChain());
11330 
11331       SDValue Val = St->getValue();
11332       StoreInt <<= ElementSizeBytes * 8;
11333       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11334         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11335       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11336         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11337       } else {
11338         llvm_unreachable("Invalid constant element type");
11339       }
11340     }
11341 
11342     // Create the new Load and Store operations.
11343     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11344     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11345   }
11346 
11347   assert(!Chains.empty());
11348 
11349   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11350   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11351                                   FirstInChain->getBasePtr(),
11352                                   FirstInChain->getPointerInfo(),
11353                                   false, false,
11354                                   FirstInChain->getAlignment());
11355 
11356   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11357                                                   : DAG.getSubtarget().useAA();
11358   if (UseAA) {
11359     // Replace all merged stores with the new store.
11360     for (unsigned i = 0; i < NumStores; ++i)
11361       CombineTo(StoreNodes[i].MemNode, NewStore);
11362   } else {
11363     // Replace the last store with the new store.
11364     CombineTo(LatestOp, NewStore);
11365     // Erase all other stores.
11366     for (unsigned i = 0; i < NumStores; ++i) {
11367       if (StoreNodes[i].MemNode == LatestOp)
11368         continue;
11369       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11370       // ReplaceAllUsesWith will replace all uses that existed when it was
11371       // called, but graph optimizations may cause new ones to appear. For
11372       // example, the case in pr14333 looks like
11373       //
11374       //  St's chain -> St -> another store -> X
11375       //
11376       // And the only difference from St to the other store is the chain.
11377       // When we change it's chain to be St's chain they become identical,
11378       // get CSEed and the net result is that X is now a use of St.
11379       // Since we know that St is redundant, just iterate.
11380       while (!St->use_empty())
11381         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11382       deleteAndRecombine(St);
11383     }
11384   }
11385 
11386   return true;
11387 }
11388 
11389 void DAGCombiner::getStoreMergeAndAliasCandidates(
11390     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11391     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11392   // This holds the base pointer, index, and the offset in bytes from the base
11393   // pointer.
11394   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
11395 
11396   // We must have a base and an offset.
11397   if (!BasePtr.Base.getNode())
11398     return;
11399 
11400   // Do not handle stores to undef base pointers.
11401   if (BasePtr.Base.isUndef())
11402     return;
11403 
11404   // Walk up the chain and look for nodes with offsets from the same
11405   // base pointer. Stop when reaching an instruction with a different kind
11406   // or instruction which has a different base pointer.
11407   EVT MemVT = St->getMemoryVT();
11408   unsigned Seq = 0;
11409   StoreSDNode *Index = St;
11410 
11411 
11412   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11413                                                   : DAG.getSubtarget().useAA();
11414 
11415   if (UseAA) {
11416     // Look at other users of the same chain. Stores on the same chain do not
11417     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11418     // to be on the same chain, so don't bother looking at adjacent chains.
11419 
11420     SDValue Chain = St->getChain();
11421     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11422       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11423         if (I.getOperandNo() != 0)
11424           continue;
11425 
11426         if (OtherST->isVolatile() || OtherST->isIndexed())
11427           continue;
11428 
11429         if (OtherST->getMemoryVT() != MemVT)
11430           continue;
11431 
11432         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
11433 
11434         if (Ptr.equalBaseIndex(BasePtr))
11435           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11436       }
11437     }
11438 
11439     return;
11440   }
11441 
11442   while (Index) {
11443     // If the chain has more than one use, then we can't reorder the mem ops.
11444     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11445       break;
11446 
11447     // Find the base pointer and offset for this memory node.
11448     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
11449 
11450     // Check that the base pointer is the same as the original one.
11451     if (!Ptr.equalBaseIndex(BasePtr))
11452       break;
11453 
11454     // The memory operands must not be volatile.
11455     if (Index->isVolatile() || Index->isIndexed())
11456       break;
11457 
11458     // No truncation.
11459     if (Index->isTruncatingStore())
11460       break;
11461 
11462     // The stored memory type must be the same.
11463     if (Index->getMemoryVT() != MemVT)
11464       break;
11465 
11466     // We do not allow under-aligned stores in order to prevent
11467     // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11468     // be irrelevant here; what MATTERS is that we not move memory
11469     // operations that potentially overlap past each-other.
11470     if (Index->getAlignment() < MemVT.getStoreSize())
11471       break;
11472 
11473     // We found a potential memory operand to merge.
11474     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11475 
11476     // Find the next memory operand in the chain. If the next operand in the
11477     // chain is a store then move up and continue the scan with the next
11478     // memory operand. If the next operand is a load save it and use alias
11479     // information to check if it interferes with anything.
11480     SDNode *NextInChain = Index->getChain().getNode();
11481     while (1) {
11482       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11483         // We found a store node. Use it for the next iteration.
11484         Index = STn;
11485         break;
11486       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11487         if (Ldn->isVolatile()) {
11488           Index = nullptr;
11489           break;
11490         }
11491 
11492         // Save the load node for later. Continue the scan.
11493         AliasLoadNodes.push_back(Ldn);
11494         NextInChain = Ldn->getChain().getNode();
11495         continue;
11496       } else {
11497         Index = nullptr;
11498         break;
11499       }
11500     }
11501   }
11502 }
11503 
11504 // We need to check that merging these stores does not cause a loop
11505 // in the DAG. Any store candidate may depend on another candidate
11506 // indirectly through its operand (we already consider dependencies
11507 // through the chain). Check in parallel by searching up from
11508 // non-chain operands of candidates.
11509 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
11510     SmallVectorImpl<MemOpLink> &StoreNodes) {
11511   SmallPtrSet<const SDNode *, 16> Visited;
11512   SmallVector<const SDNode *, 8> Worklist;
11513   // search ops of store candidates
11514   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11515     SDNode *n = StoreNodes[i].MemNode;
11516     // Potential loops may happen only through non-chain operands
11517     for (unsigned j = 1; j < n->getNumOperands(); ++j)
11518       Worklist.push_back(n->getOperand(j).getNode());
11519   }
11520   // search through DAG. We can stop early if we find a storenode
11521   for (unsigned i = 0; i < StoreNodes.size(); ++i) {
11522     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
11523       return false;
11524   }
11525   return true;
11526 }
11527 
11528 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11529   if (OptLevel == CodeGenOpt::None)
11530     return false;
11531 
11532   EVT MemVT = St->getMemoryVT();
11533   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11534   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11535       Attribute::NoImplicitFloat);
11536 
11537   // This function cannot currently deal with non-byte-sized memory sizes.
11538   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11539     return false;
11540 
11541   if (!MemVT.isSimple())
11542     return false;
11543 
11544   // Perform an early exit check. Do not bother looking at stored values that
11545   // are not constants, loads, or extracted vector elements.
11546   SDValue StoredVal = St->getValue();
11547   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11548   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11549                        isa<ConstantFPSDNode>(StoredVal);
11550   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11551                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11552 
11553   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11554     return false;
11555 
11556   // Don't merge vectors into wider vectors if the source data comes from loads.
11557   // TODO: This restriction can be lifted by using logic similar to the
11558   // ExtractVecSrc case.
11559   if (MemVT.isVector() && IsLoadSrc)
11560     return false;
11561 
11562   // Only look at ends of store sequences.
11563   SDValue Chain = SDValue(St, 0);
11564   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11565     return false;
11566 
11567   // Save the LoadSDNodes that we find in the chain.
11568   // We need to make sure that these nodes do not interfere with
11569   // any of the store nodes.
11570   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11571 
11572   // Save the StoreSDNodes that we find in the chain.
11573   SmallVector<MemOpLink, 8> StoreNodes;
11574 
11575   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11576 
11577   // Check if there is anything to merge.
11578   if (StoreNodes.size() < 2)
11579     return false;
11580 
11581   // only do dep endence check in AA case
11582   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11583                                                   : DAG.getSubtarget().useAA();
11584   if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes))
11585     return false;
11586 
11587   // Sort the memory operands according to their distance from the
11588   // base pointer.  As a secondary criteria: make sure stores coming
11589   // later in the code come first in the list. This is important for
11590   // the non-UseAA case, because we're merging stores into the FINAL
11591   // store along a chain which potentially contains aliasing stores.
11592   // Thus, if there are multiple stores to the same address, the last
11593   // one can be considered for merging but not the others.
11594   std::sort(StoreNodes.begin(), StoreNodes.end(),
11595             [](MemOpLink LHS, MemOpLink RHS) {
11596     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11597            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11598             LHS.SequenceNum < RHS.SequenceNum);
11599   });
11600 
11601   // Scan the memory operations on the chain and find the first non-consecutive
11602   // store memory address.
11603   unsigned LastConsecutiveStore = 0;
11604   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11605   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11606 
11607     // Check that the addresses are consecutive starting from the second
11608     // element in the list of stores.
11609     if (i > 0) {
11610       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11611       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11612         break;
11613     }
11614 
11615     // Check if this store interferes with any of the loads that we found.
11616     // If we find a load that alias with this store. Stop the sequence.
11617     if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(),
11618                     [&](LSBaseSDNode* Ldn) {
11619                       return isAlias(Ldn, StoreNodes[i].MemNode);
11620                     }))
11621       break;
11622 
11623     // Mark this node as useful.
11624     LastConsecutiveStore = i;
11625   }
11626 
11627   // The node with the lowest store address.
11628   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11629   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11630   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11631   LLVMContext &Context = *DAG.getContext();
11632   const DataLayout &DL = DAG.getDataLayout();
11633 
11634   // Store the constants into memory as one consecutive store.
11635   if (IsConstantSrc) {
11636     unsigned LastLegalType = 0;
11637     unsigned LastLegalVectorType = 0;
11638     bool NonZero = false;
11639     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11640       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11641       SDValue StoredVal = St->getValue();
11642 
11643       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11644         NonZero |= !C->isNullValue();
11645       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11646         NonZero |= !C->getConstantFPValue()->isNullValue();
11647       } else {
11648         // Non-constant.
11649         break;
11650       }
11651 
11652       // Find a legal type for the constant store.
11653       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11654       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11655       bool IsFast;
11656       if (TLI.isTypeLegal(StoreTy) &&
11657           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11658                                  FirstStoreAlign, &IsFast) && IsFast) {
11659         LastLegalType = i+1;
11660       // Or check whether a truncstore is legal.
11661       } else if (TLI.getTypeAction(Context, StoreTy) ==
11662                  TargetLowering::TypePromoteInteger) {
11663         EVT LegalizedStoredValueTy =
11664           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11665         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11666             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11667                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11668             IsFast) {
11669           LastLegalType = i + 1;
11670         }
11671       }
11672 
11673       // We only use vectors if the constant is known to be zero or the target
11674       // allows it and the function is not marked with the noimplicitfloat
11675       // attribute.
11676       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11677                                                         FirstStoreAS)) &&
11678           !NoVectors) {
11679         // Find a legal type for the vector store.
11680         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11681         if (TLI.isTypeLegal(Ty) &&
11682             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11683                                    FirstStoreAlign, &IsFast) && IsFast)
11684           LastLegalVectorType = i + 1;
11685       }
11686     }
11687 
11688     // Check if we found a legal integer type to store.
11689     if (LastLegalType == 0 && LastLegalVectorType == 0)
11690       return false;
11691 
11692     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11693     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11694 
11695     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11696                                            true, UseVector);
11697   }
11698 
11699   // When extracting multiple vector elements, try to store them
11700   // in one vector store rather than a sequence of scalar stores.
11701   if (IsExtractVecSrc) {
11702     unsigned NumStoresToMerge = 0;
11703     bool IsVec = MemVT.isVector();
11704     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11705       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11706       unsigned StoreValOpcode = St->getValue().getOpcode();
11707       // This restriction could be loosened.
11708       // Bail out if any stored values are not elements extracted from a vector.
11709       // It should be possible to handle mixed sources, but load sources need
11710       // more careful handling (see the block of code below that handles
11711       // consecutive loads).
11712       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11713           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11714         return false;
11715 
11716       // Find a legal type for the vector store.
11717       unsigned Elts = i + 1;
11718       if (IsVec) {
11719         // When merging vector stores, get the total number of elements.
11720         Elts *= MemVT.getVectorNumElements();
11721       }
11722       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11723       bool IsFast;
11724       if (TLI.isTypeLegal(Ty) &&
11725           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11726                                  FirstStoreAlign, &IsFast) && IsFast)
11727         NumStoresToMerge = i + 1;
11728     }
11729 
11730     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11731                                            false, true);
11732   }
11733 
11734   // Below we handle the case of multiple consecutive stores that
11735   // come from multiple consecutive loads. We merge them into a single
11736   // wide load and a single wide store.
11737 
11738   // Look for load nodes which are used by the stored values.
11739   SmallVector<MemOpLink, 8> LoadNodes;
11740 
11741   // Find acceptable loads. Loads need to have the same chain (token factor),
11742   // must not be zext, volatile, indexed, and they must be consecutive.
11743   BaseIndexOffset LdBasePtr;
11744   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11745     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11746     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11747     if (!Ld) break;
11748 
11749     // Loads must only have one use.
11750     if (!Ld->hasNUsesOfValue(1, 0))
11751       break;
11752 
11753     // The memory operands must not be volatile.
11754     if (Ld->isVolatile() || Ld->isIndexed())
11755       break;
11756 
11757     // We do not accept ext loads.
11758     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11759       break;
11760 
11761     // The stored memory type must be the same.
11762     if (Ld->getMemoryVT() != MemVT)
11763       break;
11764 
11765     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
11766     // If this is not the first ptr that we check.
11767     if (LdBasePtr.Base.getNode()) {
11768       // The base ptr must be the same.
11769       if (!LdPtr.equalBaseIndex(LdBasePtr))
11770         break;
11771     } else {
11772       // Check that all other base pointers are the same as this one.
11773       LdBasePtr = LdPtr;
11774     }
11775 
11776     // We found a potential memory operand to merge.
11777     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11778   }
11779 
11780   if (LoadNodes.size() < 2)
11781     return false;
11782 
11783   // If we have load/store pair instructions and we only have two values,
11784   // don't bother.
11785   unsigned RequiredAlignment;
11786   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11787       St->getAlignment() >= RequiredAlignment)
11788     return false;
11789 
11790   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11791   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11792   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11793 
11794   // Scan the memory operations on the chain and find the first non-consecutive
11795   // load memory address. These variables hold the index in the store node
11796   // array.
11797   unsigned LastConsecutiveLoad = 0;
11798   // This variable refers to the size and not index in the array.
11799   unsigned LastLegalVectorType = 0;
11800   unsigned LastLegalIntegerType = 0;
11801   StartAddress = LoadNodes[0].OffsetFromBase;
11802   SDValue FirstChain = FirstLoad->getChain();
11803   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11804     // All loads must share the same chain.
11805     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11806       break;
11807 
11808     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11809     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11810       break;
11811     LastConsecutiveLoad = i;
11812     // Find a legal type for the vector store.
11813     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11814     bool IsFastSt, IsFastLd;
11815     if (TLI.isTypeLegal(StoreTy) &&
11816         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11817                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11818         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11819                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11820       LastLegalVectorType = i + 1;
11821     }
11822 
11823     // Find a legal type for the integer store.
11824     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11825     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11826     if (TLI.isTypeLegal(StoreTy) &&
11827         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11828                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11829         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11830                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11831       LastLegalIntegerType = i + 1;
11832     // Or check whether a truncstore and extload is legal.
11833     else if (TLI.getTypeAction(Context, StoreTy) ==
11834              TargetLowering::TypePromoteInteger) {
11835       EVT LegalizedStoredValueTy =
11836         TLI.getTypeToTransformTo(Context, StoreTy);
11837       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11838           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11839           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11840           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11841           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11842                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11843           IsFastSt &&
11844           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11845                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11846           IsFastLd)
11847         LastLegalIntegerType = i+1;
11848     }
11849   }
11850 
11851   // Only use vector types if the vector type is larger than the integer type.
11852   // If they are the same, use integers.
11853   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11854   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11855 
11856   // We add +1 here because the LastXXX variables refer to location while
11857   // the NumElem refers to array/index size.
11858   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11859   NumElem = std::min(LastLegalType, NumElem);
11860 
11861   if (NumElem < 2)
11862     return false;
11863 
11864   // Collect the chains from all merged stores.
11865   SmallVector<SDValue, 8> MergeStoreChains;
11866   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11867 
11868   // The latest Node in the DAG.
11869   unsigned LatestNodeUsed = 0;
11870   for (unsigned i=1; i<NumElem; ++i) {
11871     // Find a chain for the new wide-store operand. Notice that some
11872     // of the store nodes that we found may not be selected for inclusion
11873     // in the wide store. The chain we use needs to be the chain of the
11874     // latest store node which is *used* and replaced by the wide store.
11875     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11876       LatestNodeUsed = i;
11877 
11878     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11879   }
11880 
11881   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11882 
11883   // Find if it is better to use vectors or integers to load and store
11884   // to memory.
11885   EVT JointMemOpVT;
11886   if (UseVectorTy) {
11887     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11888   } else {
11889     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11890     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11891   }
11892 
11893   SDLoc LoadDL(LoadNodes[0].MemNode);
11894   SDLoc StoreDL(StoreNodes[0].MemNode);
11895 
11896   // The merged loads are required to have the same incoming chain, so
11897   // using the first's chain is acceptable.
11898   SDValue NewLoad = DAG.getLoad(
11899       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11900       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11901 
11902   SDValue NewStoreChain =
11903     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11904 
11905   SDValue NewStore = DAG.getStore(
11906     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11907       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11908 
11909   // Transfer chain users from old loads to the new load.
11910   for (unsigned i = 0; i < NumElem; ++i) {
11911     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11912     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11913                                   SDValue(NewLoad.getNode(), 1));
11914   }
11915 
11916   if (UseAA) {
11917     // Replace the all stores with the new store.
11918     for (unsigned i = 0; i < NumElem; ++i)
11919       CombineTo(StoreNodes[i].MemNode, NewStore);
11920   } else {
11921     // Replace the last store with the new store.
11922     CombineTo(LatestOp, NewStore);
11923     // Erase all other stores.
11924     for (unsigned i = 0; i < NumElem; ++i) {
11925       // Remove all Store nodes.
11926       if (StoreNodes[i].MemNode == LatestOp)
11927         continue;
11928       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11929       DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11930       deleteAndRecombine(St);
11931     }
11932   }
11933 
11934   return true;
11935 }
11936 
11937 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11938   SDLoc SL(ST);
11939   SDValue ReplStore;
11940 
11941   // Replace the chain to avoid dependency.
11942   if (ST->isTruncatingStore()) {
11943     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11944                                   ST->getBasePtr(), ST->getMemoryVT(),
11945                                   ST->getMemOperand());
11946   } else {
11947     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11948                              ST->getMemOperand());
11949   }
11950 
11951   // Create token to keep both nodes around.
11952   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11953                               MVT::Other, ST->getChain(), ReplStore);
11954 
11955   // Make sure the new and old chains are cleaned up.
11956   AddToWorklist(Token.getNode());
11957 
11958   // Don't add users to work list.
11959   return CombineTo(ST, Token, false);
11960 }
11961 
11962 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11963   SDValue Value = ST->getValue();
11964   if (Value.getOpcode() == ISD::TargetConstantFP)
11965     return SDValue();
11966 
11967   SDLoc DL(ST);
11968 
11969   SDValue Chain = ST->getChain();
11970   SDValue Ptr = ST->getBasePtr();
11971 
11972   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11973 
11974   // NOTE: If the original store is volatile, this transform must not increase
11975   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11976   // processor operation but an i64 (which is not legal) requires two.  So the
11977   // transform should not be done in this case.
11978 
11979   SDValue Tmp;
11980   switch (CFP->getSimpleValueType(0).SimpleTy) {
11981   default:
11982     llvm_unreachable("Unknown FP type");
11983   case MVT::f16:    // We don't do this for these yet.
11984   case MVT::f80:
11985   case MVT::f128:
11986   case MVT::ppcf128:
11987     return SDValue();
11988   case MVT::f32:
11989     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11990         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11991       ;
11992       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11993                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11994                             MVT::i32);
11995       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11996     }
11997 
11998     return SDValue();
11999   case MVT::f64:
12000     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12001          !ST->isVolatile()) ||
12002         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12003       ;
12004       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12005                             getZExtValue(), SDLoc(CFP), MVT::i64);
12006       return DAG.getStore(Chain, DL, Tmp,
12007                           Ptr, ST->getMemOperand());
12008     }
12009 
12010     if (!ST->isVolatile() &&
12011         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12012       // Many FP stores are not made apparent until after legalize, e.g. for
12013       // argument passing.  Since this is so common, custom legalize the
12014       // 64-bit integer store into two 32-bit stores.
12015       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12016       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12017       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12018       if (DAG.getDataLayout().isBigEndian())
12019         std::swap(Lo, Hi);
12020 
12021       unsigned Alignment = ST->getAlignment();
12022       bool isVolatile = ST->isVolatile();
12023       bool isNonTemporal = ST->isNonTemporal();
12024       AAMDNodes AAInfo = ST->getAAInfo();
12025 
12026       SDValue St0 = DAG.getStore(Chain, DL, Lo,
12027                                  Ptr, ST->getPointerInfo(),
12028                                  isVolatile, isNonTemporal,
12029                                  ST->getAlignment(), AAInfo);
12030       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12031                         DAG.getConstant(4, DL, Ptr.getValueType()));
12032       Alignment = MinAlign(Alignment, 4U);
12033       SDValue St1 = DAG.getStore(Chain, DL, Hi,
12034                                  Ptr, ST->getPointerInfo().getWithOffset(4),
12035                                  isVolatile, isNonTemporal,
12036                                  Alignment, AAInfo);
12037       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12038                          St0, St1);
12039     }
12040 
12041     return SDValue();
12042   }
12043 }
12044 
12045 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12046   StoreSDNode *ST  = cast<StoreSDNode>(N);
12047   SDValue Chain = ST->getChain();
12048   SDValue Value = ST->getValue();
12049   SDValue Ptr   = ST->getBasePtr();
12050 
12051   // If this is a store of a bit convert, store the input value if the
12052   // resultant store does not need a higher alignment than the original.
12053   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12054       ST->isUnindexed()) {
12055     EVT SVT = Value.getOperand(0).getValueType();
12056     if (((!LegalOperations && !ST->isVolatile()) ||
12057          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12058         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12059       unsigned OrigAlign = ST->getAlignment();
12060       bool Fast = false;
12061       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12062                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
12063           Fast) {
12064         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
12065                             Ptr, ST->getPointerInfo(), ST->isVolatile(),
12066                             ST->isNonTemporal(), OrigAlign,
12067                             ST->getAAInfo());
12068       }
12069     }
12070   }
12071 
12072   // Turn 'store undef, Ptr' -> nothing.
12073   if (Value.isUndef() && ST->isUnindexed())
12074     return Chain;
12075 
12076   // Try to infer better alignment information than the store already has.
12077   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12078     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12079       if (Align > ST->getAlignment()) {
12080         SDValue NewStore =
12081                DAG.getTruncStore(Chain, SDLoc(N), Value,
12082                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
12083                                  ST->isVolatile(), ST->isNonTemporal(), Align,
12084                                  ST->getAAInfo());
12085         if (NewStore.getNode() != N)
12086           return CombineTo(ST, NewStore, true);
12087       }
12088     }
12089   }
12090 
12091   // Try transforming a pair floating point load / store ops to integer
12092   // load / store ops.
12093   if (SDValue NewST = TransformFPLoadStorePair(N))
12094     return NewST;
12095 
12096   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
12097                                                   : DAG.getSubtarget().useAA();
12098 #ifndef NDEBUG
12099   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12100       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12101     UseAA = false;
12102 #endif
12103   if (UseAA && ST->isUnindexed()) {
12104     // FIXME: We should do this even without AA enabled. AA will just allow
12105     // FindBetterChain to work in more situations. The problem with this is that
12106     // any combine that expects memory operations to be on consecutive chains
12107     // first needs to be updated to look for users of the same chain.
12108 
12109     // Walk up chain skipping non-aliasing memory nodes, on this store and any
12110     // adjacent stores.
12111     if (findBetterNeighborChains(ST)) {
12112       // replaceStoreChain uses CombineTo, which handled all of the worklist
12113       // manipulation. Return the original node to not do anything else.
12114       return SDValue(ST, 0);
12115     }
12116   }
12117 
12118   // Try transforming N to an indexed store.
12119   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12120     return SDValue(N, 0);
12121 
12122   // FIXME: is there such a thing as a truncating indexed store?
12123   if (ST->isTruncatingStore() && ST->isUnindexed() &&
12124       Value.getValueType().isInteger()) {
12125     // See if we can simplify the input to this truncstore with knowledge that
12126     // only the low bits are being used.  For example:
12127     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
12128     SDValue Shorter =
12129       GetDemandedBits(Value,
12130                       APInt::getLowBitsSet(
12131                         Value.getValueType().getScalarType().getSizeInBits(),
12132                         ST->getMemoryVT().getScalarType().getSizeInBits()));
12133     AddToWorklist(Value.getNode());
12134     if (Shorter.getNode())
12135       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12136                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
12137 
12138     // Otherwise, see if we can simplify the operation with
12139     // SimplifyDemandedBits, which only works if the value has a single use.
12140     if (SimplifyDemandedBits(Value,
12141                         APInt::getLowBitsSet(
12142                           Value.getValueType().getScalarType().getSizeInBits(),
12143                           ST->getMemoryVT().getScalarType().getSizeInBits())))
12144       return SDValue(N, 0);
12145   }
12146 
12147   // If this is a load followed by a store to the same location, then the store
12148   // is dead/noop.
12149   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12150     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12151         ST->isUnindexed() && !ST->isVolatile() &&
12152         // There can't be any side effects between the load and store, such as
12153         // a call or store.
12154         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12155       // The store is dead, remove it.
12156       return Chain;
12157     }
12158   }
12159 
12160   // If this is a store followed by a store with the same value to the same
12161   // location, then the store is dead/noop.
12162   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12163     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12164         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12165         ST1->isUnindexed() && !ST1->isVolatile()) {
12166       // The store is dead, remove it.
12167       return Chain;
12168     }
12169   }
12170 
12171   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12172   // truncating store.  We can do this even if this is already a truncstore.
12173   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12174       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12175       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12176                             ST->getMemoryVT())) {
12177     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12178                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
12179   }
12180 
12181   // Only perform this optimization before the types are legal, because we
12182   // don't want to perform this optimization on every DAGCombine invocation.
12183   if (!LegalTypes) {
12184     bool EverChanged = false;
12185 
12186     do {
12187       // There can be multiple store sequences on the same chain.
12188       // Keep trying to merge store sequences until we are unable to do so
12189       // or until we merge the last store on the chain.
12190       bool Changed = MergeConsecutiveStores(ST);
12191       EverChanged |= Changed;
12192       if (!Changed) break;
12193     } while (ST->getOpcode() != ISD::DELETED_NODE);
12194 
12195     if (EverChanged)
12196       return SDValue(N, 0);
12197   }
12198 
12199   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12200   //
12201   // Make sure to do this only after attempting to merge stores in order to
12202   //  avoid changing the types of some subset of stores due to visit order,
12203   //  preventing their merging.
12204   if (isa<ConstantFPSDNode>(Value)) {
12205     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12206       return NewSt;
12207   }
12208 
12209   return ReduceLoadOpStoreWidth(N);
12210 }
12211 
12212 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
12213   SDValue InVec = N->getOperand(0);
12214   SDValue InVal = N->getOperand(1);
12215   SDValue EltNo = N->getOperand(2);
12216   SDLoc dl(N);
12217 
12218   // If the inserted element is an UNDEF, just use the input vector.
12219   if (InVal.isUndef())
12220     return InVec;
12221 
12222   EVT VT = InVec.getValueType();
12223 
12224   // If we can't generate a legal BUILD_VECTOR, exit
12225   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
12226     return SDValue();
12227 
12228   // Check that we know which element is being inserted
12229   if (!isa<ConstantSDNode>(EltNo))
12230     return SDValue();
12231   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12232 
12233   // Canonicalize insert_vector_elt dag nodes.
12234   // Example:
12235   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
12236   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
12237   //
12238   // Do this only if the child insert_vector node has one use; also
12239   // do this only if indices are both constants and Idx1 < Idx0.
12240   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
12241       && isa<ConstantSDNode>(InVec.getOperand(2))) {
12242     unsigned OtherElt =
12243       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
12244     if (Elt < OtherElt) {
12245       // Swap nodes.
12246       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
12247                                   InVec.getOperand(0), InVal, EltNo);
12248       AddToWorklist(NewOp.getNode());
12249       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
12250                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
12251     }
12252   }
12253 
12254   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
12255   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
12256   // vector elements.
12257   SmallVector<SDValue, 8> Ops;
12258   // Do not combine these two vectors if the output vector will not replace
12259   // the input vector.
12260   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
12261     Ops.append(InVec.getNode()->op_begin(),
12262                InVec.getNode()->op_end());
12263   } else if (InVec.isUndef()) {
12264     unsigned NElts = VT.getVectorNumElements();
12265     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
12266   } else {
12267     return SDValue();
12268   }
12269 
12270   // Insert the element
12271   if (Elt < Ops.size()) {
12272     // All the operands of BUILD_VECTOR must have the same type;
12273     // we enforce that here.
12274     EVT OpVT = Ops[0].getValueType();
12275     if (InVal.getValueType() != OpVT)
12276       InVal = OpVT.bitsGT(InVal.getValueType()) ?
12277                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
12278                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
12279     Ops[Elt] = InVal;
12280   }
12281 
12282   // Return the new vector
12283   return DAG.getBuildVector(VT, dl, Ops);
12284 }
12285 
12286 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
12287     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
12288   EVT ResultVT = EVE->getValueType(0);
12289   EVT VecEltVT = InVecVT.getVectorElementType();
12290   unsigned Align = OriginalLoad->getAlignment();
12291   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
12292       VecEltVT.getTypeForEVT(*DAG.getContext()));
12293 
12294   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
12295     return SDValue();
12296 
12297   Align = NewAlign;
12298 
12299   SDValue NewPtr = OriginalLoad->getBasePtr();
12300   SDValue Offset;
12301   EVT PtrType = NewPtr.getValueType();
12302   MachinePointerInfo MPI;
12303   SDLoc DL(EVE);
12304   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
12305     int Elt = ConstEltNo->getZExtValue();
12306     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
12307     Offset = DAG.getConstant(PtrOff, DL, PtrType);
12308     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
12309   } else {
12310     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
12311     Offset = DAG.getNode(
12312         ISD::MUL, DL, PtrType, Offset,
12313         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
12314     MPI = OriginalLoad->getPointerInfo();
12315   }
12316   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
12317 
12318   // The replacement we need to do here is a little tricky: we need to
12319   // replace an extractelement of a load with a load.
12320   // Use ReplaceAllUsesOfValuesWith to do the replacement.
12321   // Note that this replacement assumes that the extractvalue is the only
12322   // use of the load; that's okay because we don't want to perform this
12323   // transformation in other cases anyway.
12324   SDValue Load;
12325   SDValue Chain;
12326   if (ResultVT.bitsGT(VecEltVT)) {
12327     // If the result type of vextract is wider than the load, then issue an
12328     // extending load instead.
12329     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12330                                                   VecEltVT)
12331                                    ? ISD::ZEXTLOAD
12332                                    : ISD::EXTLOAD;
12333     Load = DAG.getExtLoad(
12334         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12335         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12336         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12337     Chain = Load.getValue(1);
12338   } else {
12339     Load = DAG.getLoad(
12340         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12341         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12342         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12343     Chain = Load.getValue(1);
12344     if (ResultVT.bitsLT(VecEltVT))
12345       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12346     else
12347       Load = DAG.getBitcast(ResultVT, Load);
12348   }
12349   WorklistRemover DeadNodes(*this);
12350   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12351   SDValue To[] = { Load, Chain };
12352   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12353   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12354   // worklist explicitly as well.
12355   AddToWorklist(Load.getNode());
12356   AddUsersToWorklist(Load.getNode()); // Add users too
12357   // Make sure to revisit this node to clean it up; it will usually be dead.
12358   AddToWorklist(EVE);
12359   ++OpsNarrowed;
12360   return SDValue(EVE, 0);
12361 }
12362 
12363 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12364   // (vextract (scalar_to_vector val, 0) -> val
12365   SDValue InVec = N->getOperand(0);
12366   EVT VT = InVec.getValueType();
12367   EVT NVT = N->getValueType(0);
12368 
12369   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12370     // Check if the result type doesn't match the inserted element type. A
12371     // SCALAR_TO_VECTOR may truncate the inserted element and the
12372     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12373     SDValue InOp = InVec.getOperand(0);
12374     if (InOp.getValueType() != NVT) {
12375       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12376       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12377     }
12378     return InOp;
12379   }
12380 
12381   SDValue EltNo = N->getOperand(1);
12382   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12383 
12384   // extract_vector_elt (build_vector x, y), 1 -> y
12385   if (ConstEltNo &&
12386       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12387       TLI.isTypeLegal(VT) &&
12388       (InVec.hasOneUse() ||
12389        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12390     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12391     EVT InEltVT = Elt.getValueType();
12392 
12393     // Sometimes build_vector's scalar input types do not match result type.
12394     if (NVT == InEltVT)
12395       return Elt;
12396 
12397     // TODO: It may be useful to truncate if free if the build_vector implicitly
12398     // converts.
12399   }
12400 
12401   // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
12402   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
12403       ConstEltNo->isNullValue() && VT.isInteger()) {
12404     SDValue BCSrc = InVec.getOperand(0);
12405     if (BCSrc.getValueType().isScalarInteger())
12406       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
12407   }
12408 
12409   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12410   // We only perform this optimization before the op legalization phase because
12411   // we may introduce new vector instructions which are not backed by TD
12412   // patterns. For example on AVX, extracting elements from a wide vector
12413   // without using extract_subvector. However, if we can find an underlying
12414   // scalar value, then we can always use that.
12415   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12416     int NumElem = VT.getVectorNumElements();
12417     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12418     // Find the new index to extract from.
12419     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12420 
12421     // Extracting an undef index is undef.
12422     if (OrigElt == -1)
12423       return DAG.getUNDEF(NVT);
12424 
12425     // Select the right vector half to extract from.
12426     SDValue SVInVec;
12427     if (OrigElt < NumElem) {
12428       SVInVec = InVec->getOperand(0);
12429     } else {
12430       SVInVec = InVec->getOperand(1);
12431       OrigElt -= NumElem;
12432     }
12433 
12434     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12435       SDValue InOp = SVInVec.getOperand(OrigElt);
12436       if (InOp.getValueType() != NVT) {
12437         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12438         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12439       }
12440 
12441       return InOp;
12442     }
12443 
12444     // FIXME: We should handle recursing on other vector shuffles and
12445     // scalar_to_vector here as well.
12446 
12447     if (!LegalOperations) {
12448       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12449       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12450                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12451     }
12452   }
12453 
12454   bool BCNumEltsChanged = false;
12455   EVT ExtVT = VT.getVectorElementType();
12456   EVT LVT = ExtVT;
12457 
12458   // If the result of load has to be truncated, then it's not necessarily
12459   // profitable.
12460   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12461     return SDValue();
12462 
12463   if (InVec.getOpcode() == ISD::BITCAST) {
12464     // Don't duplicate a load with other uses.
12465     if (!InVec.hasOneUse())
12466       return SDValue();
12467 
12468     EVT BCVT = InVec.getOperand(0).getValueType();
12469     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12470       return SDValue();
12471     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12472       BCNumEltsChanged = true;
12473     InVec = InVec.getOperand(0);
12474     ExtVT = BCVT.getVectorElementType();
12475   }
12476 
12477   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12478   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12479       ISD::isNormalLoad(InVec.getNode()) &&
12480       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12481     SDValue Index = N->getOperand(1);
12482     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12483       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12484                                                            OrigLoad);
12485   }
12486 
12487   // Perform only after legalization to ensure build_vector / vector_shuffle
12488   // optimizations have already been done.
12489   if (!LegalOperations) return SDValue();
12490 
12491   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12492   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12493   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12494 
12495   if (ConstEltNo) {
12496     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12497 
12498     LoadSDNode *LN0 = nullptr;
12499     const ShuffleVectorSDNode *SVN = nullptr;
12500     if (ISD::isNormalLoad(InVec.getNode())) {
12501       LN0 = cast<LoadSDNode>(InVec);
12502     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12503                InVec.getOperand(0).getValueType() == ExtVT &&
12504                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12505       // Don't duplicate a load with other uses.
12506       if (!InVec.hasOneUse())
12507         return SDValue();
12508 
12509       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12510     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12511       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12512       // =>
12513       // (load $addr+1*size)
12514 
12515       // Don't duplicate a load with other uses.
12516       if (!InVec.hasOneUse())
12517         return SDValue();
12518 
12519       // If the bit convert changed the number of elements, it is unsafe
12520       // to examine the mask.
12521       if (BCNumEltsChanged)
12522         return SDValue();
12523 
12524       // Select the input vector, guarding against out of range extract vector.
12525       unsigned NumElems = VT.getVectorNumElements();
12526       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12527       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12528 
12529       if (InVec.getOpcode() == ISD::BITCAST) {
12530         // Don't duplicate a load with other uses.
12531         if (!InVec.hasOneUse())
12532           return SDValue();
12533 
12534         InVec = InVec.getOperand(0);
12535       }
12536       if (ISD::isNormalLoad(InVec.getNode())) {
12537         LN0 = cast<LoadSDNode>(InVec);
12538         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12539         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12540       }
12541     }
12542 
12543     // Make sure we found a non-volatile load and the extractelement is
12544     // the only use.
12545     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12546       return SDValue();
12547 
12548     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12549     if (Elt == -1)
12550       return DAG.getUNDEF(LVT);
12551 
12552     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12553   }
12554 
12555   return SDValue();
12556 }
12557 
12558 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12559 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12560   // We perform this optimization post type-legalization because
12561   // the type-legalizer often scalarizes integer-promoted vectors.
12562   // Performing this optimization before may create bit-casts which
12563   // will be type-legalized to complex code sequences.
12564   // We perform this optimization only before the operation legalizer because we
12565   // may introduce illegal operations.
12566   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12567     return SDValue();
12568 
12569   unsigned NumInScalars = N->getNumOperands();
12570   SDLoc dl(N);
12571   EVT VT = N->getValueType(0);
12572 
12573   // Check to see if this is a BUILD_VECTOR of a bunch of values
12574   // which come from any_extend or zero_extend nodes. If so, we can create
12575   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12576   // optimizations. We do not handle sign-extend because we can't fill the sign
12577   // using shuffles.
12578   EVT SourceType = MVT::Other;
12579   bool AllAnyExt = true;
12580 
12581   for (unsigned i = 0; i != NumInScalars; ++i) {
12582     SDValue In = N->getOperand(i);
12583     // Ignore undef inputs.
12584     if (In.isUndef()) continue;
12585 
12586     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12587     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12588 
12589     // Abort if the element is not an extension.
12590     if (!ZeroExt && !AnyExt) {
12591       SourceType = MVT::Other;
12592       break;
12593     }
12594 
12595     // The input is a ZeroExt or AnyExt. Check the original type.
12596     EVT InTy = In.getOperand(0).getValueType();
12597 
12598     // Check that all of the widened source types are the same.
12599     if (SourceType == MVT::Other)
12600       // First time.
12601       SourceType = InTy;
12602     else if (InTy != SourceType) {
12603       // Multiple income types. Abort.
12604       SourceType = MVT::Other;
12605       break;
12606     }
12607 
12608     // Check if all of the extends are ANY_EXTENDs.
12609     AllAnyExt &= AnyExt;
12610   }
12611 
12612   // In order to have valid types, all of the inputs must be extended from the
12613   // same source type and all of the inputs must be any or zero extend.
12614   // Scalar sizes must be a power of two.
12615   EVT OutScalarTy = VT.getScalarType();
12616   bool ValidTypes = SourceType != MVT::Other &&
12617                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12618                  isPowerOf2_32(SourceType.getSizeInBits());
12619 
12620   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12621   // turn into a single shuffle instruction.
12622   if (!ValidTypes)
12623     return SDValue();
12624 
12625   bool isLE = DAG.getDataLayout().isLittleEndian();
12626   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12627   assert(ElemRatio > 1 && "Invalid element size ratio");
12628   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12629                                DAG.getConstant(0, SDLoc(N), SourceType);
12630 
12631   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12632   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12633 
12634   // Populate the new build_vector
12635   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12636     SDValue Cast = N->getOperand(i);
12637     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12638             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12639             Cast.isUndef()) && "Invalid cast opcode");
12640     SDValue In;
12641     if (Cast.isUndef())
12642       In = DAG.getUNDEF(SourceType);
12643     else
12644       In = Cast->getOperand(0);
12645     unsigned Index = isLE ? (i * ElemRatio) :
12646                             (i * ElemRatio + (ElemRatio - 1));
12647 
12648     assert(Index < Ops.size() && "Invalid index");
12649     Ops[Index] = In;
12650   }
12651 
12652   // The type of the new BUILD_VECTOR node.
12653   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12654   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12655          "Invalid vector size");
12656   // Check if the new vector type is legal.
12657   if (!isTypeLegal(VecVT)) return SDValue();
12658 
12659   // Make the new BUILD_VECTOR.
12660   SDValue BV = DAG.getBuildVector(VecVT, dl, Ops);
12661 
12662   // The new BUILD_VECTOR node has the potential to be further optimized.
12663   AddToWorklist(BV.getNode());
12664   // Bitcast to the desired type.
12665   return DAG.getBitcast(VT, BV);
12666 }
12667 
12668 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12669   EVT VT = N->getValueType(0);
12670 
12671   unsigned NumInScalars = N->getNumOperands();
12672   SDLoc dl(N);
12673 
12674   EVT SrcVT = MVT::Other;
12675   unsigned Opcode = ISD::DELETED_NODE;
12676   unsigned NumDefs = 0;
12677 
12678   for (unsigned i = 0; i != NumInScalars; ++i) {
12679     SDValue In = N->getOperand(i);
12680     unsigned Opc = In.getOpcode();
12681 
12682     if (Opc == ISD::UNDEF)
12683       continue;
12684 
12685     // If all scalar values are floats and converted from integers.
12686     if (Opcode == ISD::DELETED_NODE &&
12687         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12688       Opcode = Opc;
12689     }
12690 
12691     if (Opc != Opcode)
12692       return SDValue();
12693 
12694     EVT InVT = In.getOperand(0).getValueType();
12695 
12696     // If all scalar values are typed differently, bail out. It's chosen to
12697     // simplify BUILD_VECTOR of integer types.
12698     if (SrcVT == MVT::Other)
12699       SrcVT = InVT;
12700     if (SrcVT != InVT)
12701       return SDValue();
12702     NumDefs++;
12703   }
12704 
12705   // If the vector has just one element defined, it's not worth to fold it into
12706   // a vectorized one.
12707   if (NumDefs < 2)
12708     return SDValue();
12709 
12710   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12711          && "Should only handle conversion from integer to float.");
12712   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12713 
12714   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12715 
12716   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12717     return SDValue();
12718 
12719   // Just because the floating-point vector type is legal does not necessarily
12720   // mean that the corresponding integer vector type is.
12721   if (!isTypeLegal(NVT))
12722     return SDValue();
12723 
12724   SmallVector<SDValue, 8> Opnds;
12725   for (unsigned i = 0; i != NumInScalars; ++i) {
12726     SDValue In = N->getOperand(i);
12727 
12728     if (In.isUndef())
12729       Opnds.push_back(DAG.getUNDEF(SrcVT));
12730     else
12731       Opnds.push_back(In.getOperand(0));
12732   }
12733   SDValue BV = DAG.getBuildVector(NVT, dl, Opnds);
12734   AddToWorklist(BV.getNode());
12735 
12736   return DAG.getNode(Opcode, dl, VT, BV);
12737 }
12738 
12739 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12740   unsigned NumInScalars = N->getNumOperands();
12741   SDLoc dl(N);
12742   EVT VT = N->getValueType(0);
12743 
12744   // A vector built entirely of undefs is undef.
12745   if (ISD::allOperandsUndef(N))
12746     return DAG.getUNDEF(VT);
12747 
12748   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12749     return V;
12750 
12751   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12752     return V;
12753 
12754   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12755   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12756   // at most two distinct vectors, turn this into a shuffle node.
12757 
12758   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12759   if (!isTypeLegal(VT))
12760     return SDValue();
12761 
12762   // May only combine to shuffle after legalize if shuffle is legal.
12763   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12764     return SDValue();
12765 
12766   SDValue VecIn1, VecIn2;
12767   bool UsesZeroVector = false;
12768   for (unsigned i = 0; i != NumInScalars; ++i) {
12769     SDValue Op = N->getOperand(i);
12770     // Ignore undef inputs.
12771     if (Op.isUndef()) continue;
12772 
12773     // See if we can combine this build_vector into a blend with a zero vector.
12774     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12775       UsesZeroVector = true;
12776       continue;
12777     }
12778 
12779     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12780     // constant index, bail out.
12781     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12782         !isa<ConstantSDNode>(Op.getOperand(1))) {
12783       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12784       break;
12785     }
12786 
12787     // We allow up to two distinct input vectors.
12788     SDValue ExtractedFromVec = Op.getOperand(0);
12789     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12790       continue;
12791 
12792     if (!VecIn1.getNode()) {
12793       VecIn1 = ExtractedFromVec;
12794     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12795       VecIn2 = ExtractedFromVec;
12796     } else {
12797       // Too many inputs.
12798       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12799       break;
12800     }
12801   }
12802 
12803   // If everything is good, we can make a shuffle operation.
12804   if (VecIn1.getNode()) {
12805     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12806     SmallVector<int, 8> Mask;
12807     for (unsigned i = 0; i != NumInScalars; ++i) {
12808       unsigned Opcode = N->getOperand(i).getOpcode();
12809       if (Opcode == ISD::UNDEF) {
12810         Mask.push_back(-1);
12811         continue;
12812       }
12813 
12814       // Operands can also be zero.
12815       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12816         assert(UsesZeroVector &&
12817                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12818                "Unexpected node found!");
12819         Mask.push_back(NumInScalars+i);
12820         continue;
12821       }
12822 
12823       // If extracting from the first vector, just use the index directly.
12824       SDValue Extract = N->getOperand(i);
12825       SDValue ExtVal = Extract.getOperand(1);
12826       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12827       if (Extract.getOperand(0) == VecIn1) {
12828         Mask.push_back(ExtIndex);
12829         continue;
12830       }
12831 
12832       // Otherwise, use InIdx + InputVecSize
12833       Mask.push_back(InNumElements + ExtIndex);
12834     }
12835 
12836     // Avoid introducing illegal shuffles with zero.
12837     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12838       return SDValue();
12839 
12840     // We can't generate a shuffle node with mismatched input and output types.
12841     // Attempt to transform a single input vector to the correct type.
12842     if ((VT != VecIn1.getValueType())) {
12843       // If the input vector type has a different base type to the output
12844       // vector type, bail out.
12845       EVT VTElemType = VT.getVectorElementType();
12846       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12847           (VecIn2.getNode() &&
12848            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12849         return SDValue();
12850 
12851       // If the input vector is too small, widen it.
12852       // We only support widening of vectors which are half the size of the
12853       // output registers. For example XMM->YMM widening on X86 with AVX.
12854       EVT VecInT = VecIn1.getValueType();
12855       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12856         // If we only have one small input, widen it by adding undef values.
12857         if (!VecIn2.getNode())
12858           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12859                                DAG.getUNDEF(VecIn1.getValueType()));
12860         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12861           // If we have two small inputs of the same type, try to concat them.
12862           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12863           VecIn2 = SDValue(nullptr, 0);
12864         } else
12865           return SDValue();
12866       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12867         // If the input vector is too large, try to split it.
12868         // We don't support having two input vectors that are too large.
12869         // If the zero vector was used, we can not split the vector,
12870         // since we'd need 3 inputs.
12871         if (UsesZeroVector || VecIn2.getNode())
12872           return SDValue();
12873 
12874         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12875           return SDValue();
12876 
12877         // Try to replace VecIn1 with two extract_subvectors
12878         // No need to update the masks, they should still be correct.
12879         VecIn2 = DAG.getNode(
12880             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12881             DAG.getConstant(VT.getVectorNumElements(), dl,
12882                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12883         VecIn1 = DAG.getNode(
12884             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12885             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12886       } else
12887         return SDValue();
12888     }
12889 
12890     if (UsesZeroVector)
12891       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12892                                 DAG.getConstantFP(0.0, dl, VT);
12893     else
12894       // If VecIn2 is unused then change it to undef.
12895       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12896 
12897     // Check that we were able to transform all incoming values to the same
12898     // type.
12899     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12900         VecIn1.getValueType() != VT)
12901           return SDValue();
12902 
12903     // Return the new VECTOR_SHUFFLE node.
12904     SDValue Ops[2];
12905     Ops[0] = VecIn1;
12906     Ops[1] = VecIn2;
12907     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12908   }
12909 
12910   return SDValue();
12911 }
12912 
12913 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12915   EVT OpVT = N->getOperand(0).getValueType();
12916 
12917   // If the operands are legal vectors, leave them alone.
12918   if (TLI.isTypeLegal(OpVT))
12919     return SDValue();
12920 
12921   SDLoc DL(N);
12922   EVT VT = N->getValueType(0);
12923   SmallVector<SDValue, 8> Ops;
12924 
12925   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12926   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12927 
12928   // Keep track of what we encounter.
12929   bool AnyInteger = false;
12930   bool AnyFP = false;
12931   for (const SDValue &Op : N->ops()) {
12932     if (ISD::BITCAST == Op.getOpcode() &&
12933         !Op.getOperand(0).getValueType().isVector())
12934       Ops.push_back(Op.getOperand(0));
12935     else if (ISD::UNDEF == Op.getOpcode())
12936       Ops.push_back(ScalarUndef);
12937     else
12938       return SDValue();
12939 
12940     // Note whether we encounter an integer or floating point scalar.
12941     // If it's neither, bail out, it could be something weird like x86mmx.
12942     EVT LastOpVT = Ops.back().getValueType();
12943     if (LastOpVT.isFloatingPoint())
12944       AnyFP = true;
12945     else if (LastOpVT.isInteger())
12946       AnyInteger = true;
12947     else
12948       return SDValue();
12949   }
12950 
12951   // If any of the operands is a floating point scalar bitcast to a vector,
12952   // use floating point types throughout, and bitcast everything.
12953   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12954   if (AnyFP) {
12955     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12956     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12957     if (AnyInteger) {
12958       for (SDValue &Op : Ops) {
12959         if (Op.getValueType() == SVT)
12960           continue;
12961         if (Op.isUndef())
12962           Op = ScalarUndef;
12963         else
12964           Op = DAG.getBitcast(SVT, Op);
12965       }
12966     }
12967   }
12968 
12969   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12970                                VT.getSizeInBits() / SVT.getSizeInBits());
12971   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
12972 }
12973 
12974 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12975 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12976 // most two distinct vectors the same size as the result, attempt to turn this
12977 // into a legal shuffle.
12978 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12979   EVT VT = N->getValueType(0);
12980   EVT OpVT = N->getOperand(0).getValueType();
12981   int NumElts = VT.getVectorNumElements();
12982   int NumOpElts = OpVT.getVectorNumElements();
12983 
12984   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12985   SmallVector<int, 8> Mask;
12986 
12987   for (SDValue Op : N->ops()) {
12988     // Peek through any bitcast.
12989     while (Op.getOpcode() == ISD::BITCAST)
12990       Op = Op.getOperand(0);
12991 
12992     // UNDEF nodes convert to UNDEF shuffle mask values.
12993     if (Op.isUndef()) {
12994       Mask.append((unsigned)NumOpElts, -1);
12995       continue;
12996     }
12997 
12998     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12999       return SDValue();
13000 
13001     // What vector are we extracting the subvector from and at what index?
13002     SDValue ExtVec = Op.getOperand(0);
13003 
13004     // We want the EVT of the original extraction to correctly scale the
13005     // extraction index.
13006     EVT ExtVT = ExtVec.getValueType();
13007 
13008     // Peek through any bitcast.
13009     while (ExtVec.getOpcode() == ISD::BITCAST)
13010       ExtVec = ExtVec.getOperand(0);
13011 
13012     // UNDEF nodes convert to UNDEF shuffle mask values.
13013     if (ExtVec.isUndef()) {
13014       Mask.append((unsigned)NumOpElts, -1);
13015       continue;
13016     }
13017 
13018     if (!isa<ConstantSDNode>(Op.getOperand(1)))
13019       return SDValue();
13020     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13021 
13022     // Ensure that we are extracting a subvector from a vector the same
13023     // size as the result.
13024     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
13025       return SDValue();
13026 
13027     // Scale the subvector index to account for any bitcast.
13028     int NumExtElts = ExtVT.getVectorNumElements();
13029     if (0 == (NumExtElts % NumElts))
13030       ExtIdx /= (NumExtElts / NumElts);
13031     else if (0 == (NumElts % NumExtElts))
13032       ExtIdx *= (NumElts / NumExtElts);
13033     else
13034       return SDValue();
13035 
13036     // At most we can reference 2 inputs in the final shuffle.
13037     if (SV0.isUndef() || SV0 == ExtVec) {
13038       SV0 = ExtVec;
13039       for (int i = 0; i != NumOpElts; ++i)
13040         Mask.push_back(i + ExtIdx);
13041     } else if (SV1.isUndef() || SV1 == ExtVec) {
13042       SV1 = ExtVec;
13043       for (int i = 0; i != NumOpElts; ++i)
13044         Mask.push_back(i + ExtIdx + NumElts);
13045     } else {
13046       return SDValue();
13047     }
13048   }
13049 
13050   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
13051     return SDValue();
13052 
13053   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
13054                               DAG.getBitcast(VT, SV1), Mask);
13055 }
13056 
13057 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
13058   // If we only have one input vector, we don't need to do any concatenation.
13059   if (N->getNumOperands() == 1)
13060     return N->getOperand(0);
13061 
13062   // Check if all of the operands are undefs.
13063   EVT VT = N->getValueType(0);
13064   if (ISD::allOperandsUndef(N))
13065     return DAG.getUNDEF(VT);
13066 
13067   // Optimize concat_vectors where all but the first of the vectors are undef.
13068   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
13069         return Op.isUndef();
13070       })) {
13071     SDValue In = N->getOperand(0);
13072     assert(In.getValueType().isVector() && "Must concat vectors");
13073 
13074     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
13075     if (In->getOpcode() == ISD::BITCAST &&
13076         !In->getOperand(0)->getValueType(0).isVector()) {
13077       SDValue Scalar = In->getOperand(0);
13078 
13079       // If the bitcast type isn't legal, it might be a trunc of a legal type;
13080       // look through the trunc so we can still do the transform:
13081       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
13082       if (Scalar->getOpcode() == ISD::TRUNCATE &&
13083           !TLI.isTypeLegal(Scalar.getValueType()) &&
13084           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
13085         Scalar = Scalar->getOperand(0);
13086 
13087       EVT SclTy = Scalar->getValueType(0);
13088 
13089       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
13090         return SDValue();
13091 
13092       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
13093                                  VT.getSizeInBits() / SclTy.getSizeInBits());
13094       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
13095         return SDValue();
13096 
13097       SDLoc dl = SDLoc(N);
13098       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
13099       return DAG.getBitcast(VT, Res);
13100     }
13101   }
13102 
13103   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
13104   // We have already tested above for an UNDEF only concatenation.
13105   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
13106   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
13107   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
13108     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
13109   };
13110   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
13111     SmallVector<SDValue, 8> Opnds;
13112     EVT SVT = VT.getScalarType();
13113 
13114     EVT MinVT = SVT;
13115     if (!SVT.isFloatingPoint()) {
13116       // If BUILD_VECTOR are from built from integer, they may have different
13117       // operand types. Get the smallest type and truncate all operands to it.
13118       bool FoundMinVT = false;
13119       for (const SDValue &Op : N->ops())
13120         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13121           EVT OpSVT = Op.getOperand(0)->getValueType(0);
13122           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
13123           FoundMinVT = true;
13124         }
13125       assert(FoundMinVT && "Concat vector type mismatch");
13126     }
13127 
13128     for (const SDValue &Op : N->ops()) {
13129       EVT OpVT = Op.getValueType();
13130       unsigned NumElts = OpVT.getVectorNumElements();
13131 
13132       if (ISD::UNDEF == Op.getOpcode())
13133         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
13134 
13135       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
13136         if (SVT.isFloatingPoint()) {
13137           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
13138           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
13139         } else {
13140           for (unsigned i = 0; i != NumElts; ++i)
13141             Opnds.push_back(
13142                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
13143         }
13144       }
13145     }
13146 
13147     assert(VT.getVectorNumElements() == Opnds.size() &&
13148            "Concat vector type mismatch");
13149     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
13150   }
13151 
13152   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
13153   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
13154     return V;
13155 
13156   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
13157   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
13158     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
13159       return V;
13160 
13161   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
13162   // nodes often generate nop CONCAT_VECTOR nodes.
13163   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
13164   // place the incoming vectors at the exact same location.
13165   SDValue SingleSource = SDValue();
13166   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
13167 
13168   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13169     SDValue Op = N->getOperand(i);
13170 
13171     if (Op.isUndef())
13172       continue;
13173 
13174     // Check if this is the identity extract:
13175     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13176       return SDValue();
13177 
13178     // Find the single incoming vector for the extract_subvector.
13179     if (SingleSource.getNode()) {
13180       if (Op.getOperand(0) != SingleSource)
13181         return SDValue();
13182     } else {
13183       SingleSource = Op.getOperand(0);
13184 
13185       // Check the source type is the same as the type of the result.
13186       // If not, this concat may extend the vector, so we can not
13187       // optimize it away.
13188       if (SingleSource.getValueType() != N->getValueType(0))
13189         return SDValue();
13190     }
13191 
13192     unsigned IdentityIndex = i * PartNumElem;
13193     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13194     // The extract index must be constant.
13195     if (!CS)
13196       return SDValue();
13197 
13198     // Check that we are reading from the identity index.
13199     if (CS->getZExtValue() != IdentityIndex)
13200       return SDValue();
13201   }
13202 
13203   if (SingleSource.getNode())
13204     return SingleSource;
13205 
13206   return SDValue();
13207 }
13208 
13209 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
13210   EVT NVT = N->getValueType(0);
13211   SDValue V = N->getOperand(0);
13212 
13213   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
13214     // Combine:
13215     //    (extract_subvec (concat V1, V2, ...), i)
13216     // Into:
13217     //    Vi if possible
13218     // Only operand 0 is checked as 'concat' assumes all inputs of the same
13219     // type.
13220     if (V->getOperand(0).getValueType() != NVT)
13221       return SDValue();
13222     unsigned Idx = N->getConstantOperandVal(1);
13223     unsigned NumElems = NVT.getVectorNumElements();
13224     assert((Idx % NumElems) == 0 &&
13225            "IDX in concat is not a multiple of the result vector length.");
13226     return V->getOperand(Idx / NumElems);
13227   }
13228 
13229   // Skip bitcasting
13230   if (V->getOpcode() == ISD::BITCAST)
13231     V = V.getOperand(0);
13232 
13233   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
13234     SDLoc dl(N);
13235     // Handle only simple case where vector being inserted and vector
13236     // being extracted are of same type, and are half size of larger vectors.
13237     EVT BigVT = V->getOperand(0).getValueType();
13238     EVT SmallVT = V->getOperand(1).getValueType();
13239     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
13240       return SDValue();
13241 
13242     // Only handle cases where both indexes are constants with the same type.
13243     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
13244     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
13245 
13246     if (InsIdx && ExtIdx &&
13247         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
13248         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
13249       // Combine:
13250       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
13251       // Into:
13252       //    indices are equal or bit offsets are equal => V1
13253       //    otherwise => (extract_subvec V1, ExtIdx)
13254       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
13255           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
13256         return DAG.getBitcast(NVT, V->getOperand(1));
13257       return DAG.getNode(
13258           ISD::EXTRACT_SUBVECTOR, dl, NVT,
13259           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
13260           N->getOperand(1));
13261     }
13262   }
13263 
13264   return SDValue();
13265 }
13266 
13267 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
13268                                                  SDValue V, SelectionDAG &DAG) {
13269   SDLoc DL(V);
13270   EVT VT = V.getValueType();
13271 
13272   switch (V.getOpcode()) {
13273   default:
13274     return V;
13275 
13276   case ISD::CONCAT_VECTORS: {
13277     EVT OpVT = V->getOperand(0).getValueType();
13278     int OpSize = OpVT.getVectorNumElements();
13279     SmallBitVector OpUsedElements(OpSize, false);
13280     bool FoundSimplification = false;
13281     SmallVector<SDValue, 4> NewOps;
13282     NewOps.reserve(V->getNumOperands());
13283     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
13284       SDValue Op = V->getOperand(i);
13285       bool OpUsed = false;
13286       for (int j = 0; j < OpSize; ++j)
13287         if (UsedElements[i * OpSize + j]) {
13288           OpUsedElements[j] = true;
13289           OpUsed = true;
13290         }
13291       NewOps.push_back(
13292           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
13293                  : DAG.getUNDEF(OpVT));
13294       FoundSimplification |= Op == NewOps.back();
13295       OpUsedElements.reset();
13296     }
13297     if (FoundSimplification)
13298       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
13299     return V;
13300   }
13301 
13302   case ISD::INSERT_SUBVECTOR: {
13303     SDValue BaseV = V->getOperand(0);
13304     SDValue SubV = V->getOperand(1);
13305     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
13306     if (!IdxN)
13307       return V;
13308 
13309     int SubSize = SubV.getValueType().getVectorNumElements();
13310     int Idx = IdxN->getZExtValue();
13311     bool SubVectorUsed = false;
13312     SmallBitVector SubUsedElements(SubSize, false);
13313     for (int i = 0; i < SubSize; ++i)
13314       if (UsedElements[i + Idx]) {
13315         SubVectorUsed = true;
13316         SubUsedElements[i] = true;
13317         UsedElements[i + Idx] = false;
13318       }
13319 
13320     // Now recurse on both the base and sub vectors.
13321     SDValue SimplifiedSubV =
13322         SubVectorUsed
13323             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
13324             : DAG.getUNDEF(SubV.getValueType());
13325     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
13326     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
13327       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
13328                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13329     return V;
13330   }
13331   }
13332 }
13333 
13334 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13335                                        SDValue N1, SelectionDAG &DAG) {
13336   EVT VT = SVN->getValueType(0);
13337   int NumElts = VT.getVectorNumElements();
13338   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13339   for (int M : SVN->getMask())
13340     if (M >= 0 && M < NumElts)
13341       N0UsedElements[M] = true;
13342     else if (M >= NumElts)
13343       N1UsedElements[M - NumElts] = true;
13344 
13345   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13346   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13347   if (S0 == N0 && S1 == N1)
13348     return SDValue();
13349 
13350   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13351 }
13352 
13353 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13354 // or turn a shuffle of a single concat into simpler shuffle then concat.
13355 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13356   EVT VT = N->getValueType(0);
13357   unsigned NumElts = VT.getVectorNumElements();
13358 
13359   SDValue N0 = N->getOperand(0);
13360   SDValue N1 = N->getOperand(1);
13361   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13362 
13363   SmallVector<SDValue, 4> Ops;
13364   EVT ConcatVT = N0.getOperand(0).getValueType();
13365   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13366   unsigned NumConcats = NumElts / NumElemsPerConcat;
13367 
13368   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13369   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13370   // half vector elements.
13371   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
13372       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13373                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13374     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13375                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13376     N1 = DAG.getUNDEF(ConcatVT);
13377     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13378   }
13379 
13380   // Look at every vector that's inserted. We're looking for exact
13381   // subvector-sized copies from a concatenated vector
13382   for (unsigned I = 0; I != NumConcats; ++I) {
13383     // Make sure we're dealing with a copy.
13384     unsigned Begin = I * NumElemsPerConcat;
13385     bool AllUndef = true, NoUndef = true;
13386     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13387       if (SVN->getMaskElt(J) >= 0)
13388         AllUndef = false;
13389       else
13390         NoUndef = false;
13391     }
13392 
13393     if (NoUndef) {
13394       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13395         return SDValue();
13396 
13397       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13398         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13399           return SDValue();
13400 
13401       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13402       if (FirstElt < N0.getNumOperands())
13403         Ops.push_back(N0.getOperand(FirstElt));
13404       else
13405         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13406 
13407     } else if (AllUndef) {
13408       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13409     } else { // Mixed with general masks and undefs, can't do optimization.
13410       return SDValue();
13411     }
13412   }
13413 
13414   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13415 }
13416 
13417 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13418   EVT VT = N->getValueType(0);
13419   unsigned NumElts = VT.getVectorNumElements();
13420 
13421   SDValue N0 = N->getOperand(0);
13422   SDValue N1 = N->getOperand(1);
13423 
13424   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13425 
13426   // Canonicalize shuffle undef, undef -> undef
13427   if (N0.isUndef() && N1.isUndef())
13428     return DAG.getUNDEF(VT);
13429 
13430   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13431 
13432   // Canonicalize shuffle v, v -> v, undef
13433   if (N0 == N1) {
13434     SmallVector<int, 8> NewMask;
13435     for (unsigned i = 0; i != NumElts; ++i) {
13436       int Idx = SVN->getMaskElt(i);
13437       if (Idx >= (int)NumElts) Idx -= NumElts;
13438       NewMask.push_back(Idx);
13439     }
13440     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13441                                 &NewMask[0]);
13442   }
13443 
13444   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13445   if (N0.isUndef()) {
13446     SmallVector<int, 8> NewMask;
13447     for (unsigned i = 0; i != NumElts; ++i) {
13448       int Idx = SVN->getMaskElt(i);
13449       if (Idx >= 0) {
13450         if (Idx >= (int)NumElts)
13451           Idx -= NumElts;
13452         else
13453           Idx = -1; // remove reference to lhs
13454       }
13455       NewMask.push_back(Idx);
13456     }
13457     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13458                                 &NewMask[0]);
13459   }
13460 
13461   // Remove references to rhs if it is undef
13462   if (N1.isUndef()) {
13463     bool Changed = false;
13464     SmallVector<int, 8> NewMask;
13465     for (unsigned i = 0; i != NumElts; ++i) {
13466       int Idx = SVN->getMaskElt(i);
13467       if (Idx >= (int)NumElts) {
13468         Idx = -1;
13469         Changed = true;
13470       }
13471       NewMask.push_back(Idx);
13472     }
13473     if (Changed)
13474       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13475   }
13476 
13477   // If it is a splat, check if the argument vector is another splat or a
13478   // build_vector.
13479   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13480     SDNode *V = N0.getNode();
13481 
13482     // If this is a bit convert that changes the element type of the vector but
13483     // not the number of vector elements, look through it.  Be careful not to
13484     // look though conversions that change things like v4f32 to v2f64.
13485     if (V->getOpcode() == ISD::BITCAST) {
13486       SDValue ConvInput = V->getOperand(0);
13487       if (ConvInput.getValueType().isVector() &&
13488           ConvInput.getValueType().getVectorNumElements() == NumElts)
13489         V = ConvInput.getNode();
13490     }
13491 
13492     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13493       assert(V->getNumOperands() == NumElts &&
13494              "BUILD_VECTOR has wrong number of operands");
13495       SDValue Base;
13496       bool AllSame = true;
13497       for (unsigned i = 0; i != NumElts; ++i) {
13498         if (!V->getOperand(i).isUndef()) {
13499           Base = V->getOperand(i);
13500           break;
13501         }
13502       }
13503       // Splat of <u, u, u, u>, return <u, u, u, u>
13504       if (!Base.getNode())
13505         return N0;
13506       for (unsigned i = 0; i != NumElts; ++i) {
13507         if (V->getOperand(i) != Base) {
13508           AllSame = false;
13509           break;
13510         }
13511       }
13512       // Splat of <x, x, x, x>, return <x, x, x, x>
13513       if (AllSame)
13514         return N0;
13515 
13516       // Canonicalize any other splat as a build_vector.
13517       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13518       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13519       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
13520 
13521       // We may have jumped through bitcasts, so the type of the
13522       // BUILD_VECTOR may not match the type of the shuffle.
13523       if (V->getValueType(0) != VT)
13524         NewBV = DAG.getBitcast(VT, NewBV);
13525       return NewBV;
13526     }
13527   }
13528 
13529   // There are various patterns used to build up a vector from smaller vectors,
13530   // subvectors, or elements. Scan chains of these and replace unused insertions
13531   // or components with undef.
13532   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13533     return S;
13534 
13535   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13536       Level < AfterLegalizeVectorOps &&
13537       (N1.isUndef() ||
13538       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13539        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13540     if (SDValue V = partitionShuffleOfConcats(N, DAG))
13541       return V;
13542   }
13543 
13544   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13545   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13546   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13547     SmallVector<SDValue, 8> Ops;
13548     for (int M : SVN->getMask()) {
13549       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13550       if (M >= 0) {
13551         int Idx = M % NumElts;
13552         SDValue &S = (M < (int)NumElts ? N0 : N1);
13553         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13554           Op = S.getOperand(Idx);
13555         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13556           if (Idx == 0)
13557             Op = S.getOperand(0);
13558         } else {
13559           // Operand can't be combined - bail out.
13560           break;
13561         }
13562       }
13563       Ops.push_back(Op);
13564     }
13565     if (Ops.size() == VT.getVectorNumElements()) {
13566       // BUILD_VECTOR requires all inputs to be of the same type, find the
13567       // maximum type and extend them all.
13568       EVT SVT = VT.getScalarType();
13569       if (SVT.isInteger())
13570         for (SDValue &Op : Ops)
13571           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13572       if (SVT != VT.getScalarType())
13573         for (SDValue &Op : Ops)
13574           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13575                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13576                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13577       return DAG.getBuildVector(VT, SDLoc(N), Ops);
13578     }
13579   }
13580 
13581   // If this shuffle only has a single input that is a bitcasted shuffle,
13582   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13583   // back to their original types.
13584   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13585       N1.isUndef() && Level < AfterLegalizeVectorOps &&
13586       TLI.isTypeLegal(VT)) {
13587 
13588     // Peek through the bitcast only if there is one user.
13589     SDValue BC0 = N0;
13590     while (BC0.getOpcode() == ISD::BITCAST) {
13591       if (!BC0.hasOneUse())
13592         break;
13593       BC0 = BC0.getOperand(0);
13594     }
13595 
13596     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13597       if (Scale == 1)
13598         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13599 
13600       SmallVector<int, 8> NewMask;
13601       for (int M : Mask)
13602         for (int s = 0; s != Scale; ++s)
13603           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13604       return NewMask;
13605     };
13606 
13607     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13608       EVT SVT = VT.getScalarType();
13609       EVT InnerVT = BC0->getValueType(0);
13610       EVT InnerSVT = InnerVT.getScalarType();
13611 
13612       // Determine which shuffle works with the smaller scalar type.
13613       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13614       EVT ScaleSVT = ScaleVT.getScalarType();
13615 
13616       if (TLI.isTypeLegal(ScaleVT) &&
13617           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13618           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13619 
13620         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13621         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13622 
13623         // Scale the shuffle masks to the smaller scalar type.
13624         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13625         SmallVector<int, 8> InnerMask =
13626             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13627         SmallVector<int, 8> OuterMask =
13628             ScaleShuffleMask(SVN->getMask(), OuterScale);
13629 
13630         // Merge the shuffle masks.
13631         SmallVector<int, 8> NewMask;
13632         for (int M : OuterMask)
13633           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13634 
13635         // Test for shuffle mask legality over both commutations.
13636         SDValue SV0 = BC0->getOperand(0);
13637         SDValue SV1 = BC0->getOperand(1);
13638         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13639         if (!LegalMask) {
13640           std::swap(SV0, SV1);
13641           ShuffleVectorSDNode::commuteMask(NewMask);
13642           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13643         }
13644 
13645         if (LegalMask) {
13646           SV0 = DAG.getBitcast(ScaleVT, SV0);
13647           SV1 = DAG.getBitcast(ScaleVT, SV1);
13648           return DAG.getBitcast(
13649               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13650         }
13651       }
13652     }
13653   }
13654 
13655   // Canonicalize shuffles according to rules:
13656   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13657   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13658   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13659   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13660       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13661       TLI.isTypeLegal(VT)) {
13662     // The incoming shuffle must be of the same type as the result of the
13663     // current shuffle.
13664     assert(N1->getOperand(0).getValueType() == VT &&
13665            "Shuffle types don't match");
13666 
13667     SDValue SV0 = N1->getOperand(0);
13668     SDValue SV1 = N1->getOperand(1);
13669     bool HasSameOp0 = N0 == SV0;
13670     bool IsSV1Undef = SV1.isUndef();
13671     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13672       // Commute the operands of this shuffle so that next rule
13673       // will trigger.
13674       return DAG.getCommutedVectorShuffle(*SVN);
13675   }
13676 
13677   // Try to fold according to rules:
13678   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13679   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13680   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13681   // Don't try to fold shuffles with illegal type.
13682   // Only fold if this shuffle is the only user of the other shuffle.
13683   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13684       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13685     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13686 
13687     // The incoming shuffle must be of the same type as the result of the
13688     // current shuffle.
13689     assert(OtherSV->getOperand(0).getValueType() == VT &&
13690            "Shuffle types don't match");
13691 
13692     SDValue SV0, SV1;
13693     SmallVector<int, 4> Mask;
13694     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13695     // operand, and SV1 as the second operand.
13696     for (unsigned i = 0; i != NumElts; ++i) {
13697       int Idx = SVN->getMaskElt(i);
13698       if (Idx < 0) {
13699         // Propagate Undef.
13700         Mask.push_back(Idx);
13701         continue;
13702       }
13703 
13704       SDValue CurrentVec;
13705       if (Idx < (int)NumElts) {
13706         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13707         // shuffle mask to identify which vector is actually referenced.
13708         Idx = OtherSV->getMaskElt(Idx);
13709         if (Idx < 0) {
13710           // Propagate Undef.
13711           Mask.push_back(Idx);
13712           continue;
13713         }
13714 
13715         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13716                                            : OtherSV->getOperand(1);
13717       } else {
13718         // This shuffle index references an element within N1.
13719         CurrentVec = N1;
13720       }
13721 
13722       // Simple case where 'CurrentVec' is UNDEF.
13723       if (CurrentVec.isUndef()) {
13724         Mask.push_back(-1);
13725         continue;
13726       }
13727 
13728       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13729       // will be the first or second operand of the combined shuffle.
13730       Idx = Idx % NumElts;
13731       if (!SV0.getNode() || SV0 == CurrentVec) {
13732         // Ok. CurrentVec is the left hand side.
13733         // Update the mask accordingly.
13734         SV0 = CurrentVec;
13735         Mask.push_back(Idx);
13736         continue;
13737       }
13738 
13739       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13740       if (SV1.getNode() && SV1 != CurrentVec)
13741         return SDValue();
13742 
13743       // Ok. CurrentVec is the right hand side.
13744       // Update the mask accordingly.
13745       SV1 = CurrentVec;
13746       Mask.push_back(Idx + NumElts);
13747     }
13748 
13749     // Check if all indices in Mask are Undef. In case, propagate Undef.
13750     bool isUndefMask = true;
13751     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13752       isUndefMask &= Mask[i] < 0;
13753 
13754     if (isUndefMask)
13755       return DAG.getUNDEF(VT);
13756 
13757     if (!SV0.getNode())
13758       SV0 = DAG.getUNDEF(VT);
13759     if (!SV1.getNode())
13760       SV1 = DAG.getUNDEF(VT);
13761 
13762     // Avoid introducing shuffles with illegal mask.
13763     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13764       ShuffleVectorSDNode::commuteMask(Mask);
13765 
13766       if (!TLI.isShuffleMaskLegal(Mask, VT))
13767         return SDValue();
13768 
13769       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13770       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13771       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13772       std::swap(SV0, SV1);
13773     }
13774 
13775     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13776     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13777     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13778     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13779   }
13780 
13781   return SDValue();
13782 }
13783 
13784 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13785   SDValue InVal = N->getOperand(0);
13786   EVT VT = N->getValueType(0);
13787 
13788   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13789   // with a VECTOR_SHUFFLE.
13790   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13791     SDValue InVec = InVal->getOperand(0);
13792     SDValue EltNo = InVal->getOperand(1);
13793 
13794     // FIXME: We could support implicit truncation if the shuffle can be
13795     // scaled to a smaller vector scalar type.
13796     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13797     if (C0 && VT == InVec.getValueType() &&
13798         VT.getScalarType() == InVal.getValueType()) {
13799       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13800       int Elt = C0->getZExtValue();
13801       NewMask[0] = Elt;
13802 
13803       if (TLI.isShuffleMaskLegal(NewMask, VT))
13804         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13805                                     NewMask);
13806     }
13807   }
13808 
13809   return SDValue();
13810 }
13811 
13812 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13813   SDValue N0 = N->getOperand(0);
13814   SDValue N1 = N->getOperand(1);
13815   SDValue N2 = N->getOperand(2);
13816 
13817   if (N0.getValueType() != N1.getValueType())
13818     return SDValue();
13819 
13820   // If the input vector is a concatenation, and the insert replaces
13821   // one of the halves, we can optimize into a single concat_vectors.
13822   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 &&
13823       N2.getOpcode() == ISD::Constant) {
13824     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13825     EVT VT = N->getValueType(0);
13826 
13827     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13828     // (concat_vectors Z, Y)
13829     if (InsIdx == 0)
13830       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1,
13831                          N0.getOperand(1));
13832 
13833     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13834     // (concat_vectors X, Z)
13835     if (InsIdx == VT.getVectorNumElements() / 2)
13836       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0),
13837                          N1);
13838   }
13839 
13840   return SDValue();
13841 }
13842 
13843 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13844   SDValue N0 = N->getOperand(0);
13845 
13846   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13847   if (N0->getOpcode() == ISD::FP16_TO_FP)
13848     return N0->getOperand(0);
13849 
13850   return SDValue();
13851 }
13852 
13853 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13854   SDValue N0 = N->getOperand(0);
13855 
13856   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13857   if (N0->getOpcode() == ISD::AND) {
13858     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13859     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13860       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13861                          N0.getOperand(0));
13862     }
13863   }
13864 
13865   return SDValue();
13866 }
13867 
13868 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13869 /// with the destination vector and a zero vector.
13870 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13871 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13872 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13873   EVT VT = N->getValueType(0);
13874   SDValue LHS = N->getOperand(0);
13875   SDValue RHS = N->getOperand(1);
13876   SDLoc dl(N);
13877 
13878   // Make sure we're not running after operation legalization where it
13879   // may have custom lowered the vector shuffles.
13880   if (LegalOperations)
13881     return SDValue();
13882 
13883   if (N->getOpcode() != ISD::AND)
13884     return SDValue();
13885 
13886   if (RHS.getOpcode() == ISD::BITCAST)
13887     RHS = RHS.getOperand(0);
13888 
13889   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13890     return SDValue();
13891 
13892   EVT RVT = RHS.getValueType();
13893   unsigned NumElts = RHS.getNumOperands();
13894 
13895   // Attempt to create a valid clear mask, splitting the mask into
13896   // sub elements and checking to see if each is
13897   // all zeros or all ones - suitable for shuffle masking.
13898   auto BuildClearMask = [&](int Split) {
13899     int NumSubElts = NumElts * Split;
13900     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13901 
13902     SmallVector<int, 8> Indices;
13903     for (int i = 0; i != NumSubElts; ++i) {
13904       int EltIdx = i / Split;
13905       int SubIdx = i % Split;
13906       SDValue Elt = RHS.getOperand(EltIdx);
13907       if (Elt.isUndef()) {
13908         Indices.push_back(-1);
13909         continue;
13910       }
13911 
13912       APInt Bits;
13913       if (isa<ConstantSDNode>(Elt))
13914         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13915       else if (isa<ConstantFPSDNode>(Elt))
13916         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13917       else
13918         return SDValue();
13919 
13920       // Extract the sub element from the constant bit mask.
13921       if (DAG.getDataLayout().isBigEndian()) {
13922         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13923       } else {
13924         Bits = Bits.lshr(SubIdx * NumSubBits);
13925       }
13926 
13927       if (Split > 1)
13928         Bits = Bits.trunc(NumSubBits);
13929 
13930       if (Bits.isAllOnesValue())
13931         Indices.push_back(i);
13932       else if (Bits == 0)
13933         Indices.push_back(i + NumSubElts);
13934       else
13935         return SDValue();
13936     }
13937 
13938     // Let's see if the target supports this vector_shuffle.
13939     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13940     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13941     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13942       return SDValue();
13943 
13944     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13945     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13946                                                    DAG.getBitcast(ClearVT, LHS),
13947                                                    Zero, &Indices[0]));
13948   };
13949 
13950   // Determine maximum split level (byte level masking).
13951   int MaxSplit = 1;
13952   if (RVT.getScalarSizeInBits() % 8 == 0)
13953     MaxSplit = RVT.getScalarSizeInBits() / 8;
13954 
13955   for (int Split = 1; Split <= MaxSplit; ++Split)
13956     if (RVT.getScalarSizeInBits() % Split == 0)
13957       if (SDValue S = BuildClearMask(Split))
13958         return S;
13959 
13960   return SDValue();
13961 }
13962 
13963 /// Visit a binary vector operation, like ADD.
13964 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13965   assert(N->getValueType(0).isVector() &&
13966          "SimplifyVBinOp only works on vectors!");
13967 
13968   SDValue LHS = N->getOperand(0);
13969   SDValue RHS = N->getOperand(1);
13970   SDValue Ops[] = {LHS, RHS};
13971 
13972   // See if we can constant fold the vector operation.
13973   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13974           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13975     return Fold;
13976 
13977   // Try to convert a constant mask AND into a shuffle clear mask.
13978   if (SDValue Shuffle = XformToShuffleWithZero(N))
13979     return Shuffle;
13980 
13981   // Type legalization might introduce new shuffles in the DAG.
13982   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13983   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13984   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13985       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13986       LHS.getOperand(1).isUndef() &&
13987       RHS.getOperand(1).isUndef()) {
13988     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13989     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13990 
13991     if (SVN0->getMask().equals(SVN1->getMask())) {
13992       EVT VT = N->getValueType(0);
13993       SDValue UndefVector = LHS.getOperand(1);
13994       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13995                                      LHS.getOperand(0), RHS.getOperand(0),
13996                                      N->getFlags());
13997       AddUsersToWorklist(N);
13998       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13999                                   &SVN0->getMask()[0]);
14000     }
14001   }
14002 
14003   return SDValue();
14004 }
14005 
14006 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
14007                                     SDValue N1, SDValue N2){
14008   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
14009 
14010   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
14011                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
14012 
14013   // If we got a simplified select_cc node back from SimplifySelectCC, then
14014   // break it down into a new SETCC node, and a new SELECT node, and then return
14015   // the SELECT node, since we were called with a SELECT node.
14016   if (SCC.getNode()) {
14017     // Check to see if we got a select_cc back (to turn into setcc/select).
14018     // Otherwise, just return whatever node we got back, like fabs.
14019     if (SCC.getOpcode() == ISD::SELECT_CC) {
14020       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
14021                                   N0.getValueType(),
14022                                   SCC.getOperand(0), SCC.getOperand(1),
14023                                   SCC.getOperand(4));
14024       AddToWorklist(SETCC.getNode());
14025       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
14026                            SCC.getOperand(2), SCC.getOperand(3));
14027     }
14028 
14029     return SCC;
14030   }
14031   return SDValue();
14032 }
14033 
14034 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
14035 /// being selected between, see if we can simplify the select.  Callers of this
14036 /// should assume that TheSelect is deleted if this returns true.  As such, they
14037 /// should return the appropriate thing (e.g. the node) back to the top-level of
14038 /// the DAG combiner loop to avoid it being looked at.
14039 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
14040                                     SDValue RHS) {
14041 
14042   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14043   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
14044   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
14045     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
14046       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
14047       SDValue Sqrt = RHS;
14048       ISD::CondCode CC;
14049       SDValue CmpLHS;
14050       const ConstantFPSDNode *Zero = nullptr;
14051 
14052       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
14053         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
14054         CmpLHS = TheSelect->getOperand(0);
14055         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
14056       } else {
14057         // SELECT or VSELECT
14058         SDValue Cmp = TheSelect->getOperand(0);
14059         if (Cmp.getOpcode() == ISD::SETCC) {
14060           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
14061           CmpLHS = Cmp.getOperand(0);
14062           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
14063         }
14064       }
14065       if (Zero && Zero->isZero() &&
14066           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
14067           CC == ISD::SETULT || CC == ISD::SETLT)) {
14068         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
14069         CombineTo(TheSelect, Sqrt);
14070         return true;
14071       }
14072     }
14073   }
14074   // Cannot simplify select with vector condition
14075   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
14076 
14077   // If this is a select from two identical things, try to pull the operation
14078   // through the select.
14079   if (LHS.getOpcode() != RHS.getOpcode() ||
14080       !LHS.hasOneUse() || !RHS.hasOneUse())
14081     return false;
14082 
14083   // If this is a load and the token chain is identical, replace the select
14084   // of two loads with a load through a select of the address to load from.
14085   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
14086   // constants have been dropped into the constant pool.
14087   if (LHS.getOpcode() == ISD::LOAD) {
14088     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
14089     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
14090 
14091     // Token chains must be identical.
14092     if (LHS.getOperand(0) != RHS.getOperand(0) ||
14093         // Do not let this transformation reduce the number of volatile loads.
14094         LLD->isVolatile() || RLD->isVolatile() ||
14095         // FIXME: If either is a pre/post inc/dec load,
14096         // we'd need to split out the address adjustment.
14097         LLD->isIndexed() || RLD->isIndexed() ||
14098         // If this is an EXTLOAD, the VT's must match.
14099         LLD->getMemoryVT() != RLD->getMemoryVT() ||
14100         // If this is an EXTLOAD, the kind of extension must match.
14101         (LLD->getExtensionType() != RLD->getExtensionType() &&
14102          // The only exception is if one of the extensions is anyext.
14103          LLD->getExtensionType() != ISD::EXTLOAD &&
14104          RLD->getExtensionType() != ISD::EXTLOAD) ||
14105         // FIXME: this discards src value information.  This is
14106         // over-conservative. It would be beneficial to be able to remember
14107         // both potential memory locations.  Since we are discarding
14108         // src value info, don't do the transformation if the memory
14109         // locations are not in the default address space.
14110         LLD->getPointerInfo().getAddrSpace() != 0 ||
14111         RLD->getPointerInfo().getAddrSpace() != 0 ||
14112         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
14113                                       LLD->getBasePtr().getValueType()))
14114       return false;
14115 
14116     // Check that the select condition doesn't reach either load.  If so,
14117     // folding this will induce a cycle into the DAG.  If not, this is safe to
14118     // xform, so create a select of the addresses.
14119     SDValue Addr;
14120     if (TheSelect->getOpcode() == ISD::SELECT) {
14121       SDNode *CondNode = TheSelect->getOperand(0).getNode();
14122       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
14123           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
14124         return false;
14125       // The loads must not depend on one another.
14126       if (LLD->isPredecessorOf(RLD) ||
14127           RLD->isPredecessorOf(LLD))
14128         return false;
14129       Addr = DAG.getSelect(SDLoc(TheSelect),
14130                            LLD->getBasePtr().getValueType(),
14131                            TheSelect->getOperand(0), LLD->getBasePtr(),
14132                            RLD->getBasePtr());
14133     } else {  // Otherwise SELECT_CC
14134       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
14135       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
14136 
14137       if ((LLD->hasAnyUseOfValue(1) &&
14138            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
14139           (RLD->hasAnyUseOfValue(1) &&
14140            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
14141         return false;
14142 
14143       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
14144                          LLD->getBasePtr().getValueType(),
14145                          TheSelect->getOperand(0),
14146                          TheSelect->getOperand(1),
14147                          LLD->getBasePtr(), RLD->getBasePtr(),
14148                          TheSelect->getOperand(4));
14149     }
14150 
14151     SDValue Load;
14152     // It is safe to replace the two loads if they have different alignments,
14153     // but the new load must be the minimum (most restrictive) alignment of the
14154     // inputs.
14155     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
14156     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
14157     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
14158       Load = DAG.getLoad(TheSelect->getValueType(0),
14159                          SDLoc(TheSelect),
14160                          // FIXME: Discards pointer and AA info.
14161                          LLD->getChain(), Addr, MachinePointerInfo(),
14162                          LLD->isVolatile(), LLD->isNonTemporal(),
14163                          isInvariant, Alignment);
14164     } else {
14165       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
14166                             RLD->getExtensionType() : LLD->getExtensionType(),
14167                             SDLoc(TheSelect),
14168                             TheSelect->getValueType(0),
14169                             // FIXME: Discards pointer and AA info.
14170                             LLD->getChain(), Addr, MachinePointerInfo(),
14171                             LLD->getMemoryVT(), LLD->isVolatile(),
14172                             LLD->isNonTemporal(), isInvariant, Alignment);
14173     }
14174 
14175     // Users of the select now use the result of the load.
14176     CombineTo(TheSelect, Load);
14177 
14178     // Users of the old loads now use the new load's chain.  We know the
14179     // old-load value is dead now.
14180     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
14181     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
14182     return true;
14183   }
14184 
14185   return false;
14186 }
14187 
14188 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
14189 /// where 'cond' is the comparison specified by CC.
14190 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
14191                                       SDValue N2, SDValue N3,
14192                                       ISD::CondCode CC, bool NotExtCompare) {
14193   // (x ? y : y) -> y.
14194   if (N2 == N3) return N2;
14195 
14196   EVT VT = N2.getValueType();
14197   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
14198   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
14199 
14200   // Determine if the condition we're dealing with is constant
14201   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
14202                               N0, N1, CC, DL, false);
14203   if (SCC.getNode()) AddToWorklist(SCC.getNode());
14204 
14205   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
14206     // fold select_cc true, x, y -> x
14207     // fold select_cc false, x, y -> y
14208     return !SCCC->isNullValue() ? N2 : N3;
14209   }
14210 
14211   // Check to see if we can simplify the select into an fabs node
14212   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
14213     // Allow either -0.0 or 0.0
14214     if (CFP->isZero()) {
14215       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
14216       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
14217           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
14218           N2 == N3.getOperand(0))
14219         return DAG.getNode(ISD::FABS, DL, VT, N0);
14220 
14221       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
14222       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
14223           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
14224           N2.getOperand(0) == N3)
14225         return DAG.getNode(ISD::FABS, DL, VT, N3);
14226     }
14227   }
14228 
14229   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
14230   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
14231   // in it.  This is a win when the constant is not otherwise available because
14232   // it replaces two constant pool loads with one.  We only do this if the FP
14233   // type is known to be legal, because if it isn't, then we are before legalize
14234   // types an we want the other legalization to happen first (e.g. to avoid
14235   // messing with soft float) and if the ConstantFP is not legal, because if
14236   // it is legal, we may not need to store the FP constant in a constant pool.
14237   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
14238     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
14239       if (TLI.isTypeLegal(N2.getValueType()) &&
14240           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
14241                TargetLowering::Legal &&
14242            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
14243            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
14244           // If both constants have multiple uses, then we won't need to do an
14245           // extra load, they are likely around in registers for other users.
14246           (TV->hasOneUse() || FV->hasOneUse())) {
14247         Constant *Elts[] = {
14248           const_cast<ConstantFP*>(FV->getConstantFPValue()),
14249           const_cast<ConstantFP*>(TV->getConstantFPValue())
14250         };
14251         Type *FPTy = Elts[0]->getType();
14252         const DataLayout &TD = DAG.getDataLayout();
14253 
14254         // Create a ConstantArray of the two constants.
14255         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
14256         SDValue CPIdx =
14257             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
14258                                 TD.getPrefTypeAlignment(FPTy));
14259         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14260 
14261         // Get the offsets to the 0 and 1 element of the array so that we can
14262         // select between them.
14263         SDValue Zero = DAG.getIntPtrConstant(0, DL);
14264         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
14265         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
14266 
14267         SDValue Cond = DAG.getSetCC(DL,
14268                                     getSetCCResultType(N0.getValueType()),
14269                                     N0, N1, CC);
14270         AddToWorklist(Cond.getNode());
14271         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
14272                                           Cond, One, Zero);
14273         AddToWorklist(CstOffset.getNode());
14274         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
14275                             CstOffset);
14276         AddToWorklist(CPIdx.getNode());
14277         return DAG.getLoad(
14278             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
14279             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14280             false, false, false, Alignment);
14281       }
14282     }
14283 
14284   // Check to see if we can perform the "gzip trick", transforming
14285   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
14286   if (isNullConstant(N3) && CC == ISD::SETLT &&
14287       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
14288        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
14289     EVT XType = N0.getValueType();
14290     EVT AType = N2.getValueType();
14291     if (XType.bitsGE(AType)) {
14292       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
14293       // single-bit constant.
14294       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
14295         unsigned ShCtV = N2C->getAPIntValue().logBase2();
14296         ShCtV = XType.getSizeInBits() - ShCtV - 1;
14297         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
14298                                        getShiftAmountTy(N0.getValueType()));
14299         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
14300                                     XType, N0, ShCt);
14301         AddToWorklist(Shift.getNode());
14302 
14303         if (XType.bitsGT(AType)) {
14304           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14305           AddToWorklist(Shift.getNode());
14306         }
14307 
14308         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14309       }
14310 
14311       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
14312                                   XType, N0,
14313                                   DAG.getConstant(XType.getSizeInBits() - 1,
14314                                                   SDLoc(N0),
14315                                          getShiftAmountTy(N0.getValueType())));
14316       AddToWorklist(Shift.getNode());
14317 
14318       if (XType.bitsGT(AType)) {
14319         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
14320         AddToWorklist(Shift.getNode());
14321       }
14322 
14323       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
14324     }
14325   }
14326 
14327   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
14328   // where y is has a single bit set.
14329   // A plaintext description would be, we can turn the SELECT_CC into an AND
14330   // when the condition can be materialized as an all-ones register.  Any
14331   // single bit-test can be materialized as an all-ones register with
14332   // shift-left and shift-right-arith.
14333   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14334       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14335     SDValue AndLHS = N0->getOperand(0);
14336     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14337     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14338       // Shift the tested bit over the sign bit.
14339       APInt AndMask = ConstAndRHS->getAPIntValue();
14340       SDValue ShlAmt =
14341         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14342                         getShiftAmountTy(AndLHS.getValueType()));
14343       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14344 
14345       // Now arithmetic right shift it all the way over, so the result is either
14346       // all-ones, or zero.
14347       SDValue ShrAmt =
14348         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14349                         getShiftAmountTy(Shl.getValueType()));
14350       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14351 
14352       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14353     }
14354   }
14355 
14356   // fold select C, 16, 0 -> shl C, 4
14357   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14358       TLI.getBooleanContents(N0.getValueType()) ==
14359           TargetLowering::ZeroOrOneBooleanContent) {
14360 
14361     // If the caller doesn't want us to simplify this into a zext of a compare,
14362     // don't do it.
14363     if (NotExtCompare && N2C->isOne())
14364       return SDValue();
14365 
14366     // Get a SetCC of the condition
14367     // NOTE: Don't create a SETCC if it's not legal on this target.
14368     if (!LegalOperations ||
14369         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14370       SDValue Temp, SCC;
14371       // cast from setcc result type to select result type
14372       if (LegalTypes) {
14373         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14374                             N0, N1, CC);
14375         if (N2.getValueType().bitsLT(SCC.getValueType()))
14376           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14377                                         N2.getValueType());
14378         else
14379           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14380                              N2.getValueType(), SCC);
14381       } else {
14382         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14383         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14384                            N2.getValueType(), SCC);
14385       }
14386 
14387       AddToWorklist(SCC.getNode());
14388       AddToWorklist(Temp.getNode());
14389 
14390       if (N2C->isOne())
14391         return Temp;
14392 
14393       // shl setcc result by log2 n2c
14394       return DAG.getNode(
14395           ISD::SHL, DL, N2.getValueType(), Temp,
14396           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14397                           getShiftAmountTy(Temp.getValueType())));
14398     }
14399   }
14400 
14401   // Check to see if this is an integer abs.
14402   // select_cc setg[te] X,  0,  X, -X ->
14403   // select_cc setgt    X, -1,  X, -X ->
14404   // select_cc setl[te] X,  0, -X,  X ->
14405   // select_cc setlt    X,  1, -X,  X ->
14406   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14407   if (N1C) {
14408     ConstantSDNode *SubC = nullptr;
14409     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14410          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14411         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14412       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14413     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14414               (N1C->isOne() && CC == ISD::SETLT)) &&
14415              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14416       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14417 
14418     EVT XType = N0.getValueType();
14419     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14420       SDLoc DL(N0);
14421       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14422                                   N0,
14423                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14424                                          getShiftAmountTy(N0.getValueType())));
14425       SDValue Add = DAG.getNode(ISD::ADD, DL,
14426                                 XType, N0, Shift);
14427       AddToWorklist(Shift.getNode());
14428       AddToWorklist(Add.getNode());
14429       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14430     }
14431   }
14432 
14433   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
14434   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
14435   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
14436   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
14437   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
14438   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
14439   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
14440   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
14441   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14442     SDValue ValueOnZero = N2;
14443     SDValue Count = N3;
14444     // If the condition is NE instead of E, swap the operands.
14445     if (CC == ISD::SETNE)
14446       std::swap(ValueOnZero, Count);
14447     // Check if the value on zero is a constant equal to the bits in the type.
14448     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
14449       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
14450         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
14451         // legal, combine to just cttz.
14452         if ((Count.getOpcode() == ISD::CTTZ ||
14453              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
14454             N0 == Count.getOperand(0) &&
14455             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
14456           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
14457         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
14458         // legal, combine to just ctlz.
14459         if ((Count.getOpcode() == ISD::CTLZ ||
14460              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
14461             N0 == Count.getOperand(0) &&
14462             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
14463           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
14464       }
14465     }
14466   }
14467 
14468   return SDValue();
14469 }
14470 
14471 /// This is a stub for TargetLowering::SimplifySetCC.
14472 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14473                                    SDValue N1, ISD::CondCode Cond,
14474                                    SDLoc DL, bool foldBooleans) {
14475   TargetLowering::DAGCombinerInfo
14476     DagCombineInfo(DAG, Level, false, this);
14477   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14478 }
14479 
14480 /// Given an ISD::SDIV node expressing a divide by constant, return
14481 /// a DAG expression to select that will generate the same value by multiplying
14482 /// by a magic number.
14483 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14484 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14485   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14486   if (!C)
14487     return SDValue();
14488 
14489   // Avoid division by zero.
14490   if (C->isNullValue())
14491     return SDValue();
14492 
14493   std::vector<SDNode*> Built;
14494   SDValue S =
14495       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14496 
14497   for (SDNode *N : Built)
14498     AddToWorklist(N);
14499   return S;
14500 }
14501 
14502 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14503 /// DAG expression that will generate the same value by right shifting.
14504 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14505   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14506   if (!C)
14507     return SDValue();
14508 
14509   // Avoid division by zero.
14510   if (C->isNullValue())
14511     return SDValue();
14512 
14513   std::vector<SDNode *> Built;
14514   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14515 
14516   for (SDNode *N : Built)
14517     AddToWorklist(N);
14518   return S;
14519 }
14520 
14521 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14522 /// expression that will generate the same value by multiplying by a magic
14523 /// number.
14524 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14525 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14526   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14527   if (!C)
14528     return SDValue();
14529 
14530   // Avoid division by zero.
14531   if (C->isNullValue())
14532     return SDValue();
14533 
14534   std::vector<SDNode*> Built;
14535   SDValue S =
14536       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14537 
14538   for (SDNode *N : Built)
14539     AddToWorklist(N);
14540   return S;
14541 }
14542 
14543 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14544   if (Level >= AfterLegalizeDAG)
14545     return SDValue();
14546 
14547   // Expose the DAG combiner to the target combiner implementations.
14548   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14549 
14550   unsigned Iterations = 0;
14551   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14552     if (Iterations) {
14553       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14554       // For the reciprocal, we need to find the zero of the function:
14555       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14556       //     =>
14557       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14558       //     does not require additional intermediate precision]
14559       EVT VT = Op.getValueType();
14560       SDLoc DL(Op);
14561       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14562 
14563       AddToWorklist(Est.getNode());
14564 
14565       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14566       for (unsigned i = 0; i < Iterations; ++i) {
14567         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14568         AddToWorklist(NewEst.getNode());
14569 
14570         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14571         AddToWorklist(NewEst.getNode());
14572 
14573         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14574         AddToWorklist(NewEst.getNode());
14575 
14576         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14577         AddToWorklist(Est.getNode());
14578       }
14579     }
14580     return Est;
14581   }
14582 
14583   return SDValue();
14584 }
14585 
14586 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14587 /// For the reciprocal sqrt, we need to find the zero of the function:
14588 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14589 ///     =>
14590 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14591 /// As a result, we precompute A/2 prior to the iteration loop.
14592 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14593                                           unsigned Iterations,
14594                                           SDNodeFlags *Flags) {
14595   EVT VT = Arg.getValueType();
14596   SDLoc DL(Arg);
14597   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14598 
14599   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14600   // this entire sequence requires only one FP constant.
14601   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14602   AddToWorklist(HalfArg.getNode());
14603 
14604   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14605   AddToWorklist(HalfArg.getNode());
14606 
14607   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14608   for (unsigned i = 0; i < Iterations; ++i) {
14609     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14610     AddToWorklist(NewEst.getNode());
14611 
14612     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14613     AddToWorklist(NewEst.getNode());
14614 
14615     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14616     AddToWorklist(NewEst.getNode());
14617 
14618     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14619     AddToWorklist(Est.getNode());
14620   }
14621   return Est;
14622 }
14623 
14624 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14625 /// For the reciprocal sqrt, we need to find the zero of the function:
14626 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14627 ///     =>
14628 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14629 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14630                                           unsigned Iterations,
14631                                           SDNodeFlags *Flags) {
14632   EVT VT = Arg.getValueType();
14633   SDLoc DL(Arg);
14634   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14635   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14636 
14637   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14638   for (unsigned i = 0; i < Iterations; ++i) {
14639     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14640     AddToWorklist(HalfEst.getNode());
14641 
14642     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14643     AddToWorklist(Est.getNode());
14644 
14645     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14646     AddToWorklist(Est.getNode());
14647 
14648     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14649     AddToWorklist(Est.getNode());
14650 
14651     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14652     AddToWorklist(Est.getNode());
14653   }
14654   return Est;
14655 }
14656 
14657 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14658   if (Level >= AfterLegalizeDAG)
14659     return SDValue();
14660 
14661   // Expose the DAG combiner to the target combiner implementations.
14662   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14663   unsigned Iterations = 0;
14664   bool UseOneConstNR = false;
14665   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14666     AddToWorklist(Est.getNode());
14667     if (Iterations) {
14668       Est = UseOneConstNR ?
14669         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14670         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14671     }
14672     return Est;
14673   }
14674 
14675   return SDValue();
14676 }
14677 
14678 /// Return true if base is a frame index, which is known not to alias with
14679 /// anything but itself.  Provides base object and offset as results.
14680 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14681                            const GlobalValue *&GV, const void *&CV) {
14682   // Assume it is a primitive operation.
14683   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14684 
14685   // If it's an adding a simple constant then integrate the offset.
14686   if (Base.getOpcode() == ISD::ADD) {
14687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14688       Base = Base.getOperand(0);
14689       Offset += C->getZExtValue();
14690     }
14691   }
14692 
14693   // Return the underlying GlobalValue, and update the Offset.  Return false
14694   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14695   // by multiple nodes with different offsets.
14696   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14697     GV = G->getGlobal();
14698     Offset += G->getOffset();
14699     return false;
14700   }
14701 
14702   // Return the underlying Constant value, and update the Offset.  Return false
14703   // for ConstantSDNodes since the same constant pool entry may be represented
14704   // by multiple nodes with different offsets.
14705   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14706     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14707                                          : (const void *)C->getConstVal();
14708     Offset += C->getOffset();
14709     return false;
14710   }
14711   // If it's any of the following then it can't alias with anything but itself.
14712   return isa<FrameIndexSDNode>(Base);
14713 }
14714 
14715 /// Return true if there is any possibility that the two addresses overlap.
14716 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14717   // If they are the same then they must be aliases.
14718   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14719 
14720   // If they are both volatile then they cannot be reordered.
14721   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14722 
14723   // If one operation reads from invariant memory, and the other may store, they
14724   // cannot alias. These should really be checking the equivalent of mayWrite,
14725   // but it only matters for memory nodes other than load /store.
14726   if (Op0->isInvariant() && Op1->writeMem())
14727     return false;
14728 
14729   if (Op1->isInvariant() && Op0->writeMem())
14730     return false;
14731 
14732   // Gather base node and offset information.
14733   SDValue Base1, Base2;
14734   int64_t Offset1, Offset2;
14735   const GlobalValue *GV1, *GV2;
14736   const void *CV1, *CV2;
14737   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14738                                       Base1, Offset1, GV1, CV1);
14739   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14740                                       Base2, Offset2, GV2, CV2);
14741 
14742   // If they have a same base address then check to see if they overlap.
14743   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14744     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14745              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14746 
14747   // It is possible for different frame indices to alias each other, mostly
14748   // when tail call optimization reuses return address slots for arguments.
14749   // To catch this case, look up the actual index of frame indices to compute
14750   // the real alias relationship.
14751   if (isFrameIndex1 && isFrameIndex2) {
14752     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14753     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14754     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14755     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14756              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14757   }
14758 
14759   // Otherwise, if we know what the bases are, and they aren't identical, then
14760   // we know they cannot alias.
14761   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14762     return false;
14763 
14764   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14765   // compared to the size and offset of the access, we may be able to prove they
14766   // do not alias.  This check is conservative for now to catch cases created by
14767   // splitting vector types.
14768   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14769       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14770       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14771        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14772       (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
14773     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14774     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14775 
14776     // There is no overlap between these relatively aligned accesses of similar
14777     // size, return no alias.
14778     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14779         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14780       return false;
14781   }
14782 
14783   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14784                    ? CombinerGlobalAA
14785                    : DAG.getSubtarget().useAA();
14786 #ifndef NDEBUG
14787   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14788       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14789     UseAA = false;
14790 #endif
14791   if (UseAA &&
14792       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14793     // Use alias analysis information.
14794     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14795                                  Op1->getSrcValueOffset());
14796     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14797         Op0->getSrcValueOffset() - MinOffset;
14798     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14799         Op1->getSrcValueOffset() - MinOffset;
14800     AliasResult AAResult =
14801         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14802                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14803                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14804                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14805     if (AAResult == NoAlias)
14806       return false;
14807   }
14808 
14809   // Otherwise we have to assume they alias.
14810   return true;
14811 }
14812 
14813 /// Walk up chain skipping non-aliasing memory nodes,
14814 /// looking for aliasing nodes and adding them to the Aliases vector.
14815 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14816                                    SmallVectorImpl<SDValue> &Aliases) {
14817   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14818   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14819 
14820   // Get alias information for node.
14821   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14822 
14823   // Starting off.
14824   Chains.push_back(OriginalChain);
14825   unsigned Depth = 0;
14826 
14827   // Look at each chain and determine if it is an alias.  If so, add it to the
14828   // aliases list.  If not, then continue up the chain looking for the next
14829   // candidate.
14830   while (!Chains.empty()) {
14831     SDValue Chain = Chains.pop_back_val();
14832 
14833     // For TokenFactor nodes, look at each operand and only continue up the
14834     // chain until we reach the depth limit.
14835     //
14836     // FIXME: The depth check could be made to return the last non-aliasing
14837     // chain we found before we hit a tokenfactor rather than the original
14838     // chain.
14839     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
14840       Aliases.clear();
14841       Aliases.push_back(OriginalChain);
14842       return;
14843     }
14844 
14845     // Don't bother if we've been before.
14846     if (!Visited.insert(Chain.getNode()).second)
14847       continue;
14848 
14849     switch (Chain.getOpcode()) {
14850     case ISD::EntryToken:
14851       // Entry token is ideal chain operand, but handled in FindBetterChain.
14852       break;
14853 
14854     case ISD::LOAD:
14855     case ISD::STORE: {
14856       // Get alias information for Chain.
14857       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14858           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14859 
14860       // If chain is alias then stop here.
14861       if (!(IsLoad && IsOpLoad) &&
14862           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14863         Aliases.push_back(Chain);
14864       } else {
14865         // Look further up the chain.
14866         Chains.push_back(Chain.getOperand(0));
14867         ++Depth;
14868       }
14869       break;
14870     }
14871 
14872     case ISD::TokenFactor:
14873       // We have to check each of the operands of the token factor for "small"
14874       // token factors, so we queue them up.  Adding the operands to the queue
14875       // (stack) in reverse order maintains the original order and increases the
14876       // likelihood that getNode will find a matching token factor (CSE.)
14877       if (Chain.getNumOperands() > 16) {
14878         Aliases.push_back(Chain);
14879         break;
14880       }
14881       for (unsigned n = Chain.getNumOperands(); n;)
14882         Chains.push_back(Chain.getOperand(--n));
14883       ++Depth;
14884       break;
14885 
14886     default:
14887       // For all other instructions we will just have to take what we can get.
14888       Aliases.push_back(Chain);
14889       break;
14890     }
14891   }
14892 }
14893 
14894 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14895 /// (aliasing node.)
14896 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14897   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14898 
14899   // Accumulate all the aliases to this node.
14900   GatherAllAliases(N, OldChain, Aliases);
14901 
14902   // If no operands then chain to entry token.
14903   if (Aliases.size() == 0)
14904     return DAG.getEntryNode();
14905 
14906   // If a single operand then chain to it.  We don't need to revisit it.
14907   if (Aliases.size() == 1)
14908     return Aliases[0];
14909 
14910   // Construct a custom tailored token factor.
14911   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14912 }
14913 
14914 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14915   // This holds the base pointer, index, and the offset in bytes from the base
14916   // pointer.
14917   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
14918 
14919   // We must have a base and an offset.
14920   if (!BasePtr.Base.getNode())
14921     return false;
14922 
14923   // Do not handle stores to undef base pointers.
14924   if (BasePtr.Base.isUndef())
14925     return false;
14926 
14927   SmallVector<StoreSDNode *, 8> ChainedStores;
14928   ChainedStores.push_back(St);
14929 
14930   // Walk up the chain and look for nodes with offsets from the same
14931   // base pointer. Stop when reaching an instruction with a different kind
14932   // or instruction which has a different base pointer.
14933   StoreSDNode *Index = St;
14934   while (Index) {
14935     // If the chain has more than one use, then we can't reorder the mem ops.
14936     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14937       break;
14938 
14939     if (Index->isVolatile() || Index->isIndexed())
14940       break;
14941 
14942     // Find the base pointer and offset for this memory node.
14943     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
14944 
14945     // Check that the base pointer is the same as the original one.
14946     if (!Ptr.equalBaseIndex(BasePtr))
14947       break;
14948 
14949     // Find the next memory operand in the chain. If the next operand in the
14950     // chain is a store then move up and continue the scan with the next
14951     // memory operand. If the next operand is a load save it and use alias
14952     // information to check if it interferes with anything.
14953     SDNode *NextInChain = Index->getChain().getNode();
14954     while (true) {
14955       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14956         // We found a store node. Use it for the next iteration.
14957         if (STn->isVolatile() || STn->isIndexed()) {
14958           Index = nullptr;
14959           break;
14960         }
14961         ChainedStores.push_back(STn);
14962         Index = STn;
14963         break;
14964       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14965         NextInChain = Ldn->getChain().getNode();
14966         continue;
14967       } else {
14968         Index = nullptr;
14969         break;
14970       }
14971     }
14972   }
14973 
14974   bool MadeChange = false;
14975   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14976 
14977   for (StoreSDNode *ChainedStore : ChainedStores) {
14978     SDValue Chain = ChainedStore->getChain();
14979     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14980 
14981     if (Chain != BetterChain) {
14982       MadeChange = true;
14983       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14984     }
14985   }
14986 
14987   // Do all replacements after finding the replacements to make to avoid making
14988   // the chains more complicated by introducing new TokenFactors.
14989   for (auto Replacement : BetterChains)
14990     replaceStoreChain(Replacement.first, Replacement.second);
14991 
14992   return MadeChange;
14993 }
14994 
14995 /// This is the entry point for the file.
14996 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14997                            CodeGenOpt::Level OptLevel) {
14998   /// This is the main entry point to this class.
14999   DAGCombiner(*this, AA, OptLevel).Run(Level);
15000 }
15001