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/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryLocation.h"
34 #include "llvm/CodeGen/DAGCombine.h"
35 #include "llvm/CodeGen/ISDOpcodes.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineValueType.h"
40 #include "llvm/CodeGen/RuntimeLibcalls.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
45 #include "llvm/CodeGen/TargetLowering.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/Constant.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <functional>
71 #include <iterator>
72 #include <string>
73 #include <tuple>
74 #include <utility>
75 #include <vector>
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "dagcombine"
80 
81 STATISTIC(NodesCombined   , "Number of dag nodes combined");
82 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
83 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
84 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
85 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
86 STATISTIC(SlicedLoads, "Number of load sliced");
87 
88 static cl::opt<bool>
89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
90                  cl::desc("Enable DAG combiner's use of IR alias analysis"));
91 
92 static cl::opt<bool>
93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
94         cl::desc("Enable DAG combiner's use of TBAA"));
95 
96 #ifndef NDEBUG
97 static cl::opt<std::string>
98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
99                    cl::desc("Only use DAG-combiner alias analysis in this"
100                             " function"));
101 #endif
102 
103 /// Hidden option to stress test load slicing, i.e., when this option
104 /// is enabled, load slicing bypasses most of its profitability guards.
105 static cl::opt<bool>
106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
107                   cl::desc("Bypass the profitability model of load slicing"),
108                   cl::init(false));
109 
110 static cl::opt<bool>
111   MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
112                     cl::desc("DAG combiner may split indexing from loads"));
113 
114 namespace {
115 
116   class DAGCombiner {
117     SelectionDAG &DAG;
118     const TargetLowering &TLI;
119     CombineLevel Level;
120     CodeGenOpt::Level OptLevel;
121     bool LegalOperations = false;
122     bool LegalTypes = false;
123     bool ForCodeSize;
124 
125     /// \brief Worklist of all of the nodes that need to be simplified.
126     ///
127     /// This must behave as a stack -- new nodes to process are pushed onto the
128     /// back and when processing we pop off of the back.
129     ///
130     /// The worklist will not contain duplicates but may contain null entries
131     /// due to nodes being deleted from the underlying DAG.
132     SmallVector<SDNode *, 64> Worklist;
133 
134     /// \brief Mapping from an SDNode to its position on the worklist.
135     ///
136     /// This is used to find and remove nodes from the worklist (by nulling
137     /// them) when they are deleted from the underlying DAG. It relies on
138     /// stable indices of nodes within the worklist.
139     DenseMap<SDNode *, unsigned> WorklistMap;
140 
141     /// \brief Set of nodes which have been combined (at least once).
142     ///
143     /// This is used to allow us to reliably add any operands of a DAG node
144     /// which have not yet been combined to the worklist.
145     SmallPtrSet<SDNode *, 32> CombinedNodes;
146 
147     // AA - Used for DAG load/store alias analysis.
148     AliasAnalysis *AA;
149 
150     /// When an instruction is simplified, add all users of the instruction to
151     /// the work lists because they might get more simplified now.
152     void AddUsersToWorklist(SDNode *N) {
153       for (SDNode *Node : N->uses())
154         AddToWorklist(Node);
155     }
156 
157     /// Call the node-specific routine that folds each particular type of node.
158     SDValue visit(SDNode *N);
159 
160   public:
161     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
162         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
163           OptLevel(OL), AA(AA) {
164       ForCodeSize = DAG.getMachineFunction().getFunction().optForSize();
165 
166       MaximumLegalStoreInBits = 0;
167       for (MVT VT : MVT::all_valuetypes())
168         if (EVT(VT).isSimple() && VT != MVT::Other &&
169             TLI.isTypeLegal(EVT(VT)) &&
170             VT.getSizeInBits() >= MaximumLegalStoreInBits)
171           MaximumLegalStoreInBits = VT.getSizeInBits();
172     }
173 
174     /// Add to the worklist making sure its instance is at the back (next to be
175     /// processed.)
176     void AddToWorklist(SDNode *N) {
177       assert(N->getOpcode() != ISD::DELETED_NODE &&
178              "Deleted Node added to Worklist");
179 
180       // Skip handle nodes as they can't usefully be combined and confuse the
181       // zero-use deletion strategy.
182       if (N->getOpcode() == ISD::HANDLENODE)
183         return;
184 
185       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
186         Worklist.push_back(N);
187     }
188 
189     /// Remove all instances of N from the worklist.
190     void removeFromWorklist(SDNode *N) {
191       CombinedNodes.erase(N);
192 
193       auto It = WorklistMap.find(N);
194       if (It == WorklistMap.end())
195         return; // Not in the worklist.
196 
197       // Null out the entry rather than erasing it to avoid a linear operation.
198       Worklist[It->second] = nullptr;
199       WorklistMap.erase(It);
200     }
201 
202     void deleteAndRecombine(SDNode *N);
203     bool recursivelyDeleteUnusedNodes(SDNode *N);
204 
205     /// Replaces all uses of the results of one DAG node with new values.
206     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
207                       bool AddTo = true);
208 
209     /// Replaces all uses of the results of one DAG node with new values.
210     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
211       return CombineTo(N, &Res, 1, AddTo);
212     }
213 
214     /// Replaces all uses of the results of one DAG node with new values.
215     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
216                       bool AddTo = true) {
217       SDValue To[] = { Res0, Res1 };
218       return CombineTo(N, To, 2, AddTo);
219     }
220 
221     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
222 
223   private:
224     unsigned MaximumLegalStoreInBits;
225 
226     /// Check the specified integer node value to see if it can be simplified or
227     /// if things it uses can be simplified by bit propagation.
228     /// If so, return true.
229     bool SimplifyDemandedBits(SDValue Op) {
230       unsigned BitWidth = Op.getScalarValueSizeInBits();
231       APInt Demanded = APInt::getAllOnesValue(BitWidth);
232       return SimplifyDemandedBits(Op, Demanded);
233     }
234 
235     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
236 
237     bool CombineToPreIndexedLoadStore(SDNode *N);
238     bool CombineToPostIndexedLoadStore(SDNode *N);
239     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
240     bool SliceUpLoad(SDNode *N);
241 
242     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
243     ///   load.
244     ///
245     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
246     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
247     /// \param EltNo index of the vector element to load.
248     /// \param OriginalLoad load that EVE came from to be replaced.
249     /// \returns EVE on success SDValue() on failure.
250     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
251         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
252     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
253     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
254     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
255     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
256     SDValue PromoteIntBinOp(SDValue Op);
257     SDValue PromoteIntShiftOp(SDValue Op);
258     SDValue PromoteExtend(SDValue Op);
259     bool PromoteLoad(SDValue Op);
260 
261     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
262                          SDValue ExtLoad, const SDLoc &DL,
263                          ISD::NodeType ExtType);
264 
265     /// Call the node-specific routine that knows how to fold each
266     /// particular type of node. If that doesn't do anything, try the
267     /// target-specific DAG combines.
268     SDValue combine(SDNode *N);
269 
270     // Visitation implementation - Implement dag node combining for different
271     // node types.  The semantics are as follows:
272     // Return Value:
273     //   SDValue.getNode() == 0 - No change was made
274     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
275     //   otherwise              - N should be replaced by the returned Operand.
276     //
277     SDValue visitTokenFactor(SDNode *N);
278     SDValue visitMERGE_VALUES(SDNode *N);
279     SDValue visitADD(SDNode *N);
280     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
281     SDValue visitSUB(SDNode *N);
282     SDValue visitADDC(SDNode *N);
283     SDValue visitUADDO(SDNode *N);
284     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
285     SDValue visitSUBC(SDNode *N);
286     SDValue visitUSUBO(SDNode *N);
287     SDValue visitADDE(SDNode *N);
288     SDValue visitADDCARRY(SDNode *N);
289     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
290     SDValue visitSUBE(SDNode *N);
291     SDValue visitSUBCARRY(SDNode *N);
292     SDValue visitMUL(SDNode *N);
293     SDValue useDivRem(SDNode *N);
294     SDValue visitSDIV(SDNode *N);
295     SDValue visitUDIV(SDNode *N);
296     SDValue visitREM(SDNode *N);
297     SDValue visitMULHU(SDNode *N);
298     SDValue visitMULHS(SDNode *N);
299     SDValue visitSMUL_LOHI(SDNode *N);
300     SDValue visitUMUL_LOHI(SDNode *N);
301     SDValue visitSMULO(SDNode *N);
302     SDValue visitUMULO(SDNode *N);
303     SDValue visitIMINMAX(SDNode *N);
304     SDValue visitAND(SDNode *N);
305     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
306     SDValue visitOR(SDNode *N);
307     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
308     SDValue visitXOR(SDNode *N);
309     SDValue SimplifyVBinOp(SDNode *N);
310     SDValue visitSHL(SDNode *N);
311     SDValue visitSRA(SDNode *N);
312     SDValue visitSRL(SDNode *N);
313     SDValue visitRotate(SDNode *N);
314     SDValue visitABS(SDNode *N);
315     SDValue visitBSWAP(SDNode *N);
316     SDValue visitBITREVERSE(SDNode *N);
317     SDValue visitCTLZ(SDNode *N);
318     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
319     SDValue visitCTTZ(SDNode *N);
320     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
321     SDValue visitCTPOP(SDNode *N);
322     SDValue visitSELECT(SDNode *N);
323     SDValue visitVSELECT(SDNode *N);
324     SDValue visitSELECT_CC(SDNode *N);
325     SDValue visitSETCC(SDNode *N);
326     SDValue visitSETCCE(SDNode *N);
327     SDValue visitSETCCCARRY(SDNode *N);
328     SDValue visitSIGN_EXTEND(SDNode *N);
329     SDValue visitZERO_EXTEND(SDNode *N);
330     SDValue visitANY_EXTEND(SDNode *N);
331     SDValue visitAssertExt(SDNode *N);
332     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
333     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
334     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
335     SDValue visitTRUNCATE(SDNode *N);
336     SDValue visitBITCAST(SDNode *N);
337     SDValue visitBUILD_PAIR(SDNode *N);
338     SDValue visitFADD(SDNode *N);
339     SDValue visitFSUB(SDNode *N);
340     SDValue visitFMUL(SDNode *N);
341     SDValue visitFMA(SDNode *N);
342     SDValue visitFDIV(SDNode *N);
343     SDValue visitFREM(SDNode *N);
344     SDValue visitFSQRT(SDNode *N);
345     SDValue visitFCOPYSIGN(SDNode *N);
346     SDValue visitSINT_TO_FP(SDNode *N);
347     SDValue visitUINT_TO_FP(SDNode *N);
348     SDValue visitFP_TO_SINT(SDNode *N);
349     SDValue visitFP_TO_UINT(SDNode *N);
350     SDValue visitFP_ROUND(SDNode *N);
351     SDValue visitFP_ROUND_INREG(SDNode *N);
352     SDValue visitFP_EXTEND(SDNode *N);
353     SDValue visitFNEG(SDNode *N);
354     SDValue visitFABS(SDNode *N);
355     SDValue visitFCEIL(SDNode *N);
356     SDValue visitFTRUNC(SDNode *N);
357     SDValue visitFFLOOR(SDNode *N);
358     SDValue visitFMINNUM(SDNode *N);
359     SDValue visitFMAXNUM(SDNode *N);
360     SDValue visitBRCOND(SDNode *N);
361     SDValue visitBR_CC(SDNode *N);
362     SDValue visitLOAD(SDNode *N);
363 
364     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
365     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
366 
367     SDValue visitSTORE(SDNode *N);
368     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
369     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
370     SDValue visitBUILD_VECTOR(SDNode *N);
371     SDValue visitCONCAT_VECTORS(SDNode *N);
372     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
373     SDValue visitVECTOR_SHUFFLE(SDNode *N);
374     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
375     SDValue visitINSERT_SUBVECTOR(SDNode *N);
376     SDValue visitMLOAD(SDNode *N);
377     SDValue visitMSTORE(SDNode *N);
378     SDValue visitMGATHER(SDNode *N);
379     SDValue visitMSCATTER(SDNode *N);
380     SDValue visitFP_TO_FP16(SDNode *N);
381     SDValue visitFP16_TO_FP(SDNode *N);
382 
383     SDValue visitFADDForFMACombine(SDNode *N);
384     SDValue visitFSUBForFMACombine(SDNode *N);
385     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
386 
387     SDValue XformToShuffleWithZero(SDNode *N);
388     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
389                            SDValue RHS);
390 
391     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
392 
393     SDValue foldSelectOfConstants(SDNode *N);
394     SDValue foldVSelectOfConstants(SDNode *N);
395     SDValue foldBinOpIntoSelect(SDNode *BO);
396     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
397     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
398     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
399     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
400                              SDValue N2, SDValue N3, ISD::CondCode CC,
401                              bool NotExtCompare = false);
402     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
403                                    SDValue N2, SDValue N3, ISD::CondCode CC);
404     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
405                               const SDLoc &DL);
406     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
407                           const SDLoc &DL, bool foldBooleans = true);
408 
409     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
410                            SDValue &CC) const;
411     bool isOneUseSetCC(SDValue N) const;
412 
413     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
414                                          unsigned HiOp);
415     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
416     SDValue CombineExtLoad(SDNode *N);
417     SDValue combineRepeatedFPDivisors(SDNode *N);
418     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
419     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
420     SDValue BuildSDIV(SDNode *N);
421     SDValue BuildSDIVPow2(SDNode *N);
422     SDValue BuildUDIV(SDNode *N);
423     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
424     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
425     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
426     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
427     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
428     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
429                                 SDNodeFlags Flags, bool Reciprocal);
430     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
431                                 SDNodeFlags Flags, bool Reciprocal);
432     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
433                                bool DemandHighBits = true);
434     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
435     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
436                               SDValue InnerPos, SDValue InnerNeg,
437                               unsigned PosOpcode, unsigned NegOpcode,
438                               const SDLoc &DL);
439     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
440     SDValue MatchLoadCombine(SDNode *N);
441     SDValue ReduceLoadWidth(SDNode *N);
442     SDValue ReduceLoadOpStoreWidth(SDNode *N);
443     SDValue splitMergedValStore(StoreSDNode *ST);
444     SDValue TransformFPLoadStorePair(SDNode *N);
445     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
446     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
447     SDValue reduceBuildVecToShuffle(SDNode *N);
448     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
449                                   ArrayRef<int> VectorMask, SDValue VecIn1,
450                                   SDValue VecIn2, unsigned LeftIdx);
451     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
452 
453     /// Walk up chain skipping non-aliasing memory nodes,
454     /// looking for aliasing nodes and adding them to the Aliases vector.
455     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
456                           SmallVectorImpl<SDValue> &Aliases);
457 
458     /// Return true if there is any possibility that the two addresses overlap.
459     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
460 
461     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
462     /// chain (aliasing node.)
463     SDValue FindBetterChain(SDNode *N, SDValue Chain);
464 
465     /// Try to replace a store and any possibly adjacent stores on
466     /// consecutive chains with better chains. Return true only if St is
467     /// replaced.
468     ///
469     /// Notice that other chains may still be replaced even if the function
470     /// returns false.
471     bool findBetterNeighborChains(StoreSDNode *St);
472 
473     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
474     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
475 
476     /// Holds a pointer to an LSBaseSDNode as well as information on where it
477     /// is located in a sequence of memory operations connected by a chain.
478     struct MemOpLink {
479       // Ptr to the mem node.
480       LSBaseSDNode *MemNode;
481 
482       // Offset from the base ptr.
483       int64_t OffsetFromBase;
484 
485       MemOpLink(LSBaseSDNode *N, int64_t Offset)
486           : MemNode(N), OffsetFromBase(Offset) {}
487     };
488 
489     /// This is a helper function for visitMUL to check the profitability
490     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
491     /// MulNode is the original multiply, AddNode is (add x, c1),
492     /// and ConstNode is c2.
493     bool isMulAddWithConstProfitable(SDNode *MulNode,
494                                      SDValue &AddNode,
495                                      SDValue &ConstNode);
496 
497     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
498     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
499     /// the type of the loaded value to be extended.
500     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
501                           EVT LoadResultTy, EVT &ExtVT);
502 
503     /// Helper function to calculate whether the given Load can have its
504     /// width reduced to ExtVT.
505     bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
506                            EVT &ExtVT, unsigned ShAmt = 0);
507 
508     /// Used by BackwardsPropagateMask to find suitable loads.
509     bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
510                            SmallPtrSetImpl<SDNode*> &NodeWithConsts,
511                            ConstantSDNode *Mask, SDNode *&UncombinedNode);
512     /// Attempt to propagate a given AND node back to load leaves so that they
513     /// can be combined into narrow loads.
514     bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
515 
516     /// Helper function for MergeConsecutiveStores which merges the
517     /// component store chains.
518     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
519                                 unsigned NumStores);
520 
521     /// This is a helper function for MergeConsecutiveStores. When the
522     /// source elements of the consecutive stores are all constants or
523     /// all extracted vector elements, try to merge them into one
524     /// larger store introducing bitcasts if necessary.  \return True
525     /// if a merged store was created.
526     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
527                                          EVT MemVT, unsigned NumStores,
528                                          bool IsConstantSrc, bool UseVector,
529                                          bool UseTrunc);
530 
531     /// This is a helper function for MergeConsecutiveStores. Stores
532     /// that potentially may be merged with St are placed in
533     /// StoreNodes.
534     void getStoreMergeCandidates(StoreSDNode *St,
535                                  SmallVectorImpl<MemOpLink> &StoreNodes);
536 
537     /// Helper function for MergeConsecutiveStores. Checks if
538     /// candidate stores have indirect dependency through their
539     /// operands. \return True if safe to merge.
540     bool checkMergeStoreCandidatesForDependencies(
541         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
542 
543     /// Merge consecutive store operations into a wide store.
544     /// This optimization uses wide integers or vectors when possible.
545     /// \return number of stores that were merged into a merged store (the
546     /// affected nodes are stored as a prefix in \p StoreNodes).
547     bool MergeConsecutiveStores(StoreSDNode *N);
548 
549     /// \brief Try to transform a truncation where C is a constant:
550     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
551     ///
552     /// \p N needs to be a truncation and its first operand an AND. Other
553     /// requirements are checked by the function (e.g. that trunc is
554     /// single-use) and if missed an empty SDValue is returned.
555     SDValue distributeTruncateThroughAnd(SDNode *N);
556 
557   public:
558     /// Runs the dag combiner on all nodes in the work list
559     void Run(CombineLevel AtLevel);
560 
561     SelectionDAG &getDAG() const { return DAG; }
562 
563     /// Returns a type large enough to hold any valid shift amount - before type
564     /// legalization these can be huge.
565     EVT getShiftAmountTy(EVT LHSTy) {
566       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
567       if (LHSTy.isVector())
568         return LHSTy;
569       auto &DL = DAG.getDataLayout();
570       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
571                         : TLI.getPointerTy(DL);
572     }
573 
574     /// This method returns true if we are running before type legalization or
575     /// if the specified VT is legal.
576     bool isTypeLegal(const EVT &VT) {
577       if (!LegalTypes) return true;
578       return TLI.isTypeLegal(VT);
579     }
580 
581     /// Convenience wrapper around TargetLowering::getSetCCResultType
582     EVT getSetCCResultType(EVT VT) const {
583       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
584     }
585   };
586 
587 /// This class is a DAGUpdateListener that removes any deleted
588 /// nodes from the worklist.
589 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
590   DAGCombiner &DC;
591 
592 public:
593   explicit WorklistRemover(DAGCombiner &dc)
594     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
595 
596   void NodeDeleted(SDNode *N, SDNode *E) override {
597     DC.removeFromWorklist(N);
598   }
599 };
600 
601 } // end anonymous namespace
602 
603 //===----------------------------------------------------------------------===//
604 //  TargetLowering::DAGCombinerInfo implementation
605 //===----------------------------------------------------------------------===//
606 
607 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
608   ((DAGCombiner*)DC)->AddToWorklist(N);
609 }
610 
611 SDValue TargetLowering::DAGCombinerInfo::
612 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
613   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
614 }
615 
616 SDValue TargetLowering::DAGCombinerInfo::
617 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
618   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
619 }
620 
621 SDValue TargetLowering::DAGCombinerInfo::
622 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
623   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
624 }
625 
626 void TargetLowering::DAGCombinerInfo::
627 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
628   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
629 }
630 
631 //===----------------------------------------------------------------------===//
632 // Helper Functions
633 //===----------------------------------------------------------------------===//
634 
635 void DAGCombiner::deleteAndRecombine(SDNode *N) {
636   removeFromWorklist(N);
637 
638   // If the operands of this node are only used by the node, they will now be
639   // dead. Make sure to re-visit them and recursively delete dead nodes.
640   for (const SDValue &Op : N->ops())
641     // For an operand generating multiple values, one of the values may
642     // become dead allowing further simplification (e.g. split index
643     // arithmetic from an indexed load).
644     if (Op->hasOneUse() || Op->getNumValues() > 1)
645       AddToWorklist(Op.getNode());
646 
647   DAG.DeleteNode(N);
648 }
649 
650 /// Return 1 if we can compute the negated form of the specified expression for
651 /// the same cost as the expression itself, or 2 if we can compute the negated
652 /// form more cheaply than the expression itself.
653 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
654                                const TargetLowering &TLI,
655                                const TargetOptions *Options,
656                                unsigned Depth = 0) {
657   // fneg is removable even if it has multiple uses.
658   if (Op.getOpcode() == ISD::FNEG) return 2;
659 
660   // Don't allow anything with multiple uses.
661   if (!Op.hasOneUse()) return 0;
662 
663   // Don't recurse exponentially.
664   if (Depth > 6) return 0;
665 
666   switch (Op.getOpcode()) {
667   default: return false;
668   case ISD::ConstantFP: {
669     if (!LegalOperations)
670       return 1;
671 
672     // Don't invert constant FP values after legalization unless the target says
673     // the negated constant is legal.
674     EVT VT = Op.getValueType();
675     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
676       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
677   }
678   case ISD::FADD:
679     // FIXME: determine better conditions for this xform.
680     if (!Options->UnsafeFPMath) return 0;
681 
682     // After operation legalization, it might not be legal to create new FSUBs.
683     if (LegalOperations &&
684         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
685       return 0;
686 
687     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
688     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
689                                     Options, Depth + 1))
690       return V;
691     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
692     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
693                               Depth + 1);
694   case ISD::FSUB:
695     // We can't turn -(A-B) into B-A when we honor signed zeros.
696     if (!Options->NoSignedZerosFPMath &&
697         !Op.getNode()->getFlags().hasNoSignedZeros())
698       return 0;
699 
700     // fold (fneg (fsub A, B)) -> (fsub B, A)
701     return 1;
702 
703   case ISD::FMUL:
704   case ISD::FDIV:
705     if (Options->HonorSignDependentRoundingFPMath()) return 0;
706 
707     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
708     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
709                                     Options, Depth + 1))
710       return V;
711 
712     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
713                               Depth + 1);
714 
715   case ISD::FP_EXTEND:
716   case ISD::FP_ROUND:
717   case ISD::FSIN:
718     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
719                               Depth + 1);
720   }
721 }
722 
723 /// If isNegatibleForFree returns true, return the newly negated expression.
724 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
725                                     bool LegalOperations, unsigned Depth = 0) {
726   const TargetOptions &Options = DAG.getTarget().Options;
727   // fneg is removable even if it has multiple uses.
728   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
729 
730   // Don't allow anything with multiple uses.
731   assert(Op.hasOneUse() && "Unknown reuse!");
732 
733   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
734 
735   const SDNodeFlags Flags = Op.getNode()->getFlags();
736 
737   switch (Op.getOpcode()) {
738   default: llvm_unreachable("Unknown code");
739   case ISD::ConstantFP: {
740     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
741     V.changeSign();
742     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
743   }
744   case ISD::FADD:
745     // FIXME: determine better conditions for this xform.
746     assert(Options.UnsafeFPMath);
747 
748     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
749     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
750                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
751       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
752                          GetNegatedExpression(Op.getOperand(0), DAG,
753                                               LegalOperations, Depth+1),
754                          Op.getOperand(1), Flags);
755     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
756     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
757                        GetNegatedExpression(Op.getOperand(1), DAG,
758                                             LegalOperations, Depth+1),
759                        Op.getOperand(0), Flags);
760   case ISD::FSUB:
761     // fold (fneg (fsub 0, B)) -> B
762     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
763       if (N0CFP->isZero())
764         return Op.getOperand(1);
765 
766     // fold (fneg (fsub A, B)) -> (fsub B, A)
767     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
768                        Op.getOperand(1), Op.getOperand(0), Flags);
769 
770   case ISD::FMUL:
771   case ISD::FDIV:
772     assert(!Options.HonorSignDependentRoundingFPMath());
773 
774     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
775     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
776                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
777       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
778                          GetNegatedExpression(Op.getOperand(0), DAG,
779                                               LegalOperations, Depth+1),
780                          Op.getOperand(1), Flags);
781 
782     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
783     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
784                        Op.getOperand(0),
785                        GetNegatedExpression(Op.getOperand(1), DAG,
786                                             LegalOperations, Depth+1), Flags);
787 
788   case ISD::FP_EXTEND:
789   case ISD::FSIN:
790     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
791                        GetNegatedExpression(Op.getOperand(0), DAG,
792                                             LegalOperations, Depth+1));
793   case ISD::FP_ROUND:
794       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
795                          GetNegatedExpression(Op.getOperand(0), DAG,
796                                               LegalOperations, Depth+1),
797                          Op.getOperand(1));
798   }
799 }
800 
801 // APInts must be the same size for most operations, this helper
802 // function zero extends the shorter of the pair so that they match.
803 // We provide an Offset so that we can create bitwidths that won't overflow.
804 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
805   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
806   LHS = LHS.zextOrSelf(Bits);
807   RHS = RHS.zextOrSelf(Bits);
808 }
809 
810 // Return true if this node is a setcc, or is a select_cc
811 // that selects between the target values used for true and false, making it
812 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
813 // the appropriate nodes based on the type of node we are checking. This
814 // simplifies life a bit for the callers.
815 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
816                                     SDValue &CC) const {
817   if (N.getOpcode() == ISD::SETCC) {
818     LHS = N.getOperand(0);
819     RHS = N.getOperand(1);
820     CC  = N.getOperand(2);
821     return true;
822   }
823 
824   if (N.getOpcode() != ISD::SELECT_CC ||
825       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
826       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
827     return false;
828 
829   if (TLI.getBooleanContents(N.getValueType()) ==
830       TargetLowering::UndefinedBooleanContent)
831     return false;
832 
833   LHS = N.getOperand(0);
834   RHS = N.getOperand(1);
835   CC  = N.getOperand(4);
836   return true;
837 }
838 
839 /// Return true if this is a SetCC-equivalent operation with only one use.
840 /// If this is true, it allows the users to invert the operation for free when
841 /// it is profitable to do so.
842 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
843   SDValue N0, N1, N2;
844   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
845     return true;
846   return false;
847 }
848 
849 // \brief Returns the SDNode if it is a constant float BuildVector
850 // or constant float.
851 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
852   if (isa<ConstantFPSDNode>(N))
853     return N.getNode();
854   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
855     return N.getNode();
856   return nullptr;
857 }
858 
859 // Determines if it is a constant integer or a build vector of constant
860 // integers (and undefs).
861 // Do not permit build vector implicit truncation.
862 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
863   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
864     return !(Const->isOpaque() && NoOpaques);
865   if (N.getOpcode() != ISD::BUILD_VECTOR)
866     return false;
867   unsigned BitWidth = N.getScalarValueSizeInBits();
868   for (const SDValue &Op : N->op_values()) {
869     if (Op.isUndef())
870       continue;
871     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
872     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
873         (Const->isOpaque() && NoOpaques))
874       return false;
875   }
876   return true;
877 }
878 
879 // Determines if it is a constant null integer or a splatted vector of a
880 // constant null integer (with no undefs).
881 // Build vector implicit truncation is not an issue for null values.
882 static bool isNullConstantOrNullSplatConstant(SDValue N) {
883   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
884     return Splat->isNullValue();
885   return false;
886 }
887 
888 // Determines if it is a constant integer of one or a splatted vector of a
889 // constant integer of one (with no undefs).
890 // Do not permit build vector implicit truncation.
891 static bool isOneConstantOrOneSplatConstant(SDValue N) {
892   unsigned BitWidth = N.getScalarValueSizeInBits();
893   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
894     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
895   return false;
896 }
897 
898 // Determines if it is a constant integer of all ones or a splatted vector of a
899 // constant integer of all ones (with no undefs).
900 // Do not permit build vector implicit truncation.
901 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
902   unsigned BitWidth = N.getScalarValueSizeInBits();
903   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
904     return Splat->isAllOnesValue() &&
905            Splat->getAPIntValue().getBitWidth() == BitWidth;
906   return false;
907 }
908 
909 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
910 // undef's.
911 static bool isAnyConstantBuildVector(const SDNode *N) {
912   return ISD::isBuildVectorOfConstantSDNodes(N) ||
913          ISD::isBuildVectorOfConstantFPSDNodes(N);
914 }
915 
916 // Attempt to match a unary predicate against a scalar/splat constant or
917 // every element of a constant BUILD_VECTOR.
918 static bool matchUnaryPredicate(SDValue Op,
919                                 std::function<bool(ConstantSDNode *)> Match) {
920   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
921     return Match(Cst);
922 
923   if (ISD::BUILD_VECTOR != Op.getOpcode())
924     return false;
925 
926   EVT SVT = Op.getValueType().getScalarType();
927   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
928     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
929     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
930       return false;
931   }
932   return true;
933 }
934 
935 // Attempt to match a binary predicate against a pair of scalar/splat constants
936 // or every element of a pair of constant BUILD_VECTORs.
937 static bool matchBinaryPredicate(
938     SDValue LHS, SDValue RHS,
939     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match) {
940   if (LHS.getValueType() != RHS.getValueType())
941     return false;
942 
943   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
944     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
945       return Match(LHSCst, RHSCst);
946 
947   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
948       ISD::BUILD_VECTOR != RHS.getOpcode())
949     return false;
950 
951   EVT SVT = LHS.getValueType().getScalarType();
952   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
953     auto *LHSCst = dyn_cast<ConstantSDNode>(LHS.getOperand(i));
954     auto *RHSCst = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
955     if (!LHSCst || !RHSCst)
956       return false;
957     if (LHSCst->getValueType(0) != SVT ||
958         LHSCst->getValueType(0) != RHSCst->getValueType(0))
959       return false;
960     if (!Match(LHSCst, RHSCst))
961       return false;
962   }
963   return true;
964 }
965 
966 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
967                                     SDValue N1) {
968   EVT VT = N0.getValueType();
969   if (N0.getOpcode() == Opc) {
970     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
971       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
972         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
973         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
974           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
975         return SDValue();
976       }
977       if (N0.hasOneUse()) {
978         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
979         // use
980         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
981         if (!OpNode.getNode())
982           return SDValue();
983         AddToWorklist(OpNode.getNode());
984         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
985       }
986     }
987   }
988 
989   if (N1.getOpcode() == Opc) {
990     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
991       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
992         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
993         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
994           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
995         return SDValue();
996       }
997       if (N1.hasOneUse()) {
998         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
999         // use
1000         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
1001         if (!OpNode.getNode())
1002           return SDValue();
1003         AddToWorklist(OpNode.getNode());
1004         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
1005       }
1006     }
1007   }
1008 
1009   return SDValue();
1010 }
1011 
1012 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1013                                bool AddTo) {
1014   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1015   ++NodesCombined;
1016   DEBUG(dbgs() << "\nReplacing.1 ";
1017         N->dump(&DAG);
1018         dbgs() << "\nWith: ";
1019         To[0].getNode()->dump(&DAG);
1020         dbgs() << " and " << NumTo-1 << " other values\n");
1021   for (unsigned i = 0, e = NumTo; i != e; ++i)
1022     assert((!To[i].getNode() ||
1023             N->getValueType(i) == To[i].getValueType()) &&
1024            "Cannot combine value to value of different type!");
1025 
1026   WorklistRemover DeadNodes(*this);
1027   DAG.ReplaceAllUsesWith(N, To);
1028   if (AddTo) {
1029     // Push the new nodes and any users onto the worklist
1030     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1031       if (To[i].getNode()) {
1032         AddToWorklist(To[i].getNode());
1033         AddUsersToWorklist(To[i].getNode());
1034       }
1035     }
1036   }
1037 
1038   // Finally, if the node is now dead, remove it from the graph.  The node
1039   // may not be dead if the replacement process recursively simplified to
1040   // something else needing this node.
1041   if (N->use_empty())
1042     deleteAndRecombine(N);
1043   return SDValue(N, 0);
1044 }
1045 
1046 void DAGCombiner::
1047 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1048   // Replace all uses.  If any nodes become isomorphic to other nodes and
1049   // are deleted, make sure to remove them from our worklist.
1050   WorklistRemover DeadNodes(*this);
1051   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1052 
1053   // Push the new node and any (possibly new) users onto the worklist.
1054   AddToWorklist(TLO.New.getNode());
1055   AddUsersToWorklist(TLO.New.getNode());
1056 
1057   // Finally, if the node is now dead, remove it from the graph.  The node
1058   // may not be dead if the replacement process recursively simplified to
1059   // something else needing this node.
1060   if (TLO.Old.getNode()->use_empty())
1061     deleteAndRecombine(TLO.Old.getNode());
1062 }
1063 
1064 /// Check the specified integer node value to see if it can be simplified or if
1065 /// things it uses can be simplified by bit propagation. If so, return true.
1066 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1067   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1068   KnownBits Known;
1069   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1070     return false;
1071 
1072   // Revisit the node.
1073   AddToWorklist(Op.getNode());
1074 
1075   // Replace the old value with the new one.
1076   ++NodesCombined;
1077   DEBUG(dbgs() << "\nReplacing.2 ";
1078         TLO.Old.getNode()->dump(&DAG);
1079         dbgs() << "\nWith: ";
1080         TLO.New.getNode()->dump(&DAG);
1081         dbgs() << '\n');
1082 
1083   CommitTargetLoweringOpt(TLO);
1084   return true;
1085 }
1086 
1087 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1088   SDLoc DL(Load);
1089   EVT VT = Load->getValueType(0);
1090   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1091 
1092   DEBUG(dbgs() << "\nReplacing.9 ";
1093         Load->dump(&DAG);
1094         dbgs() << "\nWith: ";
1095         Trunc.getNode()->dump(&DAG);
1096         dbgs() << '\n');
1097   WorklistRemover DeadNodes(*this);
1098   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1099   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1100   deleteAndRecombine(Load);
1101   AddToWorklist(Trunc.getNode());
1102 }
1103 
1104 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1105   Replace = false;
1106   SDLoc DL(Op);
1107   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1108     LoadSDNode *LD = cast<LoadSDNode>(Op);
1109     EVT MemVT = LD->getMemoryVT();
1110     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1111       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1112                                                        : ISD::EXTLOAD)
1113       : LD->getExtensionType();
1114     Replace = true;
1115     return DAG.getExtLoad(ExtType, DL, PVT,
1116                           LD->getChain(), LD->getBasePtr(),
1117                           MemVT, LD->getMemOperand());
1118   }
1119 
1120   unsigned Opc = Op.getOpcode();
1121   switch (Opc) {
1122   default: break;
1123   case ISD::AssertSext:
1124     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1125       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1126     break;
1127   case ISD::AssertZext:
1128     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1129       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1130     break;
1131   case ISD::Constant: {
1132     unsigned ExtOpc =
1133       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1134     return DAG.getNode(ExtOpc, DL, PVT, Op);
1135   }
1136   }
1137 
1138   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1139     return SDValue();
1140   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1141 }
1142 
1143 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1144   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1145     return SDValue();
1146   EVT OldVT = Op.getValueType();
1147   SDLoc DL(Op);
1148   bool Replace = false;
1149   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1150   if (!NewOp.getNode())
1151     return SDValue();
1152   AddToWorklist(NewOp.getNode());
1153 
1154   if (Replace)
1155     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1156   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1157                      DAG.getValueType(OldVT));
1158 }
1159 
1160 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1161   EVT OldVT = Op.getValueType();
1162   SDLoc DL(Op);
1163   bool Replace = false;
1164   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1165   if (!NewOp.getNode())
1166     return SDValue();
1167   AddToWorklist(NewOp.getNode());
1168 
1169   if (Replace)
1170     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1171   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1172 }
1173 
1174 /// Promote the specified integer binary operation if the target indicates it is
1175 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1176 /// i32 since i16 instructions are longer.
1177 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1178   if (!LegalOperations)
1179     return SDValue();
1180 
1181   EVT VT = Op.getValueType();
1182   if (VT.isVector() || !VT.isInteger())
1183     return SDValue();
1184 
1185   // If operation type is 'undesirable', e.g. i16 on x86, consider
1186   // promoting it.
1187   unsigned Opc = Op.getOpcode();
1188   if (TLI.isTypeDesirableForOp(Opc, VT))
1189     return SDValue();
1190 
1191   EVT PVT = VT;
1192   // Consult target whether it is a good idea to promote this operation and
1193   // what's the right type to promote it to.
1194   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1195     assert(PVT != VT && "Don't know what type to promote to!");
1196 
1197     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1198 
1199     bool Replace0 = false;
1200     SDValue N0 = Op.getOperand(0);
1201     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1202 
1203     bool Replace1 = false;
1204     SDValue N1 = Op.getOperand(1);
1205     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1206     SDLoc DL(Op);
1207 
1208     SDValue RV =
1209         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1210 
1211     // We are always replacing N0/N1's use in N and only need
1212     // additional replacements if there are additional uses.
1213     Replace0 &= !N0->hasOneUse();
1214     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1215 
1216     // Combine Op here so it is preserved past replacements.
1217     CombineTo(Op.getNode(), RV);
1218 
1219     // If operands have a use ordering, make sure we deal with
1220     // predecessor first.
1221     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1222       std::swap(N0, N1);
1223       std::swap(NN0, NN1);
1224     }
1225 
1226     if (Replace0) {
1227       AddToWorklist(NN0.getNode());
1228       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1229     }
1230     if (Replace1) {
1231       AddToWorklist(NN1.getNode());
1232       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1233     }
1234     return Op;
1235   }
1236   return SDValue();
1237 }
1238 
1239 /// Promote the specified integer shift operation if the target indicates it is
1240 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1241 /// i32 since i16 instructions are longer.
1242 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1243   if (!LegalOperations)
1244     return SDValue();
1245 
1246   EVT VT = Op.getValueType();
1247   if (VT.isVector() || !VT.isInteger())
1248     return SDValue();
1249 
1250   // If operation type is 'undesirable', e.g. i16 on x86, consider
1251   // promoting it.
1252   unsigned Opc = Op.getOpcode();
1253   if (TLI.isTypeDesirableForOp(Opc, VT))
1254     return SDValue();
1255 
1256   EVT PVT = VT;
1257   // Consult target whether it is a good idea to promote this operation and
1258   // what's the right type to promote it to.
1259   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1260     assert(PVT != VT && "Don't know what type to promote to!");
1261 
1262     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1263 
1264     bool Replace = false;
1265     SDValue N0 = Op.getOperand(0);
1266     SDValue N1 = Op.getOperand(1);
1267     if (Opc == ISD::SRA)
1268       N0 = SExtPromoteOperand(N0, PVT);
1269     else if (Opc == ISD::SRL)
1270       N0 = ZExtPromoteOperand(N0, PVT);
1271     else
1272       N0 = PromoteOperand(N0, PVT, Replace);
1273 
1274     if (!N0.getNode())
1275       return SDValue();
1276 
1277     SDLoc DL(Op);
1278     SDValue RV =
1279         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1280 
1281     AddToWorklist(N0.getNode());
1282     if (Replace)
1283       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1284 
1285     // Deal with Op being deleted.
1286     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1287       return RV;
1288   }
1289   return SDValue();
1290 }
1291 
1292 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1293   if (!LegalOperations)
1294     return SDValue();
1295 
1296   EVT VT = Op.getValueType();
1297   if (VT.isVector() || !VT.isInteger())
1298     return SDValue();
1299 
1300   // If operation type is 'undesirable', e.g. i16 on x86, consider
1301   // promoting it.
1302   unsigned Opc = Op.getOpcode();
1303   if (TLI.isTypeDesirableForOp(Opc, VT))
1304     return SDValue();
1305 
1306   EVT PVT = VT;
1307   // Consult target whether it is a good idea to promote this operation and
1308   // what's the right type to promote it to.
1309   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1310     assert(PVT != VT && "Don't know what type to promote to!");
1311     // fold (aext (aext x)) -> (aext x)
1312     // fold (aext (zext x)) -> (zext x)
1313     // fold (aext (sext x)) -> (sext x)
1314     DEBUG(dbgs() << "\nPromoting ";
1315           Op.getNode()->dump(&DAG));
1316     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1317   }
1318   return SDValue();
1319 }
1320 
1321 bool DAGCombiner::PromoteLoad(SDValue Op) {
1322   if (!LegalOperations)
1323     return false;
1324 
1325   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1326     return false;
1327 
1328   EVT VT = Op.getValueType();
1329   if (VT.isVector() || !VT.isInteger())
1330     return false;
1331 
1332   // If operation type is 'undesirable', e.g. i16 on x86, consider
1333   // promoting it.
1334   unsigned Opc = Op.getOpcode();
1335   if (TLI.isTypeDesirableForOp(Opc, VT))
1336     return false;
1337 
1338   EVT PVT = VT;
1339   // Consult target whether it is a good idea to promote this operation and
1340   // what's the right type to promote it to.
1341   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1342     assert(PVT != VT && "Don't know what type to promote to!");
1343 
1344     SDLoc DL(Op);
1345     SDNode *N = Op.getNode();
1346     LoadSDNode *LD = cast<LoadSDNode>(N);
1347     EVT MemVT = LD->getMemoryVT();
1348     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1349       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1350                                                        : ISD::EXTLOAD)
1351       : LD->getExtensionType();
1352     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1353                                    LD->getChain(), LD->getBasePtr(),
1354                                    MemVT, LD->getMemOperand());
1355     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1356 
1357     DEBUG(dbgs() << "\nPromoting ";
1358           N->dump(&DAG);
1359           dbgs() << "\nTo: ";
1360           Result.getNode()->dump(&DAG);
1361           dbgs() << '\n');
1362     WorklistRemover DeadNodes(*this);
1363     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1364     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1365     deleteAndRecombine(N);
1366     AddToWorklist(Result.getNode());
1367     return true;
1368   }
1369   return false;
1370 }
1371 
1372 /// \brief Recursively delete a node which has no uses and any operands for
1373 /// which it is the only use.
1374 ///
1375 /// Note that this both deletes the nodes and removes them from the worklist.
1376 /// It also adds any nodes who have had a user deleted to the worklist as they
1377 /// may now have only one use and subject to other combines.
1378 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1379   if (!N->use_empty())
1380     return false;
1381 
1382   SmallSetVector<SDNode *, 16> Nodes;
1383   Nodes.insert(N);
1384   do {
1385     N = Nodes.pop_back_val();
1386     if (!N)
1387       continue;
1388 
1389     if (N->use_empty()) {
1390       for (const SDValue &ChildN : N->op_values())
1391         Nodes.insert(ChildN.getNode());
1392 
1393       removeFromWorklist(N);
1394       DAG.DeleteNode(N);
1395     } else {
1396       AddToWorklist(N);
1397     }
1398   } while (!Nodes.empty());
1399   return true;
1400 }
1401 
1402 //===----------------------------------------------------------------------===//
1403 //  Main DAG Combiner implementation
1404 //===----------------------------------------------------------------------===//
1405 
1406 void DAGCombiner::Run(CombineLevel AtLevel) {
1407   // set the instance variables, so that the various visit routines may use it.
1408   Level = AtLevel;
1409   LegalOperations = Level >= AfterLegalizeVectorOps;
1410   LegalTypes = Level >= AfterLegalizeTypes;
1411 
1412   // Add all the dag nodes to the worklist.
1413   for (SDNode &Node : DAG.allnodes())
1414     AddToWorklist(&Node);
1415 
1416   // Create a dummy node (which is not added to allnodes), that adds a reference
1417   // to the root node, preventing it from being deleted, and tracking any
1418   // changes of the root.
1419   HandleSDNode Dummy(DAG.getRoot());
1420 
1421   // While the worklist isn't empty, find a node and try to combine it.
1422   while (!WorklistMap.empty()) {
1423     SDNode *N;
1424     // The Worklist holds the SDNodes in order, but it may contain null entries.
1425     do {
1426       N = Worklist.pop_back_val();
1427     } while (!N);
1428 
1429     bool GoodWorklistEntry = WorklistMap.erase(N);
1430     (void)GoodWorklistEntry;
1431     assert(GoodWorklistEntry &&
1432            "Found a worklist entry without a corresponding map entry!");
1433 
1434     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1435     // N is deleted from the DAG, since they too may now be dead or may have a
1436     // reduced number of uses, allowing other xforms.
1437     if (recursivelyDeleteUnusedNodes(N))
1438       continue;
1439 
1440     WorklistRemover DeadNodes(*this);
1441 
1442     // If this combine is running after legalizing the DAG, re-legalize any
1443     // nodes pulled off the worklist.
1444     if (Level == AfterLegalizeDAG) {
1445       SmallSetVector<SDNode *, 16> UpdatedNodes;
1446       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1447 
1448       for (SDNode *LN : UpdatedNodes) {
1449         AddToWorklist(LN);
1450         AddUsersToWorklist(LN);
1451       }
1452       if (!NIsValid)
1453         continue;
1454     }
1455 
1456     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1457 
1458     // Add any operands of the new node which have not yet been combined to the
1459     // worklist as well. Because the worklist uniques things already, this
1460     // won't repeatedly process the same operand.
1461     CombinedNodes.insert(N);
1462     for (const SDValue &ChildN : N->op_values())
1463       if (!CombinedNodes.count(ChildN.getNode()))
1464         AddToWorklist(ChildN.getNode());
1465 
1466     SDValue RV = combine(N);
1467 
1468     if (!RV.getNode())
1469       continue;
1470 
1471     ++NodesCombined;
1472 
1473     // If we get back the same node we passed in, rather than a new node or
1474     // zero, we know that the node must have defined multiple values and
1475     // CombineTo was used.  Since CombineTo takes care of the worklist
1476     // mechanics for us, we have no work to do in this case.
1477     if (RV.getNode() == N)
1478       continue;
1479 
1480     assert(N->getOpcode() != ISD::DELETED_NODE &&
1481            RV.getOpcode() != ISD::DELETED_NODE &&
1482            "Node was deleted but visit returned new node!");
1483 
1484     DEBUG(dbgs() << " ... into: ";
1485           RV.getNode()->dump(&DAG));
1486 
1487     if (N->getNumValues() == RV.getNode()->getNumValues())
1488       DAG.ReplaceAllUsesWith(N, RV.getNode());
1489     else {
1490       assert(N->getValueType(0) == RV.getValueType() &&
1491              N->getNumValues() == 1 && "Type mismatch");
1492       DAG.ReplaceAllUsesWith(N, &RV);
1493     }
1494 
1495     // Push the new node and any users onto the worklist
1496     AddToWorklist(RV.getNode());
1497     AddUsersToWorklist(RV.getNode());
1498 
1499     // Finally, if the node is now dead, remove it from the graph.  The node
1500     // may not be dead if the replacement process recursively simplified to
1501     // something else needing this node. This will also take care of adding any
1502     // operands which have lost a user to the worklist.
1503     recursivelyDeleteUnusedNodes(N);
1504   }
1505 
1506   // If the root changed (e.g. it was a dead load, update the root).
1507   DAG.setRoot(Dummy.getValue());
1508   DAG.RemoveDeadNodes();
1509 }
1510 
1511 SDValue DAGCombiner::visit(SDNode *N) {
1512   switch (N->getOpcode()) {
1513   default: break;
1514   case ISD::TokenFactor:        return visitTokenFactor(N);
1515   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1516   case ISD::ADD:                return visitADD(N);
1517   case ISD::SUB:                return visitSUB(N);
1518   case ISD::ADDC:               return visitADDC(N);
1519   case ISD::UADDO:              return visitUADDO(N);
1520   case ISD::SUBC:               return visitSUBC(N);
1521   case ISD::USUBO:              return visitUSUBO(N);
1522   case ISD::ADDE:               return visitADDE(N);
1523   case ISD::ADDCARRY:           return visitADDCARRY(N);
1524   case ISD::SUBE:               return visitSUBE(N);
1525   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1526   case ISD::MUL:                return visitMUL(N);
1527   case ISD::SDIV:               return visitSDIV(N);
1528   case ISD::UDIV:               return visitUDIV(N);
1529   case ISD::SREM:
1530   case ISD::UREM:               return visitREM(N);
1531   case ISD::MULHU:              return visitMULHU(N);
1532   case ISD::MULHS:              return visitMULHS(N);
1533   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1534   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1535   case ISD::SMULO:              return visitSMULO(N);
1536   case ISD::UMULO:              return visitUMULO(N);
1537   case ISD::SMIN:
1538   case ISD::SMAX:
1539   case ISD::UMIN:
1540   case ISD::UMAX:               return visitIMINMAX(N);
1541   case ISD::AND:                return visitAND(N);
1542   case ISD::OR:                 return visitOR(N);
1543   case ISD::XOR:                return visitXOR(N);
1544   case ISD::SHL:                return visitSHL(N);
1545   case ISD::SRA:                return visitSRA(N);
1546   case ISD::SRL:                return visitSRL(N);
1547   case ISD::ROTR:
1548   case ISD::ROTL:               return visitRotate(N);
1549   case ISD::ABS:                return visitABS(N);
1550   case ISD::BSWAP:              return visitBSWAP(N);
1551   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1552   case ISD::CTLZ:               return visitCTLZ(N);
1553   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1554   case ISD::CTTZ:               return visitCTTZ(N);
1555   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1556   case ISD::CTPOP:              return visitCTPOP(N);
1557   case ISD::SELECT:             return visitSELECT(N);
1558   case ISD::VSELECT:            return visitVSELECT(N);
1559   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1560   case ISD::SETCC:              return visitSETCC(N);
1561   case ISD::SETCCE:             return visitSETCCE(N);
1562   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1563   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1564   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1565   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1566   case ISD::AssertSext:
1567   case ISD::AssertZext:         return visitAssertExt(N);
1568   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1569   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1570   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1571   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1572   case ISD::BITCAST:            return visitBITCAST(N);
1573   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1574   case ISD::FADD:               return visitFADD(N);
1575   case ISD::FSUB:               return visitFSUB(N);
1576   case ISD::FMUL:               return visitFMUL(N);
1577   case ISD::FMA:                return visitFMA(N);
1578   case ISD::FDIV:               return visitFDIV(N);
1579   case ISD::FREM:               return visitFREM(N);
1580   case ISD::FSQRT:              return visitFSQRT(N);
1581   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1582   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1583   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1584   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1585   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1586   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1587   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1588   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1589   case ISD::FNEG:               return visitFNEG(N);
1590   case ISD::FABS:               return visitFABS(N);
1591   case ISD::FFLOOR:             return visitFFLOOR(N);
1592   case ISD::FMINNUM:            return visitFMINNUM(N);
1593   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1594   case ISD::FCEIL:              return visitFCEIL(N);
1595   case ISD::FTRUNC:             return visitFTRUNC(N);
1596   case ISD::BRCOND:             return visitBRCOND(N);
1597   case ISD::BR_CC:              return visitBR_CC(N);
1598   case ISD::LOAD:               return visitLOAD(N);
1599   case ISD::STORE:              return visitSTORE(N);
1600   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1601   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1602   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1603   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1604   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1605   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1606   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1607   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1608   case ISD::MGATHER:            return visitMGATHER(N);
1609   case ISD::MLOAD:              return visitMLOAD(N);
1610   case ISD::MSCATTER:           return visitMSCATTER(N);
1611   case ISD::MSTORE:             return visitMSTORE(N);
1612   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1613   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1614   }
1615   return SDValue();
1616 }
1617 
1618 SDValue DAGCombiner::combine(SDNode *N) {
1619   SDValue RV = visit(N);
1620 
1621   // If nothing happened, try a target-specific DAG combine.
1622   if (!RV.getNode()) {
1623     assert(N->getOpcode() != ISD::DELETED_NODE &&
1624            "Node was deleted but visit returned NULL!");
1625 
1626     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1627         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1628 
1629       // Expose the DAG combiner to the target combiner impls.
1630       TargetLowering::DAGCombinerInfo
1631         DagCombineInfo(DAG, Level, false, this);
1632 
1633       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1634     }
1635   }
1636 
1637   // If nothing happened still, try promoting the operation.
1638   if (!RV.getNode()) {
1639     switch (N->getOpcode()) {
1640     default: break;
1641     case ISD::ADD:
1642     case ISD::SUB:
1643     case ISD::MUL:
1644     case ISD::AND:
1645     case ISD::OR:
1646     case ISD::XOR:
1647       RV = PromoteIntBinOp(SDValue(N, 0));
1648       break;
1649     case ISD::SHL:
1650     case ISD::SRA:
1651     case ISD::SRL:
1652       RV = PromoteIntShiftOp(SDValue(N, 0));
1653       break;
1654     case ISD::SIGN_EXTEND:
1655     case ISD::ZERO_EXTEND:
1656     case ISD::ANY_EXTEND:
1657       RV = PromoteExtend(SDValue(N, 0));
1658       break;
1659     case ISD::LOAD:
1660       if (PromoteLoad(SDValue(N, 0)))
1661         RV = SDValue(N, 0);
1662       break;
1663     }
1664   }
1665 
1666   // If N is a commutative binary node, try eliminate it if the commuted
1667   // version is already present in the DAG.
1668   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1669       N->getNumValues() == 1) {
1670     SDValue N0 = N->getOperand(0);
1671     SDValue N1 = N->getOperand(1);
1672 
1673     // Constant operands are canonicalized to RHS.
1674     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1675       SDValue Ops[] = {N1, N0};
1676       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1677                                             N->getFlags());
1678       if (CSENode)
1679         return SDValue(CSENode, 0);
1680     }
1681   }
1682 
1683   return RV;
1684 }
1685 
1686 /// Given a node, return its input chain if it has one, otherwise return a null
1687 /// sd operand.
1688 static SDValue getInputChainForNode(SDNode *N) {
1689   if (unsigned NumOps = N->getNumOperands()) {
1690     if (N->getOperand(0).getValueType() == MVT::Other)
1691       return N->getOperand(0);
1692     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1693       return N->getOperand(NumOps-1);
1694     for (unsigned i = 1; i < NumOps-1; ++i)
1695       if (N->getOperand(i).getValueType() == MVT::Other)
1696         return N->getOperand(i);
1697   }
1698   return SDValue();
1699 }
1700 
1701 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1702   // If N has two operands, where one has an input chain equal to the other,
1703   // the 'other' chain is redundant.
1704   if (N->getNumOperands() == 2) {
1705     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1706       return N->getOperand(0);
1707     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1708       return N->getOperand(1);
1709   }
1710 
1711   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1712   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1713   SmallPtrSet<SDNode*, 16> SeenOps;
1714   bool Changed = false;             // If we should replace this token factor.
1715 
1716   // Start out with this token factor.
1717   TFs.push_back(N);
1718 
1719   // Iterate through token factors.  The TFs grows when new token factors are
1720   // encountered.
1721   for (unsigned i = 0; i < TFs.size(); ++i) {
1722     SDNode *TF = TFs[i];
1723 
1724     // Check each of the operands.
1725     for (const SDValue &Op : TF->op_values()) {
1726       switch (Op.getOpcode()) {
1727       case ISD::EntryToken:
1728         // Entry tokens don't need to be added to the list. They are
1729         // redundant.
1730         Changed = true;
1731         break;
1732 
1733       case ISD::TokenFactor:
1734         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1735           // Queue up for processing.
1736           TFs.push_back(Op.getNode());
1737           // Clean up in case the token factor is removed.
1738           AddToWorklist(Op.getNode());
1739           Changed = true;
1740           break;
1741         }
1742         LLVM_FALLTHROUGH;
1743 
1744       default:
1745         // Only add if it isn't already in the list.
1746         if (SeenOps.insert(Op.getNode()).second)
1747           Ops.push_back(Op);
1748         else
1749           Changed = true;
1750         break;
1751       }
1752     }
1753   }
1754 
1755   // Remove Nodes that are chained to another node in the list. Do so
1756   // by walking up chains breath-first stopping when we've seen
1757   // another operand. In general we must climb to the EntryNode, but we can exit
1758   // early if we find all remaining work is associated with just one operand as
1759   // no further pruning is possible.
1760 
1761   // List of nodes to search through and original Ops from which they originate.
1762   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1763   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1764   SmallPtrSet<SDNode *, 16> SeenChains;
1765   bool DidPruneOps = false;
1766 
1767   unsigned NumLeftToConsider = 0;
1768   for (const SDValue &Op : Ops) {
1769     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1770     OpWorkCount.push_back(1);
1771   }
1772 
1773   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1774     // If this is an Op, we can remove the op from the list. Remark any
1775     // search associated with it as from the current OpNumber.
1776     if (SeenOps.count(Op) != 0) {
1777       Changed = true;
1778       DidPruneOps = true;
1779       unsigned OrigOpNumber = 0;
1780       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1781         OrigOpNumber++;
1782       assert((OrigOpNumber != Ops.size()) &&
1783              "expected to find TokenFactor Operand");
1784       // Re-mark worklist from OrigOpNumber to OpNumber
1785       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1786         if (Worklist[i].second == OrigOpNumber) {
1787           Worklist[i].second = OpNumber;
1788         }
1789       }
1790       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1791       OpWorkCount[OrigOpNumber] = 0;
1792       NumLeftToConsider--;
1793     }
1794     // Add if it's a new chain
1795     if (SeenChains.insert(Op).second) {
1796       OpWorkCount[OpNumber]++;
1797       Worklist.push_back(std::make_pair(Op, OpNumber));
1798     }
1799   };
1800 
1801   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1802     // We need at least be consider at least 2 Ops to prune.
1803     if (NumLeftToConsider <= 1)
1804       break;
1805     auto CurNode = Worklist[i].first;
1806     auto CurOpNumber = Worklist[i].second;
1807     assert((OpWorkCount[CurOpNumber] > 0) &&
1808            "Node should not appear in worklist");
1809     switch (CurNode->getOpcode()) {
1810     case ISD::EntryToken:
1811       // Hitting EntryToken is the only way for the search to terminate without
1812       // hitting
1813       // another operand's search. Prevent us from marking this operand
1814       // considered.
1815       NumLeftToConsider++;
1816       break;
1817     case ISD::TokenFactor:
1818       for (const SDValue &Op : CurNode->op_values())
1819         AddToWorklist(i, Op.getNode(), CurOpNumber);
1820       break;
1821     case ISD::CopyFromReg:
1822     case ISD::CopyToReg:
1823       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1824       break;
1825     default:
1826       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1827         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1828       break;
1829     }
1830     OpWorkCount[CurOpNumber]--;
1831     if (OpWorkCount[CurOpNumber] == 0)
1832       NumLeftToConsider--;
1833   }
1834 
1835   // If we've changed things around then replace token factor.
1836   if (Changed) {
1837     SDValue Result;
1838     if (Ops.empty()) {
1839       // The entry token is the only possible outcome.
1840       Result = DAG.getEntryNode();
1841     } else {
1842       if (DidPruneOps) {
1843         SmallVector<SDValue, 8> PrunedOps;
1844         //
1845         for (const SDValue &Op : Ops) {
1846           if (SeenChains.count(Op.getNode()) == 0)
1847             PrunedOps.push_back(Op);
1848         }
1849         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1850       } else {
1851         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1852       }
1853     }
1854     return Result;
1855   }
1856   return SDValue();
1857 }
1858 
1859 /// MERGE_VALUES can always be eliminated.
1860 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1861   WorklistRemover DeadNodes(*this);
1862   // Replacing results may cause a different MERGE_VALUES to suddenly
1863   // be CSE'd with N, and carry its uses with it. Iterate until no
1864   // uses remain, to ensure that the node can be safely deleted.
1865   // First add the users of this node to the work list so that they
1866   // can be tried again once they have new operands.
1867   AddUsersToWorklist(N);
1868   do {
1869     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1870       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1871   } while (!N->use_empty());
1872   deleteAndRecombine(N);
1873   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1874 }
1875 
1876 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1877 /// ConstantSDNode pointer else nullptr.
1878 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1879   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1880   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1881 }
1882 
1883 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1884   auto BinOpcode = BO->getOpcode();
1885   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1886           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1887           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1888           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1889           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1890           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1891           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1892           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1893           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1894          "Unexpected binary operator");
1895 
1896   // Bail out if any constants are opaque because we can't constant fold those.
1897   SDValue C1 = BO->getOperand(1);
1898   if (!isConstantOrConstantVector(C1, true) &&
1899       !isConstantFPBuildVectorOrConstantFP(C1))
1900     return SDValue();
1901 
1902   // Don't do this unless the old select is going away. We want to eliminate the
1903   // binary operator, not replace a binop with a select.
1904   // TODO: Handle ISD::SELECT_CC.
1905   SDValue Sel = BO->getOperand(0);
1906   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1907     return SDValue();
1908 
1909   SDValue CT = Sel.getOperand(1);
1910   if (!isConstantOrConstantVector(CT, true) &&
1911       !isConstantFPBuildVectorOrConstantFP(CT))
1912     return SDValue();
1913 
1914   SDValue CF = Sel.getOperand(2);
1915   if (!isConstantOrConstantVector(CF, true) &&
1916       !isConstantFPBuildVectorOrConstantFP(CF))
1917     return SDValue();
1918 
1919   // We have a select-of-constants followed by a binary operator with a
1920   // constant. Eliminate the binop by pulling the constant math into the select.
1921   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1922   EVT VT = Sel.getValueType();
1923   SDLoc DL(Sel);
1924   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1925   if (!NewCT.isUndef() &&
1926       !isConstantOrConstantVector(NewCT, true) &&
1927       !isConstantFPBuildVectorOrConstantFP(NewCT))
1928     return SDValue();
1929 
1930   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1931   if (!NewCF.isUndef() &&
1932       !isConstantOrConstantVector(NewCF, true) &&
1933       !isConstantFPBuildVectorOrConstantFP(NewCF))
1934     return SDValue();
1935 
1936   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1937 }
1938 
1939 SDValue DAGCombiner::visitADD(SDNode *N) {
1940   SDValue N0 = N->getOperand(0);
1941   SDValue N1 = N->getOperand(1);
1942   EVT VT = N0.getValueType();
1943   SDLoc DL(N);
1944 
1945   // fold vector ops
1946   if (VT.isVector()) {
1947     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1948       return FoldedVOp;
1949 
1950     // fold (add x, 0) -> x, vector edition
1951     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1952       return N0;
1953     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1954       return N1;
1955   }
1956 
1957   // fold (add x, undef) -> undef
1958   if (N0.isUndef())
1959     return N0;
1960 
1961   if (N1.isUndef())
1962     return N1;
1963 
1964   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1965     // canonicalize constant to RHS
1966     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1967       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1968     // fold (add c1, c2) -> c1+c2
1969     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1970                                       N1.getNode());
1971   }
1972 
1973   // fold (add x, 0) -> x
1974   if (isNullConstant(N1))
1975     return N0;
1976 
1977   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1978     // fold ((c1-A)+c2) -> (c1+c2)-A
1979     if (N0.getOpcode() == ISD::SUB &&
1980         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1981       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1982       return DAG.getNode(ISD::SUB, DL, VT,
1983                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1984                          N0.getOperand(1));
1985     }
1986 
1987     // add (sext i1 X), 1 -> zext (not i1 X)
1988     // We don't transform this pattern:
1989     //   add (zext i1 X), -1 -> sext (not i1 X)
1990     // because most (?) targets generate better code for the zext form.
1991     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1992         isOneConstantOrOneSplatConstant(N1)) {
1993       SDValue X = N0.getOperand(0);
1994       if ((!LegalOperations ||
1995            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1996             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1997           X.getScalarValueSizeInBits() == 1) {
1998         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1999         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2000       }
2001     }
2002 
2003     // Undo the add -> or combine to merge constant offsets from a frame index.
2004     if (N0.getOpcode() == ISD::OR &&
2005         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2006         isa<ConstantSDNode>(N0.getOperand(1)) &&
2007         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2008       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2009       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2010     }
2011   }
2012 
2013   if (SDValue NewSel = foldBinOpIntoSelect(N))
2014     return NewSel;
2015 
2016   // reassociate add
2017   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
2018     return RADD;
2019 
2020   // fold ((0-A) + B) -> B-A
2021   if (N0.getOpcode() == ISD::SUB &&
2022       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2023     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2024 
2025   // fold (A + (0-B)) -> A-B
2026   if (N1.getOpcode() == ISD::SUB &&
2027       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2028     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2029 
2030   // fold (A+(B-A)) -> B
2031   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2032     return N1.getOperand(0);
2033 
2034   // fold ((B-A)+A) -> B
2035   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2036     return N0.getOperand(0);
2037 
2038   // fold (A+(B-(A+C))) to (B-C)
2039   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2040       N0 == N1.getOperand(1).getOperand(0))
2041     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2042                        N1.getOperand(1).getOperand(1));
2043 
2044   // fold (A+(B-(C+A))) to (B-C)
2045   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2046       N0 == N1.getOperand(1).getOperand(1))
2047     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2048                        N1.getOperand(1).getOperand(0));
2049 
2050   // fold (A+((B-A)+or-C)) to (B+or-C)
2051   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2052       N1.getOperand(0).getOpcode() == ISD::SUB &&
2053       N0 == N1.getOperand(0).getOperand(1))
2054     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2055                        N1.getOperand(1));
2056 
2057   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2058   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2059     SDValue N00 = N0.getOperand(0);
2060     SDValue N01 = N0.getOperand(1);
2061     SDValue N10 = N1.getOperand(0);
2062     SDValue N11 = N1.getOperand(1);
2063 
2064     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2065       return DAG.getNode(ISD::SUB, DL, VT,
2066                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2067                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2068   }
2069 
2070   if (SimplifyDemandedBits(SDValue(N, 0)))
2071     return SDValue(N, 0);
2072 
2073   // fold (a+b) -> (a|b) iff a and b share no bits.
2074   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2075       DAG.haveNoCommonBitsSet(N0, N1))
2076     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2077 
2078   if (SDValue Combined = visitADDLike(N0, N1, N))
2079     return Combined;
2080 
2081   if (SDValue Combined = visitADDLike(N1, N0, N))
2082     return Combined;
2083 
2084   return SDValue();
2085 }
2086 
2087 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2088   bool Masked = false;
2089 
2090   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2091   while (true) {
2092     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2093       V = V.getOperand(0);
2094       continue;
2095     }
2096 
2097     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2098       Masked = true;
2099       V = V.getOperand(0);
2100       continue;
2101     }
2102 
2103     break;
2104   }
2105 
2106   // If this is not a carry, return.
2107   if (V.getResNo() != 1)
2108     return SDValue();
2109 
2110   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2111       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2112     return SDValue();
2113 
2114   // If the result is masked, then no matter what kind of bool it is we can
2115   // return. If it isn't, then we need to make sure the bool type is either 0 or
2116   // 1 and not other values.
2117   if (Masked ||
2118       TLI.getBooleanContents(V.getValueType()) ==
2119           TargetLoweringBase::ZeroOrOneBooleanContent)
2120     return V;
2121 
2122   return SDValue();
2123 }
2124 
2125 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2126   EVT VT = N0.getValueType();
2127   SDLoc DL(LocReference);
2128 
2129   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2130   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2131       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2132     return DAG.getNode(ISD::SUB, DL, VT, N0,
2133                        DAG.getNode(ISD::SHL, DL, VT,
2134                                    N1.getOperand(0).getOperand(1),
2135                                    N1.getOperand(1)));
2136 
2137   if (N1.getOpcode() == ISD::AND) {
2138     SDValue AndOp0 = N1.getOperand(0);
2139     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2140     unsigned DestBits = VT.getScalarSizeInBits();
2141 
2142     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2143     // and similar xforms where the inner op is either ~0 or 0.
2144     if (NumSignBits == DestBits &&
2145         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2146       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2147   }
2148 
2149   // add (sext i1), X -> sub X, (zext i1)
2150   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2151       N0.getOperand(0).getValueType() == MVT::i1 &&
2152       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2153     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2154     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2155   }
2156 
2157   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2158   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2159     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2160     if (TN->getVT() == MVT::i1) {
2161       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2162                                  DAG.getConstant(1, DL, VT));
2163       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2164     }
2165   }
2166 
2167   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2168   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2169       N1.getResNo() == 0)
2170     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2171                        N0, N1.getOperand(0), N1.getOperand(2));
2172 
2173   // (add X, Carry) -> (addcarry X, 0, Carry)
2174   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2175     if (SDValue Carry = getAsCarry(TLI, N1))
2176       return DAG.getNode(ISD::ADDCARRY, DL,
2177                          DAG.getVTList(VT, Carry.getValueType()), N0,
2178                          DAG.getConstant(0, DL, VT), Carry);
2179 
2180   return SDValue();
2181 }
2182 
2183 SDValue DAGCombiner::visitADDC(SDNode *N) {
2184   SDValue N0 = N->getOperand(0);
2185   SDValue N1 = N->getOperand(1);
2186   EVT VT = N0.getValueType();
2187   SDLoc DL(N);
2188 
2189   // If the flag result is dead, turn this into an ADD.
2190   if (!N->hasAnyUseOfValue(1))
2191     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2192                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2193 
2194   // canonicalize constant to RHS.
2195   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2196   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2197   if (N0C && !N1C)
2198     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2199 
2200   // fold (addc x, 0) -> x + no carry out
2201   if (isNullConstant(N1))
2202     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2203                                         DL, MVT::Glue));
2204 
2205   // If it cannot overflow, transform into an add.
2206   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2207     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2208                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2209 
2210   return SDValue();
2211 }
2212 
2213 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2214   SDValue N0 = N->getOperand(0);
2215   SDValue N1 = N->getOperand(1);
2216   EVT VT = N0.getValueType();
2217   if (VT.isVector())
2218     return SDValue();
2219 
2220   EVT CarryVT = N->getValueType(1);
2221   SDLoc DL(N);
2222 
2223   // If the flag result is dead, turn this into an ADD.
2224   if (!N->hasAnyUseOfValue(1))
2225     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2226                      DAG.getUNDEF(CarryVT));
2227 
2228   // canonicalize constant to RHS.
2229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2231   if (N0C && !N1C)
2232     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2233 
2234   // fold (uaddo x, 0) -> x + no carry out
2235   if (isNullConstant(N1))
2236     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2237 
2238   // If it cannot overflow, transform into an add.
2239   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2240     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2241                      DAG.getConstant(0, DL, CarryVT));
2242 
2243   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2244     return Combined;
2245 
2246   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2247     return Combined;
2248 
2249   return SDValue();
2250 }
2251 
2252 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2253   auto VT = N0.getValueType();
2254 
2255   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2256   // If Y + 1 cannot overflow.
2257   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2258     SDValue Y = N1.getOperand(0);
2259     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2260     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2261       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2262                          N1.getOperand(2));
2263   }
2264 
2265   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2266   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2267     if (SDValue Carry = getAsCarry(TLI, N1))
2268       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2269                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2270 
2271   return SDValue();
2272 }
2273 
2274 SDValue DAGCombiner::visitADDE(SDNode *N) {
2275   SDValue N0 = N->getOperand(0);
2276   SDValue N1 = N->getOperand(1);
2277   SDValue CarryIn = N->getOperand(2);
2278 
2279   // canonicalize constant to RHS
2280   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2282   if (N0C && !N1C)
2283     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2284                        N1, N0, CarryIn);
2285 
2286   // fold (adde x, y, false) -> (addc x, y)
2287   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2288     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2289 
2290   return SDValue();
2291 }
2292 
2293 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2294   SDValue N0 = N->getOperand(0);
2295   SDValue N1 = N->getOperand(1);
2296   SDValue CarryIn = N->getOperand(2);
2297   SDLoc DL(N);
2298 
2299   // canonicalize constant to RHS
2300   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2301   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2302   if (N0C && !N1C)
2303     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2304 
2305   // fold (addcarry x, y, false) -> (uaddo x, y)
2306   if (isNullConstant(CarryIn))
2307     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2308 
2309   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2310   if (isNullConstant(N0) && isNullConstant(N1)) {
2311     EVT VT = N0.getValueType();
2312     EVT CarryVT = CarryIn.getValueType();
2313     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2314     AddToWorklist(CarryExt.getNode());
2315     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2316                                     DAG.getConstant(1, DL, VT)),
2317                      DAG.getConstant(0, DL, CarryVT));
2318   }
2319 
2320   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2321     return Combined;
2322 
2323   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2324     return Combined;
2325 
2326   return SDValue();
2327 }
2328 
2329 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2330                                        SDNode *N) {
2331   // Iff the flag result is dead:
2332   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2333   if ((N0.getOpcode() == ISD::ADD ||
2334        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2335       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2336     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2337                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2338 
2339   /**
2340    * When one of the addcarry argument is itself a carry, we may be facing
2341    * a diamond carry propagation. In which case we try to transform the DAG
2342    * to ensure linear carry propagation if that is possible.
2343    *
2344    * We are trying to get:
2345    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2346    */
2347   if (auto Y = getAsCarry(TLI, N1)) {
2348     /**
2349      *            (uaddo A, B)
2350      *             /       \
2351      *          Carry      Sum
2352      *            |          \
2353      *            | (addcarry *, 0, Z)
2354      *            |       /
2355      *             \   Carry
2356      *              |   /
2357      * (addcarry X, *, *)
2358      */
2359     if (Y.getOpcode() == ISD::UADDO &&
2360         CarryIn.getResNo() == 1 &&
2361         CarryIn.getOpcode() == ISD::ADDCARRY &&
2362         isNullConstant(CarryIn.getOperand(1)) &&
2363         CarryIn.getOperand(0) == Y.getValue(0)) {
2364       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2365                               Y.getOperand(0), Y.getOperand(1),
2366                               CarryIn.getOperand(2));
2367       AddToWorklist(NewY.getNode());
2368       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2369                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2370                          NewY.getValue(1));
2371     }
2372   }
2373 
2374   return SDValue();
2375 }
2376 
2377 // Since it may not be valid to emit a fold to zero for vector initializers
2378 // check if we can before folding.
2379 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2380                              SelectionDAG &DAG, bool LegalOperations,
2381                              bool LegalTypes) {
2382   if (!VT.isVector())
2383     return DAG.getConstant(0, DL, VT);
2384   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2385     return DAG.getConstant(0, DL, VT);
2386   return SDValue();
2387 }
2388 
2389 SDValue DAGCombiner::visitSUB(SDNode *N) {
2390   SDValue N0 = N->getOperand(0);
2391   SDValue N1 = N->getOperand(1);
2392   EVT VT = N0.getValueType();
2393   SDLoc DL(N);
2394 
2395   // fold vector ops
2396   if (VT.isVector()) {
2397     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2398       return FoldedVOp;
2399 
2400     // fold (sub x, 0) -> x, vector edition
2401     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2402       return N0;
2403   }
2404 
2405   // fold (sub x, x) -> 0
2406   // FIXME: Refactor this and xor and other similar operations together.
2407   if (N0 == N1)
2408     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2409   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2410       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2411     // fold (sub c1, c2) -> c1-c2
2412     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2413                                       N1.getNode());
2414   }
2415 
2416   if (SDValue NewSel = foldBinOpIntoSelect(N))
2417     return NewSel;
2418 
2419   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2420 
2421   // fold (sub x, c) -> (add x, -c)
2422   if (N1C) {
2423     return DAG.getNode(ISD::ADD, DL, VT, N0,
2424                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2425   }
2426 
2427   if (isNullConstantOrNullSplatConstant(N0)) {
2428     unsigned BitWidth = VT.getScalarSizeInBits();
2429     // Right-shifting everything out but the sign bit followed by negation is
2430     // the same as flipping arithmetic/logical shift type without the negation:
2431     // -(X >>u 31) -> (X >>s 31)
2432     // -(X >>s 31) -> (X >>u 31)
2433     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2434       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2435       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2436         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2437         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2438           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2439       }
2440     }
2441 
2442     // 0 - X --> 0 if the sub is NUW.
2443     if (N->getFlags().hasNoUnsignedWrap())
2444       return N0;
2445 
2446     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2447       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2448       // N1 must be 0 because negating the minimum signed value is undefined.
2449       if (N->getFlags().hasNoSignedWrap())
2450         return N0;
2451 
2452       // 0 - X --> X if X is 0 or the minimum signed value.
2453       return N1;
2454     }
2455   }
2456 
2457   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2458   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2459     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2460 
2461   // fold A-(A-B) -> B
2462   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2463     return N1.getOperand(1);
2464 
2465   // fold (A+B)-A -> B
2466   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2467     return N0.getOperand(1);
2468 
2469   // fold (A+B)-B -> A
2470   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2471     return N0.getOperand(0);
2472 
2473   // fold C2-(A+C1) -> (C2-C1)-A
2474   if (N1.getOpcode() == ISD::ADD) {
2475     SDValue N11 = N1.getOperand(1);
2476     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2477         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2478       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2479       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2480     }
2481   }
2482 
2483   // fold ((A+(B+or-C))-B) -> A+or-C
2484   if (N0.getOpcode() == ISD::ADD &&
2485       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2486        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2487       N0.getOperand(1).getOperand(0) == N1)
2488     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2489                        N0.getOperand(1).getOperand(1));
2490 
2491   // fold ((A+(C+B))-B) -> A+C
2492   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2493       N0.getOperand(1).getOperand(1) == N1)
2494     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2495                        N0.getOperand(1).getOperand(0));
2496 
2497   // fold ((A-(B-C))-C) -> A-B
2498   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2499       N0.getOperand(1).getOperand(1) == N1)
2500     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2501                        N0.getOperand(1).getOperand(0));
2502 
2503   // If either operand of a sub is undef, the result is undef
2504   if (N0.isUndef())
2505     return N0;
2506   if (N1.isUndef())
2507     return N1;
2508 
2509   // If the relocation model supports it, consider symbol offsets.
2510   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2511     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2512       // fold (sub Sym, c) -> Sym-c
2513       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2514         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2515                                     GA->getOffset() -
2516                                         (uint64_t)N1C->getSExtValue());
2517       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2518       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2519         if (GA->getGlobal() == GB->getGlobal())
2520           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2521                                  DL, VT);
2522     }
2523 
2524   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2525   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2526     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2527     if (TN->getVT() == MVT::i1) {
2528       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2529                                  DAG.getConstant(1, DL, VT));
2530       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2531     }
2532   }
2533 
2534   return SDValue();
2535 }
2536 
2537 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2538   SDValue N0 = N->getOperand(0);
2539   SDValue N1 = N->getOperand(1);
2540   EVT VT = N0.getValueType();
2541   SDLoc DL(N);
2542 
2543   // If the flag result is dead, turn this into an SUB.
2544   if (!N->hasAnyUseOfValue(1))
2545     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2546                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2547 
2548   // fold (subc x, x) -> 0 + no borrow
2549   if (N0 == N1)
2550     return CombineTo(N, DAG.getConstant(0, DL, VT),
2551                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2552 
2553   // fold (subc x, 0) -> x + no borrow
2554   if (isNullConstant(N1))
2555     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2556 
2557   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2558   if (isAllOnesConstant(N0))
2559     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2560                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2561 
2562   return SDValue();
2563 }
2564 
2565 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2566   SDValue N0 = N->getOperand(0);
2567   SDValue N1 = N->getOperand(1);
2568   EVT VT = N0.getValueType();
2569   if (VT.isVector())
2570     return SDValue();
2571 
2572   EVT CarryVT = N->getValueType(1);
2573   SDLoc DL(N);
2574 
2575   // If the flag result is dead, turn this into an SUB.
2576   if (!N->hasAnyUseOfValue(1))
2577     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2578                      DAG.getUNDEF(CarryVT));
2579 
2580   // fold (usubo x, x) -> 0 + no borrow
2581   if (N0 == N1)
2582     return CombineTo(N, DAG.getConstant(0, DL, VT),
2583                      DAG.getConstant(0, DL, CarryVT));
2584 
2585   // fold (usubo x, 0) -> x + no borrow
2586   if (isNullConstant(N1))
2587     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2588 
2589   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2590   if (isAllOnesConstant(N0))
2591     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2592                      DAG.getConstant(0, DL, CarryVT));
2593 
2594   return SDValue();
2595 }
2596 
2597 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2598   SDValue N0 = N->getOperand(0);
2599   SDValue N1 = N->getOperand(1);
2600   SDValue CarryIn = N->getOperand(2);
2601 
2602   // fold (sube x, y, false) -> (subc x, y)
2603   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2604     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2605 
2606   return SDValue();
2607 }
2608 
2609 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2610   SDValue N0 = N->getOperand(0);
2611   SDValue N1 = N->getOperand(1);
2612   SDValue CarryIn = N->getOperand(2);
2613 
2614   // fold (subcarry x, y, false) -> (usubo x, y)
2615   if (isNullConstant(CarryIn))
2616     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2617 
2618   return SDValue();
2619 }
2620 
2621 SDValue DAGCombiner::visitMUL(SDNode *N) {
2622   SDValue N0 = N->getOperand(0);
2623   SDValue N1 = N->getOperand(1);
2624   EVT VT = N0.getValueType();
2625 
2626   // fold (mul x, undef) -> 0
2627   if (N0.isUndef() || N1.isUndef())
2628     return DAG.getConstant(0, SDLoc(N), VT);
2629 
2630   bool N0IsConst = false;
2631   bool N1IsConst = false;
2632   bool N1IsOpaqueConst = false;
2633   bool N0IsOpaqueConst = false;
2634   APInt ConstValue0, ConstValue1;
2635   // fold vector ops
2636   if (VT.isVector()) {
2637     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2638       return FoldedVOp;
2639 
2640     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2641     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2642     assert((!N0IsConst ||
2643             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2644            "Splat APInt should be element width");
2645     assert((!N1IsConst ||
2646             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2647            "Splat APInt should be element width");
2648   } else {
2649     N0IsConst = isa<ConstantSDNode>(N0);
2650     if (N0IsConst) {
2651       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2652       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2653     }
2654     N1IsConst = isa<ConstantSDNode>(N1);
2655     if (N1IsConst) {
2656       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2657       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2658     }
2659   }
2660 
2661   // fold (mul c1, c2) -> c1*c2
2662   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2663     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2664                                       N0.getNode(), N1.getNode());
2665 
2666   // canonicalize constant to RHS (vector doesn't have to splat)
2667   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2668      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2669     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2670   // fold (mul x, 0) -> 0
2671   if (N1IsConst && ConstValue1.isNullValue())
2672     return N1;
2673   // fold (mul x, 1) -> x
2674   if (N1IsConst && ConstValue1.isOneValue())
2675     return N0;
2676 
2677   if (SDValue NewSel = foldBinOpIntoSelect(N))
2678     return NewSel;
2679 
2680   // fold (mul x, -1) -> 0-x
2681   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2682     SDLoc DL(N);
2683     return DAG.getNode(ISD::SUB, DL, VT,
2684                        DAG.getConstant(0, DL, VT), N0);
2685   }
2686   // fold (mul x, (1 << c)) -> x << c
2687   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2688       DAG.isKnownToBeAPowerOfTwo(N1) &&
2689       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2690     SDLoc DL(N);
2691     SDValue LogBase2 = BuildLogBase2(N1, DL);
2692     AddToWorklist(LogBase2.getNode());
2693 
2694     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2695     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2696     AddToWorklist(Trunc.getNode());
2697     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2698   }
2699   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2700   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2701     unsigned Log2Val = (-ConstValue1).logBase2();
2702     SDLoc DL(N);
2703     // FIXME: If the input is something that is easily negated (e.g. a
2704     // single-use add), we should put the negate there.
2705     return DAG.getNode(ISD::SUB, DL, VT,
2706                        DAG.getConstant(0, DL, VT),
2707                        DAG.getNode(ISD::SHL, DL, VT, N0,
2708                             DAG.getConstant(Log2Val, DL,
2709                                       getShiftAmountTy(N0.getValueType()))));
2710   }
2711 
2712   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2713   if (N0.getOpcode() == ISD::SHL &&
2714       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2715       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2716     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2717     if (isConstantOrConstantVector(C3))
2718       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2719   }
2720 
2721   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2722   // use.
2723   {
2724     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2725 
2726     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2727     if (N0.getOpcode() == ISD::SHL &&
2728         isConstantOrConstantVector(N0.getOperand(1)) &&
2729         N0.getNode()->hasOneUse()) {
2730       Sh = N0; Y = N1;
2731     } else if (N1.getOpcode() == ISD::SHL &&
2732                isConstantOrConstantVector(N1.getOperand(1)) &&
2733                N1.getNode()->hasOneUse()) {
2734       Sh = N1; Y = N0;
2735     }
2736 
2737     if (Sh.getNode()) {
2738       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2739       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2740     }
2741   }
2742 
2743   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2744   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2745       N0.getOpcode() == ISD::ADD &&
2746       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2747       isMulAddWithConstProfitable(N, N0, N1))
2748       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2749                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2750                                      N0.getOperand(0), N1),
2751                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2752                                      N0.getOperand(1), N1));
2753 
2754   // reassociate mul
2755   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2756     return RMUL;
2757 
2758   return SDValue();
2759 }
2760 
2761 /// Return true if divmod libcall is available.
2762 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2763                                      const TargetLowering &TLI) {
2764   RTLIB::Libcall LC;
2765   EVT NodeType = Node->getValueType(0);
2766   if (!NodeType.isSimple())
2767     return false;
2768   switch (NodeType.getSimpleVT().SimpleTy) {
2769   default: return false; // No libcall for vector types.
2770   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2771   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2772   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2773   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2774   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2775   }
2776 
2777   return TLI.getLibcallName(LC) != nullptr;
2778 }
2779 
2780 /// Issue divrem if both quotient and remainder are needed.
2781 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2782   if (Node->use_empty())
2783     return SDValue(); // This is a dead node, leave it alone.
2784 
2785   unsigned Opcode = Node->getOpcode();
2786   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2787   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2788 
2789   // DivMod lib calls can still work on non-legal types if using lib-calls.
2790   EVT VT = Node->getValueType(0);
2791   if (VT.isVector() || !VT.isInteger())
2792     return SDValue();
2793 
2794   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2795     return SDValue();
2796 
2797   // If DIVREM is going to get expanded into a libcall,
2798   // but there is no libcall available, then don't combine.
2799   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2800       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2801     return SDValue();
2802 
2803   // If div is legal, it's better to do the normal expansion
2804   unsigned OtherOpcode = 0;
2805   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2806     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2807     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2808       return SDValue();
2809   } else {
2810     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2811     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2812       return SDValue();
2813   }
2814 
2815   SDValue Op0 = Node->getOperand(0);
2816   SDValue Op1 = Node->getOperand(1);
2817   SDValue combined;
2818   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2819          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2820     SDNode *User = *UI;
2821     if (User == Node || User->use_empty())
2822       continue;
2823     // Convert the other matching node(s), too;
2824     // otherwise, the DIVREM may get target-legalized into something
2825     // target-specific that we won't be able to recognize.
2826     unsigned UserOpc = User->getOpcode();
2827     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2828         User->getOperand(0) == Op0 &&
2829         User->getOperand(1) == Op1) {
2830       if (!combined) {
2831         if (UserOpc == OtherOpcode) {
2832           SDVTList VTs = DAG.getVTList(VT, VT);
2833           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2834         } else if (UserOpc == DivRemOpc) {
2835           combined = SDValue(User, 0);
2836         } else {
2837           assert(UserOpc == Opcode);
2838           continue;
2839         }
2840       }
2841       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2842         CombineTo(User, combined);
2843       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2844         CombineTo(User, combined.getValue(1));
2845     }
2846   }
2847   return combined;
2848 }
2849 
2850 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2851   SDValue N0 = N->getOperand(0);
2852   SDValue N1 = N->getOperand(1);
2853   EVT VT = N->getValueType(0);
2854   SDLoc DL(N);
2855 
2856   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2857     return DAG.getUNDEF(VT);
2858 
2859   // undef / X -> 0
2860   // undef % X -> 0
2861   if (N0.isUndef())
2862     return DAG.getConstant(0, DL, VT);
2863 
2864   return SDValue();
2865 }
2866 
2867 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2868   SDValue N0 = N->getOperand(0);
2869   SDValue N1 = N->getOperand(1);
2870   EVT VT = N->getValueType(0);
2871 
2872   // fold vector ops
2873   if (VT.isVector())
2874     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2875       return FoldedVOp;
2876 
2877   SDLoc DL(N);
2878 
2879   // fold (sdiv c1, c2) -> c1/c2
2880   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2881   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2882   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2883     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2884   // fold (sdiv X, 1) -> X
2885   if (N1C && N1C->isOne())
2886     return N0;
2887   // fold (sdiv X, -1) -> 0-X
2888   if (N1C && N1C->isAllOnesValue())
2889     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2890 
2891   if (SDValue V = simplifyDivRem(N, DAG))
2892     return V;
2893 
2894   if (SDValue NewSel = foldBinOpIntoSelect(N))
2895     return NewSel;
2896 
2897   // If we know the sign bits of both operands are zero, strength reduce to a
2898   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2899   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2900     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2901 
2902   // fold (sdiv X, pow2) -> simple ops after legalize
2903   // FIXME: We check for the exact bit here because the generic lowering gives
2904   // better results in that case. The target-specific lowering should learn how
2905   // to handle exact sdivs efficiently.
2906   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2907       !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2908                                     (-N1C->getAPIntValue()).isPowerOf2())) {
2909     // Target-specific implementation of sdiv x, pow2.
2910     if (SDValue Res = BuildSDIVPow2(N))
2911       return Res;
2912 
2913     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2914 
2915     // Splat the sign bit into the register
2916     SDValue SGN =
2917         DAG.getNode(ISD::SRA, DL, VT, N0,
2918                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2919                                     getShiftAmountTy(N0.getValueType())));
2920     AddToWorklist(SGN.getNode());
2921 
2922     // Add (N0 < 0) ? abs2 - 1 : 0;
2923     SDValue SRL =
2924         DAG.getNode(ISD::SRL, DL, VT, SGN,
2925                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2926                                     getShiftAmountTy(SGN.getValueType())));
2927     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2928     AddToWorklist(SRL.getNode());
2929     AddToWorklist(ADD.getNode());    // Divide by pow2
2930     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2931                   DAG.getConstant(lg2, DL,
2932                                   getShiftAmountTy(ADD.getValueType())));
2933 
2934     // If we're dividing by a positive value, we're done.  Otherwise, we must
2935     // negate the result.
2936     if (N1C->getAPIntValue().isNonNegative())
2937       return SRA;
2938 
2939     AddToWorklist(SRA.getNode());
2940     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2941   }
2942 
2943   // If integer divide is expensive and we satisfy the requirements, emit an
2944   // alternate sequence.  Targets may check function attributes for size/speed
2945   // trade-offs.
2946   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2947   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2948     if (SDValue Op = BuildSDIV(N))
2949       return Op;
2950 
2951   // sdiv, srem -> sdivrem
2952   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2953   // true.  Otherwise, we break the simplification logic in visitREM().
2954   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2955     if (SDValue DivRem = useDivRem(N))
2956         return DivRem;
2957 
2958   return SDValue();
2959 }
2960 
2961 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2962   SDValue N0 = N->getOperand(0);
2963   SDValue N1 = N->getOperand(1);
2964   EVT VT = N->getValueType(0);
2965 
2966   // fold vector ops
2967   if (VT.isVector())
2968     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2969       return FoldedVOp;
2970 
2971   SDLoc DL(N);
2972 
2973   // fold (udiv c1, c2) -> c1/c2
2974   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2975   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2976   if (N0C && N1C)
2977     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2978                                                     N0C, N1C))
2979       return Folded;
2980 
2981   if (SDValue V = simplifyDivRem(N, DAG))
2982     return V;
2983 
2984   if (SDValue NewSel = foldBinOpIntoSelect(N))
2985     return NewSel;
2986 
2987   // fold (udiv x, (1 << c)) -> x >>u c
2988   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2989       DAG.isKnownToBeAPowerOfTwo(N1)) {
2990     SDValue LogBase2 = BuildLogBase2(N1, DL);
2991     AddToWorklist(LogBase2.getNode());
2992 
2993     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2994     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2995     AddToWorklist(Trunc.getNode());
2996     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2997   }
2998 
2999   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3000   if (N1.getOpcode() == ISD::SHL) {
3001     SDValue N10 = N1.getOperand(0);
3002     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3003         DAG.isKnownToBeAPowerOfTwo(N10)) {
3004       SDValue LogBase2 = BuildLogBase2(N10, DL);
3005       AddToWorklist(LogBase2.getNode());
3006 
3007       EVT ADDVT = N1.getOperand(1).getValueType();
3008       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3009       AddToWorklist(Trunc.getNode());
3010       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3011       AddToWorklist(Add.getNode());
3012       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3013     }
3014   }
3015 
3016   // fold (udiv x, c) -> alternate
3017   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3018   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3019     if (SDValue Op = BuildUDIV(N))
3020       return Op;
3021 
3022   // sdiv, srem -> sdivrem
3023   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3024   // true.  Otherwise, we break the simplification logic in visitREM().
3025   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3026     if (SDValue DivRem = useDivRem(N))
3027         return DivRem;
3028 
3029   return SDValue();
3030 }
3031 
3032 // handles ISD::SREM and ISD::UREM
3033 SDValue DAGCombiner::visitREM(SDNode *N) {
3034   unsigned Opcode = N->getOpcode();
3035   SDValue N0 = N->getOperand(0);
3036   SDValue N1 = N->getOperand(1);
3037   EVT VT = N->getValueType(0);
3038   bool isSigned = (Opcode == ISD::SREM);
3039   SDLoc DL(N);
3040 
3041   // fold (rem c1, c2) -> c1%c2
3042   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3043   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3044   if (N0C && N1C)
3045     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3046       return Folded;
3047 
3048   if (SDValue V = simplifyDivRem(N, DAG))
3049     return V;
3050 
3051   if (SDValue NewSel = foldBinOpIntoSelect(N))
3052     return NewSel;
3053 
3054   if (isSigned) {
3055     // If we know the sign bits of both operands are zero, strength reduce to a
3056     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3057     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3058       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3059   } else {
3060     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3061     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3062       // fold (urem x, pow2) -> (and x, pow2-1)
3063       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3064       AddToWorklist(Add.getNode());
3065       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3066     }
3067     if (N1.getOpcode() == ISD::SHL &&
3068         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3069       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3070       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3071       AddToWorklist(Add.getNode());
3072       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3073     }
3074   }
3075 
3076   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3077 
3078   // If X/C can be simplified by the division-by-constant logic, lower
3079   // X%C to the equivalent of X-X/C*C.
3080   // To avoid mangling nodes, this simplification requires that the combine()
3081   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3082   // against this by skipping the simplification if isIntDivCheap().  When
3083   // div is not cheap, combine will not return a DIVREM.  Regardless,
3084   // checking cheapness here makes sense since the simplification results in
3085   // fatter code.
3086   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3087     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3088     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3089     AddToWorklist(Div.getNode());
3090     SDValue OptimizedDiv = combine(Div.getNode());
3091     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
3092       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
3093              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
3094       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3095       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3096       AddToWorklist(Mul.getNode());
3097       return Sub;
3098     }
3099   }
3100 
3101   // sdiv, srem -> sdivrem
3102   if (SDValue DivRem = useDivRem(N))
3103     return DivRem.getValue(1);
3104 
3105   return SDValue();
3106 }
3107 
3108 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3109   SDValue N0 = N->getOperand(0);
3110   SDValue N1 = N->getOperand(1);
3111   EVT VT = N->getValueType(0);
3112   SDLoc DL(N);
3113 
3114   if (VT.isVector()) {
3115     // fold (mulhs x, 0) -> 0
3116     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3117       return N1;
3118     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3119       return N0;
3120   }
3121 
3122   // fold (mulhs x, 0) -> 0
3123   if (isNullConstant(N1))
3124     return N1;
3125   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3126   if (isOneConstant(N1))
3127     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3128                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3129                                        getShiftAmountTy(N0.getValueType())));
3130 
3131   // fold (mulhs x, undef) -> 0
3132   if (N0.isUndef() || N1.isUndef())
3133     return DAG.getConstant(0, DL, VT);
3134 
3135   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3136   // plus a shift.
3137   if (VT.isSimple() && !VT.isVector()) {
3138     MVT Simple = VT.getSimpleVT();
3139     unsigned SimpleSize = Simple.getSizeInBits();
3140     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3141     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3142       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3143       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3144       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3145       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3146             DAG.getConstant(SimpleSize, DL,
3147                             getShiftAmountTy(N1.getValueType())));
3148       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3149     }
3150   }
3151 
3152   return SDValue();
3153 }
3154 
3155 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3156   SDValue N0 = N->getOperand(0);
3157   SDValue N1 = N->getOperand(1);
3158   EVT VT = N->getValueType(0);
3159   SDLoc DL(N);
3160 
3161   if (VT.isVector()) {
3162     // fold (mulhu x, 0) -> 0
3163     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3164       return N1;
3165     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3166       return N0;
3167   }
3168 
3169   // fold (mulhu x, 0) -> 0
3170   if (isNullConstant(N1))
3171     return N1;
3172   // fold (mulhu x, 1) -> 0
3173   if (isOneConstant(N1))
3174     return DAG.getConstant(0, DL, N0.getValueType());
3175   // fold (mulhu x, undef) -> 0
3176   if (N0.isUndef() || N1.isUndef())
3177     return DAG.getConstant(0, DL, VT);
3178 
3179   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3180   // plus a shift.
3181   if (VT.isSimple() && !VT.isVector()) {
3182     MVT Simple = VT.getSimpleVT();
3183     unsigned SimpleSize = Simple.getSizeInBits();
3184     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3185     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3186       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3187       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3188       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3189       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3190             DAG.getConstant(SimpleSize, DL,
3191                             getShiftAmountTy(N1.getValueType())));
3192       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3193     }
3194   }
3195 
3196   return SDValue();
3197 }
3198 
3199 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3200 /// give the opcodes for the two computations that are being performed. Return
3201 /// true if a simplification was made.
3202 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3203                                                 unsigned HiOp) {
3204   // If the high half is not needed, just compute the low half.
3205   bool HiExists = N->hasAnyUseOfValue(1);
3206   if (!HiExists &&
3207       (!LegalOperations ||
3208        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3209     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3210     return CombineTo(N, Res, Res);
3211   }
3212 
3213   // If the low half is not needed, just compute the high half.
3214   bool LoExists = N->hasAnyUseOfValue(0);
3215   if (!LoExists &&
3216       (!LegalOperations ||
3217        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3218     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3219     return CombineTo(N, Res, Res);
3220   }
3221 
3222   // If both halves are used, return as it is.
3223   if (LoExists && HiExists)
3224     return SDValue();
3225 
3226   // If the two computed results can be simplified separately, separate them.
3227   if (LoExists) {
3228     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3229     AddToWorklist(Lo.getNode());
3230     SDValue LoOpt = combine(Lo.getNode());
3231     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3232         (!LegalOperations ||
3233          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3234       return CombineTo(N, LoOpt, LoOpt);
3235   }
3236 
3237   if (HiExists) {
3238     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3239     AddToWorklist(Hi.getNode());
3240     SDValue HiOpt = combine(Hi.getNode());
3241     if (HiOpt.getNode() && HiOpt != Hi &&
3242         (!LegalOperations ||
3243          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3244       return CombineTo(N, HiOpt, HiOpt);
3245   }
3246 
3247   return SDValue();
3248 }
3249 
3250 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3251   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3252     return Res;
3253 
3254   EVT VT = N->getValueType(0);
3255   SDLoc DL(N);
3256 
3257   // If the type is twice as wide is legal, transform the mulhu to a wider
3258   // multiply plus a shift.
3259   if (VT.isSimple() && !VT.isVector()) {
3260     MVT Simple = VT.getSimpleVT();
3261     unsigned SimpleSize = Simple.getSizeInBits();
3262     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3263     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3264       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3265       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3266       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3267       // Compute the high part as N1.
3268       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3269             DAG.getConstant(SimpleSize, DL,
3270                             getShiftAmountTy(Lo.getValueType())));
3271       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3272       // Compute the low part as N0.
3273       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3274       return CombineTo(N, Lo, Hi);
3275     }
3276   }
3277 
3278   return SDValue();
3279 }
3280 
3281 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3282   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3283     return Res;
3284 
3285   EVT VT = N->getValueType(0);
3286   SDLoc DL(N);
3287 
3288   // If the type is twice as wide is legal, transform the mulhu to a wider
3289   // multiply plus a shift.
3290   if (VT.isSimple() && !VT.isVector()) {
3291     MVT Simple = VT.getSimpleVT();
3292     unsigned SimpleSize = Simple.getSizeInBits();
3293     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3294     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3295       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3296       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3297       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3298       // Compute the high part as N1.
3299       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3300             DAG.getConstant(SimpleSize, DL,
3301                             getShiftAmountTy(Lo.getValueType())));
3302       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3303       // Compute the low part as N0.
3304       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3305       return CombineTo(N, Lo, Hi);
3306     }
3307   }
3308 
3309   return SDValue();
3310 }
3311 
3312 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3313   // (smulo x, 2) -> (saddo x, x)
3314   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3315     if (C2->getAPIntValue() == 2)
3316       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3317                          N->getOperand(0), N->getOperand(0));
3318 
3319   return SDValue();
3320 }
3321 
3322 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3323   // (umulo x, 2) -> (uaddo x, x)
3324   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3325     if (C2->getAPIntValue() == 2)
3326       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3327                          N->getOperand(0), N->getOperand(0));
3328 
3329   return SDValue();
3330 }
3331 
3332 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3333   SDValue N0 = N->getOperand(0);
3334   SDValue N1 = N->getOperand(1);
3335   EVT VT = N0.getValueType();
3336 
3337   // fold vector ops
3338   if (VT.isVector())
3339     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3340       return FoldedVOp;
3341 
3342   // fold operation with constant operands.
3343   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3344   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3345   if (N0C && N1C)
3346     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3347 
3348   // canonicalize constant to RHS
3349   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3350      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3351     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3352 
3353   return SDValue();
3354 }
3355 
3356 /// If this is a binary operator with two operands of the same opcode, try to
3357 /// simplify it.
3358 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3359   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3360   EVT VT = N0.getValueType();
3361   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3362 
3363   // Bail early if none of these transforms apply.
3364   if (N0.getNumOperands() == 0) return SDValue();
3365 
3366   // For each of OP in AND/OR/XOR:
3367   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3368   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3369   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3370   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3371   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3372   //
3373   // do not sink logical op inside of a vector extend, since it may combine
3374   // into a vsetcc.
3375   EVT Op0VT = N0.getOperand(0).getValueType();
3376   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3377        N0.getOpcode() == ISD::SIGN_EXTEND ||
3378        N0.getOpcode() == ISD::BSWAP ||
3379        // Avoid infinite looping with PromoteIntBinOp.
3380        (N0.getOpcode() == ISD::ANY_EXTEND &&
3381         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3382        (N0.getOpcode() == ISD::TRUNCATE &&
3383         (!TLI.isZExtFree(VT, Op0VT) ||
3384          !TLI.isTruncateFree(Op0VT, VT)) &&
3385         TLI.isTypeLegal(Op0VT))) &&
3386       !VT.isVector() &&
3387       Op0VT == N1.getOperand(0).getValueType() &&
3388       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3389     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3390                                  N0.getOperand(0).getValueType(),
3391                                  N0.getOperand(0), N1.getOperand(0));
3392     AddToWorklist(ORNode.getNode());
3393     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3394   }
3395 
3396   // For each of OP in SHL/SRL/SRA/AND...
3397   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3398   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3399   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3400   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3401        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3402       N0.getOperand(1) == N1.getOperand(1)) {
3403     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3404                                  N0.getOperand(0).getValueType(),
3405                                  N0.getOperand(0), N1.getOperand(0));
3406     AddToWorklist(ORNode.getNode());
3407     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3408                        ORNode, N0.getOperand(1));
3409   }
3410 
3411   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3412   // Only perform this optimization up until type legalization, before
3413   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3414   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3415   // we don't want to undo this promotion.
3416   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3417   // on scalars.
3418   if ((N0.getOpcode() == ISD::BITCAST ||
3419        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3420        Level <= AfterLegalizeTypes) {
3421     SDValue In0 = N0.getOperand(0);
3422     SDValue In1 = N1.getOperand(0);
3423     EVT In0Ty = In0.getValueType();
3424     EVT In1Ty = In1.getValueType();
3425     SDLoc DL(N);
3426     // If both incoming values are integers, and the original types are the
3427     // same.
3428     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3429       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3430       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3431       AddToWorklist(Op.getNode());
3432       return BC;
3433     }
3434   }
3435 
3436   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3437   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3438   // If both shuffles use the same mask, and both shuffle within a single
3439   // vector, then it is worthwhile to move the swizzle after the operation.
3440   // The type-legalizer generates this pattern when loading illegal
3441   // vector types from memory. In many cases this allows additional shuffle
3442   // optimizations.
3443   // There are other cases where moving the shuffle after the xor/and/or
3444   // is profitable even if shuffles don't perform a swizzle.
3445   // If both shuffles use the same mask, and both shuffles have the same first
3446   // or second operand, then it might still be profitable to move the shuffle
3447   // after the xor/and/or operation.
3448   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3449     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3450     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3451 
3452     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3453            "Inputs to shuffles are not the same type");
3454 
3455     // Check that both shuffles use the same mask. The masks are known to be of
3456     // the same length because the result vector type is the same.
3457     // Check also that shuffles have only one use to avoid introducing extra
3458     // instructions.
3459     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3460         SVN0->getMask().equals(SVN1->getMask())) {
3461       SDValue ShOp = N0->getOperand(1);
3462 
3463       // Don't try to fold this node if it requires introducing a
3464       // build vector of all zeros that might be illegal at this stage.
3465       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3466         if (!LegalTypes)
3467           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3468         else
3469           ShOp = SDValue();
3470       }
3471 
3472       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3473       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3474       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3475       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3476         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3477                                       N0->getOperand(0), N1->getOperand(0));
3478         AddToWorklist(NewNode.getNode());
3479         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3480                                     SVN0->getMask());
3481       }
3482 
3483       // Don't try to fold this node if it requires introducing a
3484       // build vector of all zeros that might be illegal at this stage.
3485       ShOp = N0->getOperand(0);
3486       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3487         if (!LegalTypes)
3488           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3489         else
3490           ShOp = SDValue();
3491       }
3492 
3493       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3494       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3495       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3496       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3497         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3498                                       N0->getOperand(1), N1->getOperand(1));
3499         AddToWorklist(NewNode.getNode());
3500         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3501                                     SVN0->getMask());
3502       }
3503     }
3504   }
3505 
3506   return SDValue();
3507 }
3508 
3509 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3510 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3511                                        const SDLoc &DL) {
3512   SDValue LL, LR, RL, RR, N0CC, N1CC;
3513   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3514       !isSetCCEquivalent(N1, RL, RR, N1CC))
3515     return SDValue();
3516 
3517   assert(N0.getValueType() == N1.getValueType() &&
3518          "Unexpected operand types for bitwise logic op");
3519   assert(LL.getValueType() == LR.getValueType() &&
3520          RL.getValueType() == RR.getValueType() &&
3521          "Unexpected operand types for setcc");
3522 
3523   // If we're here post-legalization or the logic op type is not i1, the logic
3524   // op type must match a setcc result type. Also, all folds require new
3525   // operations on the left and right operands, so those types must match.
3526   EVT VT = N0.getValueType();
3527   EVT OpVT = LL.getValueType();
3528   if (LegalOperations || VT.getScalarType() != MVT::i1)
3529     if (VT != getSetCCResultType(OpVT))
3530       return SDValue();
3531   if (OpVT != RL.getValueType())
3532     return SDValue();
3533 
3534   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3535   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3536   bool IsInteger = OpVT.isInteger();
3537   if (LR == RR && CC0 == CC1 && IsInteger) {
3538     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3539     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3540 
3541     // All bits clear?
3542     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3543     // All sign bits clear?
3544     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3545     // Any bits set?
3546     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3547     // Any sign bits set?
3548     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3549 
3550     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3551     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3552     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3553     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3554     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3555       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3556       AddToWorklist(Or.getNode());
3557       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3558     }
3559 
3560     // All bits set?
3561     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3562     // All sign bits set?
3563     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3564     // Any bits clear?
3565     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3566     // Any sign bits clear?
3567     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3568 
3569     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3570     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3571     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3572     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3573     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3574       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3575       AddToWorklist(And.getNode());
3576       return DAG.getSetCC(DL, VT, And, LR, CC1);
3577     }
3578   }
3579 
3580   // TODO: What is the 'or' equivalent of this fold?
3581   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3582   if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
3583       IsInteger && CC0 == ISD::SETNE &&
3584       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3585        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3586     SDValue One = DAG.getConstant(1, DL, OpVT);
3587     SDValue Two = DAG.getConstant(2, DL, OpVT);
3588     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3589     AddToWorklist(Add.getNode());
3590     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3591   }
3592 
3593   // Try more general transforms if the predicates match and the only user of
3594   // the compares is the 'and' or 'or'.
3595   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3596       N0.hasOneUse() && N1.hasOneUse()) {
3597     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3598     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3599     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3600       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3601       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3602       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3603       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3604       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3605     }
3606   }
3607 
3608   // Canonicalize equivalent operands to LL == RL.
3609   if (LL == RR && LR == RL) {
3610     CC1 = ISD::getSetCCSwappedOperands(CC1);
3611     std::swap(RL, RR);
3612   }
3613 
3614   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3615   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3616   if (LL == RL && LR == RR) {
3617     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3618                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3619     if (NewCC != ISD::SETCC_INVALID &&
3620         (!LegalOperations ||
3621          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3622           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3623       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3624   }
3625 
3626   return SDValue();
3627 }
3628 
3629 /// This contains all DAGCombine rules which reduce two values combined by
3630 /// an And operation to a single value. This makes them reusable in the context
3631 /// of visitSELECT(). Rules involving constants are not included as
3632 /// visitSELECT() already handles those cases.
3633 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3634   EVT VT = N1.getValueType();
3635   SDLoc DL(N);
3636 
3637   // fold (and x, undef) -> 0
3638   if (N0.isUndef() || N1.isUndef())
3639     return DAG.getConstant(0, DL, VT);
3640 
3641   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3642     return V;
3643 
3644   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3645       VT.getSizeInBits() <= 64) {
3646     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3647       if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3648         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3649         // immediate for an add, but it is legal if its top c2 bits are set,
3650         // transform the ADD so the immediate doesn't need to be materialized
3651         // in a register.
3652         APInt ADDC = ADDI->getAPIntValue();
3653         APInt SRLC = SRLI->getAPIntValue();
3654         if (ADDC.getMinSignedBits() <= 64 &&
3655             SRLC.ult(VT.getSizeInBits()) &&
3656             !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3657           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3658                                              SRLC.getZExtValue());
3659           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3660             ADDC |= Mask;
3661             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3662               SDLoc DL0(N0);
3663               SDValue NewAdd =
3664                 DAG.getNode(ISD::ADD, DL0, VT,
3665                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3666               CombineTo(N0.getNode(), NewAdd);
3667               // Return N so it doesn't get rechecked!
3668               return SDValue(N, 0);
3669             }
3670           }
3671         }
3672       }
3673     }
3674   }
3675 
3676   // Reduce bit extract of low half of an integer to the narrower type.
3677   // (and (srl i64:x, K), KMask) ->
3678   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3679   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3680     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3681       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3682         unsigned Size = VT.getSizeInBits();
3683         const APInt &AndMask = CAnd->getAPIntValue();
3684         unsigned ShiftBits = CShift->getZExtValue();
3685 
3686         // Bail out, this node will probably disappear anyway.
3687         if (ShiftBits == 0)
3688           return SDValue();
3689 
3690         unsigned MaskBits = AndMask.countTrailingOnes();
3691         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3692 
3693         if (AndMask.isMask() &&
3694             // Required bits must not span the two halves of the integer and
3695             // must fit in the half size type.
3696             (ShiftBits + MaskBits <= Size / 2) &&
3697             TLI.isNarrowingProfitable(VT, HalfVT) &&
3698             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3699             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3700             TLI.isTruncateFree(VT, HalfVT) &&
3701             TLI.isZExtFree(HalfVT, VT)) {
3702           // The isNarrowingProfitable is to avoid regressions on PPC and
3703           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3704           // on downstream users of this. Those patterns could probably be
3705           // extended to handle extensions mixed in.
3706 
3707           SDValue SL(N0);
3708           assert(MaskBits <= Size);
3709 
3710           // Extracting the highest bit of the low half.
3711           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3712           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3713                                       N0.getOperand(0));
3714 
3715           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3716           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3717           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3718           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3719           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3720         }
3721       }
3722     }
3723   }
3724 
3725   return SDValue();
3726 }
3727 
3728 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3729                                    EVT LoadResultTy, EVT &ExtVT) {
3730   if (!AndC->getAPIntValue().isMask())
3731     return false;
3732 
3733   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3734 
3735   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3736   EVT LoadedVT = LoadN->getMemoryVT();
3737 
3738   if (ExtVT == LoadedVT &&
3739       (!LegalOperations ||
3740        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3741     // ZEXTLOAD will match without needing to change the size of the value being
3742     // loaded.
3743     return true;
3744   }
3745 
3746   // Do not change the width of a volatile load.
3747   if (LoadN->isVolatile())
3748     return false;
3749 
3750   // Do not generate loads of non-round integer types since these can
3751   // be expensive (and would be wrong if the type is not byte sized).
3752   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3753     return false;
3754 
3755   if (LegalOperations &&
3756       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3757     return false;
3758 
3759   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3760     return false;
3761 
3762   return true;
3763 }
3764 
3765 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3766                                     EVT &ExtVT, unsigned ShAmt) {
3767   // Don't transform one with multiple uses, this would require adding a new
3768   // load.
3769   if (!SDValue(LoadN, 0).hasOneUse())
3770     return false;
3771 
3772   if (LegalOperations &&
3773       !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3774     return false;
3775 
3776   // Do not generate loads of non-round integer types since these can
3777   // be expensive (and would be wrong if the type is not byte sized).
3778   if (!ExtVT.isRound())
3779     return false;
3780 
3781   // Don't change the width of a volatile load.
3782   if (LoadN->isVolatile())
3783     return false;
3784 
3785   // Verify that we are actually reducing a load width here.
3786   if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3787     return false;
3788 
3789   // For the transform to be legal, the load must produce only two values
3790   // (the value loaded and the chain).  Don't transform a pre-increment
3791   // load, for example, which produces an extra value.  Otherwise the
3792   // transformation is not equivalent, and the downstream logic to replace
3793   // uses gets things wrong.
3794   if (LoadN->getNumValues() > 2)
3795     return false;
3796 
3797   // If the load that we're shrinking is an extload and we're not just
3798   // discarding the extension we can't simply shrink the load. Bail.
3799   // TODO: It would be possible to merge the extensions in some cases.
3800   if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3801       LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3802     return false;
3803 
3804   if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3805     return false;
3806 
3807   // It's not possible to generate a constant of extended or untyped type.
3808   EVT PtrType = LoadN->getOperand(1).getValueType();
3809   if (PtrType == MVT::Untyped || PtrType.isExtended())
3810     return false;
3811 
3812   return true;
3813 }
3814 
3815 bool DAGCombiner::SearchForAndLoads(SDNode *N,
3816                                     SmallPtrSetImpl<LoadSDNode*> &Loads,
3817                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3818                                     ConstantSDNode *Mask,
3819                                     SDNode *&NodeToMask) {
3820   // Recursively search for the operands, looking for loads which can be
3821   // narrowed.
3822   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3823     SDValue Op = N->getOperand(i);
3824 
3825     if (Op.getValueType().isVector())
3826       return false;
3827 
3828     // Some constants may need fixing up later if they are too large.
3829     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3830       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3831           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3832         NodesWithConsts.insert(N);
3833       continue;
3834     }
3835 
3836     if (!Op.hasOneUse())
3837       return false;
3838 
3839     switch(Op.getOpcode()) {
3840     case ISD::LOAD: {
3841       auto *Load = cast<LoadSDNode>(Op);
3842       EVT ExtVT;
3843       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3844           isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3845 
3846         // ZEXTLOAD is already small enough.
3847         if (Load->getExtensionType() == ISD::ZEXTLOAD &&
3848             ExtVT.bitsGE(Load->getMemoryVT()))
3849           continue;
3850 
3851         // Use LE to convert equal sized loads to zext.
3852         if (ExtVT.bitsLE(Load->getMemoryVT()))
3853           Loads.insert(Load);
3854 
3855         continue;
3856       }
3857       return false;
3858     }
3859     case ISD::ZERO_EXTEND:
3860     case ISD::AssertZext: {
3861       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3862       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3863       EVT VT = Op.getOpcode() == ISD::AssertZext ?
3864         cast<VTSDNode>(Op.getOperand(1))->getVT() :
3865         Op.getOperand(0).getValueType();
3866 
3867       // We can accept extending nodes if the mask is wider or an equal
3868       // width to the original type.
3869       if (ExtVT.bitsGE(VT))
3870         continue;
3871       break;
3872     }
3873     case ISD::OR:
3874     case ISD::XOR:
3875     case ISD::AND:
3876       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3877                              NodeToMask))
3878         return false;
3879       continue;
3880     }
3881 
3882     // Allow one node which will masked along with any loads found.
3883     if (NodeToMask)
3884       return false;
3885     NodeToMask = Op.getNode();
3886   }
3887   return true;
3888 }
3889 
3890 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3891   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3892   if (!Mask)
3893     return false;
3894 
3895   if (!Mask->getAPIntValue().isMask())
3896     return false;
3897 
3898   // No need to do anything if the and directly uses a load.
3899   if (isa<LoadSDNode>(N->getOperand(0)))
3900     return false;
3901 
3902   SmallPtrSet<LoadSDNode*, 8> Loads;
3903   SmallPtrSet<SDNode*, 2> NodesWithConsts;
3904   SDNode *FixupNode = nullptr;
3905   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3906     if (Loads.size() == 0)
3907       return false;
3908 
3909     DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
3910     SDValue MaskOp = N->getOperand(1);
3911 
3912     // If it exists, fixup the single node we allow in the tree that needs
3913     // masking.
3914     if (FixupNode) {
3915       DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
3916       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3917                                 FixupNode->getValueType(0),
3918                                 SDValue(FixupNode, 0), MaskOp);
3919       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3920       DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3921                              MaskOp);
3922     }
3923 
3924     // Narrow any constants that need it.
3925     for (auto *LogicN : NodesWithConsts) {
3926       SDValue Op0 = LogicN->getOperand(0);
3927       SDValue Op1 = LogicN->getOperand(1);
3928 
3929       if (isa<ConstantSDNode>(Op0))
3930           std::swap(Op0, Op1);
3931 
3932       SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
3933                                 Op1, MaskOp);
3934 
3935       DAG.UpdateNodeOperands(LogicN, Op0, And);
3936     }
3937 
3938     // Create narrow loads.
3939     for (auto *Load : Loads) {
3940       DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
3941       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3942                                 SDValue(Load, 0), MaskOp);
3943       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3944       DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3945       SDValue NewLoad = ReduceLoadWidth(And.getNode());
3946       assert(NewLoad &&
3947              "Shouldn't be masking the load if it can't be narrowed");
3948       CombineTo(Load, NewLoad, NewLoad.getValue(1));
3949     }
3950     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
3951     return true;
3952   }
3953   return false;
3954 }
3955 
3956 SDValue DAGCombiner::visitAND(SDNode *N) {
3957   SDValue N0 = N->getOperand(0);
3958   SDValue N1 = N->getOperand(1);
3959   EVT VT = N1.getValueType();
3960 
3961   // x & x --> x
3962   if (N0 == N1)
3963     return N0;
3964 
3965   // fold vector ops
3966   if (VT.isVector()) {
3967     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3968       return FoldedVOp;
3969 
3970     // fold (and x, 0) -> 0, vector edition
3971     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3972       // do not return N0, because undef node may exist in N0
3973       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3974                              SDLoc(N), N0.getValueType());
3975     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3976       // do not return N1, because undef node may exist in N1
3977       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3978                              SDLoc(N), N1.getValueType());
3979 
3980     // fold (and x, -1) -> x, vector edition
3981     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3982       return N1;
3983     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3984       return N0;
3985   }
3986 
3987   // fold (and c1, c2) -> c1&c2
3988   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3989   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3990   if (N0C && N1C && !N1C->isOpaque())
3991     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3992   // canonicalize constant to RHS
3993   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3994      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3995     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3996   // fold (and x, -1) -> x
3997   if (isAllOnesConstant(N1))
3998     return N0;
3999   // if (and x, c) is known to be zero, return 0
4000   unsigned BitWidth = VT.getScalarSizeInBits();
4001   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4002                                    APInt::getAllOnesValue(BitWidth)))
4003     return DAG.getConstant(0, SDLoc(N), VT);
4004 
4005   if (SDValue NewSel = foldBinOpIntoSelect(N))
4006     return NewSel;
4007 
4008   // reassociate and
4009   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
4010     return RAND;
4011 
4012   // Try to convert a constant mask AND into a shuffle clear mask.
4013   if (VT.isVector())
4014     if (SDValue Shuffle = XformToShuffleWithZero(N))
4015       return Shuffle;
4016 
4017   // fold (and (or x, C), D) -> D if (C & D) == D
4018   auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4019     return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4020   };
4021   if (N0.getOpcode() == ISD::OR &&
4022       matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4023     return N1;
4024   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4025   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4026     SDValue N0Op0 = N0.getOperand(0);
4027     APInt Mask = ~N1C->getAPIntValue();
4028     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4029     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4030       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4031                                  N0.getValueType(), N0Op0);
4032 
4033       // Replace uses of the AND with uses of the Zero extend node.
4034       CombineTo(N, Zext);
4035 
4036       // We actually want to replace all uses of the any_extend with the
4037       // zero_extend, to avoid duplicating things.  This will later cause this
4038       // AND to be folded.
4039       CombineTo(N0.getNode(), Zext);
4040       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4041     }
4042   }
4043   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4044   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4045   // already be zero by virtue of the width of the base type of the load.
4046   //
4047   // the 'X' node here can either be nothing or an extract_vector_elt to catch
4048   // more cases.
4049   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4050        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4051        N0.getOperand(0).getOpcode() == ISD::LOAD &&
4052        N0.getOperand(0).getResNo() == 0) ||
4053       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4054     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4055                                          N0 : N0.getOperand(0) );
4056 
4057     // Get the constant (if applicable) the zero'th operand is being ANDed with.
4058     // This can be a pure constant or a vector splat, in which case we treat the
4059     // vector as a scalar and use the splat value.
4060     APInt Constant = APInt::getNullValue(1);
4061     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4062       Constant = C->getAPIntValue();
4063     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4064       APInt SplatValue, SplatUndef;
4065       unsigned SplatBitSize;
4066       bool HasAnyUndefs;
4067       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4068                                              SplatBitSize, HasAnyUndefs);
4069       if (IsSplat) {
4070         // Undef bits can contribute to a possible optimisation if set, so
4071         // set them.
4072         SplatValue |= SplatUndef;
4073 
4074         // The splat value may be something like "0x00FFFFFF", which means 0 for
4075         // the first vector value and FF for the rest, repeating. We need a mask
4076         // that will apply equally to all members of the vector, so AND all the
4077         // lanes of the constant together.
4078         EVT VT = Vector->getValueType(0);
4079         unsigned BitWidth = VT.getScalarSizeInBits();
4080 
4081         // If the splat value has been compressed to a bitlength lower
4082         // than the size of the vector lane, we need to re-expand it to
4083         // the lane size.
4084         if (BitWidth > SplatBitSize)
4085           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4086                SplatBitSize < BitWidth;
4087                SplatBitSize = SplatBitSize * 2)
4088             SplatValue |= SplatValue.shl(SplatBitSize);
4089 
4090         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4091         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4092         if (SplatBitSize % BitWidth == 0) {
4093           Constant = APInt::getAllOnesValue(BitWidth);
4094           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4095             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4096         }
4097       }
4098     }
4099 
4100     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4101     // actually legal and isn't going to get expanded, else this is a false
4102     // optimisation.
4103     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4104                                                     Load->getValueType(0),
4105                                                     Load->getMemoryVT());
4106 
4107     // Resize the constant to the same size as the original memory access before
4108     // extension. If it is still the AllOnesValue then this AND is completely
4109     // unneeded.
4110     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4111 
4112     bool B;
4113     switch (Load->getExtensionType()) {
4114     default: B = false; break;
4115     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4116     case ISD::ZEXTLOAD:
4117     case ISD::NON_EXTLOAD: B = true; break;
4118     }
4119 
4120     if (B && Constant.isAllOnesValue()) {
4121       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4122       // preserve semantics once we get rid of the AND.
4123       SDValue NewLoad(Load, 0);
4124 
4125       // Fold the AND away. NewLoad may get replaced immediately.
4126       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4127 
4128       if (Load->getExtensionType() == ISD::EXTLOAD) {
4129         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4130                               Load->getValueType(0), SDLoc(Load),
4131                               Load->getChain(), Load->getBasePtr(),
4132                               Load->getOffset(), Load->getMemoryVT(),
4133                               Load->getMemOperand());
4134         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4135         if (Load->getNumValues() == 3) {
4136           // PRE/POST_INC loads have 3 values.
4137           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4138                            NewLoad.getValue(2) };
4139           CombineTo(Load, To, 3, true);
4140         } else {
4141           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4142         }
4143       }
4144 
4145       return SDValue(N, 0); // Return N so it doesn't get rechecked!
4146     }
4147   }
4148 
4149   // fold (and (load x), 255) -> (zextload x, i8)
4150   // fold (and (extload x, i16), 255) -> (zextload x, i8)
4151   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4152   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4153                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
4154                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4155     if (SDValue Res = ReduceLoadWidth(N)) {
4156       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4157         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4158 
4159       AddToWorklist(N);
4160       CombineTo(LN0, Res, Res.getValue(1));
4161       return SDValue(N, 0);
4162     }
4163   }
4164 
4165   if (Level >= AfterLegalizeTypes) {
4166     // Attempt to propagate the AND back up to the leaves which, if they're
4167     // loads, can be combined to narrow loads and the AND node can be removed.
4168     // Perform after legalization so that extend nodes will already be
4169     // combined into the loads.
4170     if (BackwardsPropagateMask(N, DAG)) {
4171       return SDValue(N, 0);
4172     }
4173   }
4174 
4175   if (SDValue Combined = visitANDLike(N0, N1, N))
4176     return Combined;
4177 
4178   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
4179   if (N0.getOpcode() == N1.getOpcode())
4180     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4181       return Tmp;
4182 
4183   // Masking the negated extension of a boolean is just the zero-extended
4184   // boolean:
4185   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4186   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4187   //
4188   // Note: the SimplifyDemandedBits fold below can make an information-losing
4189   // transform, and then we have no way to find this better fold.
4190   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4191     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4192       SDValue SubRHS = N0.getOperand(1);
4193       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4194           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4195         return SubRHS;
4196       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4197           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4198         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4199     }
4200   }
4201 
4202   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4203   // fold (and (sra)) -> (and (srl)) when possible.
4204   if (SimplifyDemandedBits(SDValue(N, 0)))
4205     return SDValue(N, 0);
4206 
4207   // fold (zext_inreg (extload x)) -> (zextload x)
4208   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4209     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4210     EVT MemVT = LN0->getMemoryVT();
4211     // If we zero all the possible extended bits, then we can turn this into
4212     // a zextload if we are running before legalize or the operation is legal.
4213     unsigned BitWidth = N1.getScalarValueSizeInBits();
4214     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4215                            BitWidth - MemVT.getScalarSizeInBits())) &&
4216         ((!LegalOperations && !LN0->isVolatile()) ||
4217          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4218       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4219                                        LN0->getChain(), LN0->getBasePtr(),
4220                                        MemVT, LN0->getMemOperand());
4221       AddToWorklist(N);
4222       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4223       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4224     }
4225   }
4226   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4227   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4228       N0.hasOneUse()) {
4229     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4230     EVT MemVT = LN0->getMemoryVT();
4231     // If we zero all the possible extended bits, then we can turn this into
4232     // a zextload if we are running before legalize or the operation is legal.
4233     unsigned BitWidth = N1.getScalarValueSizeInBits();
4234     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4235                            BitWidth - MemVT.getScalarSizeInBits())) &&
4236         ((!LegalOperations && !LN0->isVolatile()) ||
4237          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4238       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4239                                        LN0->getChain(), LN0->getBasePtr(),
4240                                        MemVT, LN0->getMemOperand());
4241       AddToWorklist(N);
4242       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4243       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4244     }
4245   }
4246   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4247   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4248     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4249                                            N0.getOperand(1), false))
4250       return BSwap;
4251   }
4252 
4253   return SDValue();
4254 }
4255 
4256 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4257 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4258                                         bool DemandHighBits) {
4259   if (!LegalOperations)
4260     return SDValue();
4261 
4262   EVT VT = N->getValueType(0);
4263   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4264     return SDValue();
4265   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4266     return SDValue();
4267 
4268   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4269   bool LookPassAnd0 = false;
4270   bool LookPassAnd1 = false;
4271   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4272       std::swap(N0, N1);
4273   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4274       std::swap(N0, N1);
4275   if (N0.getOpcode() == ISD::AND) {
4276     if (!N0.getNode()->hasOneUse())
4277       return SDValue();
4278     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4279     if (!N01C || N01C->getZExtValue() != 0xFF00)
4280       return SDValue();
4281     N0 = N0.getOperand(0);
4282     LookPassAnd0 = true;
4283   }
4284 
4285   if (N1.getOpcode() == ISD::AND) {
4286     if (!N1.getNode()->hasOneUse())
4287       return SDValue();
4288     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4289     if (!N11C || N11C->getZExtValue() != 0xFF)
4290       return SDValue();
4291     N1 = N1.getOperand(0);
4292     LookPassAnd1 = true;
4293   }
4294 
4295   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4296     std::swap(N0, N1);
4297   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4298     return SDValue();
4299   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4300     return SDValue();
4301 
4302   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4303   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4304   if (!N01C || !N11C)
4305     return SDValue();
4306   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4307     return SDValue();
4308 
4309   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4310   SDValue N00 = N0->getOperand(0);
4311   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4312     if (!N00.getNode()->hasOneUse())
4313       return SDValue();
4314     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4315     if (!N001C || N001C->getZExtValue() != 0xFF)
4316       return SDValue();
4317     N00 = N00.getOperand(0);
4318     LookPassAnd0 = true;
4319   }
4320 
4321   SDValue N10 = N1->getOperand(0);
4322   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4323     if (!N10.getNode()->hasOneUse())
4324       return SDValue();
4325     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4326     if (!N101C || N101C->getZExtValue() != 0xFF00)
4327       return SDValue();
4328     N10 = N10.getOperand(0);
4329     LookPassAnd1 = true;
4330   }
4331 
4332   if (N00 != N10)
4333     return SDValue();
4334 
4335   // Make sure everything beyond the low halfword gets set to zero since the SRL
4336   // 16 will clear the top bits.
4337   unsigned OpSizeInBits = VT.getSizeInBits();
4338   if (DemandHighBits && OpSizeInBits > 16) {
4339     // If the left-shift isn't masked out then the only way this is a bswap is
4340     // if all bits beyond the low 8 are 0. In that case the entire pattern
4341     // reduces to a left shift anyway: leave it for other parts of the combiner.
4342     if (!LookPassAnd0)
4343       return SDValue();
4344 
4345     // However, if the right shift isn't masked out then it might be because
4346     // it's not needed. See if we can spot that too.
4347     if (!LookPassAnd1 &&
4348         !DAG.MaskedValueIsZero(
4349             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4350       return SDValue();
4351   }
4352 
4353   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4354   if (OpSizeInBits > 16) {
4355     SDLoc DL(N);
4356     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4357                       DAG.getConstant(OpSizeInBits - 16, DL,
4358                                       getShiftAmountTy(VT)));
4359   }
4360   return Res;
4361 }
4362 
4363 /// Return true if the specified node is an element that makes up a 32-bit
4364 /// packed halfword byteswap.
4365 /// ((x & 0x000000ff) << 8) |
4366 /// ((x & 0x0000ff00) >> 8) |
4367 /// ((x & 0x00ff0000) << 8) |
4368 /// ((x & 0xff000000) >> 8)
4369 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4370   if (!N.getNode()->hasOneUse())
4371     return false;
4372 
4373   unsigned Opc = N.getOpcode();
4374   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4375     return false;
4376 
4377   SDValue N0 = N.getOperand(0);
4378   unsigned Opc0 = N0.getOpcode();
4379   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4380     return false;
4381 
4382   ConstantSDNode *N1C = nullptr;
4383   // SHL or SRL: look upstream for AND mask operand
4384   if (Opc == ISD::AND)
4385     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4386   else if (Opc0 == ISD::AND)
4387     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4388   if (!N1C)
4389     return false;
4390 
4391   unsigned MaskByteOffset;
4392   switch (N1C->getZExtValue()) {
4393   default:
4394     return false;
4395   case 0xFF:       MaskByteOffset = 0; break;
4396   case 0xFF00:     MaskByteOffset = 1; break;
4397   case 0xFF0000:   MaskByteOffset = 2; break;
4398   case 0xFF000000: MaskByteOffset = 3; break;
4399   }
4400 
4401   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4402   if (Opc == ISD::AND) {
4403     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4404       // (x >> 8) & 0xff
4405       // (x >> 8) & 0xff0000
4406       if (Opc0 != ISD::SRL)
4407         return false;
4408       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4409       if (!C || C->getZExtValue() != 8)
4410         return false;
4411     } else {
4412       // (x << 8) & 0xff00
4413       // (x << 8) & 0xff000000
4414       if (Opc0 != ISD::SHL)
4415         return false;
4416       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4417       if (!C || C->getZExtValue() != 8)
4418         return false;
4419     }
4420   } else if (Opc == ISD::SHL) {
4421     // (x & 0xff) << 8
4422     // (x & 0xff0000) << 8
4423     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4424       return false;
4425     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4426     if (!C || C->getZExtValue() != 8)
4427       return false;
4428   } else { // Opc == ISD::SRL
4429     // (x & 0xff00) >> 8
4430     // (x & 0xff000000) >> 8
4431     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4432       return false;
4433     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4434     if (!C || C->getZExtValue() != 8)
4435       return false;
4436   }
4437 
4438   if (Parts[MaskByteOffset])
4439     return false;
4440 
4441   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4442   return true;
4443 }
4444 
4445 /// Match a 32-bit packed halfword bswap. That is
4446 /// ((x & 0x000000ff) << 8) |
4447 /// ((x & 0x0000ff00) >> 8) |
4448 /// ((x & 0x00ff0000) << 8) |
4449 /// ((x & 0xff000000) >> 8)
4450 /// => (rotl (bswap x), 16)
4451 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4452   if (!LegalOperations)
4453     return SDValue();
4454 
4455   EVT VT = N->getValueType(0);
4456   if (VT != MVT::i32)
4457     return SDValue();
4458   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4459     return SDValue();
4460 
4461   // Look for either
4462   // (or (or (and), (and)), (or (and), (and)))
4463   // (or (or (or (and), (and)), (and)), (and))
4464   if (N0.getOpcode() != ISD::OR)
4465     return SDValue();
4466   SDValue N00 = N0.getOperand(0);
4467   SDValue N01 = N0.getOperand(1);
4468   SDNode *Parts[4] = {};
4469 
4470   if (N1.getOpcode() == ISD::OR &&
4471       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4472     // (or (or (and), (and)), (or (and), (and)))
4473     if (!isBSwapHWordElement(N00, Parts))
4474       return SDValue();
4475 
4476     if (!isBSwapHWordElement(N01, Parts))
4477       return SDValue();
4478     SDValue N10 = N1.getOperand(0);
4479     if (!isBSwapHWordElement(N10, Parts))
4480       return SDValue();
4481     SDValue N11 = N1.getOperand(1);
4482     if (!isBSwapHWordElement(N11, Parts))
4483       return SDValue();
4484   } else {
4485     // (or (or (or (and), (and)), (and)), (and))
4486     if (!isBSwapHWordElement(N1, Parts))
4487       return SDValue();
4488     if (!isBSwapHWordElement(N01, Parts))
4489       return SDValue();
4490     if (N00.getOpcode() != ISD::OR)
4491       return SDValue();
4492     SDValue N000 = N00.getOperand(0);
4493     if (!isBSwapHWordElement(N000, Parts))
4494       return SDValue();
4495     SDValue N001 = N00.getOperand(1);
4496     if (!isBSwapHWordElement(N001, Parts))
4497       return SDValue();
4498   }
4499 
4500   // Make sure the parts are all coming from the same node.
4501   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4502     return SDValue();
4503 
4504   SDLoc DL(N);
4505   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4506                               SDValue(Parts[0], 0));
4507 
4508   // Result of the bswap should be rotated by 16. If it's not legal, then
4509   // do  (x << 16) | (x >> 16).
4510   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4511   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4512     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4513   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4514     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4515   return DAG.getNode(ISD::OR, DL, VT,
4516                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4517                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4518 }
4519 
4520 /// This contains all DAGCombine rules which reduce two values combined by
4521 /// an Or operation to a single value \see visitANDLike().
4522 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4523   EVT VT = N1.getValueType();
4524   SDLoc DL(N);
4525 
4526   // fold (or x, undef) -> -1
4527   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4528     return DAG.getAllOnesConstant(DL, VT);
4529 
4530   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4531     return V;
4532 
4533   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4534   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4535       // Don't increase # computations.
4536       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4537     // We can only do this xform if we know that bits from X that are set in C2
4538     // but not in C1 are already zero.  Likewise for Y.
4539     if (const ConstantSDNode *N0O1C =
4540         getAsNonOpaqueConstant(N0.getOperand(1))) {
4541       if (const ConstantSDNode *N1O1C =
4542           getAsNonOpaqueConstant(N1.getOperand(1))) {
4543         // We can only do this xform if we know that bits from X that are set in
4544         // C2 but not in C1 are already zero.  Likewise for Y.
4545         const APInt &LHSMask = N0O1C->getAPIntValue();
4546         const APInt &RHSMask = N1O1C->getAPIntValue();
4547 
4548         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4549             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4550           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4551                                   N0.getOperand(0), N1.getOperand(0));
4552           return DAG.getNode(ISD::AND, DL, VT, X,
4553                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4554         }
4555       }
4556     }
4557   }
4558 
4559   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4560   if (N0.getOpcode() == ISD::AND &&
4561       N1.getOpcode() == ISD::AND &&
4562       N0.getOperand(0) == N1.getOperand(0) &&
4563       // Don't increase # computations.
4564       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4565     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4566                             N0.getOperand(1), N1.getOperand(1));
4567     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4568   }
4569 
4570   return SDValue();
4571 }
4572 
4573 SDValue DAGCombiner::visitOR(SDNode *N) {
4574   SDValue N0 = N->getOperand(0);
4575   SDValue N1 = N->getOperand(1);
4576   EVT VT = N1.getValueType();
4577 
4578   // x | x --> x
4579   if (N0 == N1)
4580     return N0;
4581 
4582   // fold vector ops
4583   if (VT.isVector()) {
4584     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4585       return FoldedVOp;
4586 
4587     // fold (or x, 0) -> x, vector edition
4588     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4589       return N1;
4590     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4591       return N0;
4592 
4593     // fold (or x, -1) -> -1, vector edition
4594     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4595       // do not return N0, because undef node may exist in N0
4596       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4597     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4598       // do not return N1, because undef node may exist in N1
4599       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4600 
4601     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4602     // Do this only if the resulting shuffle is legal.
4603     if (isa<ShuffleVectorSDNode>(N0) &&
4604         isa<ShuffleVectorSDNode>(N1) &&
4605         // Avoid folding a node with illegal type.
4606         TLI.isTypeLegal(VT)) {
4607       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4608       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4609       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4610       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4611       // Ensure both shuffles have a zero input.
4612       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4613         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4614         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4615         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4616         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4617         bool CanFold = true;
4618         int NumElts = VT.getVectorNumElements();
4619         SmallVector<int, 4> Mask(NumElts);
4620 
4621         for (int i = 0; i != NumElts; ++i) {
4622           int M0 = SV0->getMaskElt(i);
4623           int M1 = SV1->getMaskElt(i);
4624 
4625           // Determine if either index is pointing to a zero vector.
4626           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4627           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4628 
4629           // If one element is zero and the otherside is undef, keep undef.
4630           // This also handles the case that both are undef.
4631           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4632             Mask[i] = -1;
4633             continue;
4634           }
4635 
4636           // Make sure only one of the elements is zero.
4637           if (M0Zero == M1Zero) {
4638             CanFold = false;
4639             break;
4640           }
4641 
4642           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4643 
4644           // We have a zero and non-zero element. If the non-zero came from
4645           // SV0 make the index a LHS index. If it came from SV1, make it
4646           // a RHS index. We need to mod by NumElts because we don't care
4647           // which operand it came from in the original shuffles.
4648           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4649         }
4650 
4651         if (CanFold) {
4652           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4653           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4654 
4655           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4656           if (!LegalMask) {
4657             std::swap(NewLHS, NewRHS);
4658             ShuffleVectorSDNode::commuteMask(Mask);
4659             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4660           }
4661 
4662           if (LegalMask)
4663             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4664         }
4665       }
4666     }
4667   }
4668 
4669   // fold (or c1, c2) -> c1|c2
4670   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4671   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4672   if (N0C && N1C && !N1C->isOpaque())
4673     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4674   // canonicalize constant to RHS
4675   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4676      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4677     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4678   // fold (or x, 0) -> x
4679   if (isNullConstant(N1))
4680     return N0;
4681   // fold (or x, -1) -> -1
4682   if (isAllOnesConstant(N1))
4683     return N1;
4684 
4685   if (SDValue NewSel = foldBinOpIntoSelect(N))
4686     return NewSel;
4687 
4688   // fold (or x, c) -> c iff (x & ~c) == 0
4689   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4690     return N1;
4691 
4692   if (SDValue Combined = visitORLike(N0, N1, N))
4693     return Combined;
4694 
4695   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4696   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4697     return BSwap;
4698   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4699     return BSwap;
4700 
4701   // reassociate or
4702   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4703     return ROR;
4704 
4705   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4706   // iff (c1 & c2) != 0.
4707   auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4708     return LHS->getAPIntValue().intersects(RHS->getAPIntValue());
4709   };
4710   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4711       matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) {
4712     if (SDValue COR = DAG.FoldConstantArithmetic(
4713             ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
4714       SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
4715       AddToWorklist(IOR.getNode());
4716       return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
4717     }
4718   }
4719 
4720   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4721   if (N0.getOpcode() == N1.getOpcode())
4722     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4723       return Tmp;
4724 
4725   // See if this is some rotate idiom.
4726   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4727     return SDValue(Rot, 0);
4728 
4729   if (SDValue Load = MatchLoadCombine(N))
4730     return Load;
4731 
4732   // Simplify the operands using demanded-bits information.
4733   if (SimplifyDemandedBits(SDValue(N, 0)))
4734     return SDValue(N, 0);
4735 
4736   return SDValue();
4737 }
4738 
4739 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4740 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4741   if (Op.getOpcode() == ISD::AND) {
4742     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4743       Mask = Op.getOperand(1);
4744       Op = Op.getOperand(0);
4745     } else {
4746       return false;
4747     }
4748   }
4749 
4750   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4751     Shift = Op;
4752     return true;
4753   }
4754 
4755   return false;
4756 }
4757 
4758 // Return true if we can prove that, whenever Neg and Pos are both in the
4759 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4760 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4761 //
4762 //     (or (shift1 X, Neg), (shift2 X, Pos))
4763 //
4764 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4765 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4766 // to consider shift amounts with defined behavior.
4767 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4768   // If EltSize is a power of 2 then:
4769   //
4770   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4771   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4772   //
4773   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4774   // for the stronger condition:
4775   //
4776   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4777   //
4778   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4779   // we can just replace Neg with Neg' for the rest of the function.
4780   //
4781   // In other cases we check for the even stronger condition:
4782   //
4783   //     Neg == EltSize - Pos                                    [B]
4784   //
4785   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4786   // behavior if Pos == 0 (and consequently Neg == EltSize).
4787   //
4788   // We could actually use [A] whenever EltSize is a power of 2, but the
4789   // only extra cases that it would match are those uninteresting ones
4790   // where Neg and Pos are never in range at the same time.  E.g. for
4791   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4792   // as well as (sub 32, Pos), but:
4793   //
4794   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4795   //
4796   // always invokes undefined behavior for 32-bit X.
4797   //
4798   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4799   unsigned MaskLoBits = 0;
4800   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4801     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4802       if (NegC->getAPIntValue() == EltSize - 1) {
4803         Neg = Neg.getOperand(0);
4804         MaskLoBits = Log2_64(EltSize);
4805       }
4806     }
4807   }
4808 
4809   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4810   if (Neg.getOpcode() != ISD::SUB)
4811     return false;
4812   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4813   if (!NegC)
4814     return false;
4815   SDValue NegOp1 = Neg.getOperand(1);
4816 
4817   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4818   // Pos'.  The truncation is redundant for the purpose of the equality.
4819   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4820     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4821       if (PosC->getAPIntValue() == EltSize - 1)
4822         Pos = Pos.getOperand(0);
4823 
4824   // The condition we need is now:
4825   //
4826   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4827   //
4828   // If NegOp1 == Pos then we need:
4829   //
4830   //              EltSize & Mask == NegC & Mask
4831   //
4832   // (because "x & Mask" is a truncation and distributes through subtraction).
4833   APInt Width;
4834   if (Pos == NegOp1)
4835     Width = NegC->getAPIntValue();
4836 
4837   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4838   // Then the condition we want to prove becomes:
4839   //
4840   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4841   //
4842   // which, again because "x & Mask" is a truncation, becomes:
4843   //
4844   //                NegC & Mask == (EltSize - PosC) & Mask
4845   //             EltSize & Mask == (NegC + PosC) & Mask
4846   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4847     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4848       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4849     else
4850       return false;
4851   } else
4852     return false;
4853 
4854   // Now we just need to check that EltSize & Mask == Width & Mask.
4855   if (MaskLoBits)
4856     // EltSize & Mask is 0 since Mask is EltSize - 1.
4857     return Width.getLoBits(MaskLoBits) == 0;
4858   return Width == EltSize;
4859 }
4860 
4861 // A subroutine of MatchRotate used once we have found an OR of two opposite
4862 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4863 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4864 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4865 // Neg with outer conversions stripped away.
4866 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4867                                        SDValue Neg, SDValue InnerPos,
4868                                        SDValue InnerNeg, unsigned PosOpcode,
4869                                        unsigned NegOpcode, const SDLoc &DL) {
4870   // fold (or (shl x, (*ext y)),
4871   //          (srl x, (*ext (sub 32, y)))) ->
4872   //   (rotl x, y) or (rotr x, (sub 32, y))
4873   //
4874   // fold (or (shl x, (*ext (sub 32, y))),
4875   //          (srl x, (*ext y))) ->
4876   //   (rotr x, y) or (rotl x, (sub 32, y))
4877   EVT VT = Shifted.getValueType();
4878   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4879     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4880     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4881                        HasPos ? Pos : Neg).getNode();
4882   }
4883 
4884   return nullptr;
4885 }
4886 
4887 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4888 // idioms for rotate, and if the target supports rotation instructions, generate
4889 // a rot[lr].
4890 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4891   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4892   EVT VT = LHS.getValueType();
4893   if (!TLI.isTypeLegal(VT)) return nullptr;
4894 
4895   // The target must have at least one rotate flavor.
4896   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4897   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4898   if (!HasROTL && !HasROTR) return nullptr;
4899 
4900   // Check for truncated rotate.
4901   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4902       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4903     assert(LHS.getValueType() == RHS.getValueType());
4904     if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4905       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4906                          SDValue(Rot, 0)).getNode();
4907     }
4908   }
4909 
4910   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4911   SDValue LHSShift;   // The shift.
4912   SDValue LHSMask;    // AND value if any.
4913   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4914     return nullptr; // Not part of a rotate.
4915 
4916   SDValue RHSShift;   // The shift.
4917   SDValue RHSMask;    // AND value if any.
4918   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4919     return nullptr; // Not part of a rotate.
4920 
4921   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4922     return nullptr;   // Not shifting the same value.
4923 
4924   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4925     return nullptr;   // Shifts must disagree.
4926 
4927   // Canonicalize shl to left side in a shl/srl pair.
4928   if (RHSShift.getOpcode() == ISD::SHL) {
4929     std::swap(LHS, RHS);
4930     std::swap(LHSShift, RHSShift);
4931     std::swap(LHSMask, RHSMask);
4932   }
4933 
4934   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4935   SDValue LHSShiftArg = LHSShift.getOperand(0);
4936   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4937   SDValue RHSShiftArg = RHSShift.getOperand(0);
4938   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4939 
4940   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4941   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4942   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
4943                                         ConstantSDNode *RHS) {
4944     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
4945   };
4946   if (matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
4947     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4948                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4949 
4950     // If there is an AND of either shifted operand, apply it to the result.
4951     if (LHSMask.getNode() || RHSMask.getNode()) {
4952       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4953       SDValue Mask = AllOnes;
4954 
4955       if (LHSMask.getNode()) {
4956         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4957         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4958                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4959       }
4960       if (RHSMask.getNode()) {
4961         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4962         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4963                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4964       }
4965 
4966       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4967     }
4968 
4969     return Rot.getNode();
4970   }
4971 
4972   // If there is a mask here, and we have a variable shift, we can't be sure
4973   // that we're masking out the right stuff.
4974   if (LHSMask.getNode() || RHSMask.getNode())
4975     return nullptr;
4976 
4977   // If the shift amount is sign/zext/any-extended just peel it off.
4978   SDValue LExtOp0 = LHSShiftAmt;
4979   SDValue RExtOp0 = RHSShiftAmt;
4980   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4981        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4982        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4983        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4984       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4985        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4986        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4987        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4988     LExtOp0 = LHSShiftAmt.getOperand(0);
4989     RExtOp0 = RHSShiftAmt.getOperand(0);
4990   }
4991 
4992   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4993                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4994   if (TryL)
4995     return TryL;
4996 
4997   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4998                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4999   if (TryR)
5000     return TryR;
5001 
5002   return nullptr;
5003 }
5004 
5005 namespace {
5006 
5007 /// Represents known origin of an individual byte in load combine pattern. The
5008 /// value of the byte is either constant zero or comes from memory.
5009 struct ByteProvider {
5010   // For constant zero providers Load is set to nullptr. For memory providers
5011   // Load represents the node which loads the byte from memory.
5012   // ByteOffset is the offset of the byte in the value produced by the load.
5013   LoadSDNode *Load = nullptr;
5014   unsigned ByteOffset = 0;
5015 
5016   ByteProvider() = default;
5017 
5018   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
5019     return ByteProvider(Load, ByteOffset);
5020   }
5021 
5022   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
5023 
5024   bool isConstantZero() const { return !Load; }
5025   bool isMemory() const { return Load; }
5026 
5027   bool operator==(const ByteProvider &Other) const {
5028     return Other.Load == Load && Other.ByteOffset == ByteOffset;
5029   }
5030 
5031 private:
5032   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5033       : Load(Load), ByteOffset(ByteOffset) {}
5034 };
5035 
5036 } // end anonymous namespace
5037 
5038 /// Recursively traverses the expression calculating the origin of the requested
5039 /// byte of the given value. Returns None if the provider can't be calculated.
5040 ///
5041 /// For all the values except the root of the expression verifies that the value
5042 /// has exactly one use and if it's not true return None. This way if the origin
5043 /// of the byte is returned it's guaranteed that the values which contribute to
5044 /// the byte are not used outside of this expression.
5045 ///
5046 /// Because the parts of the expression are not allowed to have more than one
5047 /// use this function iterates over trees, not DAGs. So it never visits the same
5048 /// node more than once.
5049 static const Optional<ByteProvider>
5050 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5051                       bool Root = false) {
5052   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5053   if (Depth == 10)
5054     return None;
5055 
5056   if (!Root && !Op.hasOneUse())
5057     return None;
5058 
5059   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5060   unsigned BitWidth = Op.getValueSizeInBits();
5061   if (BitWidth % 8 != 0)
5062     return None;
5063   unsigned ByteWidth = BitWidth / 8;
5064   assert(Index < ByteWidth && "invalid index requested");
5065   (void) ByteWidth;
5066 
5067   switch (Op.getOpcode()) {
5068   case ISD::OR: {
5069     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5070     if (!LHS)
5071       return None;
5072     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5073     if (!RHS)
5074       return None;
5075 
5076     if (LHS->isConstantZero())
5077       return RHS;
5078     if (RHS->isConstantZero())
5079       return LHS;
5080     return None;
5081   }
5082   case ISD::SHL: {
5083     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5084     if (!ShiftOp)
5085       return None;
5086 
5087     uint64_t BitShift = ShiftOp->getZExtValue();
5088     if (BitShift % 8 != 0)
5089       return None;
5090     uint64_t ByteShift = BitShift / 8;
5091 
5092     return Index < ByteShift
5093                ? ByteProvider::getConstantZero()
5094                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5095                                        Depth + 1);
5096   }
5097   case ISD::ANY_EXTEND:
5098   case ISD::SIGN_EXTEND:
5099   case ISD::ZERO_EXTEND: {
5100     SDValue NarrowOp = Op->getOperand(0);
5101     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5102     if (NarrowBitWidth % 8 != 0)
5103       return None;
5104     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5105 
5106     if (Index >= NarrowByteWidth)
5107       return Op.getOpcode() == ISD::ZERO_EXTEND
5108                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5109                  : None;
5110     return calculateByteProvider(NarrowOp, Index, Depth + 1);
5111   }
5112   case ISD::BSWAP:
5113     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5114                                  Depth + 1);
5115   case ISD::LOAD: {
5116     auto L = cast<LoadSDNode>(Op.getNode());
5117     if (L->isVolatile() || L->isIndexed())
5118       return None;
5119 
5120     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5121     if (NarrowBitWidth % 8 != 0)
5122       return None;
5123     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5124 
5125     if (Index >= NarrowByteWidth)
5126       return L->getExtensionType() == ISD::ZEXTLOAD
5127                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5128                  : None;
5129     return ByteProvider::getMemory(L, Index);
5130   }
5131   }
5132 
5133   return None;
5134 }
5135 
5136 /// Match a pattern where a wide type scalar value is loaded by several narrow
5137 /// loads and combined by shifts and ors. Fold it into a single load or a load
5138 /// and a BSWAP if the targets supports it.
5139 ///
5140 /// Assuming little endian target:
5141 ///  i8 *a = ...
5142 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5143 /// =>
5144 ///  i32 val = *((i32)a)
5145 ///
5146 ///  i8 *a = ...
5147 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5148 /// =>
5149 ///  i32 val = BSWAP(*((i32)a))
5150 ///
5151 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5152 /// interact well with the worklist mechanism. When a part of the pattern is
5153 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5154 /// but the root node of the pattern which triggers the load combine is not
5155 /// necessarily a direct user of the changed node. For example, once the address
5156 /// of t28 load is reassociated load combine won't be triggered:
5157 ///             t25: i32 = add t4, Constant:i32<2>
5158 ///           t26: i64 = sign_extend t25
5159 ///        t27: i64 = add t2, t26
5160 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5161 ///     t29: i32 = zero_extend t28
5162 ///   t32: i32 = shl t29, Constant:i8<8>
5163 /// t33: i32 = or t23, t32
5164 /// As a possible fix visitLoad can check if the load can be a part of a load
5165 /// combine pattern and add corresponding OR roots to the worklist.
5166 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5167   assert(N->getOpcode() == ISD::OR &&
5168          "Can only match load combining against OR nodes");
5169 
5170   // Handles simple types only
5171   EVT VT = N->getValueType(0);
5172   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5173     return SDValue();
5174   unsigned ByteWidth = VT.getSizeInBits() / 8;
5175 
5176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5177   // Before legalize we can introduce too wide illegal loads which will be later
5178   // split into legal sized loads. This enables us to combine i64 load by i8
5179   // patterns to a couple of i32 loads on 32 bit targets.
5180   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5181     return SDValue();
5182 
5183   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5184     unsigned BW, unsigned i) { return i; };
5185   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5186     unsigned BW, unsigned i) { return BW - i - 1; };
5187 
5188   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5189   auto MemoryByteOffset = [&] (ByteProvider P) {
5190     assert(P.isMemory() && "Must be a memory byte provider");
5191     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5192     assert(LoadBitWidth % 8 == 0 &&
5193            "can only analyze providers for individual bytes not bit");
5194     unsigned LoadByteWidth = LoadBitWidth / 8;
5195     return IsBigEndianTarget
5196             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5197             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5198   };
5199 
5200   Optional<BaseIndexOffset> Base;
5201   SDValue Chain;
5202 
5203   SmallSet<LoadSDNode *, 8> Loads;
5204   Optional<ByteProvider> FirstByteProvider;
5205   int64_t FirstOffset = INT64_MAX;
5206 
5207   // Check if all the bytes of the OR we are looking at are loaded from the same
5208   // base address. Collect bytes offsets from Base address in ByteOffsets.
5209   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5210   for (unsigned i = 0; i < ByteWidth; i++) {
5211     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5212     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5213       return SDValue();
5214 
5215     LoadSDNode *L = P->Load;
5216     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5217            "Must be enforced by calculateByteProvider");
5218     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5219 
5220     // All loads must share the same chain
5221     SDValue LChain = L->getChain();
5222     if (!Chain)
5223       Chain = LChain;
5224     else if (Chain != LChain)
5225       return SDValue();
5226 
5227     // Loads must share the same base address
5228     BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
5229     int64_t ByteOffsetFromBase = 0;
5230     if (!Base)
5231       Base = Ptr;
5232     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5233       return SDValue();
5234 
5235     // Calculate the offset of the current byte from the base address
5236     ByteOffsetFromBase += MemoryByteOffset(*P);
5237     ByteOffsets[i] = ByteOffsetFromBase;
5238 
5239     // Remember the first byte load
5240     if (ByteOffsetFromBase < FirstOffset) {
5241       FirstByteProvider = P;
5242       FirstOffset = ByteOffsetFromBase;
5243     }
5244 
5245     Loads.insert(L);
5246   }
5247   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5248          "memory, so there must be at least one load which produces the value");
5249   assert(Base && "Base address of the accessed memory location must be set");
5250   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5251 
5252   // Check if the bytes of the OR we are looking at match with either big or
5253   // little endian value load
5254   bool BigEndian = true, LittleEndian = true;
5255   for (unsigned i = 0; i < ByteWidth; i++) {
5256     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5257     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5258     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5259     if (!BigEndian && !LittleEndian)
5260       return SDValue();
5261   }
5262   assert((BigEndian != LittleEndian) && "should be either or");
5263   assert(FirstByteProvider && "must be set");
5264 
5265   // Ensure that the first byte is loaded from zero offset of the first load.
5266   // So the combined value can be loaded from the first load address.
5267   if (MemoryByteOffset(*FirstByteProvider) != 0)
5268     return SDValue();
5269   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5270 
5271   // The node we are looking at matches with the pattern, check if we can
5272   // replace it with a single load and bswap if needed.
5273 
5274   // If the load needs byte swap check if the target supports it
5275   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5276 
5277   // Before legalize we can introduce illegal bswaps which will be later
5278   // converted to an explicit bswap sequence. This way we end up with a single
5279   // load and byte shuffling instead of several loads and byte shuffling.
5280   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5281     return SDValue();
5282 
5283   // Check that a load of the wide type is both allowed and fast on the target
5284   bool Fast = false;
5285   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5286                                         VT, FirstLoad->getAddressSpace(),
5287                                         FirstLoad->getAlignment(), &Fast);
5288   if (!Allowed || !Fast)
5289     return SDValue();
5290 
5291   SDValue NewLoad =
5292       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5293                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5294 
5295   // Transfer chain users from old loads to the new load.
5296   for (LoadSDNode *L : Loads)
5297     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5298 
5299   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5300 }
5301 
5302 SDValue DAGCombiner::visitXOR(SDNode *N) {
5303   SDValue N0 = N->getOperand(0);
5304   SDValue N1 = N->getOperand(1);
5305   EVT VT = N0.getValueType();
5306 
5307   // fold vector ops
5308   if (VT.isVector()) {
5309     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5310       return FoldedVOp;
5311 
5312     // fold (xor x, 0) -> x, vector edition
5313     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5314       return N1;
5315     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5316       return N0;
5317   }
5318 
5319   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5320   if (N0.isUndef() && N1.isUndef())
5321     return DAG.getConstant(0, SDLoc(N), VT);
5322   // fold (xor x, undef) -> undef
5323   if (N0.isUndef())
5324     return N0;
5325   if (N1.isUndef())
5326     return N1;
5327   // fold (xor c1, c2) -> c1^c2
5328   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5329   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5330   if (N0C && N1C)
5331     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5332   // canonicalize constant to RHS
5333   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5334      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5335     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5336   // fold (xor x, 0) -> x
5337   if (isNullConstant(N1))
5338     return N0;
5339 
5340   if (SDValue NewSel = foldBinOpIntoSelect(N))
5341     return NewSel;
5342 
5343   // reassociate xor
5344   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5345     return RXOR;
5346 
5347   // fold !(x cc y) -> (x !cc y)
5348   SDValue LHS, RHS, CC;
5349   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5350     bool isInt = LHS.getValueType().isInteger();
5351     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5352                                                isInt);
5353 
5354     if (!LegalOperations ||
5355         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5356       switch (N0.getOpcode()) {
5357       default:
5358         llvm_unreachable("Unhandled SetCC Equivalent!");
5359       case ISD::SETCC:
5360         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5361       case ISD::SELECT_CC:
5362         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5363                                N0.getOperand(3), NotCC);
5364       }
5365     }
5366   }
5367 
5368   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5369   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5370       N0.getNode()->hasOneUse() &&
5371       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5372     SDValue V = N0.getOperand(0);
5373     SDLoc DL(N0);
5374     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5375                     DAG.getConstant(1, DL, V.getValueType()));
5376     AddToWorklist(V.getNode());
5377     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5378   }
5379 
5380   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5381   if (isOneConstant(N1) && VT == MVT::i1 &&
5382       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5383     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5384     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5385       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5386       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5387       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5388       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5389       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5390     }
5391   }
5392   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5393   if (isAllOnesConstant(N1) &&
5394       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5395     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5396     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5397       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5398       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5399       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5400       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5401       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5402     }
5403   }
5404   // fold (xor (and x, y), y) -> (and (not x), y)
5405   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5406       N0->getOperand(1) == N1) {
5407     SDValue X = N0->getOperand(0);
5408     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5409     AddToWorklist(NotX.getNode());
5410     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5411   }
5412 
5413   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5414   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5415   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5416       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5417       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5418     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5419       if (C->getAPIntValue() == (OpSizeInBits - 1))
5420         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5421   }
5422 
5423   // fold (xor x, x) -> 0
5424   if (N0 == N1)
5425     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5426 
5427   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5428   // Here is a concrete example of this equivalence:
5429   // i16   x ==  14
5430   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5431   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5432   //
5433   // =>
5434   //
5435   // i16     ~1      == 0b1111111111111110
5436   // i16 rol(~1, 14) == 0b1011111111111111
5437   //
5438   // Some additional tips to help conceptualize this transform:
5439   // - Try to see the operation as placing a single zero in a value of all ones.
5440   // - There exists no value for x which would allow the result to contain zero.
5441   // - Values of x larger than the bitwidth are undefined and do not require a
5442   //   consistent result.
5443   // - Pushing the zero left requires shifting one bits in from the right.
5444   // A rotate left of ~1 is a nice way of achieving the desired result.
5445   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5446       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5447     SDLoc DL(N);
5448     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5449                        N0.getOperand(1));
5450   }
5451 
5452   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5453   if (N0.getOpcode() == N1.getOpcode())
5454     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5455       return Tmp;
5456 
5457   // Simplify the expression using non-local knowledge.
5458   if (SimplifyDemandedBits(SDValue(N, 0)))
5459     return SDValue(N, 0);
5460 
5461   return SDValue();
5462 }
5463 
5464 /// Handle transforms common to the three shifts, when the shift amount is a
5465 /// constant.
5466 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5467   SDNode *LHS = N->getOperand(0).getNode();
5468   if (!LHS->hasOneUse()) return SDValue();
5469 
5470   // We want to pull some binops through shifts, so that we have (and (shift))
5471   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5472   // thing happens with address calculations, so it's important to canonicalize
5473   // it.
5474   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5475 
5476   switch (LHS->getOpcode()) {
5477   default: return SDValue();
5478   case ISD::OR:
5479   case ISD::XOR:
5480     HighBitSet = false; // We can only transform sra if the high bit is clear.
5481     break;
5482   case ISD::AND:
5483     HighBitSet = true;  // We can only transform sra if the high bit is set.
5484     break;
5485   case ISD::ADD:
5486     if (N->getOpcode() != ISD::SHL)
5487       return SDValue(); // only shl(add) not sr[al](add).
5488     HighBitSet = false; // We can only transform sra if the high bit is clear.
5489     break;
5490   }
5491 
5492   // We require the RHS of the binop to be a constant and not opaque as well.
5493   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5494   if (!BinOpCst) return SDValue();
5495 
5496   // FIXME: disable this unless the input to the binop is a shift by a constant
5497   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5498   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5499   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5500                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5501                  BinOpLHSVal->getOpcode() == ISD::SRL;
5502   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5503                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5504 
5505   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5506       !isCopyOrSelect)
5507     return SDValue();
5508 
5509   if (isCopyOrSelect && N->hasOneUse())
5510     return SDValue();
5511 
5512   EVT VT = N->getValueType(0);
5513 
5514   // If this is a signed shift right, and the high bit is modified by the
5515   // logical operation, do not perform the transformation. The highBitSet
5516   // boolean indicates the value of the high bit of the constant which would
5517   // cause it to be modified for this operation.
5518   if (N->getOpcode() == ISD::SRA) {
5519     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5520     if (BinOpRHSSignSet != HighBitSet)
5521       return SDValue();
5522   }
5523 
5524   if (!TLI.isDesirableToCommuteWithShift(LHS))
5525     return SDValue();
5526 
5527   // Fold the constants, shifting the binop RHS by the shift amount.
5528   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5529                                N->getValueType(0),
5530                                LHS->getOperand(1), N->getOperand(1));
5531   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5532 
5533   // Create the new shift.
5534   SDValue NewShift = DAG.getNode(N->getOpcode(),
5535                                  SDLoc(LHS->getOperand(0)),
5536                                  VT, LHS->getOperand(0), N->getOperand(1));
5537 
5538   // Create the new binop.
5539   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5540 }
5541 
5542 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5543   assert(N->getOpcode() == ISD::TRUNCATE);
5544   assert(N->getOperand(0).getOpcode() == ISD::AND);
5545 
5546   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5547   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5548     SDValue N01 = N->getOperand(0).getOperand(1);
5549     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5550       SDLoc DL(N);
5551       EVT TruncVT = N->getValueType(0);
5552       SDValue N00 = N->getOperand(0).getOperand(0);
5553       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5554       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5555       AddToWorklist(Trunc00.getNode());
5556       AddToWorklist(Trunc01.getNode());
5557       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5558     }
5559   }
5560 
5561   return SDValue();
5562 }
5563 
5564 SDValue DAGCombiner::visitRotate(SDNode *N) {
5565   SDLoc dl(N);
5566   SDValue N0 = N->getOperand(0);
5567   SDValue N1 = N->getOperand(1);
5568   EVT VT = N->getValueType(0);
5569   unsigned Bitsize = VT.getScalarSizeInBits();
5570 
5571   // fold (rot x, 0) -> x
5572   if (isNullConstantOrNullSplatConstant(N1))
5573     return N0;
5574 
5575   // fold (rot x, c) -> (rot x, c % BitSize)
5576   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5577     if (Cst->getAPIntValue().uge(Bitsize)) {
5578       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5579       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5580                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5581     }
5582   }
5583 
5584   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5585   if (N1.getOpcode() == ISD::TRUNCATE &&
5586       N1.getOperand(0).getOpcode() == ISD::AND) {
5587     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5588       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5589   }
5590 
5591   unsigned NextOp = N0.getOpcode();
5592   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5593   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5594     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5595     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5596     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5597       EVT ShiftVT = C1->getValueType(0);
5598       bool SameSide = (N->getOpcode() == NextOp);
5599       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5600       if (SDValue CombinedShift =
5601               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5602         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5603         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5604             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5605             BitsizeC.getNode());
5606         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5607                            CombinedShiftNorm);
5608       }
5609     }
5610   }
5611   return SDValue();
5612 }
5613 
5614 SDValue DAGCombiner::visitSHL(SDNode *N) {
5615   SDValue N0 = N->getOperand(0);
5616   SDValue N1 = N->getOperand(1);
5617   EVT VT = N0.getValueType();
5618   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5619 
5620   // fold vector ops
5621   if (VT.isVector()) {
5622     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5623       return FoldedVOp;
5624 
5625     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5626     // If setcc produces all-one true value then:
5627     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5628     if (N1CV && N1CV->isConstant()) {
5629       if (N0.getOpcode() == ISD::AND) {
5630         SDValue N00 = N0->getOperand(0);
5631         SDValue N01 = N0->getOperand(1);
5632         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5633 
5634         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5635             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5636                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5637           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5638                                                      N01CV, N1CV))
5639             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5640         }
5641       }
5642     }
5643   }
5644 
5645   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5646 
5647   // fold (shl c1, c2) -> c1<<c2
5648   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5649   if (N0C && N1C && !N1C->isOpaque())
5650     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5651   // fold (shl 0, x) -> 0
5652   if (isNullConstantOrNullSplatConstant(N0))
5653     return N0;
5654   // fold (shl x, c >= size(x)) -> undef
5655   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5656   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5657     return Val->getAPIntValue().uge(OpSizeInBits);
5658   };
5659   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5660     return DAG.getUNDEF(VT);
5661   // fold (shl x, 0) -> x
5662   if (N1C && N1C->isNullValue())
5663     return N0;
5664   // fold (shl undef, x) -> 0
5665   if (N0.isUndef())
5666     return DAG.getConstant(0, SDLoc(N), VT);
5667 
5668   if (SDValue NewSel = foldBinOpIntoSelect(N))
5669     return NewSel;
5670 
5671   // if (shl x, c) is known to be zero, return 0
5672   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5673                             APInt::getAllOnesValue(OpSizeInBits)))
5674     return DAG.getConstant(0, SDLoc(N), VT);
5675   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5676   if (N1.getOpcode() == ISD::TRUNCATE &&
5677       N1.getOperand(0).getOpcode() == ISD::AND) {
5678     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5679       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5680   }
5681 
5682   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5683     return SDValue(N, 0);
5684 
5685   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5686   if (N0.getOpcode() == ISD::SHL) {
5687     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5688                                           ConstantSDNode *RHS) {
5689       APInt c1 = LHS->getAPIntValue();
5690       APInt c2 = RHS->getAPIntValue();
5691       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5692       return (c1 + c2).uge(OpSizeInBits);
5693     };
5694     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5695       return DAG.getConstant(0, SDLoc(N), VT);
5696 
5697     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5698                                        ConstantSDNode *RHS) {
5699       APInt c1 = LHS->getAPIntValue();
5700       APInt c2 = RHS->getAPIntValue();
5701       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5702       return (c1 + c2).ult(OpSizeInBits);
5703     };
5704     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5705       SDLoc DL(N);
5706       EVT ShiftVT = N1.getValueType();
5707       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5708       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5709     }
5710   }
5711 
5712   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5713   // For this to be valid, the second form must not preserve any of the bits
5714   // that are shifted out by the inner shift in the first form.  This means
5715   // the outer shift size must be >= the number of bits added by the ext.
5716   // As a corollary, we don't care what kind of ext it is.
5717   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5718               N0.getOpcode() == ISD::ANY_EXTEND ||
5719               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5720       N0.getOperand(0).getOpcode() == ISD::SHL) {
5721     SDValue N0Op0 = N0.getOperand(0);
5722     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5723       APInt c1 = N0Op0C1->getAPIntValue();
5724       APInt c2 = N1C->getAPIntValue();
5725       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5726 
5727       EVT InnerShiftVT = N0Op0.getValueType();
5728       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5729       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5730         SDLoc DL(N0);
5731         APInt Sum = c1 + c2;
5732         if (Sum.uge(OpSizeInBits))
5733           return DAG.getConstant(0, DL, VT);
5734 
5735         return DAG.getNode(
5736             ISD::SHL, DL, VT,
5737             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5738             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5739       }
5740     }
5741   }
5742 
5743   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5744   // Only fold this if the inner zext has no other uses to avoid increasing
5745   // the total number of instructions.
5746   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5747       N0.getOperand(0).getOpcode() == ISD::SRL) {
5748     SDValue N0Op0 = N0.getOperand(0);
5749     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5750       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5751         uint64_t c1 = N0Op0C1->getZExtValue();
5752         uint64_t c2 = N1C->getZExtValue();
5753         if (c1 == c2) {
5754           SDValue NewOp0 = N0.getOperand(0);
5755           EVT CountVT = NewOp0.getOperand(1).getValueType();
5756           SDLoc DL(N);
5757           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5758                                        NewOp0,
5759                                        DAG.getConstant(c2, DL, CountVT));
5760           AddToWorklist(NewSHL.getNode());
5761           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5762         }
5763       }
5764     }
5765   }
5766 
5767   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5768   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5769   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5770       N0->getFlags().hasExact()) {
5771     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5772       uint64_t C1 = N0C1->getZExtValue();
5773       uint64_t C2 = N1C->getZExtValue();
5774       SDLoc DL(N);
5775       if (C1 <= C2)
5776         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5777                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5778       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5779                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5780     }
5781   }
5782 
5783   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5784   //                               (and (srl x, (sub c1, c2), MASK)
5785   // Only fold this if the inner shift has no other uses -- if it does, folding
5786   // this will increase the total number of instructions.
5787   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5788     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5789       uint64_t c1 = N0C1->getZExtValue();
5790       if (c1 < OpSizeInBits) {
5791         uint64_t c2 = N1C->getZExtValue();
5792         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5793         SDValue Shift;
5794         if (c2 > c1) {
5795           Mask <<= c2 - c1;
5796           SDLoc DL(N);
5797           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5798                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5799         } else {
5800           Mask.lshrInPlace(c1 - c2);
5801           SDLoc DL(N);
5802           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5803                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5804         }
5805         SDLoc DL(N0);
5806         return DAG.getNode(ISD::AND, DL, VT, Shift,
5807                            DAG.getConstant(Mask, DL, VT));
5808       }
5809     }
5810   }
5811 
5812   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5813   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5814       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5815     SDLoc DL(N);
5816     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5817     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5818     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5819   }
5820 
5821   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5822   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5823   // Variant of version done on multiply, except mul by a power of 2 is turned
5824   // into a shift.
5825   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5826       N0.getNode()->hasOneUse() &&
5827       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5828       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5829     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5830     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5831     AddToWorklist(Shl0.getNode());
5832     AddToWorklist(Shl1.getNode());
5833     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5834   }
5835 
5836   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5837   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5838       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5839       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5840     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5841     if (isConstantOrConstantVector(Shl))
5842       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5843   }
5844 
5845   if (N1C && !N1C->isOpaque())
5846     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5847       return NewSHL;
5848 
5849   return SDValue();
5850 }
5851 
5852 SDValue DAGCombiner::visitSRA(SDNode *N) {
5853   SDValue N0 = N->getOperand(0);
5854   SDValue N1 = N->getOperand(1);
5855   EVT VT = N0.getValueType();
5856   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5857 
5858   // Arithmetic shifting an all-sign-bit value is a no-op.
5859   // fold (sra 0, x) -> 0
5860   // fold (sra -1, x) -> -1
5861   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5862     return N0;
5863 
5864   // fold vector ops
5865   if (VT.isVector())
5866     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5867       return FoldedVOp;
5868 
5869   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5870 
5871   // fold (sra c1, c2) -> (sra c1, c2)
5872   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5873   if (N0C && N1C && !N1C->isOpaque())
5874     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5875   // fold (sra x, c >= size(x)) -> undef
5876   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5877   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5878     return Val->getAPIntValue().uge(OpSizeInBits);
5879   };
5880   if (matchUnaryPredicate(N1, MatchShiftTooBig))
5881     return DAG.getUNDEF(VT);
5882   // fold (sra x, 0) -> x
5883   if (N1C && N1C->isNullValue())
5884     return N0;
5885 
5886   if (SDValue NewSel = foldBinOpIntoSelect(N))
5887     return NewSel;
5888 
5889   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5890   // sext_inreg.
5891   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5892     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5893     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5894     if (VT.isVector())
5895       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5896                                ExtVT, VT.getVectorNumElements());
5897     if ((!LegalOperations ||
5898          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5899       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5900                          N0.getOperand(0), DAG.getValueType(ExtVT));
5901   }
5902 
5903   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5904   if (N0.getOpcode() == ISD::SRA) {
5905     SDLoc DL(N);
5906     EVT ShiftVT = N1.getValueType();
5907 
5908     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5909                                           ConstantSDNode *RHS) {
5910       APInt c1 = LHS->getAPIntValue();
5911       APInt c2 = RHS->getAPIntValue();
5912       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5913       return (c1 + c2).uge(OpSizeInBits);
5914     };
5915     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5916       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5917                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5918 
5919     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5920                                        ConstantSDNode *RHS) {
5921       APInt c1 = LHS->getAPIntValue();
5922       APInt c2 = RHS->getAPIntValue();
5923       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5924       return (c1 + c2).ult(OpSizeInBits);
5925     };
5926     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5927       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5928       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5929     }
5930   }
5931 
5932   // fold (sra (shl X, m), (sub result_size, n))
5933   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5934   // result_size - n != m.
5935   // If truncate is free for the target sext(shl) is likely to result in better
5936   // code.
5937   if (N0.getOpcode() == ISD::SHL && N1C) {
5938     // Get the two constanst of the shifts, CN0 = m, CN = n.
5939     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5940     if (N01C) {
5941       LLVMContext &Ctx = *DAG.getContext();
5942       // Determine what the truncate's result bitsize and type would be.
5943       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5944 
5945       if (VT.isVector())
5946         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5947 
5948       // Determine the residual right-shift amount.
5949       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5950 
5951       // If the shift is not a no-op (in which case this should be just a sign
5952       // extend already), the truncated to type is legal, sign_extend is legal
5953       // on that type, and the truncate to that type is both legal and free,
5954       // perform the transform.
5955       if ((ShiftAmt > 0) &&
5956           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5957           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5958           TLI.isTruncateFree(VT, TruncVT)) {
5959         SDLoc DL(N);
5960         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5961             getShiftAmountTy(N0.getOperand(0).getValueType()));
5962         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5963                                     N0.getOperand(0), Amt);
5964         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5965                                     Shift);
5966         return DAG.getNode(ISD::SIGN_EXTEND, DL,
5967                            N->getValueType(0), Trunc);
5968       }
5969     }
5970   }
5971 
5972   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5973   if (N1.getOpcode() == ISD::TRUNCATE &&
5974       N1.getOperand(0).getOpcode() == ISD::AND) {
5975     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5976       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5977   }
5978 
5979   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5980   //      if c1 is equal to the number of bits the trunc removes
5981   if (N0.getOpcode() == ISD::TRUNCATE &&
5982       (N0.getOperand(0).getOpcode() == ISD::SRL ||
5983        N0.getOperand(0).getOpcode() == ISD::SRA) &&
5984       N0.getOperand(0).hasOneUse() &&
5985       N0.getOperand(0).getOperand(1).hasOneUse() &&
5986       N1C) {
5987     SDValue N0Op0 = N0.getOperand(0);
5988     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5989       unsigned LargeShiftVal = LargeShift->getZExtValue();
5990       EVT LargeVT = N0Op0.getValueType();
5991 
5992       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5993         SDLoc DL(N);
5994         SDValue Amt =
5995           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5996                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5997         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5998                                   N0Op0.getOperand(0), Amt);
5999         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
6000       }
6001     }
6002   }
6003 
6004   // Simplify, based on bits shifted out of the LHS.
6005   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6006     return SDValue(N, 0);
6007 
6008   // If the sign bit is known to be zero, switch this to a SRL.
6009   if (DAG.SignBitIsZero(N0))
6010     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
6011 
6012   if (N1C && !N1C->isOpaque())
6013     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6014       return NewSRA;
6015 
6016   return SDValue();
6017 }
6018 
6019 SDValue DAGCombiner::visitSRL(SDNode *N) {
6020   SDValue N0 = N->getOperand(0);
6021   SDValue N1 = N->getOperand(1);
6022   EVT VT = N0.getValueType();
6023   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6024 
6025   // fold vector ops
6026   if (VT.isVector())
6027     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6028       return FoldedVOp;
6029 
6030   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6031 
6032   // fold (srl c1, c2) -> c1 >>u c2
6033   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6034   if (N0C && N1C && !N1C->isOpaque())
6035     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6036   // fold (srl 0, x) -> 0
6037   if (isNullConstantOrNullSplatConstant(N0))
6038     return N0;
6039   // fold (srl x, c >= size(x)) -> undef
6040   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6041   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6042     return Val->getAPIntValue().uge(OpSizeInBits);
6043   };
6044   if (matchUnaryPredicate(N1, MatchShiftTooBig))
6045     return DAG.getUNDEF(VT);
6046   // fold (srl x, 0) -> x
6047   if (N1C && N1C->isNullValue())
6048     return N0;
6049 
6050   if (SDValue NewSel = foldBinOpIntoSelect(N))
6051     return NewSel;
6052 
6053   // if (srl x, c) is known to be zero, return 0
6054   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6055                                    APInt::getAllOnesValue(OpSizeInBits)))
6056     return DAG.getConstant(0, SDLoc(N), VT);
6057 
6058   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6059   if (N0.getOpcode() == ISD::SRL) {
6060     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6061                                           ConstantSDNode *RHS) {
6062       APInt c1 = LHS->getAPIntValue();
6063       APInt c2 = RHS->getAPIntValue();
6064       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6065       return (c1 + c2).uge(OpSizeInBits);
6066     };
6067     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6068       return DAG.getConstant(0, SDLoc(N), VT);
6069 
6070     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6071                                        ConstantSDNode *RHS) {
6072       APInt c1 = LHS->getAPIntValue();
6073       APInt c2 = RHS->getAPIntValue();
6074       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6075       return (c1 + c2).ult(OpSizeInBits);
6076     };
6077     if (matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6078       SDLoc DL(N);
6079       EVT ShiftVT = N1.getValueType();
6080       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6081       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6082     }
6083   }
6084 
6085   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6086   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6087       N0.getOperand(0).getOpcode() == ISD::SRL) {
6088     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6089       uint64_t c1 = N001C->getZExtValue();
6090       uint64_t c2 = N1C->getZExtValue();
6091       EVT InnerShiftVT = N0.getOperand(0).getValueType();
6092       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6093       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6094       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6095       if (c1 + OpSizeInBits == InnerShiftSize) {
6096         SDLoc DL(N0);
6097         if (c1 + c2 >= InnerShiftSize)
6098           return DAG.getConstant(0, DL, VT);
6099         return DAG.getNode(ISD::TRUNCATE, DL, VT,
6100                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6101                                        N0.getOperand(0).getOperand(0),
6102                                        DAG.getConstant(c1 + c2, DL,
6103                                                        ShiftCountVT)));
6104       }
6105     }
6106   }
6107 
6108   // fold (srl (shl x, c), c) -> (and x, cst2)
6109   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6110       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6111     SDLoc DL(N);
6112     SDValue Mask =
6113         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6114     AddToWorklist(Mask.getNode());
6115     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6116   }
6117 
6118   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6119   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6120     // Shifting in all undef bits?
6121     EVT SmallVT = N0.getOperand(0).getValueType();
6122     unsigned BitSize = SmallVT.getScalarSizeInBits();
6123     if (N1C->getZExtValue() >= BitSize)
6124       return DAG.getUNDEF(VT);
6125 
6126     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6127       uint64_t ShiftAmt = N1C->getZExtValue();
6128       SDLoc DL0(N0);
6129       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6130                                        N0.getOperand(0),
6131                           DAG.getConstant(ShiftAmt, DL0,
6132                                           getShiftAmountTy(SmallVT)));
6133       AddToWorklist(SmallShift.getNode());
6134       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6135       SDLoc DL(N);
6136       return DAG.getNode(ISD::AND, DL, VT,
6137                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6138                          DAG.getConstant(Mask, DL, VT));
6139     }
6140   }
6141 
6142   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
6143   // bit, which is unmodified by sra.
6144   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6145     if (N0.getOpcode() == ISD::SRA)
6146       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6147   }
6148 
6149   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
6150   if (N1C && N0.getOpcode() == ISD::CTLZ &&
6151       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6152     KnownBits Known;
6153     DAG.computeKnownBits(N0.getOperand(0), Known);
6154 
6155     // If any of the input bits are KnownOne, then the input couldn't be all
6156     // zeros, thus the result of the srl will always be zero.
6157     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6158 
6159     // If all of the bits input the to ctlz node are known to be zero, then
6160     // the result of the ctlz is "32" and the result of the shift is one.
6161     APInt UnknownBits = ~Known.Zero;
6162     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6163 
6164     // Otherwise, check to see if there is exactly one bit input to the ctlz.
6165     if (UnknownBits.isPowerOf2()) {
6166       // Okay, we know that only that the single bit specified by UnknownBits
6167       // could be set on input to the CTLZ node. If this bit is set, the SRL
6168       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6169       // to an SRL/XOR pair, which is likely to simplify more.
6170       unsigned ShAmt = UnknownBits.countTrailingZeros();
6171       SDValue Op = N0.getOperand(0);
6172 
6173       if (ShAmt) {
6174         SDLoc DL(N0);
6175         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6176                   DAG.getConstant(ShAmt, DL,
6177                                   getShiftAmountTy(Op.getValueType())));
6178         AddToWorklist(Op.getNode());
6179       }
6180 
6181       SDLoc DL(N);
6182       return DAG.getNode(ISD::XOR, DL, VT,
6183                          Op, DAG.getConstant(1, DL, VT));
6184     }
6185   }
6186 
6187   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6188   if (N1.getOpcode() == ISD::TRUNCATE &&
6189       N1.getOperand(0).getOpcode() == ISD::AND) {
6190     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6191       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6192   }
6193 
6194   // fold operands of srl based on knowledge that the low bits are not
6195   // demanded.
6196   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6197     return SDValue(N, 0);
6198 
6199   if (N1C && !N1C->isOpaque())
6200     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6201       return NewSRL;
6202 
6203   // Attempt to convert a srl of a load into a narrower zero-extending load.
6204   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6205     return NarrowLoad;
6206 
6207   // Here is a common situation. We want to optimize:
6208   //
6209   //   %a = ...
6210   //   %b = and i32 %a, 2
6211   //   %c = srl i32 %b, 1
6212   //   brcond i32 %c ...
6213   //
6214   // into
6215   //
6216   //   %a = ...
6217   //   %b = and %a, 2
6218   //   %c = setcc eq %b, 0
6219   //   brcond %c ...
6220   //
6221   // However when after the source operand of SRL is optimized into AND, the SRL
6222   // itself may not be optimized further. Look for it and add the BRCOND into
6223   // the worklist.
6224   if (N->hasOneUse()) {
6225     SDNode *Use = *N->use_begin();
6226     if (Use->getOpcode() == ISD::BRCOND)
6227       AddToWorklist(Use);
6228     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6229       // Also look pass the truncate.
6230       Use = *Use->use_begin();
6231       if (Use->getOpcode() == ISD::BRCOND)
6232         AddToWorklist(Use);
6233     }
6234   }
6235 
6236   return SDValue();
6237 }
6238 
6239 SDValue DAGCombiner::visitABS(SDNode *N) {
6240   SDValue N0 = N->getOperand(0);
6241   EVT VT = N->getValueType(0);
6242 
6243   // fold (abs c1) -> c2
6244   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6245     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6246   // fold (abs (abs x)) -> (abs x)
6247   if (N0.getOpcode() == ISD::ABS)
6248     return N0;
6249   // fold (abs x) -> x iff not-negative
6250   if (DAG.SignBitIsZero(N0))
6251     return N0;
6252   return SDValue();
6253 }
6254 
6255 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6256   SDValue N0 = N->getOperand(0);
6257   EVT VT = N->getValueType(0);
6258 
6259   // fold (bswap c1) -> c2
6260   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6261     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6262   // fold (bswap (bswap x)) -> x
6263   if (N0.getOpcode() == ISD::BSWAP)
6264     return N0->getOperand(0);
6265   return SDValue();
6266 }
6267 
6268 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6269   SDValue N0 = N->getOperand(0);
6270   EVT VT = N->getValueType(0);
6271 
6272   // fold (bitreverse c1) -> c2
6273   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6274     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6275   // fold (bitreverse (bitreverse x)) -> x
6276   if (N0.getOpcode() == ISD::BITREVERSE)
6277     return N0.getOperand(0);
6278   return SDValue();
6279 }
6280 
6281 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6282   SDValue N0 = N->getOperand(0);
6283   EVT VT = N->getValueType(0);
6284 
6285   // fold (ctlz c1) -> c2
6286   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6287     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6288   return SDValue();
6289 }
6290 
6291 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6292   SDValue N0 = N->getOperand(0);
6293   EVT VT = N->getValueType(0);
6294 
6295   // fold (ctlz_zero_undef c1) -> c2
6296   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6297     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6298   return SDValue();
6299 }
6300 
6301 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6302   SDValue N0 = N->getOperand(0);
6303   EVT VT = N->getValueType(0);
6304 
6305   // fold (cttz c1) -> c2
6306   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6307     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6308   return SDValue();
6309 }
6310 
6311 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6312   SDValue N0 = N->getOperand(0);
6313   EVT VT = N->getValueType(0);
6314 
6315   // fold (cttz_zero_undef c1) -> c2
6316   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6317     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6318   return SDValue();
6319 }
6320 
6321 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6322   SDValue N0 = N->getOperand(0);
6323   EVT VT = N->getValueType(0);
6324 
6325   // fold (ctpop c1) -> c2
6326   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6327     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6328   return SDValue();
6329 }
6330 
6331 /// \brief Generate Min/Max node
6332 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6333                                    SDValue RHS, SDValue True, SDValue False,
6334                                    ISD::CondCode CC, const TargetLowering &TLI,
6335                                    SelectionDAG &DAG) {
6336   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6337     return SDValue();
6338 
6339   switch (CC) {
6340   case ISD::SETOLT:
6341   case ISD::SETOLE:
6342   case ISD::SETLT:
6343   case ISD::SETLE:
6344   case ISD::SETULT:
6345   case ISD::SETULE: {
6346     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6347     if (TLI.isOperationLegal(Opcode, VT))
6348       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6349     return SDValue();
6350   }
6351   case ISD::SETOGT:
6352   case ISD::SETOGE:
6353   case ISD::SETGT:
6354   case ISD::SETGE:
6355   case ISD::SETUGT:
6356   case ISD::SETUGE: {
6357     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6358     if (TLI.isOperationLegal(Opcode, VT))
6359       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6360     return SDValue();
6361   }
6362   default:
6363     return SDValue();
6364   }
6365 }
6366 
6367 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6368   SDValue Cond = N->getOperand(0);
6369   SDValue N1 = N->getOperand(1);
6370   SDValue N2 = N->getOperand(2);
6371   EVT VT = N->getValueType(0);
6372   EVT CondVT = Cond.getValueType();
6373   SDLoc DL(N);
6374 
6375   if (!VT.isInteger())
6376     return SDValue();
6377 
6378   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6379   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6380   if (!C1 || !C2)
6381     return SDValue();
6382 
6383   // Only do this before legalization to avoid conflicting with target-specific
6384   // transforms in the other direction (create a select from a zext/sext). There
6385   // is also a target-independent combine here in DAGCombiner in the other
6386   // direction for (select Cond, -1, 0) when the condition is not i1.
6387   if (CondVT == MVT::i1 && !LegalOperations) {
6388     if (C1->isNullValue() && C2->isOne()) {
6389       // select Cond, 0, 1 --> zext (!Cond)
6390       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6391       if (VT != MVT::i1)
6392         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6393       return NotCond;
6394     }
6395     if (C1->isNullValue() && C2->isAllOnesValue()) {
6396       // select Cond, 0, -1 --> sext (!Cond)
6397       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6398       if (VT != MVT::i1)
6399         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6400       return NotCond;
6401     }
6402     if (C1->isOne() && C2->isNullValue()) {
6403       // select Cond, 1, 0 --> zext (Cond)
6404       if (VT != MVT::i1)
6405         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6406       return Cond;
6407     }
6408     if (C1->isAllOnesValue() && C2->isNullValue()) {
6409       // select Cond, -1, 0 --> sext (Cond)
6410       if (VT != MVT::i1)
6411         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6412       return Cond;
6413     }
6414 
6415     // For any constants that differ by 1, we can transform the select into an
6416     // extend and add. Use a target hook because some targets may prefer to
6417     // transform in the other direction.
6418     if (TLI.convertSelectOfConstantsToMath(VT)) {
6419       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6420         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6421         if (VT != MVT::i1)
6422           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6423         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6424       }
6425       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6426         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6427         if (VT != MVT::i1)
6428           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6429         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6430       }
6431     }
6432 
6433     return SDValue();
6434   }
6435 
6436   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6437   // We can't do this reliably if integer based booleans have different contents
6438   // to floating point based booleans. This is because we can't tell whether we
6439   // have an integer-based boolean or a floating-point-based boolean unless we
6440   // can find the SETCC that produced it and inspect its operands. This is
6441   // fairly easy if C is the SETCC node, but it can potentially be
6442   // undiscoverable (or not reasonably discoverable). For example, it could be
6443   // in another basic block or it could require searching a complicated
6444   // expression.
6445   if (CondVT.isInteger() &&
6446       TLI.getBooleanContents(false, true) ==
6447           TargetLowering::ZeroOrOneBooleanContent &&
6448       TLI.getBooleanContents(false, false) ==
6449           TargetLowering::ZeroOrOneBooleanContent &&
6450       C1->isNullValue() && C2->isOne()) {
6451     SDValue NotCond =
6452         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6453     if (VT.bitsEq(CondVT))
6454       return NotCond;
6455     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6456   }
6457 
6458   return SDValue();
6459 }
6460 
6461 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6462   SDValue N0 = N->getOperand(0);
6463   SDValue N1 = N->getOperand(1);
6464   SDValue N2 = N->getOperand(2);
6465   EVT VT = N->getValueType(0);
6466   EVT VT0 = N0.getValueType();
6467   SDLoc DL(N);
6468 
6469   // fold (select C, X, X) -> X
6470   if (N1 == N2)
6471     return N1;
6472 
6473   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6474     // fold (select true, X, Y) -> X
6475     // fold (select false, X, Y) -> Y
6476     return !N0C->isNullValue() ? N1 : N2;
6477   }
6478 
6479   // fold (select X, X, Y) -> (or X, Y)
6480   // fold (select X, 1, Y) -> (or C, Y)
6481   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6482     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6483 
6484   if (SDValue V = foldSelectOfConstants(N))
6485     return V;
6486 
6487   // fold (select C, 0, X) -> (and (not C), X)
6488   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6489     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6490     AddToWorklist(NOTNode.getNode());
6491     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6492   }
6493   // fold (select C, X, 1) -> (or (not C), X)
6494   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6495     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6496     AddToWorklist(NOTNode.getNode());
6497     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6498   }
6499   // fold (select X, Y, X) -> (and X, Y)
6500   // fold (select X, Y, 0) -> (and X, Y)
6501   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6502     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6503 
6504   // If we can fold this based on the true/false value, do so.
6505   if (SimplifySelectOps(N, N1, N2))
6506     return SDValue(N, 0); // Don't revisit N.
6507 
6508   if (VT0 == MVT::i1) {
6509     // The code in this block deals with the following 2 equivalences:
6510     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6511     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6512     // The target can specify its preferred form with the
6513     // shouldNormalizeToSelectSequence() callback. However we always transform
6514     // to the right anyway if we find the inner select exists in the DAG anyway
6515     // and we always transform to the left side if we know that we can further
6516     // optimize the combination of the conditions.
6517     bool normalizeToSequence =
6518         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6519     // select (and Cond0, Cond1), X, Y
6520     //   -> select Cond0, (select Cond1, X, Y), Y
6521     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6522       SDValue Cond0 = N0->getOperand(0);
6523       SDValue Cond1 = N0->getOperand(1);
6524       SDValue InnerSelect =
6525           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6526       if (normalizeToSequence || !InnerSelect.use_empty())
6527         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6528                            InnerSelect, N2);
6529     }
6530     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6531     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6532       SDValue Cond0 = N0->getOperand(0);
6533       SDValue Cond1 = N0->getOperand(1);
6534       SDValue InnerSelect =
6535           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6536       if (normalizeToSequence || !InnerSelect.use_empty())
6537         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6538                            InnerSelect);
6539     }
6540 
6541     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6542     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6543       SDValue N1_0 = N1->getOperand(0);
6544       SDValue N1_1 = N1->getOperand(1);
6545       SDValue N1_2 = N1->getOperand(2);
6546       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6547         // Create the actual and node if we can generate good code for it.
6548         if (!normalizeToSequence) {
6549           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6550           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6551         }
6552         // Otherwise see if we can optimize the "and" to a better pattern.
6553         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6554           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6555                              N2);
6556       }
6557     }
6558     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6559     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6560       SDValue N2_0 = N2->getOperand(0);
6561       SDValue N2_1 = N2->getOperand(1);
6562       SDValue N2_2 = N2->getOperand(2);
6563       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6564         // Create the actual or node if we can generate good code for it.
6565         if (!normalizeToSequence) {
6566           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6567           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6568         }
6569         // Otherwise see if we can optimize to a better pattern.
6570         if (SDValue Combined = visitORLike(N0, N2_0, N))
6571           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6572                              N2_2);
6573       }
6574     }
6575   }
6576 
6577   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6578   if (VT0 == MVT::i1) {
6579     if (N0->getOpcode() == ISD::XOR) {
6580       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6581         SDValue Cond0 = N0->getOperand(0);
6582         if (C->isOne())
6583           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6584       }
6585     }
6586   }
6587 
6588   // fold selects based on a setcc into other things, such as min/max/abs
6589   if (N0.getOpcode() == ISD::SETCC) {
6590     // select x, y (fcmp lt x, y) -> fminnum x, y
6591     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6592     //
6593     // This is OK if we don't care about what happens if either operand is a
6594     // NaN.
6595     //
6596 
6597     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6598     // no signed zeros as well as no nans.
6599     const TargetOptions &Options = DAG.getTarget().Options;
6600     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6601         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6602       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6603 
6604       if (SDValue FMinMax = combineMinNumMaxNum(
6605               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6606         return FMinMax;
6607     }
6608 
6609     if ((!LegalOperations &&
6610          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6611         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6612       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6613                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6614     return SimplifySelect(DL, N0, N1, N2);
6615   }
6616 
6617   return SDValue();
6618 }
6619 
6620 static
6621 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6622   SDLoc DL(N);
6623   EVT LoVT, HiVT;
6624   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6625 
6626   // Split the inputs.
6627   SDValue Lo, Hi, LL, LH, RL, RH;
6628   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6629   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6630 
6631   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6632   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6633 
6634   return std::make_pair(Lo, Hi);
6635 }
6636 
6637 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6638 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6639 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6640   SDLoc DL(N);
6641   SDValue Cond = N->getOperand(0);
6642   SDValue LHS = N->getOperand(1);
6643   SDValue RHS = N->getOperand(2);
6644   EVT VT = N->getValueType(0);
6645   int NumElems = VT.getVectorNumElements();
6646   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6647          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6648          Cond.getOpcode() == ISD::BUILD_VECTOR);
6649 
6650   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6651   // binary ones here.
6652   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6653     return SDValue();
6654 
6655   // We're sure we have an even number of elements due to the
6656   // concat_vectors we have as arguments to vselect.
6657   // Skip BV elements until we find one that's not an UNDEF
6658   // After we find an UNDEF element, keep looping until we get to half the
6659   // length of the BV and see if all the non-undef nodes are the same.
6660   ConstantSDNode *BottomHalf = nullptr;
6661   for (int i = 0; i < NumElems / 2; ++i) {
6662     if (Cond->getOperand(i)->isUndef())
6663       continue;
6664 
6665     if (BottomHalf == nullptr)
6666       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6667     else if (Cond->getOperand(i).getNode() != BottomHalf)
6668       return SDValue();
6669   }
6670 
6671   // Do the same for the second half of the BuildVector
6672   ConstantSDNode *TopHalf = nullptr;
6673   for (int i = NumElems / 2; i < NumElems; ++i) {
6674     if (Cond->getOperand(i)->isUndef())
6675       continue;
6676 
6677     if (TopHalf == nullptr)
6678       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6679     else if (Cond->getOperand(i).getNode() != TopHalf)
6680       return SDValue();
6681   }
6682 
6683   assert(TopHalf && BottomHalf &&
6684          "One half of the selector was all UNDEFs and the other was all the "
6685          "same value. This should have been addressed before this function.");
6686   return DAG.getNode(
6687       ISD::CONCAT_VECTORS, DL, VT,
6688       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6689       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6690 }
6691 
6692 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6693   if (Level >= AfterLegalizeTypes)
6694     return SDValue();
6695 
6696   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6697   SDValue Mask = MSC->getMask();
6698   SDValue Data  = MSC->getValue();
6699   SDLoc DL(N);
6700 
6701   // If the MSCATTER data type requires splitting and the mask is provided by a
6702   // SETCC, then split both nodes and its operands before legalization. This
6703   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6704   // and enables future optimizations (e.g. min/max pattern matching on X86).
6705   if (Mask.getOpcode() != ISD::SETCC)
6706     return SDValue();
6707 
6708   // Check if any splitting is required.
6709   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6710       TargetLowering::TypeSplitVector)
6711     return SDValue();
6712   SDValue MaskLo, MaskHi, Lo, Hi;
6713   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6714 
6715   EVT LoVT, HiVT;
6716   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6717 
6718   SDValue Chain = MSC->getChain();
6719 
6720   EVT MemoryVT = MSC->getMemoryVT();
6721   unsigned Alignment = MSC->getOriginalAlignment();
6722 
6723   EVT LoMemVT, HiMemVT;
6724   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6725 
6726   SDValue DataLo, DataHi;
6727   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6728 
6729   SDValue Scale = MSC->getScale();
6730   SDValue BasePtr = MSC->getBasePtr();
6731   SDValue IndexLo, IndexHi;
6732   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6733 
6734   MachineMemOperand *MMO = DAG.getMachineFunction().
6735     getMachineMemOperand(MSC->getPointerInfo(),
6736                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6737                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6738 
6739   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale };
6740   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6741                             DL, OpsLo, MMO);
6742 
6743   SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale };
6744   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6745                             DL, OpsHi, MMO);
6746 
6747   AddToWorklist(Lo.getNode());
6748   AddToWorklist(Hi.getNode());
6749 
6750   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6751 }
6752 
6753 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6754   if (Level >= AfterLegalizeTypes)
6755     return SDValue();
6756 
6757   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6758   SDValue Mask = MST->getMask();
6759   SDValue Data  = MST->getValue();
6760   EVT VT = Data.getValueType();
6761   SDLoc DL(N);
6762 
6763   // If the MSTORE data type requires splitting and the mask is provided by a
6764   // SETCC, then split both nodes and its operands before legalization. This
6765   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6766   // and enables future optimizations (e.g. min/max pattern matching on X86).
6767   if (Mask.getOpcode() == ISD::SETCC) {
6768     // Check if any splitting is required.
6769     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6770         TargetLowering::TypeSplitVector)
6771       return SDValue();
6772 
6773     SDValue MaskLo, MaskHi, Lo, Hi;
6774     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6775 
6776     SDValue Chain = MST->getChain();
6777     SDValue Ptr   = MST->getBasePtr();
6778 
6779     EVT MemoryVT = MST->getMemoryVT();
6780     unsigned Alignment = MST->getOriginalAlignment();
6781 
6782     // if Alignment is equal to the vector size,
6783     // take the half of it for the second part
6784     unsigned SecondHalfAlignment =
6785       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6786 
6787     EVT LoMemVT, HiMemVT;
6788     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6789 
6790     SDValue DataLo, DataHi;
6791     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6792 
6793     MachineMemOperand *MMO = DAG.getMachineFunction().
6794       getMachineMemOperand(MST->getPointerInfo(),
6795                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6796                            Alignment, MST->getAAInfo(), MST->getRanges());
6797 
6798     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6799                             MST->isTruncatingStore(),
6800                             MST->isCompressingStore());
6801 
6802     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6803                                      MST->isCompressingStore());
6804 
6805     MMO = DAG.getMachineFunction().
6806       getMachineMemOperand(MST->getPointerInfo(),
6807                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
6808                            SecondHalfAlignment, MST->getAAInfo(),
6809                            MST->getRanges());
6810 
6811     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6812                             MST->isTruncatingStore(),
6813                             MST->isCompressingStore());
6814 
6815     AddToWorklist(Lo.getNode());
6816     AddToWorklist(Hi.getNode());
6817 
6818     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6819   }
6820   return SDValue();
6821 }
6822 
6823 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6824   if (Level >= AfterLegalizeTypes)
6825     return SDValue();
6826 
6827   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
6828   SDValue Mask = MGT->getMask();
6829   SDLoc DL(N);
6830 
6831   // If the MGATHER result requires splitting and the mask is provided by a
6832   // SETCC, then split both nodes and its operands before legalization. This
6833   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6834   // and enables future optimizations (e.g. min/max pattern matching on X86).
6835 
6836   if (Mask.getOpcode() != ISD::SETCC)
6837     return SDValue();
6838 
6839   EVT VT = N->getValueType(0);
6840 
6841   // Check if any splitting is required.
6842   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6843       TargetLowering::TypeSplitVector)
6844     return SDValue();
6845 
6846   SDValue MaskLo, MaskHi, Lo, Hi;
6847   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6848 
6849   SDValue Src0 = MGT->getValue();
6850   SDValue Src0Lo, Src0Hi;
6851   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6852 
6853   EVT LoVT, HiVT;
6854   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6855 
6856   SDValue Chain = MGT->getChain();
6857   EVT MemoryVT = MGT->getMemoryVT();
6858   unsigned Alignment = MGT->getOriginalAlignment();
6859 
6860   EVT LoMemVT, HiMemVT;
6861   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6862 
6863   SDValue Scale = MGT->getScale();
6864   SDValue BasePtr = MGT->getBasePtr();
6865   SDValue Index = MGT->getIndex();
6866   SDValue IndexLo, IndexHi;
6867   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6868 
6869   MachineMemOperand *MMO = DAG.getMachineFunction().
6870     getMachineMemOperand(MGT->getPointerInfo(),
6871                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6872                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6873 
6874   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale };
6875   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6876                            MMO);
6877 
6878   SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale };
6879   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6880                            MMO);
6881 
6882   AddToWorklist(Lo.getNode());
6883   AddToWorklist(Hi.getNode());
6884 
6885   // Build a factor node to remember that this load is independent of the
6886   // other one.
6887   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6888                       Hi.getValue(1));
6889 
6890   // Legalized the chain result - switch anything that used the old chain to
6891   // use the new one.
6892   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6893 
6894   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6895 
6896   SDValue RetOps[] = { GatherRes, Chain };
6897   return DAG.getMergeValues(RetOps, DL);
6898 }
6899 
6900 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6901   if (Level >= AfterLegalizeTypes)
6902     return SDValue();
6903 
6904   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6905   SDValue Mask = MLD->getMask();
6906   SDLoc DL(N);
6907 
6908   // If the MLOAD result requires splitting and the mask is provided by a
6909   // SETCC, then split both nodes and its operands before legalization. This
6910   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6911   // and enables future optimizations (e.g. min/max pattern matching on X86).
6912   if (Mask.getOpcode() == ISD::SETCC) {
6913     EVT VT = N->getValueType(0);
6914 
6915     // Check if any splitting is required.
6916     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6917         TargetLowering::TypeSplitVector)
6918       return SDValue();
6919 
6920     SDValue MaskLo, MaskHi, Lo, Hi;
6921     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6922 
6923     SDValue Src0 = MLD->getSrc0();
6924     SDValue Src0Lo, Src0Hi;
6925     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6926 
6927     EVT LoVT, HiVT;
6928     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6929 
6930     SDValue Chain = MLD->getChain();
6931     SDValue Ptr   = MLD->getBasePtr();
6932     EVT MemoryVT = MLD->getMemoryVT();
6933     unsigned Alignment = MLD->getOriginalAlignment();
6934 
6935     // if Alignment is equal to the vector size,
6936     // take the half of it for the second part
6937     unsigned SecondHalfAlignment =
6938       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6939          Alignment/2 : Alignment;
6940 
6941     EVT LoMemVT, HiMemVT;
6942     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6943 
6944     MachineMemOperand *MMO = DAG.getMachineFunction().
6945     getMachineMemOperand(MLD->getPointerInfo(),
6946                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6947                          Alignment, MLD->getAAInfo(), MLD->getRanges());
6948 
6949     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6950                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6951 
6952     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6953                                      MLD->isExpandingLoad());
6954 
6955     MMO = DAG.getMachineFunction().
6956     getMachineMemOperand(MLD->getPointerInfo(),
6957                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
6958                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6959 
6960     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6961                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6962 
6963     AddToWorklist(Lo.getNode());
6964     AddToWorklist(Hi.getNode());
6965 
6966     // Build a factor node to remember that this load is independent of the
6967     // other one.
6968     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6969                         Hi.getValue(1));
6970 
6971     // Legalized the chain result - switch anything that used the old chain to
6972     // use the new one.
6973     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6974 
6975     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6976 
6977     SDValue RetOps[] = { LoadRes, Chain };
6978     return DAG.getMergeValues(RetOps, DL);
6979   }
6980   return SDValue();
6981 }
6982 
6983 /// A vector select of 2 constant vectors can be simplified to math/logic to
6984 /// avoid a variable select instruction and possibly avoid constant loads.
6985 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
6986   SDValue Cond = N->getOperand(0);
6987   SDValue N1 = N->getOperand(1);
6988   SDValue N2 = N->getOperand(2);
6989   EVT VT = N->getValueType(0);
6990   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
6991       !TLI.convertSelectOfConstantsToMath(VT) ||
6992       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
6993       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
6994     return SDValue();
6995 
6996   // Check if we can use the condition value to increment/decrement a single
6997   // constant value. This simplifies a select to an add and removes a constant
6998   // load/materialization from the general case.
6999   bool AllAddOne = true;
7000   bool AllSubOne = true;
7001   unsigned Elts = VT.getVectorNumElements();
7002   for (unsigned i = 0; i != Elts; ++i) {
7003     SDValue N1Elt = N1.getOperand(i);
7004     SDValue N2Elt = N2.getOperand(i);
7005     if (N1Elt.isUndef() || N2Elt.isUndef())
7006       continue;
7007 
7008     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
7009     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7010     if (C1 != C2 + 1)
7011       AllAddOne = false;
7012     if (C1 != C2 - 1)
7013       AllSubOne = false;
7014   }
7015 
7016   // Further simplifications for the extra-special cases where the constants are
7017   // all 0 or all -1 should be implemented as folds of these patterns.
7018   SDLoc DL(N);
7019   if (AllAddOne || AllSubOne) {
7020     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7021     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7022     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7023     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7024     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7025   }
7026 
7027   // The general case for select-of-constants:
7028   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7029   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7030   // leave that to a machine-specific pass.
7031   return SDValue();
7032 }
7033 
7034 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7035   SDValue N0 = N->getOperand(0);
7036   SDValue N1 = N->getOperand(1);
7037   SDValue N2 = N->getOperand(2);
7038   SDLoc DL(N);
7039 
7040   // fold (vselect C, X, X) -> X
7041   if (N1 == N2)
7042     return N1;
7043 
7044   // Canonicalize integer abs.
7045   // vselect (setg[te] X,  0),  X, -X ->
7046   // vselect (setgt    X, -1),  X, -X ->
7047   // vselect (setl[te] X,  0), -X,  X ->
7048   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7049   if (N0.getOpcode() == ISD::SETCC) {
7050     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7051     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7052     bool isAbs = false;
7053     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7054 
7055     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7056          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7057         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7058       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7059     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7060              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7061       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7062 
7063     if (isAbs) {
7064       EVT VT = LHS.getValueType();
7065       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7066         return DAG.getNode(ISD::ABS, DL, VT, LHS);
7067 
7068       SDValue Shift = DAG.getNode(
7069           ISD::SRA, DL, VT, LHS,
7070           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7071       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7072       AddToWorklist(Shift.getNode());
7073       AddToWorklist(Add.getNode());
7074       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7075     }
7076   }
7077 
7078   if (SimplifySelectOps(N, N1, N2))
7079     return SDValue(N, 0);  // Don't revisit N.
7080 
7081   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7082   if (ISD::isBuildVectorAllOnes(N0.getNode()))
7083     return N1;
7084   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7085   if (ISD::isBuildVectorAllZeros(N0.getNode()))
7086     return N2;
7087 
7088   // The ConvertSelectToConcatVector function is assuming both the above
7089   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7090   // and addressed.
7091   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7092       N2.getOpcode() == ISD::CONCAT_VECTORS &&
7093       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7094     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7095       return CV;
7096   }
7097 
7098   if (SDValue V = foldVSelectOfConstants(N))
7099     return V;
7100 
7101   return SDValue();
7102 }
7103 
7104 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7105   SDValue N0 = N->getOperand(0);
7106   SDValue N1 = N->getOperand(1);
7107   SDValue N2 = N->getOperand(2);
7108   SDValue N3 = N->getOperand(3);
7109   SDValue N4 = N->getOperand(4);
7110   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7111 
7112   // fold select_cc lhs, rhs, x, x, cc -> x
7113   if (N2 == N3)
7114     return N2;
7115 
7116   // Determine if the condition we're dealing with is constant
7117   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7118                                   CC, SDLoc(N), false)) {
7119     AddToWorklist(SCC.getNode());
7120 
7121     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7122       if (!SCCC->isNullValue())
7123         return N2;    // cond always true -> true val
7124       else
7125         return N3;    // cond always false -> false val
7126     } else if (SCC->isUndef()) {
7127       // When the condition is UNDEF, just return the first operand. This is
7128       // coherent the DAG creation, no setcc node is created in this case
7129       return N2;
7130     } else if (SCC.getOpcode() == ISD::SETCC) {
7131       // Fold to a simpler select_cc
7132       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7133                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7134                          SCC.getOperand(2));
7135     }
7136   }
7137 
7138   // If we can fold this based on the true/false value, do so.
7139   if (SimplifySelectOps(N, N2, N3))
7140     return SDValue(N, 0);  // Don't revisit N.
7141 
7142   // fold select_cc into other things, such as min/max/abs
7143   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7144 }
7145 
7146 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7147   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
7148                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
7149                        SDLoc(N));
7150 }
7151 
7152 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7153   SDValue LHS = N->getOperand(0);
7154   SDValue RHS = N->getOperand(1);
7155   SDValue Carry = N->getOperand(2);
7156   SDValue Cond = N->getOperand(3);
7157 
7158   // If Carry is false, fold to a regular SETCC.
7159   if (Carry.getOpcode() == ISD::CARRY_FALSE)
7160     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7161 
7162   return SDValue();
7163 }
7164 
7165 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7166   SDValue LHS = N->getOperand(0);
7167   SDValue RHS = N->getOperand(1);
7168   SDValue Carry = N->getOperand(2);
7169   SDValue Cond = N->getOperand(3);
7170 
7171   // If Carry is false, fold to a regular SETCC.
7172   if (isNullConstant(Carry))
7173     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7174 
7175   return SDValue();
7176 }
7177 
7178 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7179 /// a build_vector of constants.
7180 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7181 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7182 /// Vector extends are not folded if operations are legal; this is to
7183 /// avoid introducing illegal build_vector dag nodes.
7184 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7185                                          SelectionDAG &DAG, bool LegalTypes,
7186                                          bool LegalOperations) {
7187   unsigned Opcode = N->getOpcode();
7188   SDValue N0 = N->getOperand(0);
7189   EVT VT = N->getValueType(0);
7190 
7191   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7192          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7193          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7194          && "Expected EXTEND dag node in input!");
7195 
7196   // fold (sext c1) -> c1
7197   // fold (zext c1) -> c1
7198   // fold (aext c1) -> c1
7199   if (isa<ConstantSDNode>(N0))
7200     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7201 
7202   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7203   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7204   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7205   EVT SVT = VT.getScalarType();
7206   if (!(VT.isVector() &&
7207       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7208       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7209     return nullptr;
7210 
7211   // We can fold this node into a build_vector.
7212   unsigned VTBits = SVT.getSizeInBits();
7213   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7214   SmallVector<SDValue, 8> Elts;
7215   unsigned NumElts = VT.getVectorNumElements();
7216   SDLoc DL(N);
7217 
7218   for (unsigned i=0; i != NumElts; ++i) {
7219     SDValue Op = N0->getOperand(i);
7220     if (Op->isUndef()) {
7221       Elts.push_back(DAG.getUNDEF(SVT));
7222       continue;
7223     }
7224 
7225     SDLoc DL(Op);
7226     // Get the constant value and if needed trunc it to the size of the type.
7227     // Nodes like build_vector might have constants wider than the scalar type.
7228     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7229     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7230       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7231     else
7232       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7233   }
7234 
7235   return DAG.getBuildVector(VT, DL, Elts).getNode();
7236 }
7237 
7238 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7239 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7240 // transformation. Returns true if extension are possible and the above
7241 // mentioned transformation is profitable.
7242 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
7243                                     unsigned ExtOpc,
7244                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7245                                     const TargetLowering &TLI) {
7246   bool HasCopyToRegUses = false;
7247   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
7248   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7249                             UE = N0.getNode()->use_end();
7250        UI != UE; ++UI) {
7251     SDNode *User = *UI;
7252     if (User == N)
7253       continue;
7254     if (UI.getUse().getResNo() != N0.getResNo())
7255       continue;
7256     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7257     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7258       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7259       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7260         // Sign bits will be lost after a zext.
7261         return false;
7262       bool Add = false;
7263       for (unsigned i = 0; i != 2; ++i) {
7264         SDValue UseOp = User->getOperand(i);
7265         if (UseOp == N0)
7266           continue;
7267         if (!isa<ConstantSDNode>(UseOp))
7268           return false;
7269         Add = true;
7270       }
7271       if (Add)
7272         ExtendNodes.push_back(User);
7273       continue;
7274     }
7275     // If truncates aren't free and there are users we can't
7276     // extend, it isn't worthwhile.
7277     if (!isTruncFree)
7278       return false;
7279     // Remember if this value is live-out.
7280     if (User->getOpcode() == ISD::CopyToReg)
7281       HasCopyToRegUses = true;
7282   }
7283 
7284   if (HasCopyToRegUses) {
7285     bool BothLiveOut = false;
7286     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7287          UI != UE; ++UI) {
7288       SDUse &Use = UI.getUse();
7289       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7290         BothLiveOut = true;
7291         break;
7292       }
7293     }
7294     if (BothLiveOut)
7295       // Both unextended and extended values are live out. There had better be
7296       // a good reason for the transformation.
7297       return ExtendNodes.size();
7298   }
7299   return true;
7300 }
7301 
7302 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7303                                   SDValue Trunc, SDValue ExtLoad,
7304                                   const SDLoc &DL, ISD::NodeType ExtType) {
7305   // Extend SetCC uses if necessary.
7306   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7307     SDNode *SetCC = SetCCs[i];
7308     SmallVector<SDValue, 4> Ops;
7309 
7310     for (unsigned j = 0; j != 2; ++j) {
7311       SDValue SOp = SetCC->getOperand(j);
7312       if (SOp == Trunc)
7313         Ops.push_back(ExtLoad);
7314       else
7315         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7316     }
7317 
7318     Ops.push_back(SetCC->getOperand(2));
7319     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7320   }
7321 }
7322 
7323 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7324 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7325   SDValue N0 = N->getOperand(0);
7326   EVT DstVT = N->getValueType(0);
7327   EVT SrcVT = N0.getValueType();
7328 
7329   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7330           N->getOpcode() == ISD::ZERO_EXTEND) &&
7331          "Unexpected node type (not an extend)!");
7332 
7333   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7334   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7335   //   (v8i32 (sext (v8i16 (load x))))
7336   // into:
7337   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7338   //                          (v4i32 (sextload (x + 16)))))
7339   // Where uses of the original load, i.e.:
7340   //   (v8i16 (load x))
7341   // are replaced with:
7342   //   (v8i16 (truncate
7343   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7344   //                            (v4i32 (sextload (x + 16)))))))
7345   //
7346   // This combine is only applicable to illegal, but splittable, vectors.
7347   // All legal types, and illegal non-vector types, are handled elsewhere.
7348   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7349   //
7350   if (N0->getOpcode() != ISD::LOAD)
7351     return SDValue();
7352 
7353   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7354 
7355   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7356       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7357       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7358     return SDValue();
7359 
7360   SmallVector<SDNode *, 4> SetCCs;
7361   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
7362     return SDValue();
7363 
7364   ISD::LoadExtType ExtType =
7365       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7366 
7367   // Try to split the vector types to get down to legal types.
7368   EVT SplitSrcVT = SrcVT;
7369   EVT SplitDstVT = DstVT;
7370   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7371          SplitSrcVT.getVectorNumElements() > 1) {
7372     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7373     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7374   }
7375 
7376   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7377     return SDValue();
7378 
7379   SDLoc DL(N);
7380   const unsigned NumSplits =
7381       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7382   const unsigned Stride = SplitSrcVT.getStoreSize();
7383   SmallVector<SDValue, 4> Loads;
7384   SmallVector<SDValue, 4> Chains;
7385 
7386   SDValue BasePtr = LN0->getBasePtr();
7387   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7388     const unsigned Offset = Idx * Stride;
7389     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7390 
7391     SDValue SplitLoad = DAG.getExtLoad(
7392         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7393         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7394         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7395 
7396     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7397                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7398 
7399     Loads.push_back(SplitLoad.getValue(0));
7400     Chains.push_back(SplitLoad.getValue(1));
7401   }
7402 
7403   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7404   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7405 
7406   // Simplify TF.
7407   AddToWorklist(NewChain.getNode());
7408 
7409   CombineTo(N, NewValue);
7410 
7411   // Replace uses of the original load (before extension)
7412   // with a truncate of the concatenated sextloaded vectors.
7413   SDValue Trunc =
7414       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7415   CombineTo(N0.getNode(), Trunc, NewChain);
7416   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7417                   (ISD::NodeType)N->getOpcode());
7418   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7419 }
7420 
7421 /// If we're narrowing or widening the result of a vector select and the final
7422 /// size is the same size as a setcc (compare) feeding the select, then try to
7423 /// apply the cast operation to the select's operands because matching vector
7424 /// sizes for a select condition and other operands should be more efficient.
7425 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7426   unsigned CastOpcode = Cast->getOpcode();
7427   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7428           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7429           CastOpcode == ISD::FP_ROUND) &&
7430          "Unexpected opcode for vector select narrowing/widening");
7431 
7432   // We only do this transform before legal ops because the pattern may be
7433   // obfuscated by target-specific operations after legalization. Do not create
7434   // an illegal select op, however, because that may be difficult to lower.
7435   EVT VT = Cast->getValueType(0);
7436   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7437     return SDValue();
7438 
7439   SDValue VSel = Cast->getOperand(0);
7440   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7441       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7442     return SDValue();
7443 
7444   // Does the setcc have the same vector size as the casted select?
7445   SDValue SetCC = VSel.getOperand(0);
7446   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7447   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7448     return SDValue();
7449 
7450   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7451   SDValue A = VSel.getOperand(1);
7452   SDValue B = VSel.getOperand(2);
7453   SDValue CastA, CastB;
7454   SDLoc DL(Cast);
7455   if (CastOpcode == ISD::FP_ROUND) {
7456     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7457     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7458     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7459   } else {
7460     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7461     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7462   }
7463   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7464 }
7465 
7466 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7467   SDValue N0 = N->getOperand(0);
7468   EVT VT = N->getValueType(0);
7469   SDLoc DL(N);
7470 
7471   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7472                                               LegalOperations))
7473     return SDValue(Res, 0);
7474 
7475   // fold (sext (sext x)) -> (sext x)
7476   // fold (sext (aext x)) -> (sext x)
7477   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7478     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7479 
7480   if (N0.getOpcode() == ISD::TRUNCATE) {
7481     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7482     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7483     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7484       SDNode *oye = N0.getOperand(0).getNode();
7485       if (NarrowLoad.getNode() != N0.getNode()) {
7486         CombineTo(N0.getNode(), NarrowLoad);
7487         // CombineTo deleted the truncate, if needed, but not what's under it.
7488         AddToWorklist(oye);
7489       }
7490       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7491     }
7492 
7493     // See if the value being truncated is already sign extended.  If so, just
7494     // eliminate the trunc/sext pair.
7495     SDValue Op = N0.getOperand(0);
7496     unsigned OpBits   = Op.getScalarValueSizeInBits();
7497     unsigned MidBits  = N0.getScalarValueSizeInBits();
7498     unsigned DestBits = VT.getScalarSizeInBits();
7499     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7500 
7501     if (OpBits == DestBits) {
7502       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7503       // bits, it is already ready.
7504       if (NumSignBits > DestBits-MidBits)
7505         return Op;
7506     } else if (OpBits < DestBits) {
7507       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7508       // bits, just sext from i32.
7509       if (NumSignBits > OpBits-MidBits)
7510         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7511     } else {
7512       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7513       // bits, just truncate to i32.
7514       if (NumSignBits > OpBits-MidBits)
7515         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7516     }
7517 
7518     // fold (sext (truncate x)) -> (sextinreg x).
7519     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7520                                                  N0.getValueType())) {
7521       if (OpBits < DestBits)
7522         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7523       else if (OpBits > DestBits)
7524         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7525       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7526                          DAG.getValueType(N0.getValueType()));
7527     }
7528   }
7529 
7530   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7531   // Only generate vector extloads when 1) they're legal, and 2) they are
7532   // deemed desirable by the target.
7533   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7534       ((!LegalOperations && !VT.isVector() &&
7535         !cast<LoadSDNode>(N0)->isVolatile()) ||
7536        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7537     bool DoXform = true;
7538     SmallVector<SDNode*, 4> SetCCs;
7539     if (!N0.hasOneUse())
7540       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7541     if (VT.isVector())
7542       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7543     if (DoXform) {
7544       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7545       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7546                                        LN0->getBasePtr(), N0.getValueType(),
7547                                        LN0->getMemOperand());
7548       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7549                                   N0.getValueType(), ExtLoad);
7550       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7551       // If the load value is used only by N, replace it via CombineTo N.
7552       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7553       CombineTo(N, ExtLoad);
7554       if (NoReplaceTrunc)
7555         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7556       else
7557         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7558       return SDValue(N, 0);
7559     }
7560   }
7561 
7562   // fold (sext (load x)) to multiple smaller sextloads.
7563   // Only on illegal but splittable vectors.
7564   if (SDValue ExtLoad = CombineExtLoad(N))
7565     return ExtLoad;
7566 
7567   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7568   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7569   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7570       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7571     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7572     EVT MemVT = LN0->getMemoryVT();
7573     if ((!LegalOperations && !LN0->isVolatile()) ||
7574         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7575       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7576                                        LN0->getBasePtr(), MemVT,
7577                                        LN0->getMemOperand());
7578       CombineTo(N, ExtLoad);
7579       CombineTo(N0.getNode(),
7580                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7581                             N0.getValueType(), ExtLoad),
7582                 ExtLoad.getValue(1));
7583       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7584     }
7585   }
7586 
7587   // fold (sext (and/or/xor (load x), cst)) ->
7588   //      (and/or/xor (sextload x), (sext cst))
7589   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7590        N0.getOpcode() == ISD::XOR) &&
7591       isa<LoadSDNode>(N0.getOperand(0)) &&
7592       N0.getOperand(1).getOpcode() == ISD::Constant &&
7593       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7594       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7595     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7596     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7597       bool DoXform = true;
7598       SmallVector<SDNode*, 4> SetCCs;
7599       if (!N0.hasOneUse())
7600         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7601                                           SetCCs, TLI);
7602       if (DoXform) {
7603         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7604                                          LN0->getChain(), LN0->getBasePtr(),
7605                                          LN0->getMemoryVT(),
7606                                          LN0->getMemOperand());
7607         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7608         Mask = Mask.sext(VT.getSizeInBits());
7609         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7610                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7611         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7612                                     SDLoc(N0.getOperand(0)),
7613                                     N0.getOperand(0).getValueType(), ExtLoad);
7614         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7615         bool NoReplaceTruncAnd = !N0.hasOneUse();
7616         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7617         CombineTo(N, And);
7618         // If N0 has multiple uses, change other uses as well.
7619         if (NoReplaceTruncAnd) {
7620           SDValue TruncAnd =
7621               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7622           CombineTo(N0.getNode(), TruncAnd);
7623         }
7624         if (NoReplaceTrunc)
7625           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7626         else
7627           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7628         return SDValue(N,0); // Return N so it doesn't get rechecked!
7629       }
7630     }
7631   }
7632 
7633   if (N0.getOpcode() == ISD::SETCC) {
7634     SDValue N00 = N0.getOperand(0);
7635     SDValue N01 = N0.getOperand(1);
7636     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7637     EVT N00VT = N0.getOperand(0).getValueType();
7638 
7639     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7640     // Only do this before legalize for now.
7641     if (VT.isVector() && !LegalOperations &&
7642         TLI.getBooleanContents(N00VT) ==
7643             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7644       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7645       // of the same size as the compared operands. Only optimize sext(setcc())
7646       // if this is the case.
7647       EVT SVT = getSetCCResultType(N00VT);
7648 
7649       // We know that the # elements of the results is the same as the
7650       // # elements of the compare (and the # elements of the compare result
7651       // for that matter).  Check to see that they are the same size.  If so,
7652       // we know that the element size of the sext'd result matches the
7653       // element size of the compare operands.
7654       if (VT.getSizeInBits() == SVT.getSizeInBits())
7655         return DAG.getSetCC(DL, VT, N00, N01, CC);
7656 
7657       // If the desired elements are smaller or larger than the source
7658       // elements, we can use a matching integer vector type and then
7659       // truncate/sign extend.
7660       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7661       if (SVT == MatchingVecType) {
7662         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7663         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7664       }
7665     }
7666 
7667     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7668     // Here, T can be 1 or -1, depending on the type of the setcc and
7669     // getBooleanContents().
7670     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7671 
7672     // To determine the "true" side of the select, we need to know the high bit
7673     // of the value returned by the setcc if it evaluates to true.
7674     // If the type of the setcc is i1, then the true case of the select is just
7675     // sext(i1 1), that is, -1.
7676     // If the type of the setcc is larger (say, i8) then the value of the high
7677     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7678     // of the appropriate width.
7679     SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7680                                            : TLI.getConstTrueVal(DAG, VT, DL);
7681     SDValue Zero = DAG.getConstant(0, DL, VT);
7682     if (SDValue SCC =
7683             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7684       return SCC;
7685 
7686     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7687       EVT SetCCVT = getSetCCResultType(N00VT);
7688       // Don't do this transform for i1 because there's a select transform
7689       // that would reverse it.
7690       // TODO: We should not do this transform at all without a target hook
7691       // because a sext is likely cheaper than a select?
7692       if (SetCCVT.getScalarSizeInBits() != 1 &&
7693           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7694         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7695         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7696       }
7697     }
7698   }
7699 
7700   // fold (sext x) -> (zext x) if the sign bit is known zero.
7701   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7702       DAG.SignBitIsZero(N0))
7703     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7704 
7705   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7706     return NewVSel;
7707 
7708   return SDValue();
7709 }
7710 
7711 // isTruncateOf - If N is a truncate of some other value, return true, record
7712 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7713 // This function computes KnownBits to avoid a duplicated call to
7714 // computeKnownBits in the caller.
7715 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7716                          KnownBits &Known) {
7717   if (N->getOpcode() == ISD::TRUNCATE) {
7718     Op = N->getOperand(0);
7719     DAG.computeKnownBits(Op, Known);
7720     return true;
7721   }
7722 
7723   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7724       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7725     return false;
7726 
7727   SDValue Op0 = N->getOperand(0);
7728   SDValue Op1 = N->getOperand(1);
7729   assert(Op0.getValueType() == Op1.getValueType());
7730 
7731   if (isNullConstant(Op0))
7732     Op = Op1;
7733   else if (isNullConstant(Op1))
7734     Op = Op0;
7735   else
7736     return false;
7737 
7738   DAG.computeKnownBits(Op, Known);
7739 
7740   if (!(Known.Zero | 1).isAllOnesValue())
7741     return false;
7742 
7743   return true;
7744 }
7745 
7746 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7747   SDValue N0 = N->getOperand(0);
7748   EVT VT = N->getValueType(0);
7749 
7750   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7751                                               LegalOperations))
7752     return SDValue(Res, 0);
7753 
7754   // fold (zext (zext x)) -> (zext x)
7755   // fold (zext (aext x)) -> (zext x)
7756   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7757     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7758                        N0.getOperand(0));
7759 
7760   // fold (zext (truncate x)) -> (zext x) or
7761   //      (zext (truncate x)) -> (truncate x)
7762   // This is valid when the truncated bits of x are already zero.
7763   // FIXME: We should extend this to work for vectors too.
7764   SDValue Op;
7765   KnownBits Known;
7766   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7767     APInt TruncatedBits =
7768       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7769       APInt(Op.getValueSizeInBits(), 0) :
7770       APInt::getBitsSet(Op.getValueSizeInBits(),
7771                         N0.getValueSizeInBits(),
7772                         std::min(Op.getValueSizeInBits(),
7773                                  VT.getSizeInBits()));
7774     if (TruncatedBits.isSubsetOf(Known.Zero))
7775       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7776   }
7777 
7778   // fold (zext (truncate x)) -> (and x, mask)
7779   if (N0.getOpcode() == ISD::TRUNCATE) {
7780     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7781     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7782     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7783       SDNode *oye = N0.getOperand(0).getNode();
7784       if (NarrowLoad.getNode() != N0.getNode()) {
7785         CombineTo(N0.getNode(), NarrowLoad);
7786         // CombineTo deleted the truncate, if needed, but not what's under it.
7787         AddToWorklist(oye);
7788       }
7789       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7790     }
7791 
7792     EVT SrcVT = N0.getOperand(0).getValueType();
7793     EVT MinVT = N0.getValueType();
7794 
7795     // Try to mask before the extension to avoid having to generate a larger mask,
7796     // possibly over several sub-vectors.
7797     if (SrcVT.bitsLT(VT)) {
7798       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7799                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7800         SDValue Op = N0.getOperand(0);
7801         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7802         AddToWorklist(Op.getNode());
7803         SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7804         // Transfer the debug info; the new node is equivalent to N0.
7805         DAG.transferDbgValues(N0, ZExtOrTrunc);
7806         return ZExtOrTrunc;
7807       }
7808     }
7809 
7810     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7811       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7812       AddToWorklist(Op.getNode());
7813       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7814       // We may safely transfer the debug info describing the truncate node over
7815       // to the equivalent and operation.
7816       DAG.transferDbgValues(N0, And);
7817       return And;
7818     }
7819   }
7820 
7821   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7822   // if either of the casts is not free.
7823   if (N0.getOpcode() == ISD::AND &&
7824       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7825       N0.getOperand(1).getOpcode() == ISD::Constant &&
7826       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7827                            N0.getValueType()) ||
7828        !TLI.isZExtFree(N0.getValueType(), VT))) {
7829     SDValue X = N0.getOperand(0).getOperand(0);
7830     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7831     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7832     Mask = Mask.zext(VT.getSizeInBits());
7833     SDLoc DL(N);
7834     return DAG.getNode(ISD::AND, DL, VT,
7835                        X, DAG.getConstant(Mask, DL, VT));
7836   }
7837 
7838   // fold (zext (load x)) -> (zext (truncate (zextload x)))
7839   // Only generate vector extloads when 1) they're legal, and 2) they are
7840   // deemed desirable by the target.
7841   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7842       ((!LegalOperations && !VT.isVector() &&
7843         !cast<LoadSDNode>(N0)->isVolatile()) ||
7844        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7845     bool DoXform = true;
7846     SmallVector<SDNode*, 4> SetCCs;
7847     if (!N0.hasOneUse())
7848       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7849     if (VT.isVector())
7850       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7851     if (DoXform) {
7852       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7853       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7854                                        LN0->getChain(),
7855                                        LN0->getBasePtr(), N0.getValueType(),
7856                                        LN0->getMemOperand());
7857 
7858       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7859                                   N0.getValueType(), ExtLoad);
7860       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7861       // If the load value is used only by N, replace it via CombineTo N.
7862       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7863       CombineTo(N, ExtLoad);
7864       if (NoReplaceTrunc)
7865         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7866       else
7867         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7868       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7869     }
7870   }
7871 
7872   // fold (zext (load x)) to multiple smaller zextloads.
7873   // Only on illegal but splittable vectors.
7874   if (SDValue ExtLoad = CombineExtLoad(N))
7875     return ExtLoad;
7876 
7877   // fold (zext (and/or/xor (load x), cst)) ->
7878   //      (and/or/xor (zextload x), (zext cst))
7879   // Unless (and (load x) cst) will match as a zextload already and has
7880   // additional users.
7881   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7882        N0.getOpcode() == ISD::XOR) &&
7883       isa<LoadSDNode>(N0.getOperand(0)) &&
7884       N0.getOperand(1).getOpcode() == ISD::Constant &&
7885       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7886       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7887     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7888     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7889       bool DoXform = true;
7890       SmallVector<SDNode*, 4> SetCCs;
7891       if (!N0.hasOneUse()) {
7892         if (N0.getOpcode() == ISD::AND) {
7893           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7894           EVT LoadResultTy = AndC->getValueType(0);
7895           EVT ExtVT;
7896           if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT))
7897             DoXform = false;
7898         }
7899         if (DoXform)
7900           DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7901                                             ISD::ZERO_EXTEND, SetCCs, TLI);
7902       }
7903       if (DoXform) {
7904         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7905                                          LN0->getChain(), LN0->getBasePtr(),
7906                                          LN0->getMemoryVT(),
7907                                          LN0->getMemOperand());
7908         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7909         Mask = Mask.zext(VT.getSizeInBits());
7910         SDLoc DL(N);
7911         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7912                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7913         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7914                                     SDLoc(N0.getOperand(0)),
7915                                     N0.getOperand(0).getValueType(), ExtLoad);
7916         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7917         bool NoReplaceTruncAnd = !N0.hasOneUse();
7918         bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7919         CombineTo(N, And);
7920         // If N0 has multiple uses, change other uses as well.
7921         if (NoReplaceTruncAnd) {
7922           SDValue TruncAnd =
7923               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7924           CombineTo(N0.getNode(), TruncAnd);
7925         }
7926         if (NoReplaceTrunc)
7927           DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7928         else
7929           CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7930         return SDValue(N,0); // Return N so it doesn't get rechecked!
7931       }
7932     }
7933   }
7934 
7935   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7936   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7937   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7938       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7939     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7940     EVT MemVT = LN0->getMemoryVT();
7941     if ((!LegalOperations && !LN0->isVolatile()) ||
7942         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7943       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7944                                        LN0->getChain(),
7945                                        LN0->getBasePtr(), MemVT,
7946                                        LN0->getMemOperand());
7947       CombineTo(N, ExtLoad);
7948       CombineTo(N0.getNode(),
7949                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7950                             ExtLoad),
7951                 ExtLoad.getValue(1));
7952       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7953     }
7954   }
7955 
7956   if (N0.getOpcode() == ISD::SETCC) {
7957     // Only do this before legalize for now.
7958     if (!LegalOperations && VT.isVector() &&
7959         N0.getValueType().getVectorElementType() == MVT::i1) {
7960       EVT N00VT = N0.getOperand(0).getValueType();
7961       if (getSetCCResultType(N00VT) == N0.getValueType())
7962         return SDValue();
7963 
7964       // We know that the # elements of the results is the same as the #
7965       // elements of the compare (and the # elements of the compare result for
7966       // that matter). Check to see that they are the same size. If so, we know
7967       // that the element size of the sext'd result matches the element size of
7968       // the compare operands.
7969       SDLoc DL(N);
7970       SDValue VecOnes = DAG.getConstant(1, DL, VT);
7971       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7972         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7973         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7974                                      N0.getOperand(1), N0.getOperand(2));
7975         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7976       }
7977 
7978       // If the desired elements are smaller or larger than the source
7979       // elements we can use a matching integer vector type and then
7980       // truncate/sign extend.
7981       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
7982       SDValue VsetCC =
7983           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7984                       N0.getOperand(1), N0.getOperand(2));
7985       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7986                          VecOnes);
7987     }
7988 
7989     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7990     SDLoc DL(N);
7991     if (SDValue SCC = SimplifySelectCC(
7992             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7993             DAG.getConstant(0, DL, VT),
7994             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7995       return SCC;
7996   }
7997 
7998   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7999   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
8000       isa<ConstantSDNode>(N0.getOperand(1)) &&
8001       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
8002       N0.hasOneUse()) {
8003     SDValue ShAmt = N0.getOperand(1);
8004     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8005     if (N0.getOpcode() == ISD::SHL) {
8006       SDValue InnerZExt = N0.getOperand(0);
8007       // If the original shl may be shifting out bits, do not perform this
8008       // transformation.
8009       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
8010         InnerZExt.getOperand(0).getValueSizeInBits();
8011       if (ShAmtVal > KnownZeroBits)
8012         return SDValue();
8013     }
8014 
8015     SDLoc DL(N);
8016 
8017     // Ensure that the shift amount is wide enough for the shifted value.
8018     if (VT.getSizeInBits() >= 256)
8019       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8020 
8021     return DAG.getNode(N0.getOpcode(), DL, VT,
8022                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8023                        ShAmt);
8024   }
8025 
8026   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8027     return NewVSel;
8028 
8029   return SDValue();
8030 }
8031 
8032 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8033   SDValue N0 = N->getOperand(0);
8034   EVT VT = N->getValueType(0);
8035 
8036   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8037                                               LegalOperations))
8038     return SDValue(Res, 0);
8039 
8040   // fold (aext (aext x)) -> (aext x)
8041   // fold (aext (zext x)) -> (zext x)
8042   // fold (aext (sext x)) -> (sext x)
8043   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
8044       N0.getOpcode() == ISD::ZERO_EXTEND ||
8045       N0.getOpcode() == ISD::SIGN_EXTEND)
8046     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8047 
8048   // fold (aext (truncate (load x))) -> (aext (smaller load x))
8049   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8050   if (N0.getOpcode() == ISD::TRUNCATE) {
8051     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8052       SDNode *oye = N0.getOperand(0).getNode();
8053       if (NarrowLoad.getNode() != N0.getNode()) {
8054         CombineTo(N0.getNode(), NarrowLoad);
8055         // CombineTo deleted the truncate, if needed, but not what's under it.
8056         AddToWorklist(oye);
8057       }
8058       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8059     }
8060   }
8061 
8062   // fold (aext (truncate x))
8063   if (N0.getOpcode() == ISD::TRUNCATE)
8064     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8065 
8066   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8067   // if the trunc is not free.
8068   if (N0.getOpcode() == ISD::AND &&
8069       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8070       N0.getOperand(1).getOpcode() == ISD::Constant &&
8071       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8072                           N0.getValueType())) {
8073     SDLoc DL(N);
8074     SDValue X = N0.getOperand(0).getOperand(0);
8075     X = DAG.getAnyExtOrTrunc(X, DL, VT);
8076     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8077     Mask = Mask.zext(VT.getSizeInBits());
8078     return DAG.getNode(ISD::AND, DL, VT,
8079                        X, DAG.getConstant(Mask, DL, VT));
8080   }
8081 
8082   // fold (aext (load x)) -> (aext (truncate (extload x)))
8083   // None of the supported targets knows how to perform load and any_ext
8084   // on vectors in one instruction.  We only perform this transformation on
8085   // scalars.
8086   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8087       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8088       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8089     bool DoXform = true;
8090     SmallVector<SDNode*, 4> SetCCs;
8091     if (!N0.hasOneUse())
8092       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
8093     if (DoXform) {
8094       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8095       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8096                                        LN0->getChain(),
8097                                        LN0->getBasePtr(), N0.getValueType(),
8098                                        LN0->getMemOperand());
8099       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8100                                   N0.getValueType(), ExtLoad);
8101       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
8102                       ISD::ANY_EXTEND);
8103       // If the load value is used only by N, replace it via CombineTo N.
8104       bool NoReplaceTrunc = N0.hasOneUse();
8105       CombineTo(N, ExtLoad);
8106       if (NoReplaceTrunc)
8107         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8108       else
8109         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8110       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8111     }
8112   }
8113 
8114   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8115   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8116   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
8117   if (N0.getOpcode() == ISD::LOAD &&
8118       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8119       N0.hasOneUse()) {
8120     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8121     ISD::LoadExtType ExtType = LN0->getExtensionType();
8122     EVT MemVT = LN0->getMemoryVT();
8123     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8124       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8125                                        VT, LN0->getChain(), LN0->getBasePtr(),
8126                                        MemVT, LN0->getMemOperand());
8127       CombineTo(N, ExtLoad);
8128       CombineTo(N0.getNode(),
8129                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8130                             N0.getValueType(), ExtLoad),
8131                 ExtLoad.getValue(1));
8132       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8133     }
8134   }
8135 
8136   if (N0.getOpcode() == ISD::SETCC) {
8137     // For vectors:
8138     // aext(setcc) -> vsetcc
8139     // aext(setcc) -> truncate(vsetcc)
8140     // aext(setcc) -> aext(vsetcc)
8141     // Only do this before legalize for now.
8142     if (VT.isVector() && !LegalOperations) {
8143       EVT N00VT = N0.getOperand(0).getValueType();
8144       if (getSetCCResultType(N00VT) == N0.getValueType())
8145         return SDValue();
8146 
8147       // We know that the # elements of the results is the same as the
8148       // # elements of the compare (and the # elements of the compare result
8149       // for that matter).  Check to see that they are the same size.  If so,
8150       // we know that the element size of the sext'd result matches the
8151       // element size of the compare operands.
8152       if (VT.getSizeInBits() == N00VT.getSizeInBits())
8153         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8154                              N0.getOperand(1),
8155                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
8156       // If the desired elements are smaller or larger than the source
8157       // elements we can use a matching integer vector type and then
8158       // truncate/any extend
8159       else {
8160         EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8161         SDValue VsetCC =
8162           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8163                         N0.getOperand(1),
8164                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
8165         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8166       }
8167     }
8168 
8169     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8170     SDLoc DL(N);
8171     if (SDValue SCC = SimplifySelectCC(
8172             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8173             DAG.getConstant(0, DL, VT),
8174             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8175       return SCC;
8176   }
8177 
8178   return SDValue();
8179 }
8180 
8181 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8182   unsigned Opcode = N->getOpcode();
8183   SDValue N0 = N->getOperand(0);
8184   SDValue N1 = N->getOperand(1);
8185   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8186 
8187   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8188   if (N0.getOpcode() == Opcode &&
8189       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8190     return N0;
8191 
8192   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8193       N0.getOperand(0).getOpcode() == Opcode) {
8194     // We have an assert, truncate, assert sandwich. Make one stronger assert
8195     // by asserting on the smallest asserted type to the larger source type.
8196     // This eliminates the later assert:
8197     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8198     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8199     SDValue BigA = N0.getOperand(0);
8200     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8201     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8202            "Asserting zero/sign-extended bits to a type larger than the "
8203            "truncated destination does not provide information");
8204 
8205     SDLoc DL(N);
8206     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8207     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8208     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8209                                     BigA.getOperand(0), MinAssertVTVal);
8210     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8211   }
8212 
8213   return SDValue();
8214 }
8215 
8216 /// If the result of a wider load is shifted to right of N  bits and then
8217 /// truncated to a narrower type and where N is a multiple of number of bits of
8218 /// the narrower type, transform it to a narrower load from address + N / num of
8219 /// bits of new type. Also narrow the load if the result is masked with an AND
8220 /// to effectively produce a smaller type. If the result is to be extended, also
8221 /// fold the extension to form a extending load.
8222 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8223   unsigned Opc = N->getOpcode();
8224 
8225   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8226   SDValue N0 = N->getOperand(0);
8227   EVT VT = N->getValueType(0);
8228   EVT ExtVT = VT;
8229 
8230   // This transformation isn't valid for vector loads.
8231   if (VT.isVector())
8232     return SDValue();
8233 
8234   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8235   // extended to VT.
8236   if (Opc == ISD::SIGN_EXTEND_INREG) {
8237     ExtType = ISD::SEXTLOAD;
8238     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8239   } else if (Opc == ISD::SRL) {
8240     // Another special-case: SRL is basically zero-extending a narrower value,
8241     // or it maybe shifting a higher subword, half or byte into the lowest
8242     // bits.
8243     ExtType = ISD::ZEXTLOAD;
8244     N0 = SDValue(N, 0);
8245 
8246     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8247     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8248     if (!N01 || !LN0)
8249       return SDValue();
8250 
8251     uint64_t ShiftAmt = N01->getZExtValue();
8252     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8253     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8254       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8255     else
8256       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8257                                 VT.getSizeInBits() - ShiftAmt);
8258   } else if (Opc == ISD::AND) {
8259     // An AND with a constant mask is the same as a truncate + zero-extend.
8260     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8261     if (!AndC || !AndC->getAPIntValue().isMask())
8262       return SDValue();
8263 
8264     unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8265     ExtType = ISD::ZEXTLOAD;
8266     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8267   }
8268 
8269   unsigned ShAmt = 0;
8270   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8271     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8272       ShAmt = N01->getZExtValue();
8273       unsigned EVTBits = ExtVT.getSizeInBits();
8274       // Is the shift amount a multiple of size of VT?
8275       if ((ShAmt & (EVTBits-1)) == 0) {
8276         N0 = N0.getOperand(0);
8277         // Is the load width a multiple of size of VT?
8278         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8279           return SDValue();
8280       }
8281 
8282       // At this point, we must have a load or else we can't do the transform.
8283       if (!isa<LoadSDNode>(N0)) return SDValue();
8284 
8285       // Because a SRL must be assumed to *need* to zero-extend the high bits
8286       // (as opposed to anyext the high bits), we can't combine the zextload
8287       // lowering of SRL and an sextload.
8288       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
8289         return SDValue();
8290 
8291       // If the shift amount is larger than the input type then we're not
8292       // accessing any of the loaded bytes.  If the load was a zextload/extload
8293       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8294       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
8295         return SDValue();
8296     }
8297   }
8298 
8299   // If the load is shifted left (and the result isn't shifted back right),
8300   // we can fold the truncate through the shift.
8301   unsigned ShLeftAmt = 0;
8302   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8303       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8304     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8305       ShLeftAmt = N01->getZExtValue();
8306       N0 = N0.getOperand(0);
8307     }
8308   }
8309 
8310   // If we haven't found a load, we can't narrow it.
8311   if (!isa<LoadSDNode>(N0))
8312     return SDValue();
8313 
8314   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8315   if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8316     return SDValue();
8317 
8318   // For big endian targets, we need to adjust the offset to the pointer to
8319   // load the correct bytes.
8320   if (DAG.getDataLayout().isBigEndian()) {
8321     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8322     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8323     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8324   }
8325 
8326   EVT PtrType = N0.getOperand(1).getValueType();
8327   uint64_t PtrOff = ShAmt / 8;
8328   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8329   SDLoc DL(LN0);
8330   // The original load itself didn't wrap, so an offset within it doesn't.
8331   SDNodeFlags Flags;
8332   Flags.setNoUnsignedWrap(true);
8333   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8334                                PtrType, LN0->getBasePtr(),
8335                                DAG.getConstant(PtrOff, DL, PtrType),
8336                                Flags);
8337   AddToWorklist(NewPtr.getNode());
8338 
8339   SDValue Load;
8340   if (ExtType == ISD::NON_EXTLOAD)
8341     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8342                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8343                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8344   else
8345     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8346                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8347                           NewAlign, LN0->getMemOperand()->getFlags(),
8348                           LN0->getAAInfo());
8349 
8350   // Replace the old load's chain with the new load's chain.
8351   WorklistRemover DeadNodes(*this);
8352   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8353 
8354   // Shift the result left, if we've swallowed a left shift.
8355   SDValue Result = Load;
8356   if (ShLeftAmt != 0) {
8357     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8358     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8359       ShImmTy = VT;
8360     // If the shift amount is as large as the result size (but, presumably,
8361     // no larger than the source) then the useful bits of the result are
8362     // zero; we can't simply return the shortened shift, because the result
8363     // of that operation is undefined.
8364     SDLoc DL(N0);
8365     if (ShLeftAmt >= VT.getSizeInBits())
8366       Result = DAG.getConstant(0, DL, VT);
8367     else
8368       Result = DAG.getNode(ISD::SHL, DL, VT,
8369                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8370   }
8371 
8372   // Return the new loaded value.
8373   return Result;
8374 }
8375 
8376 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8377   SDValue N0 = N->getOperand(0);
8378   SDValue N1 = N->getOperand(1);
8379   EVT VT = N->getValueType(0);
8380   EVT EVT = cast<VTSDNode>(N1)->getVT();
8381   unsigned VTBits = VT.getScalarSizeInBits();
8382   unsigned EVTBits = EVT.getScalarSizeInBits();
8383 
8384   if (N0.isUndef())
8385     return DAG.getUNDEF(VT);
8386 
8387   // fold (sext_in_reg c1) -> c1
8388   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8389     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8390 
8391   // If the input is already sign extended, just drop the extension.
8392   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8393     return N0;
8394 
8395   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8396   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8397       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8398     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8399                        N0.getOperand(0), N1);
8400 
8401   // fold (sext_in_reg (sext x)) -> (sext x)
8402   // fold (sext_in_reg (aext x)) -> (sext x)
8403   // if x is small enough.
8404   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8405     SDValue N00 = N0.getOperand(0);
8406     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8407         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8408       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8409   }
8410 
8411   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8412   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8413        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8414        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8415       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8416     if (!LegalOperations ||
8417         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8418       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8419   }
8420 
8421   // fold (sext_in_reg (zext x)) -> (sext x)
8422   // iff we are extending the source sign bit.
8423   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8424     SDValue N00 = N0.getOperand(0);
8425     if (N00.getScalarValueSizeInBits() == EVTBits &&
8426         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8427       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8428   }
8429 
8430   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8431   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8432     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8433 
8434   // fold operands of sext_in_reg based on knowledge that the top bits are not
8435   // demanded.
8436   if (SimplifyDemandedBits(SDValue(N, 0)))
8437     return SDValue(N, 0);
8438 
8439   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8440   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8441   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8442     return NarrowLoad;
8443 
8444   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8445   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8446   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8447   if (N0.getOpcode() == ISD::SRL) {
8448     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8449       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8450         // We can turn this into an SRA iff the input to the SRL is already sign
8451         // extended enough.
8452         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8453         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8454           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8455                              N0.getOperand(0), N0.getOperand(1));
8456       }
8457   }
8458 
8459   // fold (sext_inreg (extload x)) -> (sextload x)
8460   // If sextload is not supported by target, we can only do the combine when
8461   // load has one use. Doing otherwise can block folding the extload with other
8462   // extends that the target does support.
8463   if (ISD::isEXTLoad(N0.getNode()) &&
8464       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8465       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8466       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8467         N0.hasOneUse()) ||
8468        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8469     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8470     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8471                                      LN0->getChain(),
8472                                      LN0->getBasePtr(), EVT,
8473                                      LN0->getMemOperand());
8474     CombineTo(N, ExtLoad);
8475     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8476     AddToWorklist(ExtLoad.getNode());
8477     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8478   }
8479   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8480   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8481       N0.hasOneUse() &&
8482       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8483       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8484        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8485     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8486     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8487                                      LN0->getChain(),
8488                                      LN0->getBasePtr(), EVT,
8489                                      LN0->getMemOperand());
8490     CombineTo(N, ExtLoad);
8491     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8492     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8493   }
8494 
8495   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8496   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8497     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8498                                            N0.getOperand(1), false))
8499       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8500                          BSwap, N1);
8501   }
8502 
8503   return SDValue();
8504 }
8505 
8506 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8507   SDValue N0 = N->getOperand(0);
8508   EVT VT = N->getValueType(0);
8509 
8510   if (N0.isUndef())
8511     return DAG.getUNDEF(VT);
8512 
8513   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8514                                               LegalOperations))
8515     return SDValue(Res, 0);
8516 
8517   return SDValue();
8518 }
8519 
8520 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8521   SDValue N0 = N->getOperand(0);
8522   EVT VT = N->getValueType(0);
8523 
8524   if (N0.isUndef())
8525     return DAG.getUNDEF(VT);
8526 
8527   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8528                                               LegalOperations))
8529     return SDValue(Res, 0);
8530 
8531   return SDValue();
8532 }
8533 
8534 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8535   SDValue N0 = N->getOperand(0);
8536   EVT VT = N->getValueType(0);
8537   bool isLE = DAG.getDataLayout().isLittleEndian();
8538 
8539   // noop truncate
8540   if (N0.getValueType() == N->getValueType(0))
8541     return N0;
8542 
8543   // fold (truncate (truncate x)) -> (truncate x)
8544   if (N0.getOpcode() == ISD::TRUNCATE)
8545     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8546 
8547   // fold (truncate c1) -> c1
8548   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8549     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8550     if (C.getNode() != N)
8551       return C;
8552   }
8553 
8554   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8555   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8556       N0.getOpcode() == ISD::SIGN_EXTEND ||
8557       N0.getOpcode() == ISD::ANY_EXTEND) {
8558     // if the source is smaller than the dest, we still need an extend.
8559     if (N0.getOperand(0).getValueType().bitsLT(VT))
8560       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8561     // if the source is larger than the dest, than we just need the truncate.
8562     if (N0.getOperand(0).getValueType().bitsGT(VT))
8563       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8564     // if the source and dest are the same type, we can drop both the extend
8565     // and the truncate.
8566     return N0.getOperand(0);
8567   }
8568 
8569   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8570   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8571     return SDValue();
8572 
8573   // Fold extract-and-trunc into a narrow extract. For example:
8574   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8575   //   i32 y = TRUNCATE(i64 x)
8576   //        -- becomes --
8577   //   v16i8 b = BITCAST (v2i64 val)
8578   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8579   //
8580   // Note: We only run this optimization after type legalization (which often
8581   // creates this pattern) and before operation legalization after which
8582   // we need to be more careful about the vector instructions that we generate.
8583   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8584       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8585     EVT VecTy = N0.getOperand(0).getValueType();
8586     EVT ExTy = N0.getValueType();
8587     EVT TrTy = N->getValueType(0);
8588 
8589     unsigned NumElem = VecTy.getVectorNumElements();
8590     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8591 
8592     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8593     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8594 
8595     SDValue EltNo = N0->getOperand(1);
8596     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8597       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8598       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8599       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8600 
8601       SDLoc DL(N);
8602       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8603                          DAG.getBitcast(NVT, N0.getOperand(0)),
8604                          DAG.getConstant(Index, DL, IndexTy));
8605     }
8606   }
8607 
8608   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8609   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8610     EVT SrcVT = N0.getValueType();
8611     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8612         TLI.isTruncateFree(SrcVT, VT)) {
8613       SDLoc SL(N0);
8614       SDValue Cond = N0.getOperand(0);
8615       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8616       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8617       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8618     }
8619   }
8620 
8621   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8622   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8623       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8624       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8625     SDValue Amt = N0.getOperand(1);
8626     KnownBits Known;
8627     DAG.computeKnownBits(Amt, Known);
8628     unsigned Size = VT.getScalarSizeInBits();
8629     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8630       SDLoc SL(N);
8631       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8632 
8633       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8634       if (AmtVT != Amt.getValueType()) {
8635         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8636         AddToWorklist(Amt.getNode());
8637       }
8638       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8639     }
8640   }
8641 
8642   // Fold a series of buildvector, bitcast, and truncate if possible.
8643   // For example fold
8644   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8645   //   (2xi32 (buildvector x, y)).
8646   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8647       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8648       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8649       N0.getOperand(0).hasOneUse()) {
8650     SDValue BuildVect = N0.getOperand(0);
8651     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8652     EVT TruncVecEltTy = VT.getVectorElementType();
8653 
8654     // Check that the element types match.
8655     if (BuildVectEltTy == TruncVecEltTy) {
8656       // Now we only need to compute the offset of the truncated elements.
8657       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8658       unsigned TruncVecNumElts = VT.getVectorNumElements();
8659       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8660 
8661       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8662              "Invalid number of elements");
8663 
8664       SmallVector<SDValue, 8> Opnds;
8665       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8666         Opnds.push_back(BuildVect.getOperand(i));
8667 
8668       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8669     }
8670   }
8671 
8672   // See if we can simplify the input to this truncate through knowledge that
8673   // only the low bits are being used.
8674   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8675   // Currently we only perform this optimization on scalars because vectors
8676   // may have different active low bits.
8677   if (!VT.isVector()) {
8678     APInt Mask =
8679         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8680     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8681       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8682   }
8683 
8684   // fold (truncate (load x)) -> (smaller load x)
8685   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8686   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8687     if (SDValue Reduced = ReduceLoadWidth(N))
8688       return Reduced;
8689 
8690     // Handle the case where the load remains an extending load even
8691     // after truncation.
8692     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8693       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8694       if (!LN0->isVolatile() &&
8695           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8696         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8697                                          VT, LN0->getChain(), LN0->getBasePtr(),
8698                                          LN0->getMemoryVT(),
8699                                          LN0->getMemOperand());
8700         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8701         return NewLoad;
8702       }
8703     }
8704   }
8705 
8706   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8707   // where ... are all 'undef'.
8708   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8709     SmallVector<EVT, 8> VTs;
8710     SDValue V;
8711     unsigned Idx = 0;
8712     unsigned NumDefs = 0;
8713 
8714     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8715       SDValue X = N0.getOperand(i);
8716       if (!X.isUndef()) {
8717         V = X;
8718         Idx = i;
8719         NumDefs++;
8720       }
8721       // Stop if more than one members are non-undef.
8722       if (NumDefs > 1)
8723         break;
8724       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8725                                      VT.getVectorElementType(),
8726                                      X.getValueType().getVectorNumElements()));
8727     }
8728 
8729     if (NumDefs == 0)
8730       return DAG.getUNDEF(VT);
8731 
8732     if (NumDefs == 1) {
8733       assert(V.getNode() && "The single defined operand is empty!");
8734       SmallVector<SDValue, 8> Opnds;
8735       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8736         if (i != Idx) {
8737           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8738           continue;
8739         }
8740         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8741         AddToWorklist(NV.getNode());
8742         Opnds.push_back(NV);
8743       }
8744       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8745     }
8746   }
8747 
8748   // Fold truncate of a bitcast of a vector to an extract of the low vector
8749   // element.
8750   //
8751   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8752   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8753     SDValue VecSrc = N0.getOperand(0);
8754     EVT SrcVT = VecSrc.getValueType();
8755     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8756         (!LegalOperations ||
8757          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8758       SDLoc SL(N);
8759 
8760       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8761       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8762       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8763                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8764     }
8765   }
8766 
8767   // Simplify the operands using demanded-bits information.
8768   if (!VT.isVector() &&
8769       SimplifyDemandedBits(SDValue(N, 0)))
8770     return SDValue(N, 0);
8771 
8772   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8773   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8774   // When the adde's carry is not used.
8775   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8776       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8777       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8778     SDLoc SL(N);
8779     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8780     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8781     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8782     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8783   }
8784 
8785   // fold (truncate (extract_subvector(ext x))) ->
8786   //      (extract_subvector x)
8787   // TODO: This can be generalized to cover cases where the truncate and extract
8788   // do not fully cancel each other out.
8789   if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8790     SDValue N00 = N0.getOperand(0);
8791     if (N00.getOpcode() == ISD::SIGN_EXTEND ||
8792         N00.getOpcode() == ISD::ZERO_EXTEND ||
8793         N00.getOpcode() == ISD::ANY_EXTEND) {
8794       if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
8795           VT.getVectorElementType())
8796         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
8797                            N00.getOperand(0), N0.getOperand(1));
8798     }
8799   }
8800 
8801   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8802     return NewVSel;
8803 
8804   return SDValue();
8805 }
8806 
8807 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8808   SDValue Elt = N->getOperand(i);
8809   if (Elt.getOpcode() != ISD::MERGE_VALUES)
8810     return Elt.getNode();
8811   return Elt.getOperand(Elt.getResNo()).getNode();
8812 }
8813 
8814 /// build_pair (load, load) -> load
8815 /// if load locations are consecutive.
8816 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8817   assert(N->getOpcode() == ISD::BUILD_PAIR);
8818 
8819   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8820   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8821 
8822   // A BUILD_PAIR is always having the least significant part in elt 0 and the
8823   // most significant part in elt 1. So when combining into one large load, we
8824   // need to consider the endianness.
8825   if (DAG.getDataLayout().isBigEndian())
8826     std::swap(LD1, LD2);
8827 
8828   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8829       LD1->getAddressSpace() != LD2->getAddressSpace())
8830     return SDValue();
8831   EVT LD1VT = LD1->getValueType(0);
8832   unsigned LD1Bytes = LD1VT.getStoreSize();
8833   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8834       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8835     unsigned Align = LD1->getAlignment();
8836     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8837         VT.getTypeForEVT(*DAG.getContext()));
8838 
8839     if (NewAlign <= Align &&
8840         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8841       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8842                          LD1->getPointerInfo(), Align);
8843   }
8844 
8845   return SDValue();
8846 }
8847 
8848 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8849   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8850   // and Lo parts; on big-endian machines it doesn't.
8851   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8852 }
8853 
8854 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8855                                     const TargetLowering &TLI) {
8856   // If this is not a bitcast to an FP type or if the target doesn't have
8857   // IEEE754-compliant FP logic, we're done.
8858   EVT VT = N->getValueType(0);
8859   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8860     return SDValue();
8861 
8862   // TODO: Use splat values for the constant-checking below and remove this
8863   // restriction.
8864   SDValue N0 = N->getOperand(0);
8865   EVT SourceVT = N0.getValueType();
8866   if (SourceVT.isVector())
8867     return SDValue();
8868 
8869   unsigned FPOpcode;
8870   APInt SignMask;
8871   switch (N0.getOpcode()) {
8872   case ISD::AND:
8873     FPOpcode = ISD::FABS;
8874     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8875     break;
8876   case ISD::XOR:
8877     FPOpcode = ISD::FNEG;
8878     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8879     break;
8880   // TODO: ISD::OR --> ISD::FNABS?
8881   default:
8882     return SDValue();
8883   }
8884 
8885   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8886   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8887   SDValue LogicOp0 = N0.getOperand(0);
8888   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8889   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8890       LogicOp0.getOpcode() == ISD::BITCAST &&
8891       LogicOp0->getOperand(0).getValueType() == VT)
8892     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8893 
8894   return SDValue();
8895 }
8896 
8897 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8898   SDValue N0 = N->getOperand(0);
8899   EVT VT = N->getValueType(0);
8900 
8901   if (N0.isUndef())
8902     return DAG.getUNDEF(VT);
8903 
8904   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8905   // Only do this before legalize, since afterward the target may be depending
8906   // on the bitconvert.
8907   // First check to see if this is all constant.
8908   if (!LegalTypes &&
8909       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8910       VT.isVector()) {
8911     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8912 
8913     EVT DestEltVT = N->getValueType(0).getVectorElementType();
8914     assert(!DestEltVT.isVector() &&
8915            "Element type of vector ValueType must not be vector!");
8916     if (isSimple)
8917       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8918   }
8919 
8920   // If the input is a constant, let getNode fold it.
8921   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8922     // If we can't allow illegal operations, we need to check that this is just
8923     // a fp -> int or int -> conversion and that the resulting operation will
8924     // be legal.
8925     if (!LegalOperations ||
8926         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8927          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8928         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8929          TLI.isOperationLegal(ISD::Constant, VT)))
8930       return DAG.getBitcast(VT, N0);
8931   }
8932 
8933   // (conv (conv x, t1), t2) -> (conv x, t2)
8934   if (N0.getOpcode() == ISD::BITCAST)
8935     return DAG.getBitcast(VT, N0.getOperand(0));
8936 
8937   // fold (conv (load x)) -> (load (conv*)x)
8938   // If the resultant load doesn't need a higher alignment than the original!
8939   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8940       // Do not change the width of a volatile load.
8941       !cast<LoadSDNode>(N0)->isVolatile() &&
8942       // Do not remove the cast if the types differ in endian layout.
8943       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8944           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8945       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8946       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8947     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8948     unsigned OrigAlign = LN0->getAlignment();
8949 
8950     bool Fast = false;
8951     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8952                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
8953         Fast) {
8954       SDValue Load =
8955           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8956                       LN0->getPointerInfo(), OrigAlign,
8957                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8958       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8959       return Load;
8960     }
8961   }
8962 
8963   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8964     return V;
8965 
8966   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8967   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8968   //
8969   // For ppc_fp128:
8970   // fold (bitcast (fneg x)) ->
8971   //     flipbit = signbit
8972   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8973   //
8974   // fold (bitcast (fabs x)) ->
8975   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
8976   //     (xor (bitcast x) (build_pair flipbit, flipbit))
8977   // This often reduces constant pool loads.
8978   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8979        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8980       N0.getNode()->hasOneUse() && VT.isInteger() &&
8981       !VT.isVector() && !N0.getValueType().isVector()) {
8982     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8983     AddToWorklist(NewConv.getNode());
8984 
8985     SDLoc DL(N);
8986     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8987       assert(VT.getSizeInBits() == 128);
8988       SDValue SignBit = DAG.getConstant(
8989           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8990       SDValue FlipBit;
8991       if (N0.getOpcode() == ISD::FNEG) {
8992         FlipBit = SignBit;
8993         AddToWorklist(FlipBit.getNode());
8994       } else {
8995         assert(N0.getOpcode() == ISD::FABS);
8996         SDValue Hi =
8997             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8998                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8999                                               SDLoc(NewConv)));
9000         AddToWorklist(Hi.getNode());
9001         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
9002         AddToWorklist(FlipBit.getNode());
9003       }
9004       SDValue FlipBits =
9005           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9006       AddToWorklist(FlipBits.getNode());
9007       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
9008     }
9009     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9010     if (N0.getOpcode() == ISD::FNEG)
9011       return DAG.getNode(ISD::XOR, DL, VT,
9012                          NewConv, DAG.getConstant(SignBit, DL, VT));
9013     assert(N0.getOpcode() == ISD::FABS);
9014     return DAG.getNode(ISD::AND, DL, VT,
9015                        NewConv, DAG.getConstant(~SignBit, DL, VT));
9016   }
9017 
9018   // fold (bitconvert (fcopysign cst, x)) ->
9019   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
9020   // Note that we don't handle (copysign x, cst) because this can always be
9021   // folded to an fneg or fabs.
9022   //
9023   // For ppc_fp128:
9024   // fold (bitcast (fcopysign cst, x)) ->
9025   //     flipbit = (and (extract_element
9026   //                     (xor (bitcast cst), (bitcast x)), 0),
9027   //                    signbit)
9028   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
9029   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
9030       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
9031       VT.isInteger() && !VT.isVector()) {
9032     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
9033     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
9034     if (isTypeLegal(IntXVT)) {
9035       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9036       AddToWorklist(X.getNode());
9037 
9038       // If X has a different width than the result/lhs, sext it or truncate it.
9039       unsigned VTWidth = VT.getSizeInBits();
9040       if (OrigXWidth < VTWidth) {
9041         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9042         AddToWorklist(X.getNode());
9043       } else if (OrigXWidth > VTWidth) {
9044         // To get the sign bit in the right place, we have to shift it right
9045         // before truncating.
9046         SDLoc DL(X);
9047         X = DAG.getNode(ISD::SRL, DL,
9048                         X.getValueType(), X,
9049                         DAG.getConstant(OrigXWidth-VTWidth, DL,
9050                                         X.getValueType()));
9051         AddToWorklist(X.getNode());
9052         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9053         AddToWorklist(X.getNode());
9054       }
9055 
9056       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9057         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9058         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9059         AddToWorklist(Cst.getNode());
9060         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9061         AddToWorklist(X.getNode());
9062         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9063         AddToWorklist(XorResult.getNode());
9064         SDValue XorResult64 = DAG.getNode(
9065             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9066             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9067                                   SDLoc(XorResult)));
9068         AddToWorklist(XorResult64.getNode());
9069         SDValue FlipBit =
9070             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9071                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9072         AddToWorklist(FlipBit.getNode());
9073         SDValue FlipBits =
9074             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9075         AddToWorklist(FlipBits.getNode());
9076         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9077       }
9078       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9079       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9080                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
9081       AddToWorklist(X.getNode());
9082 
9083       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9084       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9085                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9086       AddToWorklist(Cst.getNode());
9087 
9088       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9089     }
9090   }
9091 
9092   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9093   if (N0.getOpcode() == ISD::BUILD_PAIR)
9094     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9095       return CombineLD;
9096 
9097   // Remove double bitcasts from shuffles - this is often a legacy of
9098   // XformToShuffleWithZero being used to combine bitmaskings (of
9099   // float vectors bitcast to integer vectors) into shuffles.
9100   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9101   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9102       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9103       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9104       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9105     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9106 
9107     // If operands are a bitcast, peek through if it casts the original VT.
9108     // If operands are a constant, just bitcast back to original VT.
9109     auto PeekThroughBitcast = [&](SDValue Op) {
9110       if (Op.getOpcode() == ISD::BITCAST &&
9111           Op.getOperand(0).getValueType() == VT)
9112         return SDValue(Op.getOperand(0));
9113       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9114           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9115         return DAG.getBitcast(VT, Op);
9116       return SDValue();
9117     };
9118 
9119     // FIXME: If either input vector is bitcast, try to convert the shuffle to
9120     // the result type of this bitcast. This would eliminate at least one
9121     // bitcast. See the transform in InstCombine.
9122     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9123     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9124     if (!(SV0 && SV1))
9125       return SDValue();
9126 
9127     int MaskScale =
9128         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9129     SmallVector<int, 8> NewMask;
9130     for (int M : SVN->getMask())
9131       for (int i = 0; i != MaskScale; ++i)
9132         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9133 
9134     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9135     if (!LegalMask) {
9136       std::swap(SV0, SV1);
9137       ShuffleVectorSDNode::commuteMask(NewMask);
9138       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9139     }
9140 
9141     if (LegalMask)
9142       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9143   }
9144 
9145   return SDValue();
9146 }
9147 
9148 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9149   EVT VT = N->getValueType(0);
9150   return CombineConsecutiveLoads(N, VT);
9151 }
9152 
9153 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9154 /// operands. DstEltVT indicates the destination element value type.
9155 SDValue DAGCombiner::
9156 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9157   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9158 
9159   // If this is already the right type, we're done.
9160   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9161 
9162   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9163   unsigned DstBitSize = DstEltVT.getSizeInBits();
9164 
9165   // If this is a conversion of N elements of one type to N elements of another
9166   // type, convert each element.  This handles FP<->INT cases.
9167   if (SrcBitSize == DstBitSize) {
9168     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9169                               BV->getValueType(0).getVectorNumElements());
9170 
9171     // Due to the FP element handling below calling this routine recursively,
9172     // we can end up with a scalar-to-vector node here.
9173     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9174       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9175                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9176 
9177     SmallVector<SDValue, 8> Ops;
9178     for (SDValue Op : BV->op_values()) {
9179       // If the vector element type is not legal, the BUILD_VECTOR operands
9180       // are promoted and implicitly truncated.  Make that explicit here.
9181       if (Op.getValueType() != SrcEltVT)
9182         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9183       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9184       AddToWorklist(Ops.back().getNode());
9185     }
9186     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9187   }
9188 
9189   // Otherwise, we're growing or shrinking the elements.  To avoid having to
9190   // handle annoying details of growing/shrinking FP values, we convert them to
9191   // int first.
9192   if (SrcEltVT.isFloatingPoint()) {
9193     // Convert the input float vector to a int vector where the elements are the
9194     // same sizes.
9195     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9196     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9197     SrcEltVT = IntVT;
9198   }
9199 
9200   // Now we know the input is an integer vector.  If the output is a FP type,
9201   // convert to integer first, then to FP of the right size.
9202   if (DstEltVT.isFloatingPoint()) {
9203     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9204     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9205 
9206     // Next, convert to FP elements of the same size.
9207     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9208   }
9209 
9210   SDLoc DL(BV);
9211 
9212   // Okay, we know the src/dst types are both integers of differing types.
9213   // Handling growing first.
9214   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9215   if (SrcBitSize < DstBitSize) {
9216     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9217 
9218     SmallVector<SDValue, 8> Ops;
9219     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9220          i += NumInputsPerOutput) {
9221       bool isLE = DAG.getDataLayout().isLittleEndian();
9222       APInt NewBits = APInt(DstBitSize, 0);
9223       bool EltIsUndef = true;
9224       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9225         // Shift the previously computed bits over.
9226         NewBits <<= SrcBitSize;
9227         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9228         if (Op.isUndef()) continue;
9229         EltIsUndef = false;
9230 
9231         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9232                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9233       }
9234 
9235       if (EltIsUndef)
9236         Ops.push_back(DAG.getUNDEF(DstEltVT));
9237       else
9238         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9239     }
9240 
9241     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9242     return DAG.getBuildVector(VT, DL, Ops);
9243   }
9244 
9245   // Finally, this must be the case where we are shrinking elements: each input
9246   // turns into multiple outputs.
9247   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9248   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9249                             NumOutputsPerInput*BV->getNumOperands());
9250   SmallVector<SDValue, 8> Ops;
9251 
9252   for (const SDValue &Op : BV->op_values()) {
9253     if (Op.isUndef()) {
9254       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9255       continue;
9256     }
9257 
9258     APInt OpVal = cast<ConstantSDNode>(Op)->
9259                   getAPIntValue().zextOrTrunc(SrcBitSize);
9260 
9261     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9262       APInt ThisVal = OpVal.trunc(DstBitSize);
9263       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9264       OpVal.lshrInPlace(DstBitSize);
9265     }
9266 
9267     // For big endian targets, swap the order of the pieces of each element.
9268     if (DAG.getDataLayout().isBigEndian())
9269       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9270   }
9271 
9272   return DAG.getBuildVector(VT, DL, Ops);
9273 }
9274 
9275 static bool isContractable(SDNode *N) {
9276   SDNodeFlags F = N->getFlags();
9277   return F.hasAllowContract() || F.hasUnsafeAlgebra();
9278 }
9279 
9280 /// Try to perform FMA combining on a given FADD node.
9281 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9282   SDValue N0 = N->getOperand(0);
9283   SDValue N1 = N->getOperand(1);
9284   EVT VT = N->getValueType(0);
9285   SDLoc SL(N);
9286 
9287   const TargetOptions &Options = DAG.getTarget().Options;
9288 
9289   // Floating-point multiply-add with intermediate rounding.
9290   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9291 
9292   // Floating-point multiply-add without intermediate rounding.
9293   bool HasFMA =
9294       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9295       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9296 
9297   // No valid opcode, do not combine.
9298   if (!HasFMAD && !HasFMA)
9299     return SDValue();
9300 
9301   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9302                               Options.UnsafeFPMath || HasFMAD);
9303   // If the addition is not contractable, do not combine.
9304   if (!AllowFusionGlobally && !isContractable(N))
9305     return SDValue();
9306 
9307   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9308   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9309     return SDValue();
9310 
9311   // Always prefer FMAD to FMA for precision.
9312   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9313   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9314 
9315   // Is the node an FMUL and contractable either due to global flags or
9316   // SDNodeFlags.
9317   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9318     if (N.getOpcode() != ISD::FMUL)
9319       return false;
9320     return AllowFusionGlobally || isContractable(N.getNode());
9321   };
9322   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9323   // prefer to fold the multiply with fewer uses.
9324   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9325     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9326       std::swap(N0, N1);
9327   }
9328 
9329   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9330   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9331     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9332                        N0.getOperand(0), N0.getOperand(1), N1);
9333   }
9334 
9335   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9336   // Note: Commutes FADD operands.
9337   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9338     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9339                        N1.getOperand(0), N1.getOperand(1), N0);
9340   }
9341 
9342   // Look through FP_EXTEND nodes to do more combining.
9343 
9344   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9345   if (N0.getOpcode() == ISD::FP_EXTEND) {
9346     SDValue N00 = N0.getOperand(0);
9347     if (isContractableFMUL(N00) &&
9348         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9349       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9350                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9351                                      N00.getOperand(0)),
9352                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9353                                      N00.getOperand(1)), N1);
9354     }
9355   }
9356 
9357   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9358   // Note: Commutes FADD operands.
9359   if (N1.getOpcode() == ISD::FP_EXTEND) {
9360     SDValue N10 = N1.getOperand(0);
9361     if (isContractableFMUL(N10) &&
9362         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9363       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9364                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9365                                      N10.getOperand(0)),
9366                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9367                                      N10.getOperand(1)), N0);
9368     }
9369   }
9370 
9371   // More folding opportunities when target permits.
9372   if (Aggressive) {
9373     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9374     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9375     // are currently only supported on binary nodes.
9376     if (Options.UnsafeFPMath &&
9377         N0.getOpcode() == PreferredFusedOpcode &&
9378         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9379         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9380       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9381                          N0.getOperand(0), N0.getOperand(1),
9382                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9383                                      N0.getOperand(2).getOperand(0),
9384                                      N0.getOperand(2).getOperand(1),
9385                                      N1));
9386     }
9387 
9388     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9389     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9390     // are currently only supported on binary nodes.
9391     if (Options.UnsafeFPMath &&
9392         N1->getOpcode() == PreferredFusedOpcode &&
9393         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9394         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9395       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9396                          N1.getOperand(0), N1.getOperand(1),
9397                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9398                                      N1.getOperand(2).getOperand(0),
9399                                      N1.getOperand(2).getOperand(1),
9400                                      N0));
9401     }
9402 
9403 
9404     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9405     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9406     auto FoldFAddFMAFPExtFMul = [&] (
9407       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9408       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9409                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9410                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9411                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9412                                      Z));
9413     };
9414     if (N0.getOpcode() == PreferredFusedOpcode) {
9415       SDValue N02 = N0.getOperand(2);
9416       if (N02.getOpcode() == ISD::FP_EXTEND) {
9417         SDValue N020 = N02.getOperand(0);
9418         if (isContractableFMUL(N020) &&
9419             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9420           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9421                                       N020.getOperand(0), N020.getOperand(1),
9422                                       N1);
9423         }
9424       }
9425     }
9426 
9427     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9428     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9429     // FIXME: This turns two single-precision and one double-precision
9430     // operation into two double-precision operations, which might not be
9431     // interesting for all targets, especially GPUs.
9432     auto FoldFAddFPExtFMAFMul = [&] (
9433       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9434       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9435                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9436                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9437                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9438                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9439                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9440                                      Z));
9441     };
9442     if (N0.getOpcode() == ISD::FP_EXTEND) {
9443       SDValue N00 = N0.getOperand(0);
9444       if (N00.getOpcode() == PreferredFusedOpcode) {
9445         SDValue N002 = N00.getOperand(2);
9446         if (isContractableFMUL(N002) &&
9447             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9448           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9449                                       N002.getOperand(0), N002.getOperand(1),
9450                                       N1);
9451         }
9452       }
9453     }
9454 
9455     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9456     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9457     if (N1.getOpcode() == PreferredFusedOpcode) {
9458       SDValue N12 = N1.getOperand(2);
9459       if (N12.getOpcode() == ISD::FP_EXTEND) {
9460         SDValue N120 = N12.getOperand(0);
9461         if (isContractableFMUL(N120) &&
9462             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9463           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9464                                       N120.getOperand(0), N120.getOperand(1),
9465                                       N0);
9466         }
9467       }
9468     }
9469 
9470     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9471     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9472     // FIXME: This turns two single-precision and one double-precision
9473     // operation into two double-precision operations, which might not be
9474     // interesting for all targets, especially GPUs.
9475     if (N1.getOpcode() == ISD::FP_EXTEND) {
9476       SDValue N10 = N1.getOperand(0);
9477       if (N10.getOpcode() == PreferredFusedOpcode) {
9478         SDValue N102 = N10.getOperand(2);
9479         if (isContractableFMUL(N102) &&
9480             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9481           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9482                                       N102.getOperand(0), N102.getOperand(1),
9483                                       N0);
9484         }
9485       }
9486     }
9487   }
9488 
9489   return SDValue();
9490 }
9491 
9492 /// Try to perform FMA combining on a given FSUB node.
9493 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9494   SDValue N0 = N->getOperand(0);
9495   SDValue N1 = N->getOperand(1);
9496   EVT VT = N->getValueType(0);
9497   SDLoc SL(N);
9498 
9499   const TargetOptions &Options = DAG.getTarget().Options;
9500   // Floating-point multiply-add with intermediate rounding.
9501   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9502 
9503   // Floating-point multiply-add without intermediate rounding.
9504   bool HasFMA =
9505       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9506       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9507 
9508   // No valid opcode, do not combine.
9509   if (!HasFMAD && !HasFMA)
9510     return SDValue();
9511 
9512   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9513                               Options.UnsafeFPMath || HasFMAD);
9514   // If the subtraction is not contractable, do not combine.
9515   if (!AllowFusionGlobally && !isContractable(N))
9516     return SDValue();
9517 
9518   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9519   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9520     return SDValue();
9521 
9522   // Always prefer FMAD to FMA for precision.
9523   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9524   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9525 
9526   // Is the node an FMUL and contractable either due to global flags or
9527   // SDNodeFlags.
9528   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9529     if (N.getOpcode() != ISD::FMUL)
9530       return false;
9531     return AllowFusionGlobally || isContractable(N.getNode());
9532   };
9533 
9534   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9535   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9536     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9537                        N0.getOperand(0), N0.getOperand(1),
9538                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9539   }
9540 
9541   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9542   // Note: Commutes FSUB operands.
9543   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9544     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9545                        DAG.getNode(ISD::FNEG, SL, VT,
9546                                    N1.getOperand(0)),
9547                        N1.getOperand(1), N0);
9548 
9549   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9550   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9551       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9552     SDValue N00 = N0.getOperand(0).getOperand(0);
9553     SDValue N01 = N0.getOperand(0).getOperand(1);
9554     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9555                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9556                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9557   }
9558 
9559   // Look through FP_EXTEND nodes to do more combining.
9560 
9561   // fold (fsub (fpext (fmul x, y)), z)
9562   //   -> (fma (fpext x), (fpext y), (fneg z))
9563   if (N0.getOpcode() == ISD::FP_EXTEND) {
9564     SDValue N00 = N0.getOperand(0);
9565     if (isContractableFMUL(N00) &&
9566         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9567       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9568                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9569                                      N00.getOperand(0)),
9570                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9571                                      N00.getOperand(1)),
9572                          DAG.getNode(ISD::FNEG, SL, VT, N1));
9573     }
9574   }
9575 
9576   // fold (fsub x, (fpext (fmul y, z)))
9577   //   -> (fma (fneg (fpext y)), (fpext z), x)
9578   // Note: Commutes FSUB operands.
9579   if (N1.getOpcode() == ISD::FP_EXTEND) {
9580     SDValue N10 = N1.getOperand(0);
9581     if (isContractableFMUL(N10) &&
9582         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9583       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9584                          DAG.getNode(ISD::FNEG, SL, VT,
9585                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
9586                                                  N10.getOperand(0))),
9587                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9588                                      N10.getOperand(1)),
9589                          N0);
9590     }
9591   }
9592 
9593   // fold (fsub (fpext (fneg (fmul, x, y))), z)
9594   //   -> (fneg (fma (fpext x), (fpext y), z))
9595   // Note: This could be removed with appropriate canonicalization of the
9596   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9597   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9598   // from implementing the canonicalization in visitFSUB.
9599   if (N0.getOpcode() == ISD::FP_EXTEND) {
9600     SDValue N00 = N0.getOperand(0);
9601     if (N00.getOpcode() == ISD::FNEG) {
9602       SDValue N000 = N00.getOperand(0);
9603       if (isContractableFMUL(N000) &&
9604           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9605         return DAG.getNode(ISD::FNEG, SL, VT,
9606                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9607                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9608                                                    N000.getOperand(0)),
9609                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9610                                                    N000.getOperand(1)),
9611                                        N1));
9612       }
9613     }
9614   }
9615 
9616   // fold (fsub (fneg (fpext (fmul, x, y))), z)
9617   //   -> (fneg (fma (fpext x)), (fpext y), z)
9618   // Note: This could be removed with appropriate canonicalization of the
9619   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9620   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9621   // from implementing the canonicalization in visitFSUB.
9622   if (N0.getOpcode() == ISD::FNEG) {
9623     SDValue N00 = N0.getOperand(0);
9624     if (N00.getOpcode() == ISD::FP_EXTEND) {
9625       SDValue N000 = N00.getOperand(0);
9626       if (isContractableFMUL(N000) &&
9627           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9628         return DAG.getNode(ISD::FNEG, SL, VT,
9629                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9630                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9631                                                    N000.getOperand(0)),
9632                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9633                                                    N000.getOperand(1)),
9634                                        N1));
9635       }
9636     }
9637   }
9638 
9639   // More folding opportunities when target permits.
9640   if (Aggressive) {
9641     // fold (fsub (fma x, y, (fmul u, v)), z)
9642     //   -> (fma x, y (fma u, v, (fneg z)))
9643     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9644     // are currently only supported on binary nodes.
9645     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9646         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9647         N0.getOperand(2)->hasOneUse()) {
9648       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9649                          N0.getOperand(0), N0.getOperand(1),
9650                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9651                                      N0.getOperand(2).getOperand(0),
9652                                      N0.getOperand(2).getOperand(1),
9653                                      DAG.getNode(ISD::FNEG, SL, VT,
9654                                                  N1)));
9655     }
9656 
9657     // fold (fsub x, (fma y, z, (fmul u, v)))
9658     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9659     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9660     // are currently only supported on binary nodes.
9661     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9662         isContractableFMUL(N1.getOperand(2))) {
9663       SDValue N20 = N1.getOperand(2).getOperand(0);
9664       SDValue N21 = N1.getOperand(2).getOperand(1);
9665       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9666                          DAG.getNode(ISD::FNEG, SL, VT,
9667                                      N1.getOperand(0)),
9668                          N1.getOperand(1),
9669                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9670                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9671 
9672                                      N21, N0));
9673     }
9674 
9675 
9676     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9677     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9678     if (N0.getOpcode() == PreferredFusedOpcode) {
9679       SDValue N02 = N0.getOperand(2);
9680       if (N02.getOpcode() == ISD::FP_EXTEND) {
9681         SDValue N020 = N02.getOperand(0);
9682         if (isContractableFMUL(N020) &&
9683             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9684           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9685                              N0.getOperand(0), N0.getOperand(1),
9686                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9687                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9688                                                      N020.getOperand(0)),
9689                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9690                                                      N020.getOperand(1)),
9691                                          DAG.getNode(ISD::FNEG, SL, VT,
9692                                                      N1)));
9693         }
9694       }
9695     }
9696 
9697     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9698     //   -> (fma (fpext x), (fpext y),
9699     //           (fma (fpext u), (fpext v), (fneg z)))
9700     // FIXME: This turns two single-precision and one double-precision
9701     // operation into two double-precision operations, which might not be
9702     // interesting for all targets, especially GPUs.
9703     if (N0.getOpcode() == ISD::FP_EXTEND) {
9704       SDValue N00 = N0.getOperand(0);
9705       if (N00.getOpcode() == PreferredFusedOpcode) {
9706         SDValue N002 = N00.getOperand(2);
9707         if (isContractableFMUL(N002) &&
9708             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9709           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9710                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9711                                          N00.getOperand(0)),
9712                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9713                                          N00.getOperand(1)),
9714                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9715                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9716                                                      N002.getOperand(0)),
9717                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9718                                                      N002.getOperand(1)),
9719                                          DAG.getNode(ISD::FNEG, SL, VT,
9720                                                      N1)));
9721         }
9722       }
9723     }
9724 
9725     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9726     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9727     if (N1.getOpcode() == PreferredFusedOpcode &&
9728         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9729       SDValue N120 = N1.getOperand(2).getOperand(0);
9730       if (isContractableFMUL(N120) &&
9731           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9732         SDValue N1200 = N120.getOperand(0);
9733         SDValue N1201 = N120.getOperand(1);
9734         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9735                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9736                            N1.getOperand(1),
9737                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9738                                        DAG.getNode(ISD::FNEG, SL, VT,
9739                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9740                                                                VT, N1200)),
9741                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9742                                                    N1201),
9743                                        N0));
9744       }
9745     }
9746 
9747     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9748     //   -> (fma (fneg (fpext y)), (fpext z),
9749     //           (fma (fneg (fpext u)), (fpext v), x))
9750     // FIXME: This turns two single-precision and one double-precision
9751     // operation into two double-precision operations, which might not be
9752     // interesting for all targets, especially GPUs.
9753     if (N1.getOpcode() == ISD::FP_EXTEND &&
9754         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9755       SDValue CvtSrc = N1.getOperand(0);
9756       SDValue N100 = CvtSrc.getOperand(0);
9757       SDValue N101 = CvtSrc.getOperand(1);
9758       SDValue N102 = CvtSrc.getOperand(2);
9759       if (isContractableFMUL(N102) &&
9760           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
9761         SDValue N1020 = N102.getOperand(0);
9762         SDValue N1021 = N102.getOperand(1);
9763         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9764                            DAG.getNode(ISD::FNEG, SL, VT,
9765                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9766                                                    N100)),
9767                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9768                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9769                                        DAG.getNode(ISD::FNEG, SL, VT,
9770                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9771                                                                VT, N1020)),
9772                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9773                                                    N1021),
9774                                        N0));
9775       }
9776     }
9777   }
9778 
9779   return SDValue();
9780 }
9781 
9782 /// Try to perform FMA combining on a given FMUL node based on the distributive
9783 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9784 /// subtraction instead of addition).
9785 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9786   SDValue N0 = N->getOperand(0);
9787   SDValue N1 = N->getOperand(1);
9788   EVT VT = N->getValueType(0);
9789   SDLoc SL(N);
9790 
9791   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9792 
9793   const TargetOptions &Options = DAG.getTarget().Options;
9794 
9795   // The transforms below are incorrect when x == 0 and y == inf, because the
9796   // intermediate multiplication produces a nan.
9797   if (!Options.NoInfsFPMath)
9798     return SDValue();
9799 
9800   // Floating-point multiply-add without intermediate rounding.
9801   bool HasFMA =
9802       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9803       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9804       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9805 
9806   // Floating-point multiply-add with intermediate rounding. This can result
9807   // in a less precise result due to the changed rounding order.
9808   bool HasFMAD = Options.UnsafeFPMath &&
9809                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9810 
9811   // No valid opcode, do not combine.
9812   if (!HasFMAD && !HasFMA)
9813     return SDValue();
9814 
9815   // Always prefer FMAD to FMA for precision.
9816   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9817   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9818 
9819   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9820   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9821   auto FuseFADD = [&](SDValue X, SDValue Y) {
9822     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9823       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9824       if (XC1 && XC1->isExactlyValue(+1.0))
9825         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9826       if (XC1 && XC1->isExactlyValue(-1.0))
9827         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9828                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9829     }
9830     return SDValue();
9831   };
9832 
9833   if (SDValue FMA = FuseFADD(N0, N1))
9834     return FMA;
9835   if (SDValue FMA = FuseFADD(N1, N0))
9836     return FMA;
9837 
9838   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9839   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9840   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9841   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9842   auto FuseFSUB = [&](SDValue X, SDValue Y) {
9843     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9844       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9845       if (XC0 && XC0->isExactlyValue(+1.0))
9846         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9847                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9848                            Y);
9849       if (XC0 && XC0->isExactlyValue(-1.0))
9850         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9851                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9852                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9853 
9854       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9855       if (XC1 && XC1->isExactlyValue(+1.0))
9856         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9857                            DAG.getNode(ISD::FNEG, SL, VT, Y));
9858       if (XC1 && XC1->isExactlyValue(-1.0))
9859         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9860     }
9861     return SDValue();
9862   };
9863 
9864   if (SDValue FMA = FuseFSUB(N0, N1))
9865     return FMA;
9866   if (SDValue FMA = FuseFSUB(N1, N0))
9867     return FMA;
9868 
9869   return SDValue();
9870 }
9871 
9872 static bool isFMulNegTwo(SDValue &N) {
9873   if (N.getOpcode() != ISD::FMUL)
9874     return false;
9875   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9876     return CFP->isExactlyValue(-2.0);
9877   return false;
9878 }
9879 
9880 SDValue DAGCombiner::visitFADD(SDNode *N) {
9881   SDValue N0 = N->getOperand(0);
9882   SDValue N1 = N->getOperand(1);
9883   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9884   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9885   EVT VT = N->getValueType(0);
9886   SDLoc DL(N);
9887   const TargetOptions &Options = DAG.getTarget().Options;
9888   const SDNodeFlags Flags = N->getFlags();
9889 
9890   // fold vector ops
9891   if (VT.isVector())
9892     if (SDValue FoldedVOp = SimplifyVBinOp(N))
9893       return FoldedVOp;
9894 
9895   // fold (fadd c1, c2) -> c1 + c2
9896   if (N0CFP && N1CFP)
9897     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9898 
9899   // canonicalize constant to RHS
9900   if (N0CFP && !N1CFP)
9901     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9902 
9903   if (SDValue NewSel = foldBinOpIntoSelect(N))
9904     return NewSel;
9905 
9906   // fold (fadd A, (fneg B)) -> (fsub A, B)
9907   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9908       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9909     return DAG.getNode(ISD::FSUB, DL, VT, N0,
9910                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9911 
9912   // fold (fadd (fneg A), B) -> (fsub B, A)
9913   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9914       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9915     return DAG.getNode(ISD::FSUB, DL, VT, N1,
9916                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9917 
9918   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9919   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9920   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9921       (isFMulNegTwo(N1) && N1.hasOneUse())) {
9922     bool N1IsFMul = isFMulNegTwo(N1);
9923     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9924     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9925     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9926   }
9927 
9928   // FIXME: Auto-upgrade the target/function-level option.
9929   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9930     // fold (fadd A, 0) -> A
9931     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9932       if (N1C->isZero())
9933         return N0;
9934   }
9935 
9936   // If 'unsafe math' is enabled, fold lots of things.
9937   if (Options.UnsafeFPMath) {
9938     // No FP constant should be created after legalization as Instruction
9939     // Selection pass has a hard time dealing with FP constants.
9940     bool AllowNewConst = (Level < AfterLegalizeDAG);
9941 
9942     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9943     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9944         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9945       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9946                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9947                                      Flags),
9948                          Flags);
9949 
9950     // If allowed, fold (fadd (fneg x), x) -> 0.0
9951     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9952       return DAG.getConstantFP(0.0, DL, VT);
9953 
9954     // If allowed, fold (fadd x, (fneg x)) -> 0.0
9955     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9956       return DAG.getConstantFP(0.0, DL, VT);
9957 
9958     // We can fold chains of FADD's of the same value into multiplications.
9959     // This transform is not safe in general because we are reducing the number
9960     // of rounding steps.
9961     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9962       if (N0.getOpcode() == ISD::FMUL) {
9963         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9964         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9965 
9966         // (fadd (fmul x, c), x) -> (fmul x, c+1)
9967         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9968           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9969                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9970           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9971         }
9972 
9973         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9974         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9975             N1.getOperand(0) == N1.getOperand(1) &&
9976             N0.getOperand(0) == N1.getOperand(0)) {
9977           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9978                                        DAG.getConstantFP(2.0, DL, VT), Flags);
9979           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9980         }
9981       }
9982 
9983       if (N1.getOpcode() == ISD::FMUL) {
9984         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9985         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9986 
9987         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9988         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9989           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9990                                        DAG.getConstantFP(1.0, DL, VT), Flags);
9991           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9992         }
9993 
9994         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9995         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9996             N0.getOperand(0) == N0.getOperand(1) &&
9997             N1.getOperand(0) == N0.getOperand(0)) {
9998           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9999                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10000           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
10001         }
10002       }
10003 
10004       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
10005         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10006         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
10007         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
10008             (N0.getOperand(0) == N1)) {
10009           return DAG.getNode(ISD::FMUL, DL, VT,
10010                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
10011         }
10012       }
10013 
10014       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
10015         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10016         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
10017         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
10018             N1.getOperand(0) == N0) {
10019           return DAG.getNode(ISD::FMUL, DL, VT,
10020                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
10021         }
10022       }
10023 
10024       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
10025       if (AllowNewConst &&
10026           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
10027           N0.getOperand(0) == N0.getOperand(1) &&
10028           N1.getOperand(0) == N1.getOperand(1) &&
10029           N0.getOperand(0) == N1.getOperand(0)) {
10030         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
10031                            DAG.getConstantFP(4.0, DL, VT), Flags);
10032       }
10033     }
10034   } // enable-unsafe-fp-math
10035 
10036   // FADD -> FMA combines:
10037   if (SDValue Fused = visitFADDForFMACombine(N)) {
10038     AddToWorklist(Fused.getNode());
10039     return Fused;
10040   }
10041   return SDValue();
10042 }
10043 
10044 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10045   SDValue N0 = N->getOperand(0);
10046   SDValue N1 = N->getOperand(1);
10047   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10048   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10049   EVT VT = N->getValueType(0);
10050   SDLoc DL(N);
10051   const TargetOptions &Options = DAG.getTarget().Options;
10052   const SDNodeFlags Flags = N->getFlags();
10053 
10054   // fold vector ops
10055   if (VT.isVector())
10056     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10057       return FoldedVOp;
10058 
10059   // fold (fsub c1, c2) -> c1-c2
10060   if (N0CFP && N1CFP)
10061     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10062 
10063   if (SDValue NewSel = foldBinOpIntoSelect(N))
10064     return NewSel;
10065 
10066   // fold (fsub A, (fneg B)) -> (fadd A, B)
10067   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10068     return DAG.getNode(ISD::FADD, DL, VT, N0,
10069                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10070 
10071   // FIXME: Auto-upgrade the target/function-level option.
10072   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
10073     // (fsub 0, B) -> -B
10074     if (N0CFP && N0CFP->isZero()) {
10075       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10076         return GetNegatedExpression(N1, DAG, LegalOperations);
10077       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10078         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10079     }
10080   }
10081 
10082   // If 'unsafe math' is enabled, fold lots of things.
10083   if (Options.UnsafeFPMath) {
10084     // (fsub A, 0) -> A
10085     if (N1CFP && N1CFP->isZero())
10086       return N0;
10087 
10088     // (fsub x, x) -> 0.0
10089     if (N0 == N1)
10090       return DAG.getConstantFP(0.0f, DL, VT);
10091 
10092     // (fsub x, (fadd x, y)) -> (fneg y)
10093     // (fsub x, (fadd y, x)) -> (fneg y)
10094     if (N1.getOpcode() == ISD::FADD) {
10095       SDValue N10 = N1->getOperand(0);
10096       SDValue N11 = N1->getOperand(1);
10097 
10098       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10099         return GetNegatedExpression(N11, DAG, LegalOperations);
10100 
10101       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10102         return GetNegatedExpression(N10, DAG, LegalOperations);
10103     }
10104   }
10105 
10106   // FSUB -> FMA combines:
10107   if (SDValue Fused = visitFSUBForFMACombine(N)) {
10108     AddToWorklist(Fused.getNode());
10109     return Fused;
10110   }
10111 
10112   return SDValue();
10113 }
10114 
10115 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10116   SDValue N0 = N->getOperand(0);
10117   SDValue N1 = N->getOperand(1);
10118   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10119   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10120   EVT VT = N->getValueType(0);
10121   SDLoc DL(N);
10122   const TargetOptions &Options = DAG.getTarget().Options;
10123   const SDNodeFlags Flags = N->getFlags();
10124 
10125   // fold vector ops
10126   if (VT.isVector()) {
10127     // This just handles C1 * C2 for vectors. Other vector folds are below.
10128     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10129       return FoldedVOp;
10130   }
10131 
10132   // fold (fmul c1, c2) -> c1*c2
10133   if (N0CFP && N1CFP)
10134     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10135 
10136   // canonicalize constant to RHS
10137   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10138      !isConstantFPBuildVectorOrConstantFP(N1))
10139     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10140 
10141   // fold (fmul A, 1.0) -> A
10142   if (N1CFP && N1CFP->isExactlyValue(1.0))
10143     return N0;
10144 
10145   if (SDValue NewSel = foldBinOpIntoSelect(N))
10146     return NewSel;
10147 
10148   if (Options.UnsafeFPMath) {
10149     // fold (fmul A, 0) -> 0
10150     if (N1CFP && N1CFP->isZero())
10151       return N1;
10152 
10153     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10154     if (N0.getOpcode() == ISD::FMUL) {
10155       // Fold scalars or any vector constants (not just splats).
10156       // This fold is done in general by InstCombine, but extra fmul insts
10157       // may have been generated during lowering.
10158       SDValue N00 = N0.getOperand(0);
10159       SDValue N01 = N0.getOperand(1);
10160       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10161       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10162       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10163 
10164       // Check 1: Make sure that the first operand of the inner multiply is NOT
10165       // a constant. Otherwise, we may induce infinite looping.
10166       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10167         // Check 2: Make sure that the second operand of the inner multiply and
10168         // the second operand of the outer multiply are constants.
10169         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10170             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10171           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10172           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10173         }
10174       }
10175     }
10176 
10177     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10178     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10179     // during an early run of DAGCombiner can prevent folding with fmuls
10180     // inserted during lowering.
10181     if (N0.getOpcode() == ISD::FADD &&
10182         (N0.getOperand(0) == N0.getOperand(1)) &&
10183         N0.hasOneUse()) {
10184       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10185       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10186       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10187     }
10188   }
10189 
10190   // fold (fmul X, 2.0) -> (fadd X, X)
10191   if (N1CFP && N1CFP->isExactlyValue(+2.0))
10192     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10193 
10194   // fold (fmul X, -1.0) -> (fneg X)
10195   if (N1CFP && N1CFP->isExactlyValue(-1.0))
10196     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10197       return DAG.getNode(ISD::FNEG, DL, VT, N0);
10198 
10199   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10200   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10201     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10202       // Both can be negated for free, check to see if at least one is cheaper
10203       // negated.
10204       if (LHSNeg == 2 || RHSNeg == 2)
10205         return DAG.getNode(ISD::FMUL, DL, VT,
10206                            GetNegatedExpression(N0, DAG, LegalOperations),
10207                            GetNegatedExpression(N1, DAG, LegalOperations),
10208                            Flags);
10209     }
10210   }
10211 
10212   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10213   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10214   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10215       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10216       TLI.isOperationLegal(ISD::FABS, VT)) {
10217     SDValue Select = N0, X = N1;
10218     if (Select.getOpcode() != ISD::SELECT)
10219       std::swap(Select, X);
10220 
10221     SDValue Cond = Select.getOperand(0);
10222     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10223     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10224 
10225     if (TrueOpnd && FalseOpnd &&
10226         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10227         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10228         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10229       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10230       switch (CC) {
10231       default: break;
10232       case ISD::SETOLT:
10233       case ISD::SETULT:
10234       case ISD::SETOLE:
10235       case ISD::SETULE:
10236       case ISD::SETLT:
10237       case ISD::SETLE:
10238         std::swap(TrueOpnd, FalseOpnd);
10239         LLVM_FALLTHROUGH;
10240       case ISD::SETOGT:
10241       case ISD::SETUGT:
10242       case ISD::SETOGE:
10243       case ISD::SETUGE:
10244       case ISD::SETGT:
10245       case ISD::SETGE:
10246         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10247             TLI.isOperationLegal(ISD::FNEG, VT))
10248           return DAG.getNode(ISD::FNEG, DL, VT,
10249                    DAG.getNode(ISD::FABS, DL, VT, X));
10250         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10251           return DAG.getNode(ISD::FABS, DL, VT, X);
10252 
10253         break;
10254       }
10255     }
10256   }
10257 
10258   // FMUL -> FMA combines:
10259   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10260     AddToWorklist(Fused.getNode());
10261     return Fused;
10262   }
10263 
10264   return SDValue();
10265 }
10266 
10267 SDValue DAGCombiner::visitFMA(SDNode *N) {
10268   SDValue N0 = N->getOperand(0);
10269   SDValue N1 = N->getOperand(1);
10270   SDValue N2 = N->getOperand(2);
10271   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10272   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10273   EVT VT = N->getValueType(0);
10274   SDLoc DL(N);
10275   const TargetOptions &Options = DAG.getTarget().Options;
10276 
10277   // Constant fold FMA.
10278   if (isa<ConstantFPSDNode>(N0) &&
10279       isa<ConstantFPSDNode>(N1) &&
10280       isa<ConstantFPSDNode>(N2)) {
10281     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10282   }
10283 
10284   if (Options.UnsafeFPMath) {
10285     if (N0CFP && N0CFP->isZero())
10286       return N2;
10287     if (N1CFP && N1CFP->isZero())
10288       return N2;
10289   }
10290   // TODO: The FMA node should have flags that propagate to these nodes.
10291   if (N0CFP && N0CFP->isExactlyValue(1.0))
10292     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10293   if (N1CFP && N1CFP->isExactlyValue(1.0))
10294     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10295 
10296   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10297   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10298      !isConstantFPBuildVectorOrConstantFP(N1))
10299     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10300 
10301   // TODO: FMA nodes should have flags that propagate to the created nodes.
10302   // For now, create a Flags object for use with all unsafe math transforms.
10303   SDNodeFlags Flags;
10304   Flags.setUnsafeAlgebra(true);
10305 
10306   if (Options.UnsafeFPMath) {
10307     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10308     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10309         isConstantFPBuildVectorOrConstantFP(N1) &&
10310         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10311       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10312                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10313                                      Flags), Flags);
10314     }
10315 
10316     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10317     if (N0.getOpcode() == ISD::FMUL &&
10318         isConstantFPBuildVectorOrConstantFP(N1) &&
10319         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10320       return DAG.getNode(ISD::FMA, DL, VT,
10321                          N0.getOperand(0),
10322                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10323                                      Flags),
10324                          N2);
10325     }
10326   }
10327 
10328   // (fma x, 1, y) -> (fadd x, y)
10329   // (fma x, -1, y) -> (fadd (fneg x), y)
10330   if (N1CFP) {
10331     if (N1CFP->isExactlyValue(1.0))
10332       // TODO: The FMA node should have flags that propagate to this node.
10333       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10334 
10335     if (N1CFP->isExactlyValue(-1.0) &&
10336         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10337       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10338       AddToWorklist(RHSNeg.getNode());
10339       // TODO: The FMA node should have flags that propagate to this node.
10340       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10341     }
10342 
10343     // fma (fneg x), K, y -> fma x -K, y
10344     if (N0.getOpcode() == ISD::FNEG &&
10345         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10346          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10347       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10348                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10349     }
10350   }
10351 
10352   if (Options.UnsafeFPMath) {
10353     // (fma x, c, x) -> (fmul x, (c+1))
10354     if (N1CFP && N0 == N2) {
10355       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10356                          DAG.getNode(ISD::FADD, DL, VT, N1,
10357                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10358                          Flags);
10359     }
10360 
10361     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10362     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10363       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10364                          DAG.getNode(ISD::FADD, DL, VT, N1,
10365                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10366                          Flags);
10367     }
10368   }
10369 
10370   return SDValue();
10371 }
10372 
10373 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10374 // reciprocal.
10375 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10376 // Notice that this is not always beneficial. One reason is different targets
10377 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10378 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10379 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10380 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10381   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10382   const SDNodeFlags Flags = N->getFlags();
10383   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10384     return SDValue();
10385 
10386   // Skip if current node is a reciprocal.
10387   SDValue N0 = N->getOperand(0);
10388   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10389   if (N0CFP && N0CFP->isExactlyValue(1.0))
10390     return SDValue();
10391 
10392   // Exit early if the target does not want this transform or if there can't
10393   // possibly be enough uses of the divisor to make the transform worthwhile.
10394   SDValue N1 = N->getOperand(1);
10395   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10396   if (!MinUses || N1->use_size() < MinUses)
10397     return SDValue();
10398 
10399   // Find all FDIV users of the same divisor.
10400   // Use a set because duplicates may be present in the user list.
10401   SetVector<SDNode *> Users;
10402   for (auto *U : N1->uses()) {
10403     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10404       // This division is eligible for optimization only if global unsafe math
10405       // is enabled or if this division allows reciprocal formation.
10406       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10407         Users.insert(U);
10408     }
10409   }
10410 
10411   // Now that we have the actual number of divisor uses, make sure it meets
10412   // the minimum threshold specified by the target.
10413   if (Users.size() < MinUses)
10414     return SDValue();
10415 
10416   EVT VT = N->getValueType(0);
10417   SDLoc DL(N);
10418   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10419   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10420 
10421   // Dividend / Divisor -> Dividend * Reciprocal
10422   for (auto *U : Users) {
10423     SDValue Dividend = U->getOperand(0);
10424     if (Dividend != FPOne) {
10425       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10426                                     Reciprocal, Flags);
10427       CombineTo(U, NewNode);
10428     } else if (U != Reciprocal.getNode()) {
10429       // In the absence of fast-math-flags, this user node is always the
10430       // same node as Reciprocal, but with FMF they may be different nodes.
10431       CombineTo(U, Reciprocal);
10432     }
10433   }
10434   return SDValue(N, 0);  // N was replaced.
10435 }
10436 
10437 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10438   SDValue N0 = N->getOperand(0);
10439   SDValue N1 = N->getOperand(1);
10440   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10441   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10442   EVT VT = N->getValueType(0);
10443   SDLoc DL(N);
10444   const TargetOptions &Options = DAG.getTarget().Options;
10445   SDNodeFlags Flags = N->getFlags();
10446 
10447   // fold vector ops
10448   if (VT.isVector())
10449     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10450       return FoldedVOp;
10451 
10452   // fold (fdiv c1, c2) -> c1/c2
10453   if (N0CFP && N1CFP)
10454     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10455 
10456   if (SDValue NewSel = foldBinOpIntoSelect(N))
10457     return NewSel;
10458 
10459   if (Options.UnsafeFPMath) {
10460     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10461     if (N1CFP) {
10462       // Compute the reciprocal 1.0 / c2.
10463       const APFloat &N1APF = N1CFP->getValueAPF();
10464       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10465       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10466       // Only do the transform if the reciprocal is a legal fp immediate that
10467       // isn't too nasty (eg NaN, denormal, ...).
10468       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10469           (!LegalOperations ||
10470            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10471            // backend)... we should handle this gracefully after Legalize.
10472            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10473            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10474            TLI.isFPImmLegal(Recip, VT)))
10475         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10476                            DAG.getConstantFP(Recip, DL, VT), Flags);
10477     }
10478 
10479     // If this FDIV is part of a reciprocal square root, it may be folded
10480     // into a target-specific square root estimate instruction.
10481     if (N1.getOpcode() == ISD::FSQRT) {
10482       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10483         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10484       }
10485     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10486                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10487       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10488                                           Flags)) {
10489         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10490         AddToWorklist(RV.getNode());
10491         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10492       }
10493     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10494                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10495       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10496                                           Flags)) {
10497         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10498         AddToWorklist(RV.getNode());
10499         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10500       }
10501     } else if (N1.getOpcode() == ISD::FMUL) {
10502       // Look through an FMUL. Even though this won't remove the FDIV directly,
10503       // it's still worthwhile to get rid of the FSQRT if possible.
10504       SDValue SqrtOp;
10505       SDValue OtherOp;
10506       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10507         SqrtOp = N1.getOperand(0);
10508         OtherOp = N1.getOperand(1);
10509       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10510         SqrtOp = N1.getOperand(1);
10511         OtherOp = N1.getOperand(0);
10512       }
10513       if (SqrtOp.getNode()) {
10514         // We found a FSQRT, so try to make this fold:
10515         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10516         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10517           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10518           AddToWorklist(RV.getNode());
10519           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10520         }
10521       }
10522     }
10523 
10524     // Fold into a reciprocal estimate and multiply instead of a real divide.
10525     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10526       AddToWorklist(RV.getNode());
10527       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10528     }
10529   }
10530 
10531   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10532   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10533     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10534       // Both can be negated for free, check to see if at least one is cheaper
10535       // negated.
10536       if (LHSNeg == 2 || RHSNeg == 2)
10537         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10538                            GetNegatedExpression(N0, DAG, LegalOperations),
10539                            GetNegatedExpression(N1, DAG, LegalOperations),
10540                            Flags);
10541     }
10542   }
10543 
10544   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10545     return CombineRepeatedDivisors;
10546 
10547   return SDValue();
10548 }
10549 
10550 SDValue DAGCombiner::visitFREM(SDNode *N) {
10551   SDValue N0 = N->getOperand(0);
10552   SDValue N1 = N->getOperand(1);
10553   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10554   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10555   EVT VT = N->getValueType(0);
10556 
10557   // fold (frem c1, c2) -> fmod(c1,c2)
10558   if (N0CFP && N1CFP)
10559     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10560 
10561   if (SDValue NewSel = foldBinOpIntoSelect(N))
10562     return NewSel;
10563 
10564   return SDValue();
10565 }
10566 
10567 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10568   if (!DAG.getTarget().Options.UnsafeFPMath)
10569     return SDValue();
10570 
10571   SDValue N0 = N->getOperand(0);
10572   if (TLI.isFsqrtCheap(N0, DAG))
10573     return SDValue();
10574 
10575   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10576   // For now, create a Flags object for use with all unsafe math transforms.
10577   SDNodeFlags Flags;
10578   Flags.setUnsafeAlgebra(true);
10579   return buildSqrtEstimate(N0, Flags);
10580 }
10581 
10582 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10583 /// copysign(x, fp_round(y)) -> copysign(x, y)
10584 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10585   SDValue N1 = N->getOperand(1);
10586   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10587        N1.getOpcode() == ISD::FP_ROUND)) {
10588     // Do not optimize out type conversion of f128 type yet.
10589     // For some targets like x86_64, configuration is changed to keep one f128
10590     // value in one SSE register, but instruction selection cannot handle
10591     // FCOPYSIGN on SSE registers yet.
10592     EVT N1VT = N1->getValueType(0);
10593     EVT N1Op0VT = N1->getOperand(0).getValueType();
10594     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10595   }
10596   return false;
10597 }
10598 
10599 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10600   SDValue N0 = N->getOperand(0);
10601   SDValue N1 = N->getOperand(1);
10602   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10603   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10604   EVT VT = N->getValueType(0);
10605 
10606   if (N0CFP && N1CFP) // Constant fold
10607     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10608 
10609   if (N1CFP) {
10610     const APFloat &V = N1CFP->getValueAPF();
10611     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10612     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10613     if (!V.isNegative()) {
10614       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10615         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10616     } else {
10617       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10618         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10619                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10620     }
10621   }
10622 
10623   // copysign(fabs(x), y) -> copysign(x, y)
10624   // copysign(fneg(x), y) -> copysign(x, y)
10625   // copysign(copysign(x,z), y) -> copysign(x, y)
10626   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10627       N0.getOpcode() == ISD::FCOPYSIGN)
10628     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10629 
10630   // copysign(x, abs(y)) -> abs(x)
10631   if (N1.getOpcode() == ISD::FABS)
10632     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10633 
10634   // copysign(x, copysign(y,z)) -> copysign(x, z)
10635   if (N1.getOpcode() == ISD::FCOPYSIGN)
10636     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10637 
10638   // copysign(x, fp_extend(y)) -> copysign(x, y)
10639   // copysign(x, fp_round(y)) -> copysign(x, y)
10640   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10641     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10642 
10643   return SDValue();
10644 }
10645 
10646 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10647   SDValue N0 = N->getOperand(0);
10648   EVT VT = N->getValueType(0);
10649   EVT OpVT = N0.getValueType();
10650 
10651   // fold (sint_to_fp c1) -> c1fp
10652   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10653       // ...but only if the target supports immediate floating-point values
10654       (!LegalOperations ||
10655        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10656     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10657 
10658   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10659   // but UINT_TO_FP is legal on this target, try to convert.
10660   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10661       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10662     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10663     if (DAG.SignBitIsZero(N0))
10664       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10665   }
10666 
10667   // The next optimizations are desirable only if SELECT_CC can be lowered.
10668   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10669     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10670     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10671         !VT.isVector() &&
10672         (!LegalOperations ||
10673          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10674       SDLoc DL(N);
10675       SDValue Ops[] =
10676         { N0.getOperand(0), N0.getOperand(1),
10677           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10678           N0.getOperand(2) };
10679       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10680     }
10681 
10682     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10683     //      (select_cc x, y, 1.0, 0.0,, cc)
10684     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10685         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10686         (!LegalOperations ||
10687          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10688       SDLoc DL(N);
10689       SDValue Ops[] =
10690         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10691           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10692           N0.getOperand(0).getOperand(2) };
10693       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10694     }
10695   }
10696 
10697   return SDValue();
10698 }
10699 
10700 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10701   SDValue N0 = N->getOperand(0);
10702   EVT VT = N->getValueType(0);
10703   EVT OpVT = N0.getValueType();
10704 
10705   // fold (uint_to_fp c1) -> c1fp
10706   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10707       // ...but only if the target supports immediate floating-point values
10708       (!LegalOperations ||
10709        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10710     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10711 
10712   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10713   // but SINT_TO_FP is legal on this target, try to convert.
10714   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10715       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10716     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10717     if (DAG.SignBitIsZero(N0))
10718       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10719   }
10720 
10721   // The next optimizations are desirable only if SELECT_CC can be lowered.
10722   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10723     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10724     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10725         (!LegalOperations ||
10726          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10727       SDLoc DL(N);
10728       SDValue Ops[] =
10729         { N0.getOperand(0), N0.getOperand(1),
10730           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10731           N0.getOperand(2) };
10732       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10733     }
10734   }
10735 
10736   return SDValue();
10737 }
10738 
10739 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10740 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10741   SDValue N0 = N->getOperand(0);
10742   EVT VT = N->getValueType(0);
10743 
10744   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10745     return SDValue();
10746 
10747   SDValue Src = N0.getOperand(0);
10748   EVT SrcVT = Src.getValueType();
10749   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10750   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10751 
10752   // We can safely assume the conversion won't overflow the output range,
10753   // because (for example) (uint8_t)18293.f is undefined behavior.
10754 
10755   // Since we can assume the conversion won't overflow, our decision as to
10756   // whether the input will fit in the float should depend on the minimum
10757   // of the input range and output range.
10758 
10759   // This means this is also safe for a signed input and unsigned output, since
10760   // a negative input would lead to undefined behavior.
10761   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10762   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10763   unsigned ActualSize = std::min(InputSize, OutputSize);
10764   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10765 
10766   // We can only fold away the float conversion if the input range can be
10767   // represented exactly in the float range.
10768   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10769     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10770       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10771                                                        : ISD::ZERO_EXTEND;
10772       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10773     }
10774     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10775       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10776     return DAG.getBitcast(VT, Src);
10777   }
10778   return SDValue();
10779 }
10780 
10781 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10782   SDValue N0 = N->getOperand(0);
10783   EVT VT = N->getValueType(0);
10784 
10785   // fold (fp_to_sint c1fp) -> c1
10786   if (isConstantFPBuildVectorOrConstantFP(N0))
10787     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10788 
10789   return FoldIntToFPToInt(N, DAG);
10790 }
10791 
10792 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10793   SDValue N0 = N->getOperand(0);
10794   EVT VT = N->getValueType(0);
10795 
10796   // fold (fp_to_uint c1fp) -> c1
10797   if (isConstantFPBuildVectorOrConstantFP(N0))
10798     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10799 
10800   return FoldIntToFPToInt(N, DAG);
10801 }
10802 
10803 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10804   SDValue N0 = N->getOperand(0);
10805   SDValue N1 = N->getOperand(1);
10806   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10807   EVT VT = N->getValueType(0);
10808 
10809   // fold (fp_round c1fp) -> c1fp
10810   if (N0CFP)
10811     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10812 
10813   // fold (fp_round (fp_extend x)) -> x
10814   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10815     return N0.getOperand(0);
10816 
10817   // fold (fp_round (fp_round x)) -> (fp_round x)
10818   if (N0.getOpcode() == ISD::FP_ROUND) {
10819     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10820     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10821 
10822     // Skip this folding if it results in an fp_round from f80 to f16.
10823     //
10824     // f80 to f16 always generates an expensive (and as yet, unimplemented)
10825     // libcall to __truncxfhf2 instead of selecting native f16 conversion
10826     // instructions from f32 or f64.  Moreover, the first (value-preserving)
10827     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10828     // x86.
10829     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10830       return SDValue();
10831 
10832     // If the first fp_round isn't a value preserving truncation, it might
10833     // introduce a tie in the second fp_round, that wouldn't occur in the
10834     // single-step fp_round we want to fold to.
10835     // In other words, double rounding isn't the same as rounding.
10836     // Also, this is a value preserving truncation iff both fp_round's are.
10837     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10838       SDLoc DL(N);
10839       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10840                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10841     }
10842   }
10843 
10844   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10845   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10846     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10847                               N0.getOperand(0), N1);
10848     AddToWorklist(Tmp.getNode());
10849     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10850                        Tmp, N0.getOperand(1));
10851   }
10852 
10853   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10854     return NewVSel;
10855 
10856   return SDValue();
10857 }
10858 
10859 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10860   SDValue N0 = N->getOperand(0);
10861   EVT VT = N->getValueType(0);
10862   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10863   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10864 
10865   // fold (fp_round_inreg c1fp) -> c1fp
10866   if (N0CFP && isTypeLegal(EVT)) {
10867     SDLoc DL(N);
10868     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10869     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10870   }
10871 
10872   return SDValue();
10873 }
10874 
10875 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10876   SDValue N0 = N->getOperand(0);
10877   EVT VT = N->getValueType(0);
10878 
10879   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10880   if (N->hasOneUse() &&
10881       N->use_begin()->getOpcode() == ISD::FP_ROUND)
10882     return SDValue();
10883 
10884   // fold (fp_extend c1fp) -> c1fp
10885   if (isConstantFPBuildVectorOrConstantFP(N0))
10886     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10887 
10888   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10889   if (N0.getOpcode() == ISD::FP16_TO_FP &&
10890       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10891     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10892 
10893   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10894   // value of X.
10895   if (N0.getOpcode() == ISD::FP_ROUND
10896       && N0.getConstantOperandVal(1) == 1) {
10897     SDValue In = N0.getOperand(0);
10898     if (In.getValueType() == VT) return In;
10899     if (VT.bitsLT(In.getValueType()))
10900       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10901                          In, N0.getOperand(1));
10902     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10903   }
10904 
10905   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10906   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10907        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10908     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10909     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10910                                      LN0->getChain(),
10911                                      LN0->getBasePtr(), N0.getValueType(),
10912                                      LN0->getMemOperand());
10913     CombineTo(N, ExtLoad);
10914     CombineTo(N0.getNode(),
10915               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10916                           N0.getValueType(), ExtLoad,
10917                           DAG.getIntPtrConstant(1, SDLoc(N0))),
10918               ExtLoad.getValue(1));
10919     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10920   }
10921 
10922   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10923     return NewVSel;
10924 
10925   return SDValue();
10926 }
10927 
10928 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10929   SDValue N0 = N->getOperand(0);
10930   EVT VT = N->getValueType(0);
10931 
10932   // fold (fceil c1) -> fceil(c1)
10933   if (isConstantFPBuildVectorOrConstantFP(N0))
10934     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10935 
10936   return SDValue();
10937 }
10938 
10939 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10940   SDValue N0 = N->getOperand(0);
10941   EVT VT = N->getValueType(0);
10942 
10943   // fold (ftrunc c1) -> ftrunc(c1)
10944   if (isConstantFPBuildVectorOrConstantFP(N0))
10945     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10946 
10947   // fold ftrunc (known rounded int x) -> x
10948   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
10949   // likely to be generated to extract integer from a rounded floating value.
10950   switch (N0.getOpcode()) {
10951   default: break;
10952   case ISD::FRINT:
10953   case ISD::FTRUNC:
10954   case ISD::FNEARBYINT:
10955   case ISD::FFLOOR:
10956   case ISD::FCEIL:
10957     return N0;
10958   }
10959 
10960   return SDValue();
10961 }
10962 
10963 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10964   SDValue N0 = N->getOperand(0);
10965   EVT VT = N->getValueType(0);
10966 
10967   // fold (ffloor c1) -> ffloor(c1)
10968   if (isConstantFPBuildVectorOrConstantFP(N0))
10969     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10970 
10971   return SDValue();
10972 }
10973 
10974 // FIXME: FNEG and FABS have a lot in common; refactor.
10975 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10976   SDValue N0 = N->getOperand(0);
10977   EVT VT = N->getValueType(0);
10978 
10979   // Constant fold FNEG.
10980   if (isConstantFPBuildVectorOrConstantFP(N0))
10981     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10982 
10983   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10984                          &DAG.getTarget().Options))
10985     return GetNegatedExpression(N0, DAG, LegalOperations);
10986 
10987   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10988   // constant pool values.
10989   if (!TLI.isFNegFree(VT) &&
10990       N0.getOpcode() == ISD::BITCAST &&
10991       N0.getNode()->hasOneUse()) {
10992     SDValue Int = N0.getOperand(0);
10993     EVT IntVT = Int.getValueType();
10994     if (IntVT.isInteger() && !IntVT.isVector()) {
10995       APInt SignMask;
10996       if (N0.getValueType().isVector()) {
10997         // For a vector, get a mask such as 0x80... per scalar element
10998         // and splat it.
10999         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
11000         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11001       } else {
11002         // For a scalar, just generate 0x80...
11003         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
11004       }
11005       SDLoc DL0(N0);
11006       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
11007                         DAG.getConstant(SignMask, DL0, IntVT));
11008       AddToWorklist(Int.getNode());
11009       return DAG.getBitcast(VT, Int);
11010     }
11011   }
11012 
11013   // (fneg (fmul c, x)) -> (fmul -c, x)
11014   if (N0.getOpcode() == ISD::FMUL &&
11015       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
11016     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
11017     if (CFP1) {
11018       APFloat CVal = CFP1->getValueAPF();
11019       CVal.changeSign();
11020       if (Level >= AfterLegalizeDAG &&
11021           (TLI.isFPImmLegal(CVal, VT) ||
11022            TLI.isOperationLegal(ISD::ConstantFP, VT)))
11023         return DAG.getNode(
11024             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
11025             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
11026             N0->getFlags());
11027     }
11028   }
11029 
11030   return SDValue();
11031 }
11032 
11033 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
11034   SDValue N0 = N->getOperand(0);
11035   SDValue N1 = N->getOperand(1);
11036   EVT VT = N->getValueType(0);
11037   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11038   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11039 
11040   if (N0CFP && N1CFP) {
11041     const APFloat &C0 = N0CFP->getValueAPF();
11042     const APFloat &C1 = N1CFP->getValueAPF();
11043     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11044   }
11045 
11046   // Canonicalize to constant on RHS.
11047   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11048      !isConstantFPBuildVectorOrConstantFP(N1))
11049     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11050 
11051   return SDValue();
11052 }
11053 
11054 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11055   SDValue N0 = N->getOperand(0);
11056   SDValue N1 = N->getOperand(1);
11057   EVT VT = N->getValueType(0);
11058   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11059   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11060 
11061   if (N0CFP && N1CFP) {
11062     const APFloat &C0 = N0CFP->getValueAPF();
11063     const APFloat &C1 = N1CFP->getValueAPF();
11064     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11065   }
11066 
11067   // Canonicalize to constant on RHS.
11068   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11069      !isConstantFPBuildVectorOrConstantFP(N1))
11070     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11071 
11072   return SDValue();
11073 }
11074 
11075 SDValue DAGCombiner::visitFABS(SDNode *N) {
11076   SDValue N0 = N->getOperand(0);
11077   EVT VT = N->getValueType(0);
11078 
11079   // fold (fabs c1) -> fabs(c1)
11080   if (isConstantFPBuildVectorOrConstantFP(N0))
11081     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11082 
11083   // fold (fabs (fabs x)) -> (fabs x)
11084   if (N0.getOpcode() == ISD::FABS)
11085     return N->getOperand(0);
11086 
11087   // fold (fabs (fneg x)) -> (fabs x)
11088   // fold (fabs (fcopysign x, y)) -> (fabs x)
11089   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11090     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11091 
11092   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11093   // constant pool values.
11094   if (!TLI.isFAbsFree(VT) &&
11095       N0.getOpcode() == ISD::BITCAST &&
11096       N0.getNode()->hasOneUse()) {
11097     SDValue Int = N0.getOperand(0);
11098     EVT IntVT = Int.getValueType();
11099     if (IntVT.isInteger() && !IntVT.isVector()) {
11100       APInt SignMask;
11101       if (N0.getValueType().isVector()) {
11102         // For a vector, get a mask such as 0x7f... per scalar element
11103         // and splat it.
11104         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11105         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11106       } else {
11107         // For a scalar, just generate 0x7f...
11108         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11109       }
11110       SDLoc DL(N0);
11111       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11112                         DAG.getConstant(SignMask, DL, IntVT));
11113       AddToWorklist(Int.getNode());
11114       return DAG.getBitcast(N->getValueType(0), Int);
11115     }
11116   }
11117 
11118   return SDValue();
11119 }
11120 
11121 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11122   SDValue Chain = N->getOperand(0);
11123   SDValue N1 = N->getOperand(1);
11124   SDValue N2 = N->getOperand(2);
11125 
11126   // If N is a constant we could fold this into a fallthrough or unconditional
11127   // branch. However that doesn't happen very often in normal code, because
11128   // Instcombine/SimplifyCFG should have handled the available opportunities.
11129   // If we did this folding here, it would be necessary to update the
11130   // MachineBasicBlock CFG, which is awkward.
11131 
11132   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11133   // on the target.
11134   if (N1.getOpcode() == ISD::SETCC &&
11135       TLI.isOperationLegalOrCustom(ISD::BR_CC,
11136                                    N1.getOperand(0).getValueType())) {
11137     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11138                        Chain, N1.getOperand(2),
11139                        N1.getOperand(0), N1.getOperand(1), N2);
11140   }
11141 
11142   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
11143       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
11144        (N1.getOperand(0).hasOneUse() &&
11145         N1.getOperand(0).getOpcode() == ISD::SRL))) {
11146     SDNode *Trunc = nullptr;
11147     if (N1.getOpcode() == ISD::TRUNCATE) {
11148       // Look pass the truncate.
11149       Trunc = N1.getNode();
11150       N1 = N1.getOperand(0);
11151     }
11152 
11153     // Match this pattern so that we can generate simpler code:
11154     //
11155     //   %a = ...
11156     //   %b = and i32 %a, 2
11157     //   %c = srl i32 %b, 1
11158     //   brcond i32 %c ...
11159     //
11160     // into
11161     //
11162     //   %a = ...
11163     //   %b = and i32 %a, 2
11164     //   %c = setcc eq %b, 0
11165     //   brcond %c ...
11166     //
11167     // This applies only when the AND constant value has one bit set and the
11168     // SRL constant is equal to the log2 of the AND constant. The back-end is
11169     // smart enough to convert the result into a TEST/JMP sequence.
11170     SDValue Op0 = N1.getOperand(0);
11171     SDValue Op1 = N1.getOperand(1);
11172 
11173     if (Op0.getOpcode() == ISD::AND &&
11174         Op1.getOpcode() == ISD::Constant) {
11175       SDValue AndOp1 = Op0.getOperand(1);
11176 
11177       if (AndOp1.getOpcode() == ISD::Constant) {
11178         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11179 
11180         if (AndConst.isPowerOf2() &&
11181             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
11182           SDLoc DL(N);
11183           SDValue SetCC =
11184             DAG.getSetCC(DL,
11185                          getSetCCResultType(Op0.getValueType()),
11186                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11187                          ISD::SETNE);
11188 
11189           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
11190                                           MVT::Other, Chain, SetCC, N2);
11191           // Don't add the new BRCond into the worklist or else SimplifySelectCC
11192           // will convert it back to (X & C1) >> C2.
11193           CombineTo(N, NewBRCond, false);
11194           // Truncate is dead.
11195           if (Trunc)
11196             deleteAndRecombine(Trunc);
11197           // Replace the uses of SRL with SETCC
11198           WorklistRemover DeadNodes(*this);
11199           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11200           deleteAndRecombine(N1.getNode());
11201           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11202         }
11203       }
11204     }
11205 
11206     if (Trunc)
11207       // Restore N1 if the above transformation doesn't match.
11208       N1 = N->getOperand(1);
11209   }
11210 
11211   // Transform br(xor(x, y)) -> br(x != y)
11212   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11213   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
11214     SDNode *TheXor = N1.getNode();
11215     SDValue Op0 = TheXor->getOperand(0);
11216     SDValue Op1 = TheXor->getOperand(1);
11217     if (Op0.getOpcode() == Op1.getOpcode()) {
11218       // Avoid missing important xor optimizations.
11219       if (SDValue Tmp = visitXOR(TheXor)) {
11220         if (Tmp.getNode() != TheXor) {
11221           DEBUG(dbgs() << "\nReplacing.8 ";
11222                 TheXor->dump(&DAG);
11223                 dbgs() << "\nWith: ";
11224                 Tmp.getNode()->dump(&DAG);
11225                 dbgs() << '\n');
11226           WorklistRemover DeadNodes(*this);
11227           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
11228           deleteAndRecombine(TheXor);
11229           return DAG.getNode(ISD::BRCOND, SDLoc(N),
11230                              MVT::Other, Chain, Tmp, N2);
11231         }
11232 
11233         // visitXOR has changed XOR's operands or replaced the XOR completely,
11234         // bail out.
11235         return SDValue(N, 0);
11236       }
11237     }
11238 
11239     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11240       bool Equal = false;
11241       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11242           Op0.getOpcode() == ISD::XOR) {
11243         TheXor = Op0.getNode();
11244         Equal = true;
11245       }
11246 
11247       EVT SetCCVT = N1.getValueType();
11248       if (LegalTypes)
11249         SetCCVT = getSetCCResultType(SetCCVT);
11250       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
11251                                    SetCCVT,
11252                                    Op0, Op1,
11253                                    Equal ? ISD::SETEQ : ISD::SETNE);
11254       // Replace the uses of XOR with SETCC
11255       WorklistRemover DeadNodes(*this);
11256       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
11257       deleteAndRecombine(N1.getNode());
11258       return DAG.getNode(ISD::BRCOND, SDLoc(N),
11259                          MVT::Other, Chain, SetCC, N2);
11260     }
11261   }
11262 
11263   return SDValue();
11264 }
11265 
11266 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11267 //
11268 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11269   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11270   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11271 
11272   // If N is a constant we could fold this into a fallthrough or unconditional
11273   // branch. However that doesn't happen very often in normal code, because
11274   // Instcombine/SimplifyCFG should have handled the available opportunities.
11275   // If we did this folding here, it would be necessary to update the
11276   // MachineBasicBlock CFG, which is awkward.
11277 
11278   // Use SimplifySetCC to simplify SETCC's.
11279   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11280                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11281                                false);
11282   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11283 
11284   // fold to a simpler setcc
11285   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11286     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11287                        N->getOperand(0), Simp.getOperand(2),
11288                        Simp.getOperand(0), Simp.getOperand(1),
11289                        N->getOperand(4));
11290 
11291   return SDValue();
11292 }
11293 
11294 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11295 /// and that N may be folded in the load / store addressing mode.
11296 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11297                                     SelectionDAG &DAG,
11298                                     const TargetLowering &TLI) {
11299   EVT VT;
11300   unsigned AS;
11301 
11302   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11303     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11304       return false;
11305     VT = LD->getMemoryVT();
11306     AS = LD->getAddressSpace();
11307   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11308     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11309       return false;
11310     VT = ST->getMemoryVT();
11311     AS = ST->getAddressSpace();
11312   } else
11313     return false;
11314 
11315   TargetLowering::AddrMode AM;
11316   if (N->getOpcode() == ISD::ADD) {
11317     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11318     if (Offset)
11319       // [reg +/- imm]
11320       AM.BaseOffs = Offset->getSExtValue();
11321     else
11322       // [reg +/- reg]
11323       AM.Scale = 1;
11324   } else if (N->getOpcode() == ISD::SUB) {
11325     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11326     if (Offset)
11327       // [reg +/- imm]
11328       AM.BaseOffs = -Offset->getSExtValue();
11329     else
11330       // [reg +/- reg]
11331       AM.Scale = 1;
11332   } else
11333     return false;
11334 
11335   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11336                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11337 }
11338 
11339 /// Try turning a load/store into a pre-indexed load/store when the base
11340 /// pointer is an add or subtract and it has other uses besides the load/store.
11341 /// After the transformation, the new indexed load/store has effectively folded
11342 /// the add/subtract in and all of its other uses are redirected to the
11343 /// new load/store.
11344 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11345   if (Level < AfterLegalizeDAG)
11346     return false;
11347 
11348   bool isLoad = true;
11349   SDValue Ptr;
11350   EVT VT;
11351   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11352     if (LD->isIndexed())
11353       return false;
11354     VT = LD->getMemoryVT();
11355     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11356         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11357       return false;
11358     Ptr = LD->getBasePtr();
11359   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11360     if (ST->isIndexed())
11361       return false;
11362     VT = ST->getMemoryVT();
11363     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11364         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11365       return false;
11366     Ptr = ST->getBasePtr();
11367     isLoad = false;
11368   } else {
11369     return false;
11370   }
11371 
11372   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11373   // out.  There is no reason to make this a preinc/predec.
11374   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11375       Ptr.getNode()->hasOneUse())
11376     return false;
11377 
11378   // Ask the target to do addressing mode selection.
11379   SDValue BasePtr;
11380   SDValue Offset;
11381   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11382   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11383     return false;
11384 
11385   // Backends without true r+i pre-indexed forms may need to pass a
11386   // constant base with a variable offset so that constant coercion
11387   // will work with the patterns in canonical form.
11388   bool Swapped = false;
11389   if (isa<ConstantSDNode>(BasePtr)) {
11390     std::swap(BasePtr, Offset);
11391     Swapped = true;
11392   }
11393 
11394   // Don't create a indexed load / store with zero offset.
11395   if (isNullConstant(Offset))
11396     return false;
11397 
11398   // Try turning it into a pre-indexed load / store except when:
11399   // 1) The new base ptr is a frame index.
11400   // 2) If N is a store and the new base ptr is either the same as or is a
11401   //    predecessor of the value being stored.
11402   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11403   //    that would create a cycle.
11404   // 4) All uses are load / store ops that use it as old base ptr.
11405 
11406   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11407   // (plus the implicit offset) to a register to preinc anyway.
11408   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11409     return false;
11410 
11411   // Check #2.
11412   if (!isLoad) {
11413     SDValue Val = cast<StoreSDNode>(N)->getValue();
11414     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11415       return false;
11416   }
11417 
11418   // Caches for hasPredecessorHelper.
11419   SmallPtrSet<const SDNode *, 32> Visited;
11420   SmallVector<const SDNode *, 16> Worklist;
11421   Worklist.push_back(N);
11422 
11423   // If the offset is a constant, there may be other adds of constants that
11424   // can be folded with this one. We should do this to avoid having to keep
11425   // a copy of the original base pointer.
11426   SmallVector<SDNode *, 16> OtherUses;
11427   if (isa<ConstantSDNode>(Offset))
11428     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11429                               UE = BasePtr.getNode()->use_end();
11430          UI != UE; ++UI) {
11431       SDUse &Use = UI.getUse();
11432       // Skip the use that is Ptr and uses of other results from BasePtr's
11433       // node (important for nodes that return multiple results).
11434       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11435         continue;
11436 
11437       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11438         continue;
11439 
11440       if (Use.getUser()->getOpcode() != ISD::ADD &&
11441           Use.getUser()->getOpcode() != ISD::SUB) {
11442         OtherUses.clear();
11443         break;
11444       }
11445 
11446       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11447       if (!isa<ConstantSDNode>(Op1)) {
11448         OtherUses.clear();
11449         break;
11450       }
11451 
11452       // FIXME: In some cases, we can be smarter about this.
11453       if (Op1.getValueType() != Offset.getValueType()) {
11454         OtherUses.clear();
11455         break;
11456       }
11457 
11458       OtherUses.push_back(Use.getUser());
11459     }
11460 
11461   if (Swapped)
11462     std::swap(BasePtr, Offset);
11463 
11464   // Now check for #3 and #4.
11465   bool RealUse = false;
11466 
11467   for (SDNode *Use : Ptr.getNode()->uses()) {
11468     if (Use == N)
11469       continue;
11470     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11471       return false;
11472 
11473     // If Ptr may be folded in addressing mode of other use, then it's
11474     // not profitable to do this transformation.
11475     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11476       RealUse = true;
11477   }
11478 
11479   if (!RealUse)
11480     return false;
11481 
11482   SDValue Result;
11483   if (isLoad)
11484     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11485                                 BasePtr, Offset, AM);
11486   else
11487     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11488                                  BasePtr, Offset, AM);
11489   ++PreIndexedNodes;
11490   ++NodesCombined;
11491   DEBUG(dbgs() << "\nReplacing.4 ";
11492         N->dump(&DAG);
11493         dbgs() << "\nWith: ";
11494         Result.getNode()->dump(&DAG);
11495         dbgs() << '\n');
11496   WorklistRemover DeadNodes(*this);
11497   if (isLoad) {
11498     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11499     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11500   } else {
11501     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11502   }
11503 
11504   // Finally, since the node is now dead, remove it from the graph.
11505   deleteAndRecombine(N);
11506 
11507   if (Swapped)
11508     std::swap(BasePtr, Offset);
11509 
11510   // Replace other uses of BasePtr that can be updated to use Ptr
11511   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11512     unsigned OffsetIdx = 1;
11513     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11514       OffsetIdx = 0;
11515     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11516            BasePtr.getNode() && "Expected BasePtr operand");
11517 
11518     // We need to replace ptr0 in the following expression:
11519     //   x0 * offset0 + y0 * ptr0 = t0
11520     // knowing that
11521     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11522     //
11523     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11524     // indexed load/store and the expression that needs to be re-written.
11525     //
11526     // Therefore, we have:
11527     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11528 
11529     ConstantSDNode *CN =
11530       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11531     int X0, X1, Y0, Y1;
11532     const APInt &Offset0 = CN->getAPIntValue();
11533     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11534 
11535     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11536     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11537     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11538     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11539 
11540     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11541 
11542     APInt CNV = Offset0;
11543     if (X0 < 0) CNV = -CNV;
11544     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11545     else CNV = CNV - Offset1;
11546 
11547     SDLoc DL(OtherUses[i]);
11548 
11549     // We can now generate the new expression.
11550     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11551     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11552 
11553     SDValue NewUse = DAG.getNode(Opcode,
11554                                  DL,
11555                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11556     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11557     deleteAndRecombine(OtherUses[i]);
11558   }
11559 
11560   // Replace the uses of Ptr with uses of the updated base value.
11561   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11562   deleteAndRecombine(Ptr.getNode());
11563   AddToWorklist(Result.getNode());
11564 
11565   return true;
11566 }
11567 
11568 /// Try to combine a load/store with a add/sub of the base pointer node into a
11569 /// post-indexed load/store. The transformation folded the add/subtract into the
11570 /// new indexed load/store effectively and all of its uses are redirected to the
11571 /// new load/store.
11572 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11573   if (Level < AfterLegalizeDAG)
11574     return false;
11575 
11576   bool isLoad = true;
11577   SDValue Ptr;
11578   EVT VT;
11579   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11580     if (LD->isIndexed())
11581       return false;
11582     VT = LD->getMemoryVT();
11583     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11584         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11585       return false;
11586     Ptr = LD->getBasePtr();
11587   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11588     if (ST->isIndexed())
11589       return false;
11590     VT = ST->getMemoryVT();
11591     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11592         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11593       return false;
11594     Ptr = ST->getBasePtr();
11595     isLoad = false;
11596   } else {
11597     return false;
11598   }
11599 
11600   if (Ptr.getNode()->hasOneUse())
11601     return false;
11602 
11603   for (SDNode *Op : Ptr.getNode()->uses()) {
11604     if (Op == N ||
11605         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11606       continue;
11607 
11608     SDValue BasePtr;
11609     SDValue Offset;
11610     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11611     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11612       // Don't create a indexed load / store with zero offset.
11613       if (isNullConstant(Offset))
11614         continue;
11615 
11616       // Try turning it into a post-indexed load / store except when
11617       // 1) All uses are load / store ops that use it as base ptr (and
11618       //    it may be folded as addressing mmode).
11619       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11620       //    nor a successor of N. Otherwise, if Op is folded that would
11621       //    create a cycle.
11622 
11623       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11624         continue;
11625 
11626       // Check for #1.
11627       bool TryNext = false;
11628       for (SDNode *Use : BasePtr.getNode()->uses()) {
11629         if (Use == Ptr.getNode())
11630           continue;
11631 
11632         // If all the uses are load / store addresses, then don't do the
11633         // transformation.
11634         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11635           bool RealUse = false;
11636           for (SDNode *UseUse : Use->uses()) {
11637             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11638               RealUse = true;
11639           }
11640 
11641           if (!RealUse) {
11642             TryNext = true;
11643             break;
11644           }
11645         }
11646       }
11647 
11648       if (TryNext)
11649         continue;
11650 
11651       // Check for #2
11652       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11653         SDValue Result = isLoad
11654           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11655                                BasePtr, Offset, AM)
11656           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11657                                 BasePtr, Offset, AM);
11658         ++PostIndexedNodes;
11659         ++NodesCombined;
11660         DEBUG(dbgs() << "\nReplacing.5 ";
11661               N->dump(&DAG);
11662               dbgs() << "\nWith: ";
11663               Result.getNode()->dump(&DAG);
11664               dbgs() << '\n');
11665         WorklistRemover DeadNodes(*this);
11666         if (isLoad) {
11667           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11668           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11669         } else {
11670           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11671         }
11672 
11673         // Finally, since the node is now dead, remove it from the graph.
11674         deleteAndRecombine(N);
11675 
11676         // Replace the uses of Use with uses of the updated base value.
11677         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11678                                       Result.getValue(isLoad ? 1 : 0));
11679         deleteAndRecombine(Op);
11680         return true;
11681       }
11682     }
11683   }
11684 
11685   return false;
11686 }
11687 
11688 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11689 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11690   ISD::MemIndexedMode AM = LD->getAddressingMode();
11691   assert(AM != ISD::UNINDEXED);
11692   SDValue BP = LD->getOperand(1);
11693   SDValue Inc = LD->getOperand(2);
11694 
11695   // Some backends use TargetConstants for load offsets, but don't expect
11696   // TargetConstants in general ADD nodes. We can convert these constants into
11697   // regular Constants (if the constant is not opaque).
11698   assert((Inc.getOpcode() != ISD::TargetConstant ||
11699           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11700          "Cannot split out indexing using opaque target constants");
11701   if (Inc.getOpcode() == ISD::TargetConstant) {
11702     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11703     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11704                           ConstInc->getValueType(0));
11705   }
11706 
11707   unsigned Opc =
11708       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11709   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11710 }
11711 
11712 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11713   LoadSDNode *LD  = cast<LoadSDNode>(N);
11714   SDValue Chain = LD->getChain();
11715   SDValue Ptr   = LD->getBasePtr();
11716 
11717   // If load is not volatile and there are no uses of the loaded value (and
11718   // the updated indexed value in case of indexed loads), change uses of the
11719   // chain value into uses of the chain input (i.e. delete the dead load).
11720   if (!LD->isVolatile()) {
11721     if (N->getValueType(1) == MVT::Other) {
11722       // Unindexed loads.
11723       if (!N->hasAnyUseOfValue(0)) {
11724         // It's not safe to use the two value CombineTo variant here. e.g.
11725         // v1, chain2 = load chain1, loc
11726         // v2, chain3 = load chain2, loc
11727         // v3         = add v2, c
11728         // Now we replace use of chain2 with chain1.  This makes the second load
11729         // isomorphic to the one we are deleting, and thus makes this load live.
11730         DEBUG(dbgs() << "\nReplacing.6 ";
11731               N->dump(&DAG);
11732               dbgs() << "\nWith chain: ";
11733               Chain.getNode()->dump(&DAG);
11734               dbgs() << "\n");
11735         WorklistRemover DeadNodes(*this);
11736         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11737         AddUsersToWorklist(Chain.getNode());
11738         if (N->use_empty())
11739           deleteAndRecombine(N);
11740 
11741         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11742       }
11743     } else {
11744       // Indexed loads.
11745       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11746 
11747       // If this load has an opaque TargetConstant offset, then we cannot split
11748       // the indexing into an add/sub directly (that TargetConstant may not be
11749       // valid for a different type of node, and we cannot convert an opaque
11750       // target constant into a regular constant).
11751       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11752                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11753 
11754       if (!N->hasAnyUseOfValue(0) &&
11755           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11756         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11757         SDValue Index;
11758         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11759           Index = SplitIndexingFromLoad(LD);
11760           // Try to fold the base pointer arithmetic into subsequent loads and
11761           // stores.
11762           AddUsersToWorklist(N);
11763         } else
11764           Index = DAG.getUNDEF(N->getValueType(1));
11765         DEBUG(dbgs() << "\nReplacing.7 ";
11766               N->dump(&DAG);
11767               dbgs() << "\nWith: ";
11768               Undef.getNode()->dump(&DAG);
11769               dbgs() << " and 2 other values\n");
11770         WorklistRemover DeadNodes(*this);
11771         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11772         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11773         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11774         deleteAndRecombine(N);
11775         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11776       }
11777     }
11778   }
11779 
11780   // If this load is directly stored, replace the load value with the stored
11781   // value.
11782   // TODO: Handle store large -> read small portion.
11783   // TODO: Handle TRUNCSTORE/LOADEXT
11784   if (OptLevel != CodeGenOpt::None &&
11785       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11786     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11787       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11788       if (PrevST->getBasePtr() == Ptr &&
11789           PrevST->getValue().getValueType() == N->getValueType(0))
11790         return CombineTo(N, PrevST->getOperand(1), Chain);
11791     }
11792   }
11793 
11794   // Try to infer better alignment information than the load already has.
11795   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11796     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11797       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11798         SDValue NewLoad = DAG.getExtLoad(
11799             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11800             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11801             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11802         if (NewLoad.getNode() != N)
11803           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11804       }
11805     }
11806   }
11807 
11808   if (LD->isUnindexed()) {
11809     // Walk up chain skipping non-aliasing memory nodes.
11810     SDValue BetterChain = FindBetterChain(N, Chain);
11811 
11812     // If there is a better chain.
11813     if (Chain != BetterChain) {
11814       SDValue ReplLoad;
11815 
11816       // Replace the chain to void dependency.
11817       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11818         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11819                                BetterChain, Ptr, LD->getMemOperand());
11820       } else {
11821         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11822                                   LD->getValueType(0),
11823                                   BetterChain, Ptr, LD->getMemoryVT(),
11824                                   LD->getMemOperand());
11825       }
11826 
11827       // Create token factor to keep old chain connected.
11828       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11829                                   MVT::Other, Chain, ReplLoad.getValue(1));
11830 
11831       // Replace uses with load result and token factor
11832       return CombineTo(N, ReplLoad.getValue(0), Token);
11833     }
11834   }
11835 
11836   // Try transforming N to an indexed load.
11837   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11838     return SDValue(N, 0);
11839 
11840   // Try to slice up N to more direct loads if the slices are mapped to
11841   // different register banks or pairing can take place.
11842   if (SliceUpLoad(N))
11843     return SDValue(N, 0);
11844 
11845   return SDValue();
11846 }
11847 
11848 namespace {
11849 
11850 /// \brief Helper structure used to slice a load in smaller loads.
11851 /// Basically a slice is obtained from the following sequence:
11852 /// Origin = load Ty1, Base
11853 /// Shift = srl Ty1 Origin, CstTy Amount
11854 /// Inst = trunc Shift to Ty2
11855 ///
11856 /// Then, it will be rewritten into:
11857 /// Slice = load SliceTy, Base + SliceOffset
11858 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11859 ///
11860 /// SliceTy is deduced from the number of bits that are actually used to
11861 /// build Inst.
11862 struct LoadedSlice {
11863   /// \brief Helper structure used to compute the cost of a slice.
11864   struct Cost {
11865     /// Are we optimizing for code size.
11866     bool ForCodeSize;
11867 
11868     /// Various cost.
11869     unsigned Loads = 0;
11870     unsigned Truncates = 0;
11871     unsigned CrossRegisterBanksCopies = 0;
11872     unsigned ZExts = 0;
11873     unsigned Shift = 0;
11874 
11875     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
11876 
11877     /// \brief Get the cost of one isolated slice.
11878     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11879         : ForCodeSize(ForCodeSize), Loads(1) {
11880       EVT TruncType = LS.Inst->getValueType(0);
11881       EVT LoadedType = LS.getLoadedType();
11882       if (TruncType != LoadedType &&
11883           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11884         ZExts = 1;
11885     }
11886 
11887     /// \brief Account for slicing gain in the current cost.
11888     /// Slicing provide a few gains like removing a shift or a
11889     /// truncate. This method allows to grow the cost of the original
11890     /// load with the gain from this slice.
11891     void addSliceGain(const LoadedSlice &LS) {
11892       // Each slice saves a truncate.
11893       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11894       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11895                               LS.Inst->getValueType(0)))
11896         ++Truncates;
11897       // If there is a shift amount, this slice gets rid of it.
11898       if (LS.Shift)
11899         ++Shift;
11900       // If this slice can merge a cross register bank copy, account for it.
11901       if (LS.canMergeExpensiveCrossRegisterBankCopy())
11902         ++CrossRegisterBanksCopies;
11903     }
11904 
11905     Cost &operator+=(const Cost &RHS) {
11906       Loads += RHS.Loads;
11907       Truncates += RHS.Truncates;
11908       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11909       ZExts += RHS.ZExts;
11910       Shift += RHS.Shift;
11911       return *this;
11912     }
11913 
11914     bool operator==(const Cost &RHS) const {
11915       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11916              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11917              ZExts == RHS.ZExts && Shift == RHS.Shift;
11918     }
11919 
11920     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11921 
11922     bool operator<(const Cost &RHS) const {
11923       // Assume cross register banks copies are as expensive as loads.
11924       // FIXME: Do we want some more target hooks?
11925       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11926       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11927       // Unless we are optimizing for code size, consider the
11928       // expensive operation first.
11929       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11930         return ExpensiveOpsLHS < ExpensiveOpsRHS;
11931       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11932              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11933     }
11934 
11935     bool operator>(const Cost &RHS) const { return RHS < *this; }
11936 
11937     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11938 
11939     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11940   };
11941 
11942   // The last instruction that represent the slice. This should be a
11943   // truncate instruction.
11944   SDNode *Inst;
11945 
11946   // The original load instruction.
11947   LoadSDNode *Origin;
11948 
11949   // The right shift amount in bits from the original load.
11950   unsigned Shift;
11951 
11952   // The DAG from which Origin came from.
11953   // This is used to get some contextual information about legal types, etc.
11954   SelectionDAG *DAG;
11955 
11956   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11957               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11958       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11959 
11960   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11961   /// \return Result is \p BitWidth and has used bits set to 1 and
11962   ///         not used bits set to 0.
11963   APInt getUsedBits() const {
11964     // Reproduce the trunc(lshr) sequence:
11965     // - Start from the truncated value.
11966     // - Zero extend to the desired bit width.
11967     // - Shift left.
11968     assert(Origin && "No original load to compare against.");
11969     unsigned BitWidth = Origin->getValueSizeInBits(0);
11970     assert(Inst && "This slice is not bound to an instruction");
11971     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11972            "Extracted slice is bigger than the whole type!");
11973     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11974     UsedBits.setAllBits();
11975     UsedBits = UsedBits.zext(BitWidth);
11976     UsedBits <<= Shift;
11977     return UsedBits;
11978   }
11979 
11980   /// \brief Get the size of the slice to be loaded in bytes.
11981   unsigned getLoadedSize() const {
11982     unsigned SliceSize = getUsedBits().countPopulation();
11983     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11984     return SliceSize / 8;
11985   }
11986 
11987   /// \brief Get the type that will be loaded for this slice.
11988   /// Note: This may not be the final type for the slice.
11989   EVT getLoadedType() const {
11990     assert(DAG && "Missing context");
11991     LLVMContext &Ctxt = *DAG->getContext();
11992     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11993   }
11994 
11995   /// \brief Get the alignment of the load used for this slice.
11996   unsigned getAlignment() const {
11997     unsigned Alignment = Origin->getAlignment();
11998     unsigned Offset = getOffsetFromBase();
11999     if (Offset != 0)
12000       Alignment = MinAlign(Alignment, Alignment + Offset);
12001     return Alignment;
12002   }
12003 
12004   /// \brief Check if this slice can be rewritten with legal operations.
12005   bool isLegal() const {
12006     // An invalid slice is not legal.
12007     if (!Origin || !Inst || !DAG)
12008       return false;
12009 
12010     // Offsets are for indexed load only, we do not handle that.
12011     if (!Origin->getOffset().isUndef())
12012       return false;
12013 
12014     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12015 
12016     // Check that the type is legal.
12017     EVT SliceType = getLoadedType();
12018     if (!TLI.isTypeLegal(SliceType))
12019       return false;
12020 
12021     // Check that the load is legal for this type.
12022     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
12023       return false;
12024 
12025     // Check that the offset can be computed.
12026     // 1. Check its type.
12027     EVT PtrType = Origin->getBasePtr().getValueType();
12028     if (PtrType == MVT::Untyped || PtrType.isExtended())
12029       return false;
12030 
12031     // 2. Check that it fits in the immediate.
12032     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12033       return false;
12034 
12035     // 3. Check that the computation is legal.
12036     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12037       return false;
12038 
12039     // Check that the zext is legal if it needs one.
12040     EVT TruncateType = Inst->getValueType(0);
12041     if (TruncateType != SliceType &&
12042         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12043       return false;
12044 
12045     return true;
12046   }
12047 
12048   /// \brief Get the offset in bytes of this slice in the original chunk of
12049   /// bits.
12050   /// \pre DAG != nullptr.
12051   uint64_t getOffsetFromBase() const {
12052     assert(DAG && "Missing context.");
12053     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12054     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12055     uint64_t Offset = Shift / 8;
12056     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12057     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12058            "The size of the original loaded type is not a multiple of a"
12059            " byte.");
12060     // If Offset is bigger than TySizeInBytes, it means we are loading all
12061     // zeros. This should have been optimized before in the process.
12062     assert(TySizeInBytes > Offset &&
12063            "Invalid shift amount for given loaded size");
12064     if (IsBigEndian)
12065       Offset = TySizeInBytes - Offset - getLoadedSize();
12066     return Offset;
12067   }
12068 
12069   /// \brief Generate the sequence of instructions to load the slice
12070   /// represented by this object and redirect the uses of this slice to
12071   /// this new sequence of instructions.
12072   /// \pre this->Inst && this->Origin are valid Instructions and this
12073   /// object passed the legal check: LoadedSlice::isLegal returned true.
12074   /// \return The last instruction of the sequence used to load the slice.
12075   SDValue loadSlice() const {
12076     assert(Inst && Origin && "Unable to replace a non-existing slice.");
12077     const SDValue &OldBaseAddr = Origin->getBasePtr();
12078     SDValue BaseAddr = OldBaseAddr;
12079     // Get the offset in that chunk of bytes w.r.t. the endianness.
12080     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12081     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12082     if (Offset) {
12083       // BaseAddr = BaseAddr + Offset.
12084       EVT ArithType = BaseAddr.getValueType();
12085       SDLoc DL(Origin);
12086       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12087                               DAG->getConstant(Offset, DL, ArithType));
12088     }
12089 
12090     // Create the type of the loaded slice according to its size.
12091     EVT SliceType = getLoadedType();
12092 
12093     // Create the load for the slice.
12094     SDValue LastInst =
12095         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12096                      Origin->getPointerInfo().getWithOffset(Offset),
12097                      getAlignment(), Origin->getMemOperand()->getFlags());
12098     // If the final type is not the same as the loaded type, this means that
12099     // we have to pad with zero. Create a zero extend for that.
12100     EVT FinalType = Inst->getValueType(0);
12101     if (SliceType != FinalType)
12102       LastInst =
12103           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12104     return LastInst;
12105   }
12106 
12107   /// \brief Check if this slice can be merged with an expensive cross register
12108   /// bank copy. E.g.,
12109   /// i = load i32
12110   /// f = bitcast i32 i to float
12111   bool canMergeExpensiveCrossRegisterBankCopy() const {
12112     if (!Inst || !Inst->hasOneUse())
12113       return false;
12114     SDNode *Use = *Inst->use_begin();
12115     if (Use->getOpcode() != ISD::BITCAST)
12116       return false;
12117     assert(DAG && "Missing context");
12118     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12119     EVT ResVT = Use->getValueType(0);
12120     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12121     const TargetRegisterClass *ArgRC =
12122         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12123     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12124       return false;
12125 
12126     // At this point, we know that we perform a cross-register-bank copy.
12127     // Check if it is expensive.
12128     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12129     // Assume bitcasts are cheap, unless both register classes do not
12130     // explicitly share a common sub class.
12131     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12132       return false;
12133 
12134     // Check if it will be merged with the load.
12135     // 1. Check the alignment constraint.
12136     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12137         ResVT.getTypeForEVT(*DAG->getContext()));
12138 
12139     if (RequiredAlignment > getAlignment())
12140       return false;
12141 
12142     // 2. Check that the load is a legal operation for that type.
12143     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12144       return false;
12145 
12146     // 3. Check that we do not have a zext in the way.
12147     if (Inst->getValueType(0) != getLoadedType())
12148       return false;
12149 
12150     return true;
12151   }
12152 };
12153 
12154 } // end anonymous namespace
12155 
12156 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
12157 /// \p UsedBits looks like 0..0 1..1 0..0.
12158 static bool areUsedBitsDense(const APInt &UsedBits) {
12159   // If all the bits are one, this is dense!
12160   if (UsedBits.isAllOnesValue())
12161     return true;
12162 
12163   // Get rid of the unused bits on the right.
12164   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12165   // Get rid of the unused bits on the left.
12166   if (NarrowedUsedBits.countLeadingZeros())
12167     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12168   // Check that the chunk of bits is completely used.
12169   return NarrowedUsedBits.isAllOnesValue();
12170 }
12171 
12172 /// \brief Check whether or not \p First and \p Second are next to each other
12173 /// in memory. This means that there is no hole between the bits loaded
12174 /// by \p First and the bits loaded by \p Second.
12175 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12176                                      const LoadedSlice &Second) {
12177   assert(First.Origin == Second.Origin && First.Origin &&
12178          "Unable to match different memory origins.");
12179   APInt UsedBits = First.getUsedBits();
12180   assert((UsedBits & Second.getUsedBits()) == 0 &&
12181          "Slices are not supposed to overlap.");
12182   UsedBits |= Second.getUsedBits();
12183   return areUsedBitsDense(UsedBits);
12184 }
12185 
12186 /// \brief Adjust the \p GlobalLSCost according to the target
12187 /// paring capabilities and the layout of the slices.
12188 /// \pre \p GlobalLSCost should account for at least as many loads as
12189 /// there is in the slices in \p LoadedSlices.
12190 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12191                                  LoadedSlice::Cost &GlobalLSCost) {
12192   unsigned NumberOfSlices = LoadedSlices.size();
12193   // If there is less than 2 elements, no pairing is possible.
12194   if (NumberOfSlices < 2)
12195     return;
12196 
12197   // Sort the slices so that elements that are likely to be next to each
12198   // other in memory are next to each other in the list.
12199   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
12200             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12201     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12202     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12203   });
12204   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12205   // First (resp. Second) is the first (resp. Second) potentially candidate
12206   // to be placed in a paired load.
12207   const LoadedSlice *First = nullptr;
12208   const LoadedSlice *Second = nullptr;
12209   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12210                 // Set the beginning of the pair.
12211                                                            First = Second) {
12212     Second = &LoadedSlices[CurrSlice];
12213 
12214     // If First is NULL, it means we start a new pair.
12215     // Get to the next slice.
12216     if (!First)
12217       continue;
12218 
12219     EVT LoadedType = First->getLoadedType();
12220 
12221     // If the types of the slices are different, we cannot pair them.
12222     if (LoadedType != Second->getLoadedType())
12223       continue;
12224 
12225     // Check if the target supplies paired loads for this type.
12226     unsigned RequiredAlignment = 0;
12227     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12228       // move to the next pair, this type is hopeless.
12229       Second = nullptr;
12230       continue;
12231     }
12232     // Check if we meet the alignment requirement.
12233     if (RequiredAlignment > First->getAlignment())
12234       continue;
12235 
12236     // Check that both loads are next to each other in memory.
12237     if (!areSlicesNextToEachOther(*First, *Second))
12238       continue;
12239 
12240     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12241     --GlobalLSCost.Loads;
12242     // Move to the next pair.
12243     Second = nullptr;
12244   }
12245 }
12246 
12247 /// \brief Check the profitability of all involved LoadedSlice.
12248 /// Currently, it is considered profitable if there is exactly two
12249 /// involved slices (1) which are (2) next to each other in memory, and
12250 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12251 ///
12252 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12253 /// the elements themselves.
12254 ///
12255 /// FIXME: When the cost model will be mature enough, we can relax
12256 /// constraints (1) and (2).
12257 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12258                                 const APInt &UsedBits, bool ForCodeSize) {
12259   unsigned NumberOfSlices = LoadedSlices.size();
12260   if (StressLoadSlicing)
12261     return NumberOfSlices > 1;
12262 
12263   // Check (1).
12264   if (NumberOfSlices != 2)
12265     return false;
12266 
12267   // Check (2).
12268   if (!areUsedBitsDense(UsedBits))
12269     return false;
12270 
12271   // Check (3).
12272   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12273   // The original code has one big load.
12274   OrigCost.Loads = 1;
12275   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12276     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12277     // Accumulate the cost of all the slices.
12278     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12279     GlobalSlicingCost += SliceCost;
12280 
12281     // Account as cost in the original configuration the gain obtained
12282     // with the current slices.
12283     OrigCost.addSliceGain(LS);
12284   }
12285 
12286   // If the target supports paired load, adjust the cost accordingly.
12287   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12288   return OrigCost > GlobalSlicingCost;
12289 }
12290 
12291 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12292 /// operations, split it in the various pieces being extracted.
12293 ///
12294 /// This sort of thing is introduced by SROA.
12295 /// This slicing takes care not to insert overlapping loads.
12296 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12297 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12298   if (Level < AfterLegalizeDAG)
12299     return false;
12300 
12301   LoadSDNode *LD = cast<LoadSDNode>(N);
12302   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12303       !LD->getValueType(0).isInteger())
12304     return false;
12305 
12306   // Keep track of already used bits to detect overlapping values.
12307   // In that case, we will just abort the transformation.
12308   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12309 
12310   SmallVector<LoadedSlice, 4> LoadedSlices;
12311 
12312   // Check if this load is used as several smaller chunks of bits.
12313   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12314   // of computation for each trunc.
12315   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12316        UI != UIEnd; ++UI) {
12317     // Skip the uses of the chain.
12318     if (UI.getUse().getResNo() != 0)
12319       continue;
12320 
12321     SDNode *User = *UI;
12322     unsigned Shift = 0;
12323 
12324     // Check if this is a trunc(lshr).
12325     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12326         isa<ConstantSDNode>(User->getOperand(1))) {
12327       Shift = User->getConstantOperandVal(1);
12328       User = *User->use_begin();
12329     }
12330 
12331     // At this point, User is a Truncate, iff we encountered, trunc or
12332     // trunc(lshr).
12333     if (User->getOpcode() != ISD::TRUNCATE)
12334       return false;
12335 
12336     // The width of the type must be a power of 2 and greater than 8-bits.
12337     // Otherwise the load cannot be represented in LLVM IR.
12338     // Moreover, if we shifted with a non-8-bits multiple, the slice
12339     // will be across several bytes. We do not support that.
12340     unsigned Width = User->getValueSizeInBits(0);
12341     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12342       return false;
12343 
12344     // Build the slice for this chain of computations.
12345     LoadedSlice LS(User, LD, Shift, &DAG);
12346     APInt CurrentUsedBits = LS.getUsedBits();
12347 
12348     // Check if this slice overlaps with another.
12349     if ((CurrentUsedBits & UsedBits) != 0)
12350       return false;
12351     // Update the bits used globally.
12352     UsedBits |= CurrentUsedBits;
12353 
12354     // Check if the new slice would be legal.
12355     if (!LS.isLegal())
12356       return false;
12357 
12358     // Record the slice.
12359     LoadedSlices.push_back(LS);
12360   }
12361 
12362   // Abort slicing if it does not seem to be profitable.
12363   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12364     return false;
12365 
12366   ++SlicedLoads;
12367 
12368   // Rewrite each chain to use an independent load.
12369   // By construction, each chain can be represented by a unique load.
12370 
12371   // Prepare the argument for the new token factor for all the slices.
12372   SmallVector<SDValue, 8> ArgChains;
12373   for (SmallVectorImpl<LoadedSlice>::const_iterator
12374            LSIt = LoadedSlices.begin(),
12375            LSItEnd = LoadedSlices.end();
12376        LSIt != LSItEnd; ++LSIt) {
12377     SDValue SliceInst = LSIt->loadSlice();
12378     CombineTo(LSIt->Inst, SliceInst, true);
12379     if (SliceInst.getOpcode() != ISD::LOAD)
12380       SliceInst = SliceInst.getOperand(0);
12381     assert(SliceInst->getOpcode() == ISD::LOAD &&
12382            "It takes more than a zext to get to the loaded slice!!");
12383     ArgChains.push_back(SliceInst.getValue(1));
12384   }
12385 
12386   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12387                               ArgChains);
12388   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12389   AddToWorklist(Chain.getNode());
12390   return true;
12391 }
12392 
12393 /// Check to see if V is (and load (ptr), imm), where the load is having
12394 /// specific bytes cleared out.  If so, return the byte size being masked out
12395 /// and the shift amount.
12396 static std::pair<unsigned, unsigned>
12397 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12398   std::pair<unsigned, unsigned> Result(0, 0);
12399 
12400   // Check for the structure we're looking for.
12401   if (V->getOpcode() != ISD::AND ||
12402       !isa<ConstantSDNode>(V->getOperand(1)) ||
12403       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12404     return Result;
12405 
12406   // Check the chain and pointer.
12407   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12408   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12409 
12410   // The store should be chained directly to the load or be an operand of a
12411   // tokenfactor.
12412   if (LD == Chain.getNode())
12413     ; // ok.
12414   else if (Chain->getOpcode() != ISD::TokenFactor)
12415     return Result; // Fail.
12416   else {
12417     bool isOk = false;
12418     for (const SDValue &ChainOp : Chain->op_values())
12419       if (ChainOp.getNode() == LD) {
12420         isOk = true;
12421         break;
12422       }
12423     if (!isOk) return Result;
12424   }
12425 
12426   // This only handles simple types.
12427   if (V.getValueType() != MVT::i16 &&
12428       V.getValueType() != MVT::i32 &&
12429       V.getValueType() != MVT::i64)
12430     return Result;
12431 
12432   // Check the constant mask.  Invert it so that the bits being masked out are
12433   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12434   // follow the sign bit for uniformity.
12435   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12436   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12437   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12438   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12439   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12440   if (NotMaskLZ == 64) return Result;  // All zero mask.
12441 
12442   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12443   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12444     return Result;
12445 
12446   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12447   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12448     NotMaskLZ -= 64-V.getValueSizeInBits();
12449 
12450   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12451   switch (MaskedBytes) {
12452   case 1:
12453   case 2:
12454   case 4: break;
12455   default: return Result; // All one mask, or 5-byte mask.
12456   }
12457 
12458   // Verify that the first bit starts at a multiple of mask so that the access
12459   // is aligned the same as the access width.
12460   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12461 
12462   Result.first = MaskedBytes;
12463   Result.second = NotMaskTZ/8;
12464   return Result;
12465 }
12466 
12467 /// Check to see if IVal is something that provides a value as specified by
12468 /// MaskInfo. If so, replace the specified store with a narrower store of
12469 /// truncated IVal.
12470 static SDNode *
12471 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12472                                 SDValue IVal, StoreSDNode *St,
12473                                 DAGCombiner *DC) {
12474   unsigned NumBytes = MaskInfo.first;
12475   unsigned ByteShift = MaskInfo.second;
12476   SelectionDAG &DAG = DC->getDAG();
12477 
12478   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12479   // that uses this.  If not, this is not a replacement.
12480   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12481                                   ByteShift*8, (ByteShift+NumBytes)*8);
12482   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12483 
12484   // Check that it is legal on the target to do this.  It is legal if the new
12485   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12486   // legalization.
12487   MVT VT = MVT::getIntegerVT(NumBytes*8);
12488   if (!DC->isTypeLegal(VT))
12489     return nullptr;
12490 
12491   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12492   // shifted by ByteShift and truncated down to NumBytes.
12493   if (ByteShift) {
12494     SDLoc DL(IVal);
12495     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12496                        DAG.getConstant(ByteShift*8, DL,
12497                                     DC->getShiftAmountTy(IVal.getValueType())));
12498   }
12499 
12500   // Figure out the offset for the store and the alignment of the access.
12501   unsigned StOffset;
12502   unsigned NewAlign = St->getAlignment();
12503 
12504   if (DAG.getDataLayout().isLittleEndian())
12505     StOffset = ByteShift;
12506   else
12507     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12508 
12509   SDValue Ptr = St->getBasePtr();
12510   if (StOffset) {
12511     SDLoc DL(IVal);
12512     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12513                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12514     NewAlign = MinAlign(NewAlign, StOffset);
12515   }
12516 
12517   // Truncate down to the new size.
12518   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12519 
12520   ++OpsNarrowed;
12521   return DAG
12522       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12523                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12524       .getNode();
12525 }
12526 
12527 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12528 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12529 /// narrowing the load and store if it would end up being a win for performance
12530 /// or code size.
12531 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12532   StoreSDNode *ST  = cast<StoreSDNode>(N);
12533   if (ST->isVolatile())
12534     return SDValue();
12535 
12536   SDValue Chain = ST->getChain();
12537   SDValue Value = ST->getValue();
12538   SDValue Ptr   = ST->getBasePtr();
12539   EVT VT = Value.getValueType();
12540 
12541   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12542     return SDValue();
12543 
12544   unsigned Opc = Value.getOpcode();
12545 
12546   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12547   // is a byte mask indicating a consecutive number of bytes, check to see if
12548   // Y is known to provide just those bytes.  If so, we try to replace the
12549   // load + replace + store sequence with a single (narrower) store, which makes
12550   // the load dead.
12551   if (Opc == ISD::OR) {
12552     std::pair<unsigned, unsigned> MaskedLoad;
12553     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12554     if (MaskedLoad.first)
12555       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12556                                                   Value.getOperand(1), ST,this))
12557         return SDValue(NewST, 0);
12558 
12559     // Or is commutative, so try swapping X and Y.
12560     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12561     if (MaskedLoad.first)
12562       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12563                                                   Value.getOperand(0), ST,this))
12564         return SDValue(NewST, 0);
12565   }
12566 
12567   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12568       Value.getOperand(1).getOpcode() != ISD::Constant)
12569     return SDValue();
12570 
12571   SDValue N0 = Value.getOperand(0);
12572   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12573       Chain == SDValue(N0.getNode(), 1)) {
12574     LoadSDNode *LD = cast<LoadSDNode>(N0);
12575     if (LD->getBasePtr() != Ptr ||
12576         LD->getPointerInfo().getAddrSpace() !=
12577         ST->getPointerInfo().getAddrSpace())
12578       return SDValue();
12579 
12580     // Find the type to narrow it the load / op / store to.
12581     SDValue N1 = Value.getOperand(1);
12582     unsigned BitWidth = N1.getValueSizeInBits();
12583     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12584     if (Opc == ISD::AND)
12585       Imm ^= APInt::getAllOnesValue(BitWidth);
12586     if (Imm == 0 || Imm.isAllOnesValue())
12587       return SDValue();
12588     unsigned ShAmt = Imm.countTrailingZeros();
12589     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12590     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12591     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12592     // The narrowing should be profitable, the load/store operation should be
12593     // legal (or custom) and the store size should be equal to the NewVT width.
12594     while (NewBW < BitWidth &&
12595            (NewVT.getStoreSizeInBits() != NewBW ||
12596             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12597             !TLI.isNarrowingProfitable(VT, NewVT))) {
12598       NewBW = NextPowerOf2(NewBW);
12599       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12600     }
12601     if (NewBW >= BitWidth)
12602       return SDValue();
12603 
12604     // If the lsb changed does not start at the type bitwidth boundary,
12605     // start at the previous one.
12606     if (ShAmt % NewBW)
12607       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12608     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12609                                    std::min(BitWidth, ShAmt + NewBW));
12610     if ((Imm & Mask) == Imm) {
12611       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12612       if (Opc == ISD::AND)
12613         NewImm ^= APInt::getAllOnesValue(NewBW);
12614       uint64_t PtrOff = ShAmt / 8;
12615       // For big endian targets, we need to adjust the offset to the pointer to
12616       // load the correct bytes.
12617       if (DAG.getDataLayout().isBigEndian())
12618         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12619 
12620       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12621       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12622       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12623         return SDValue();
12624 
12625       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12626                                    Ptr.getValueType(), Ptr,
12627                                    DAG.getConstant(PtrOff, SDLoc(LD),
12628                                                    Ptr.getValueType()));
12629       SDValue NewLD =
12630           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12631                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12632                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12633       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12634                                    DAG.getConstant(NewImm, SDLoc(Value),
12635                                                    NewVT));
12636       SDValue NewST =
12637           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12638                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12639 
12640       AddToWorklist(NewPtr.getNode());
12641       AddToWorklist(NewLD.getNode());
12642       AddToWorklist(NewVal.getNode());
12643       WorklistRemover DeadNodes(*this);
12644       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12645       ++OpsNarrowed;
12646       return NewST;
12647     }
12648   }
12649 
12650   return SDValue();
12651 }
12652 
12653 /// For a given floating point load / store pair, if the load value isn't used
12654 /// by any other operations, then consider transforming the pair to integer
12655 /// load / store operations if the target deems the transformation profitable.
12656 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12657   StoreSDNode *ST  = cast<StoreSDNode>(N);
12658   SDValue Chain = ST->getChain();
12659   SDValue Value = ST->getValue();
12660   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12661       Value.hasOneUse() &&
12662       Chain == SDValue(Value.getNode(), 1)) {
12663     LoadSDNode *LD = cast<LoadSDNode>(Value);
12664     EVT VT = LD->getMemoryVT();
12665     if (!VT.isFloatingPoint() ||
12666         VT != ST->getMemoryVT() ||
12667         LD->isNonTemporal() ||
12668         ST->isNonTemporal() ||
12669         LD->getPointerInfo().getAddrSpace() != 0 ||
12670         ST->getPointerInfo().getAddrSpace() != 0)
12671       return SDValue();
12672 
12673     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12674     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12675         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12676         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12677         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12678       return SDValue();
12679 
12680     unsigned LDAlign = LD->getAlignment();
12681     unsigned STAlign = ST->getAlignment();
12682     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12683     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12684     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12685       return SDValue();
12686 
12687     SDValue NewLD =
12688         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12689                     LD->getPointerInfo(), LDAlign);
12690 
12691     SDValue NewST =
12692         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12693                      ST->getPointerInfo(), STAlign);
12694 
12695     AddToWorklist(NewLD.getNode());
12696     AddToWorklist(NewST.getNode());
12697     WorklistRemover DeadNodes(*this);
12698     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12699     ++LdStFP2Int;
12700     return NewST;
12701   }
12702 
12703   return SDValue();
12704 }
12705 
12706 // This is a helper function for visitMUL to check the profitability
12707 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12708 // MulNode is the original multiply, AddNode is (add x, c1),
12709 // and ConstNode is c2.
12710 //
12711 // If the (add x, c1) has multiple uses, we could increase
12712 // the number of adds if we make this transformation.
12713 // It would only be worth doing this if we can remove a
12714 // multiply in the process. Check for that here.
12715 // To illustrate:
12716 //     (A + c1) * c3
12717 //     (A + c2) * c3
12718 // We're checking for cases where we have common "c3 * A" expressions.
12719 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12720                                               SDValue &AddNode,
12721                                               SDValue &ConstNode) {
12722   APInt Val;
12723 
12724   // If the add only has one use, this would be OK to do.
12725   if (AddNode.getNode()->hasOneUse())
12726     return true;
12727 
12728   // Walk all the users of the constant with which we're multiplying.
12729   for (SDNode *Use : ConstNode->uses()) {
12730     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12731       continue;
12732 
12733     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12734       SDNode *OtherOp;
12735       SDNode *MulVar = AddNode.getOperand(0).getNode();
12736 
12737       // OtherOp is what we're multiplying against the constant.
12738       if (Use->getOperand(0) == ConstNode)
12739         OtherOp = Use->getOperand(1).getNode();
12740       else
12741         OtherOp = Use->getOperand(0).getNode();
12742 
12743       // Check to see if multiply is with the same operand of our "add".
12744       //
12745       //     ConstNode  = CONST
12746       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12747       //     ...
12748       //     AddNode  = (A + c1)  <-- MulVar is A.
12749       //         = AddNode * ConstNode   <-- current visiting instruction.
12750       //
12751       // If we make this transformation, we will have a common
12752       // multiply (ConstNode * A) that we can save.
12753       if (OtherOp == MulVar)
12754         return true;
12755 
12756       // Now check to see if a future expansion will give us a common
12757       // multiply.
12758       //
12759       //     ConstNode  = CONST
12760       //     AddNode    = (A + c1)
12761       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12762       //     ...
12763       //     OtherOp = (A + c2)
12764       //     Use     = OtherOp * ConstNode <-- visiting Use.
12765       //
12766       // If we make this transformation, we will have a common
12767       // multiply (CONST * A) after we also do the same transformation
12768       // to the "t2" instruction.
12769       if (OtherOp->getOpcode() == ISD::ADD &&
12770           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12771           OtherOp->getOperand(0).getNode() == MulVar)
12772         return true;
12773     }
12774   }
12775 
12776   // Didn't find a case where this would be profitable.
12777   return false;
12778 }
12779 
12780 static SDValue peekThroughBitcast(SDValue V) {
12781   while (V.getOpcode() == ISD::BITCAST)
12782     V = V.getOperand(0);
12783   return V;
12784 }
12785 
12786 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12787                                          unsigned NumStores) {
12788   SmallVector<SDValue, 8> Chains;
12789   SmallPtrSet<const SDNode *, 8> Visited;
12790   SDLoc StoreDL(StoreNodes[0].MemNode);
12791 
12792   for (unsigned i = 0; i < NumStores; ++i) {
12793     Visited.insert(StoreNodes[i].MemNode);
12794   }
12795 
12796   // don't include nodes that are children
12797   for (unsigned i = 0; i < NumStores; ++i) {
12798     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12799       Chains.push_back(StoreNodes[i].MemNode->getChain());
12800   }
12801 
12802   assert(Chains.size() > 0 && "Chain should have generated a chain");
12803   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12804 }
12805 
12806 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12807     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12808     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12809   // Make sure we have something to merge.
12810   if (NumStores < 2)
12811     return false;
12812 
12813   // The latest Node in the DAG.
12814   SDLoc DL(StoreNodes[0].MemNode);
12815 
12816   int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
12817   unsigned SizeInBits = NumStores * ElementSizeBits;
12818   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12819 
12820   EVT StoreTy;
12821   if (UseVector) {
12822     unsigned Elts = NumStores * NumMemElts;
12823     // Get the type for the merged vector store.
12824     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12825   } else
12826     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12827 
12828   SDValue StoredVal;
12829   if (UseVector) {
12830     if (IsConstantSrc) {
12831       SmallVector<SDValue, 8> BuildVector;
12832       for (unsigned I = 0; I != NumStores; ++I) {
12833         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12834         SDValue Val = St->getValue();
12835         // If constant is of the wrong type, convert it now.
12836         if (MemVT != Val.getValueType()) {
12837           Val = peekThroughBitcast(Val);
12838           // Deal with constants of wrong size.
12839           if (ElementSizeBits != Val.getValueSizeInBits()) {
12840             EVT IntMemVT =
12841                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
12842             if (isa<ConstantFPSDNode>(Val)) {
12843               // Not clear how to truncate FP values.
12844               return false;
12845             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
12846               Val = DAG.getConstant(C->getAPIntValue()
12847                                         .zextOrTrunc(Val.getValueSizeInBits())
12848                                         .zextOrTrunc(ElementSizeBits),
12849                                     SDLoc(C), IntMemVT);
12850           }
12851           // Make sure correctly size type is the correct type.
12852           Val = DAG.getBitcast(MemVT, Val);
12853         }
12854         BuildVector.push_back(Val);
12855       }
12856       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12857                                                : ISD::BUILD_VECTOR,
12858                               DL, StoreTy, BuildVector);
12859     } else {
12860       SmallVector<SDValue, 8> Ops;
12861       for (unsigned i = 0; i < NumStores; ++i) {
12862         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12863         SDValue Val = peekThroughBitcast(St->getValue());
12864         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
12865         // type MemVT. If the underlying value is not the correct
12866         // type, but it is an extraction of an appropriate vector we
12867         // can recast Val to be of the correct type. This may require
12868         // converting between EXTRACT_VECTOR_ELT and
12869         // EXTRACT_SUBVECTOR.
12870         if ((MemVT != Val.getValueType()) &&
12871             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12872              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
12873           SDValue Vec = Val.getOperand(0);
12874           EVT MemVTScalarTy = MemVT.getScalarType();
12875           // We may need to add a bitcast here to get types to line up.
12876           if (MemVTScalarTy != Vec.getValueType()) {
12877             unsigned Elts = Vec.getValueType().getSizeInBits() /
12878                             MemVTScalarTy.getSizeInBits();
12879             EVT NewVecTy =
12880                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
12881             Vec = DAG.getBitcast(NewVecTy, Vec);
12882           }
12883           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
12884                                         : ISD::EXTRACT_VECTOR_ELT;
12885           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
12886         }
12887         Ops.push_back(Val);
12888       }
12889 
12890       // Build the extracted vector elements back into a vector.
12891       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
12892                                                : ISD::BUILD_VECTOR,
12893                               DL, StoreTy, Ops);
12894     }
12895   } else {
12896     // We should always use a vector store when merging extracted vector
12897     // elements, so this path implies a store of constants.
12898     assert(IsConstantSrc && "Merged vector elements should use vector store");
12899 
12900     APInt StoreInt(SizeInBits, 0);
12901 
12902     // Construct a single integer constant which is made of the smaller
12903     // constant inputs.
12904     bool IsLE = DAG.getDataLayout().isLittleEndian();
12905     for (unsigned i = 0; i < NumStores; ++i) {
12906       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12907       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12908 
12909       SDValue Val = St->getValue();
12910       StoreInt <<= ElementSizeBits;
12911       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12912         StoreInt |= C->getAPIntValue()
12913                         .zextOrTrunc(ElementSizeBits)
12914                         .zextOrTrunc(SizeInBits);
12915       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12916         StoreInt |= C->getValueAPF()
12917                         .bitcastToAPInt()
12918                         .zextOrTrunc(ElementSizeBits)
12919                         .zextOrTrunc(SizeInBits);
12920         // If fp truncation is necessary give up for now.
12921         if (MemVT.getSizeInBits() != ElementSizeBits)
12922           return false;
12923       } else {
12924         llvm_unreachable("Invalid constant element type");
12925       }
12926     }
12927 
12928     // Create the new Load and Store operations.
12929     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12930   }
12931 
12932   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12933   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12934 
12935   // make sure we use trunc store if it's necessary to be legal.
12936   SDValue NewStore;
12937   if (!UseTrunc) {
12938     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12939                             FirstInChain->getPointerInfo(),
12940                             FirstInChain->getAlignment());
12941   } else { // Must be realized as a trunc store
12942     EVT LegalizedStoredValueTy =
12943         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12944     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12945     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12946     SDValue ExtendedStoreVal =
12947         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12948                         LegalizedStoredValueTy);
12949     NewStore = DAG.getTruncStore(
12950         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12951         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12952         FirstInChain->getAlignment(),
12953         FirstInChain->getMemOperand()->getFlags());
12954   }
12955 
12956   // Replace all merged stores with the new store.
12957   for (unsigned i = 0; i < NumStores; ++i)
12958     CombineTo(StoreNodes[i].MemNode, NewStore);
12959 
12960   AddToWorklist(NewChain.getNode());
12961   return true;
12962 }
12963 
12964 void DAGCombiner::getStoreMergeCandidates(
12965     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12966   // This holds the base pointer, index, and the offset in bytes from the base
12967   // pointer.
12968   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
12969   EVT MemVT = St->getMemoryVT();
12970 
12971   SDValue Val = peekThroughBitcast(St->getValue());
12972   // We must have a base and an offset.
12973   if (!BasePtr.getBase().getNode())
12974     return;
12975 
12976   // Do not handle stores to undef base pointers.
12977   if (BasePtr.getBase().isUndef())
12978     return;
12979 
12980   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
12981   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12982                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12983   bool IsLoadSrc = isa<LoadSDNode>(Val);
12984   BaseIndexOffset LBasePtr;
12985   // Match on loadbaseptr if relevant.
12986   EVT LoadVT;
12987   if (IsLoadSrc) {
12988     auto *Ld = cast<LoadSDNode>(Val);
12989     LBasePtr = BaseIndexOffset::match(Ld, DAG);
12990     LoadVT = Ld->getMemoryVT();
12991     // Load and store should be the same type.
12992     if (MemVT != LoadVT)
12993       return;
12994   }
12995   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12996                             int64_t &Offset) -> bool {
12997     if (Other->isVolatile() || Other->isIndexed())
12998       return false;
12999     SDValue Val = peekThroughBitcast(Other->getValue());
13000     // Allow merging constants of different types as integers.
13001     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
13002                                            : Other->getMemoryVT() != MemVT;
13003     if (IsLoadSrc) {
13004       if (NoTypeMatch)
13005         return false;
13006       // The Load's Base Ptr must also match
13007       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
13008         auto LPtr = BaseIndexOffset::match(OtherLd, DAG);
13009         if (LoadVT != OtherLd->getMemoryVT())
13010           return false;
13011         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
13012           return false;
13013       } else
13014         return false;
13015     }
13016     if (IsConstantSrc) {
13017       if (NoTypeMatch)
13018         return false;
13019       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
13020         return false;
13021     }
13022     if (IsExtractVecSrc) {
13023       // Do not merge truncated stores here.
13024       if (Other->isTruncatingStore())
13025         return false;
13026       if (!MemVT.bitsEq(Val.getValueType()))
13027         return false;
13028       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13029           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13030         return false;
13031     }
13032     Ptr = BaseIndexOffset::match(Other, DAG);
13033     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13034   };
13035 
13036   // We looking for a root node which is an ancestor to all mergable
13037   // stores. We search up through a load, to our root and then down
13038   // through all children. For instance we will find Store{1,2,3} if
13039   // St is Store1, Store2. or Store3 where the root is not a load
13040   // which always true for nonvolatile ops. TODO: Expand
13041   // the search to find all valid candidates through multiple layers of loads.
13042   //
13043   // Root
13044   // |-------|-------|
13045   // Load    Load    Store3
13046   // |       |
13047   // Store1   Store2
13048   //
13049   // FIXME: We should be able to climb and
13050   // descend TokenFactors to find candidates as well.
13051 
13052   SDNode *RootNode = (St->getChain()).getNode();
13053 
13054   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13055     RootNode = Ldn->getChain().getNode();
13056     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13057       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13058         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13059           if (I2.getOperandNo() == 0)
13060             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13061               BaseIndexOffset Ptr;
13062               int64_t PtrDiff;
13063               if (CandidateMatch(OtherST, Ptr, PtrDiff))
13064                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13065             }
13066   } else
13067     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13068       if (I.getOperandNo() == 0)
13069         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13070           BaseIndexOffset Ptr;
13071           int64_t PtrDiff;
13072           if (CandidateMatch(OtherST, Ptr, PtrDiff))
13073             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13074         }
13075 }
13076 
13077 // We need to check that merging these stores does not cause a loop in
13078 // the DAG. Any store candidate may depend on another candidate
13079 // indirectly through its operand (we already consider dependencies
13080 // through the chain). Check in parallel by searching up from
13081 // non-chain operands of candidates.
13082 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13083     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
13084   // FIXME: We should be able to truncate a full search of
13085   // predecessors by doing a BFS and keeping tabs the originating
13086   // stores from which worklist nodes come from in a similar way to
13087   // TokenFactor simplfication.
13088 
13089   SmallPtrSet<const SDNode *, 16> Visited;
13090   SmallVector<const SDNode *, 8> Worklist;
13091   unsigned int Max = 8192;
13092   // Search Ops of store candidates.
13093   for (unsigned i = 0; i < NumStores; ++i) {
13094     SDNode *n = StoreNodes[i].MemNode;
13095     // Potential loops may happen only through non-chain operands
13096     for (unsigned j = 1; j < n->getNumOperands(); ++j)
13097       Worklist.push_back(n->getOperand(j).getNode());
13098   }
13099   // Search through DAG. We can stop early if we find a store node.
13100   for (unsigned i = 0; i < NumStores; ++i) {
13101     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13102                                      Max))
13103       return false;
13104     // Check if we ended early, failing conservatively if so.
13105     if (Visited.size() >= Max)
13106       return false;
13107   }
13108   return true;
13109 }
13110 
13111 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13112   if (OptLevel == CodeGenOpt::None)
13113     return false;
13114 
13115   EVT MemVT = St->getMemoryVT();
13116   int64_t ElementSizeBytes = MemVT.getStoreSize();
13117   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13118 
13119   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13120     return false;
13121 
13122   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13123       Attribute::NoImplicitFloat);
13124 
13125   // This function cannot currently deal with non-byte-sized memory sizes.
13126   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13127     return false;
13128 
13129   if (!MemVT.isSimple())
13130     return false;
13131 
13132   // Perform an early exit check. Do not bother looking at stored values that
13133   // are not constants, loads, or extracted vector elements.
13134   SDValue StoredVal = peekThroughBitcast(St->getValue());
13135   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13136   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13137                        isa<ConstantFPSDNode>(StoredVal);
13138   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13139                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13140 
13141   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13142     return false;
13143 
13144   SmallVector<MemOpLink, 8> StoreNodes;
13145   // Find potential store merge candidates by searching through chain sub-DAG
13146   getStoreMergeCandidates(St, StoreNodes);
13147 
13148   // Check if there is anything to merge.
13149   if (StoreNodes.size() < 2)
13150     return false;
13151 
13152   // Sort the memory operands according to their distance from the
13153   // base pointer.
13154   std::sort(StoreNodes.begin(), StoreNodes.end(),
13155             [](MemOpLink LHS, MemOpLink RHS) {
13156               return LHS.OffsetFromBase < RHS.OffsetFromBase;
13157             });
13158 
13159   // Store Merge attempts to merge the lowest stores. This generally
13160   // works out as if successful, as the remaining stores are checked
13161   // after the first collection of stores is merged. However, in the
13162   // case that a non-mergeable store is found first, e.g., {p[-2],
13163   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13164   // mergeable cases. To prevent this, we prune such stores from the
13165   // front of StoreNodes here.
13166 
13167   bool RV = false;
13168   while (StoreNodes.size() > 1) {
13169     unsigned StartIdx = 0;
13170     while ((StartIdx + 1 < StoreNodes.size()) &&
13171            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13172                StoreNodes[StartIdx + 1].OffsetFromBase)
13173       ++StartIdx;
13174 
13175     // Bail if we don't have enough candidates to merge.
13176     if (StartIdx + 1 >= StoreNodes.size())
13177       return RV;
13178 
13179     if (StartIdx)
13180       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13181 
13182     // Scan the memory operations on the chain and find the first
13183     // non-consecutive store memory address.
13184     unsigned NumConsecutiveStores = 1;
13185     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13186     // Check that the addresses are consecutive starting from the second
13187     // element in the list of stores.
13188     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13189       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13190       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13191         break;
13192       NumConsecutiveStores = i + 1;
13193     }
13194 
13195     if (NumConsecutiveStores < 2) {
13196       StoreNodes.erase(StoreNodes.begin(),
13197                        StoreNodes.begin() + NumConsecutiveStores);
13198       continue;
13199     }
13200 
13201     // Check that we can merge these candidates without causing a cycle
13202     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
13203                                                   NumConsecutiveStores)) {
13204       StoreNodes.erase(StoreNodes.begin(),
13205                        StoreNodes.begin() + NumConsecutiveStores);
13206       continue;
13207     }
13208 
13209     // The node with the lowest store address.
13210     LLVMContext &Context = *DAG.getContext();
13211     const DataLayout &DL = DAG.getDataLayout();
13212 
13213     // Store the constants into memory as one consecutive store.
13214     if (IsConstantSrc) {
13215       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13216       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13217       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13218       unsigned LastLegalType = 1;
13219       unsigned LastLegalVectorType = 1;
13220       bool LastIntegerTrunc = false;
13221       bool NonZero = false;
13222       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13223       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13224         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13225         SDValue StoredVal = ST->getValue();
13226         bool IsElementZero = false;
13227         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13228           IsElementZero = C->isNullValue();
13229         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13230           IsElementZero = C->getConstantFPValue()->isNullValue();
13231         if (IsElementZero) {
13232           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13233             FirstZeroAfterNonZero = i;
13234         }
13235         NonZero |= !IsElementZero;
13236 
13237         // Find a legal type for the constant store.
13238         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13239         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13240         bool IsFast = false;
13241         if (TLI.isTypeLegal(StoreTy) &&
13242             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13243             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13244                                    FirstStoreAlign, &IsFast) &&
13245             IsFast) {
13246           LastIntegerTrunc = false;
13247           LastLegalType = i + 1;
13248           // Or check whether a truncstore is legal.
13249         } else if (TLI.getTypeAction(Context, StoreTy) ==
13250                    TargetLowering::TypePromoteInteger) {
13251           EVT LegalizedStoredValueTy =
13252               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13253           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13254               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13255               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13256                                      FirstStoreAlign, &IsFast) &&
13257               IsFast) {
13258             LastIntegerTrunc = true;
13259             LastLegalType = i + 1;
13260           }
13261         }
13262 
13263         // We only use vectors if the constant is known to be zero or the target
13264         // allows it and the function is not marked with the noimplicitfloat
13265         // attribute.
13266         if ((!NonZero ||
13267              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13268             !NoVectors) {
13269           // Find a legal type for the vector store.
13270           unsigned Elts = (i + 1) * NumMemElts;
13271           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13272           if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13273               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13274               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13275                                      FirstStoreAlign, &IsFast) &&
13276               IsFast)
13277             LastLegalVectorType = i + 1;
13278         }
13279       }
13280 
13281       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13282       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13283 
13284       // Check if we found a legal integer type that creates a meaningful merge.
13285       if (NumElem < 2) {
13286         // We know that candidate stores are in order and of correct
13287         // shape. While there is no mergeable sequence from the
13288         // beginning one may start later in the sequence. The only
13289         // reason a merge of size N could have failed where another of
13290         // the same size would not have, is if the alignment has
13291         // improved or we've dropped a non-zero value. Drop as many
13292         // candidates as we can here.
13293         unsigned NumSkip = 1;
13294         while (
13295             (NumSkip < NumConsecutiveStores) &&
13296             (NumSkip < FirstZeroAfterNonZero) &&
13297             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13298           NumSkip++;
13299         }
13300         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13301         continue;
13302       }
13303 
13304       bool Merged = MergeStoresOfConstantsOrVecElts(
13305           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13306       RV |= Merged;
13307 
13308       // Remove merged stores for next iteration.
13309       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13310       continue;
13311     }
13312 
13313     // When extracting multiple vector elements, try to store them
13314     // in one vector store rather than a sequence of scalar stores.
13315     if (IsExtractVecSrc) {
13316       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13317       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13318       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13319       unsigned NumStoresToMerge = 1;
13320       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13321         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13322         SDValue StVal = peekThroughBitcast(St->getValue());
13323         // This restriction could be loosened.
13324         // Bail out if any stored values are not elements extracted from a
13325         // vector. It should be possible to handle mixed sources, but load
13326         // sources need more careful handling (see the block of code below that
13327         // handles consecutive loads).
13328         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13329             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13330           return RV;
13331 
13332         // Find a legal type for the vector store.
13333         unsigned Elts = (i + 1) * NumMemElts;
13334         EVT Ty =
13335             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13336         bool IsFast;
13337         if (TLI.isTypeLegal(Ty) &&
13338             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13339             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13340                                    FirstStoreAlign, &IsFast) &&
13341             IsFast)
13342           NumStoresToMerge = i + 1;
13343       }
13344 
13345       // Check if we found a legal integer type that creates a meaningful merge.
13346       if (NumStoresToMerge < 2) {
13347         // We know that candidate stores are in order and of correct
13348         // shape. While there is no mergeable sequence from the
13349         // beginning one may start later in the sequence. The only
13350         // reason a merge of size N could have failed where another of
13351         // the same size would not have, is if the alignment has
13352         // improved. Drop as many candidates as we can here.
13353         unsigned NumSkip = 1;
13354         while ((NumSkip < NumConsecutiveStores) &&
13355                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13356           NumSkip++;
13357 
13358         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13359         continue;
13360       }
13361 
13362       bool Merged = MergeStoresOfConstantsOrVecElts(
13363           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13364       if (!Merged) {
13365         StoreNodes.erase(StoreNodes.begin(),
13366                          StoreNodes.begin() + NumStoresToMerge);
13367         continue;
13368       }
13369       // Remove merged stores for next iteration.
13370       StoreNodes.erase(StoreNodes.begin(),
13371                        StoreNodes.begin() + NumStoresToMerge);
13372       RV = true;
13373       continue;
13374     }
13375 
13376     // Below we handle the case of multiple consecutive stores that
13377     // come from multiple consecutive loads. We merge them into a single
13378     // wide load and a single wide store.
13379 
13380     // Look for load nodes which are used by the stored values.
13381     SmallVector<MemOpLink, 8> LoadNodes;
13382 
13383     // Find acceptable loads. Loads need to have the same chain (token factor),
13384     // must not be zext, volatile, indexed, and they must be consecutive.
13385     BaseIndexOffset LdBasePtr;
13386     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13387       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13388       SDValue Val = peekThroughBitcast(St->getValue());
13389       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13390       if (!Ld)
13391         break;
13392 
13393       // Loads must only have one use.
13394       if (!Ld->hasNUsesOfValue(1, 0))
13395         break;
13396 
13397       // The memory operands must not be volatile.
13398       if (Ld->isVolatile() || Ld->isIndexed())
13399         break;
13400 
13401       // The stored memory type must be the same.
13402       if (Ld->getMemoryVT() != MemVT)
13403         break;
13404 
13405       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
13406       // If this is not the first ptr that we check.
13407       int64_t LdOffset = 0;
13408       if (LdBasePtr.getBase().getNode()) {
13409         // The base ptr must be the same.
13410         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13411           break;
13412       } else {
13413         // Check that all other base pointers are the same as this one.
13414         LdBasePtr = LdPtr;
13415       }
13416 
13417       // We found a potential memory operand to merge.
13418       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13419     }
13420 
13421     if (LoadNodes.size() < 2) {
13422       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13423       continue;
13424     }
13425 
13426     // If we have load/store pair instructions and we only have two values,
13427     // don't bother merging.
13428     unsigned RequiredAlignment;
13429     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13430         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13431       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13432       continue;
13433     }
13434     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13435     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13436     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13437     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13438     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13439     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13440 
13441     // Scan the memory operations on the chain and find the first
13442     // non-consecutive load memory address. These variables hold the index in
13443     // the store node array.
13444     unsigned LastConsecutiveLoad = 1;
13445     // This variable refers to the size and not index in the array.
13446     unsigned LastLegalVectorType = 1;
13447     unsigned LastLegalIntegerType = 1;
13448     bool isDereferenceable = true;
13449     bool DoIntegerTruncate = false;
13450     StartAddress = LoadNodes[0].OffsetFromBase;
13451     SDValue FirstChain = FirstLoad->getChain();
13452     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13453       // All loads must share the same chain.
13454       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13455         break;
13456 
13457       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13458       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13459         break;
13460       LastConsecutiveLoad = i;
13461 
13462       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13463         isDereferenceable = false;
13464 
13465       // Find a legal type for the vector store.
13466       unsigned Elts = (i + 1) * NumMemElts;
13467       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13468 
13469       bool IsFastSt, IsFastLd;
13470       if (TLI.isTypeLegal(StoreTy) &&
13471           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13472           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13473                                  FirstStoreAlign, &IsFastSt) &&
13474           IsFastSt &&
13475           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13476                                  FirstLoadAlign, &IsFastLd) &&
13477           IsFastLd) {
13478         LastLegalVectorType = i + 1;
13479       }
13480 
13481       // Find a legal type for the integer store.
13482       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13483       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13484       if (TLI.isTypeLegal(StoreTy) &&
13485           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13486           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13487                                  FirstStoreAlign, &IsFastSt) &&
13488           IsFastSt &&
13489           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13490                                  FirstLoadAlign, &IsFastLd) &&
13491           IsFastLd) {
13492         LastLegalIntegerType = i + 1;
13493         DoIntegerTruncate = false;
13494         // Or check whether a truncstore and extload is legal.
13495       } else if (TLI.getTypeAction(Context, StoreTy) ==
13496                  TargetLowering::TypePromoteInteger) {
13497         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13498         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13499             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13500             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13501                                StoreTy) &&
13502             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13503                                StoreTy) &&
13504             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13505             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13506                                    FirstStoreAlign, &IsFastSt) &&
13507             IsFastSt &&
13508             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13509                                    FirstLoadAlign, &IsFastLd) &&
13510             IsFastLd) {
13511           LastLegalIntegerType = i + 1;
13512           DoIntegerTruncate = true;
13513         }
13514       }
13515     }
13516 
13517     // Only use vector types if the vector type is larger than the integer type.
13518     // If they are the same, use integers.
13519     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13520     unsigned LastLegalType =
13521         std::max(LastLegalVectorType, LastLegalIntegerType);
13522 
13523     // We add +1 here because the LastXXX variables refer to location while
13524     // the NumElem refers to array/index size.
13525     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13526     NumElem = std::min(LastLegalType, NumElem);
13527 
13528     if (NumElem < 2) {
13529       // We know that candidate stores are in order and of correct
13530       // shape. While there is no mergeable sequence from the
13531       // beginning one may start later in the sequence. The only
13532       // reason a merge of size N could have failed where another of
13533       // the same size would not have is if the alignment or either
13534       // the load or store has improved. Drop as many candidates as we
13535       // can here.
13536       unsigned NumSkip = 1;
13537       while ((NumSkip < LoadNodes.size()) &&
13538              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13539              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13540         NumSkip++;
13541       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13542       continue;
13543     }
13544 
13545     // Find if it is better to use vectors or integers to load and store
13546     // to memory.
13547     EVT JointMemOpVT;
13548     if (UseVectorTy) {
13549       // Find a legal type for the vector store.
13550       unsigned Elts = NumElem * NumMemElts;
13551       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13552     } else {
13553       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13554       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13555     }
13556 
13557     SDLoc LoadDL(LoadNodes[0].MemNode);
13558     SDLoc StoreDL(StoreNodes[0].MemNode);
13559 
13560     // The merged loads are required to have the same incoming chain, so
13561     // using the first's chain is acceptable.
13562 
13563     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13564     AddToWorklist(NewStoreChain.getNode());
13565 
13566     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13567                                           MachineMemOperand::MODereferenceable:
13568                                           MachineMemOperand::MONone;
13569 
13570     SDValue NewLoad, NewStore;
13571     if (UseVectorTy || !DoIntegerTruncate) {
13572       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13573                             FirstLoad->getBasePtr(),
13574                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13575                             MMOFlags);
13576       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13577                               FirstInChain->getBasePtr(),
13578                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13579     } else { // This must be the truncstore/extload case
13580       EVT ExtendedTy =
13581           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13582       NewLoad =
13583           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13584                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13585                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13586       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13587                                    FirstInChain->getBasePtr(),
13588                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13589                                    FirstInChain->getAlignment(),
13590                                    FirstInChain->getMemOperand()->getFlags());
13591     }
13592 
13593     // Transfer chain users from old loads to the new load.
13594     for (unsigned i = 0; i < NumElem; ++i) {
13595       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13596       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13597                                     SDValue(NewLoad.getNode(), 1));
13598     }
13599 
13600     // Replace the all stores with the new store. Recursively remove
13601     // corresponding value if its no longer used.
13602     for (unsigned i = 0; i < NumElem; ++i) {
13603       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13604       CombineTo(StoreNodes[i].MemNode, NewStore);
13605       if (Val.getNode()->use_empty())
13606         recursivelyDeleteUnusedNodes(Val.getNode());
13607     }
13608 
13609     RV = true;
13610     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13611   }
13612   return RV;
13613 }
13614 
13615 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13616   SDLoc SL(ST);
13617   SDValue ReplStore;
13618 
13619   // Replace the chain to avoid dependency.
13620   if (ST->isTruncatingStore()) {
13621     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13622                                   ST->getBasePtr(), ST->getMemoryVT(),
13623                                   ST->getMemOperand());
13624   } else {
13625     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13626                              ST->getMemOperand());
13627   }
13628 
13629   // Create token to keep both nodes around.
13630   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13631                               MVT::Other, ST->getChain(), ReplStore);
13632 
13633   // Make sure the new and old chains are cleaned up.
13634   AddToWorklist(Token.getNode());
13635 
13636   // Don't add users to work list.
13637   return CombineTo(ST, Token, false);
13638 }
13639 
13640 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13641   SDValue Value = ST->getValue();
13642   if (Value.getOpcode() == ISD::TargetConstantFP)
13643     return SDValue();
13644 
13645   SDLoc DL(ST);
13646 
13647   SDValue Chain = ST->getChain();
13648   SDValue Ptr = ST->getBasePtr();
13649 
13650   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13651 
13652   // NOTE: If the original store is volatile, this transform must not increase
13653   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13654   // processor operation but an i64 (which is not legal) requires two.  So the
13655   // transform should not be done in this case.
13656 
13657   SDValue Tmp;
13658   switch (CFP->getSimpleValueType(0).SimpleTy) {
13659   default:
13660     llvm_unreachable("Unknown FP type");
13661   case MVT::f16:    // We don't do this for these yet.
13662   case MVT::f80:
13663   case MVT::f128:
13664   case MVT::ppcf128:
13665     return SDValue();
13666   case MVT::f32:
13667     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13668         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13669       ;
13670       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13671                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13672                             MVT::i32);
13673       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13674     }
13675 
13676     return SDValue();
13677   case MVT::f64:
13678     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13679          !ST->isVolatile()) ||
13680         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13681       ;
13682       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13683                             getZExtValue(), SDLoc(CFP), MVT::i64);
13684       return DAG.getStore(Chain, DL, Tmp,
13685                           Ptr, ST->getMemOperand());
13686     }
13687 
13688     if (!ST->isVolatile() &&
13689         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13690       // Many FP stores are not made apparent until after legalize, e.g. for
13691       // argument passing.  Since this is so common, custom legalize the
13692       // 64-bit integer store into two 32-bit stores.
13693       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13694       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13695       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13696       if (DAG.getDataLayout().isBigEndian())
13697         std::swap(Lo, Hi);
13698 
13699       unsigned Alignment = ST->getAlignment();
13700       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13701       AAMDNodes AAInfo = ST->getAAInfo();
13702 
13703       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13704                                  ST->getAlignment(), MMOFlags, AAInfo);
13705       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13706                         DAG.getConstant(4, DL, Ptr.getValueType()));
13707       Alignment = MinAlign(Alignment, 4U);
13708       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13709                                  ST->getPointerInfo().getWithOffset(4),
13710                                  Alignment, MMOFlags, AAInfo);
13711       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13712                          St0, St1);
13713     }
13714 
13715     return SDValue();
13716   }
13717 }
13718 
13719 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13720   StoreSDNode *ST  = cast<StoreSDNode>(N);
13721   SDValue Chain = ST->getChain();
13722   SDValue Value = ST->getValue();
13723   SDValue Ptr   = ST->getBasePtr();
13724 
13725   // If this is a store of a bit convert, store the input value if the
13726   // resultant store does not need a higher alignment than the original.
13727   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13728       ST->isUnindexed()) {
13729     EVT SVT = Value.getOperand(0).getValueType();
13730     if (((!LegalOperations && !ST->isVolatile()) ||
13731          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13732         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13733       unsigned OrigAlign = ST->getAlignment();
13734       bool Fast = false;
13735       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13736                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13737           Fast) {
13738         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13739                             ST->getPointerInfo(), OrigAlign,
13740                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13741       }
13742     }
13743   }
13744 
13745   // Turn 'store undef, Ptr' -> nothing.
13746   if (Value.isUndef() && ST->isUnindexed())
13747     return Chain;
13748 
13749   // Try to infer better alignment information than the store already has.
13750   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13751     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13752       if (Align > ST->getAlignment()) {
13753         SDValue NewStore =
13754             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13755                               ST->getMemoryVT(), Align,
13756                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13757         if (NewStore.getNode() != N)
13758           return CombineTo(ST, NewStore, true);
13759       }
13760     }
13761   }
13762 
13763   // Try transforming a pair floating point load / store ops to integer
13764   // load / store ops.
13765   if (SDValue NewST = TransformFPLoadStorePair(N))
13766     return NewST;
13767 
13768   if (ST->isUnindexed()) {
13769     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13770     // adjacent stores.
13771     if (findBetterNeighborChains(ST)) {
13772       // replaceStoreChain uses CombineTo, which handled all of the worklist
13773       // manipulation. Return the original node to not do anything else.
13774       return SDValue(ST, 0);
13775     }
13776     Chain = ST->getChain();
13777   }
13778 
13779   // FIXME: is there such a thing as a truncating indexed store?
13780   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13781       Value.getValueType().isInteger()) {
13782     // See if we can simplify the input to this truncstore with knowledge that
13783     // only the low bits are being used.  For example:
13784     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13785     SDValue Shorter = DAG.GetDemandedBits(
13786         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13787                                     ST->getMemoryVT().getScalarSizeInBits()));
13788     AddToWorklist(Value.getNode());
13789     if (Shorter.getNode())
13790       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13791                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13792 
13793     // Otherwise, see if we can simplify the operation with
13794     // SimplifyDemandedBits, which only works if the value has a single use.
13795     if (SimplifyDemandedBits(
13796             Value,
13797             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13798                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13799       // Re-visit the store if anything changed and the store hasn't been merged
13800       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13801       // node back to the worklist if necessary, but we also need to re-visit
13802       // the Store node itself.
13803       if (N->getOpcode() != ISD::DELETED_NODE)
13804         AddToWorklist(N);
13805       return SDValue(N, 0);
13806     }
13807   }
13808 
13809   // If this is a load followed by a store to the same location, then the store
13810   // is dead/noop.
13811   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13812     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13813         ST->isUnindexed() && !ST->isVolatile() &&
13814         // There can't be any side effects between the load and store, such as
13815         // a call or store.
13816         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13817       // The store is dead, remove it.
13818       return Chain;
13819     }
13820   }
13821 
13822   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13823     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13824         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13825         ST->getMemoryVT() == ST1->getMemoryVT()) {
13826       // If this is a store followed by a store with the same value to the same
13827       // location, then the store is dead/noop.
13828       if (ST1->getValue() == Value) {
13829         // The store is dead, remove it.
13830         return Chain;
13831       }
13832 
13833       // If this is a store who's preceeding store to the same location
13834       // and no one other node is chained to that store we can effectively
13835       // drop the store. Do not remove stores to undef as they may be used as
13836       // data sinks.
13837       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13838           !ST1->getBasePtr().isUndef()) {
13839         // ST1 is fully overwritten and can be elided. Combine with it's chain
13840         // value.
13841         CombineTo(ST1, ST1->getChain());
13842         return SDValue();
13843       }
13844     }
13845   }
13846 
13847   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13848   // truncating store.  We can do this even if this is already a truncstore.
13849   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13850       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13851       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13852                             ST->getMemoryVT())) {
13853     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13854                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
13855   }
13856 
13857   // Always perform this optimization before types are legal. If the target
13858   // prefers, also try this after legalization to catch stores that were created
13859   // by intrinsics or other nodes.
13860   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
13861     while (true) {
13862       // There can be multiple store sequences on the same chain.
13863       // Keep trying to merge store sequences until we are unable to do so
13864       // or until we merge the last store on the chain.
13865       bool Changed = MergeConsecutiveStores(ST);
13866       if (!Changed) break;
13867       // Return N as merge only uses CombineTo and no worklist clean
13868       // up is necessary.
13869       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13870         return SDValue(N, 0);
13871     }
13872   }
13873 
13874   // Try transforming N to an indexed store.
13875   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13876     return SDValue(N, 0);
13877 
13878   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13879   //
13880   // Make sure to do this only after attempting to merge stores in order to
13881   //  avoid changing the types of some subset of stores due to visit order,
13882   //  preventing their merging.
13883   if (isa<ConstantFPSDNode>(ST->getValue())) {
13884     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13885       return NewSt;
13886   }
13887 
13888   if (SDValue NewSt = splitMergedValStore(ST))
13889     return NewSt;
13890 
13891   return ReduceLoadOpStoreWidth(N);
13892 }
13893 
13894 /// For the instruction sequence of store below, F and I values
13895 /// are bundled together as an i64 value before being stored into memory.
13896 /// Sometimes it is more efficent to generate separate stores for F and I,
13897 /// which can remove the bitwise instructions or sink them to colder places.
13898 ///
13899 ///   (store (or (zext (bitcast F to i32) to i64),
13900 ///              (shl (zext I to i64), 32)), addr)  -->
13901 ///   (store F, addr) and (store I, addr+4)
13902 ///
13903 /// Similarly, splitting for other merged store can also be beneficial, like:
13904 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13905 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13906 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13907 /// For pair of {i16, i8},  i32 store --> two i16 stores.
13908 /// For pair of {i8, i8},   i16 store --> two i8 stores.
13909 ///
13910 /// We allow each target to determine specifically which kind of splitting is
13911 /// supported.
13912 ///
13913 /// The store patterns are commonly seen from the simple code snippet below
13914 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13915 ///   void goo(const std::pair<int, float> &);
13916 ///   hoo() {
13917 ///     ...
13918 ///     goo(std::make_pair(tmp, ftmp));
13919 ///     ...
13920 ///   }
13921 ///
13922 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13923   if (OptLevel == CodeGenOpt::None)
13924     return SDValue();
13925 
13926   SDValue Val = ST->getValue();
13927   SDLoc DL(ST);
13928 
13929   // Match OR operand.
13930   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13931     return SDValue();
13932 
13933   // Match SHL operand and get Lower and Higher parts of Val.
13934   SDValue Op1 = Val.getOperand(0);
13935   SDValue Op2 = Val.getOperand(1);
13936   SDValue Lo, Hi;
13937   if (Op1.getOpcode() != ISD::SHL) {
13938     std::swap(Op1, Op2);
13939     if (Op1.getOpcode() != ISD::SHL)
13940       return SDValue();
13941   }
13942   Lo = Op2;
13943   Hi = Op1.getOperand(0);
13944   if (!Op1.hasOneUse())
13945     return SDValue();
13946 
13947   // Match shift amount to HalfValBitSize.
13948   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13949   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13950   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13951     return SDValue();
13952 
13953   // Lo and Hi are zero-extended from int with size less equal than 32
13954   // to i64.
13955   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13956       !Lo.getOperand(0).getValueType().isScalarInteger() ||
13957       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13958       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13959       !Hi.getOperand(0).getValueType().isScalarInteger() ||
13960       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13961     return SDValue();
13962 
13963   // Use the EVT of low and high parts before bitcast as the input
13964   // of target query.
13965   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13966                   ? Lo.getOperand(0).getValueType()
13967                   : Lo.getValueType();
13968   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13969                    ? Hi.getOperand(0).getValueType()
13970                    : Hi.getValueType();
13971   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13972     return SDValue();
13973 
13974   // Start to split store.
13975   unsigned Alignment = ST->getAlignment();
13976   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13977   AAMDNodes AAInfo = ST->getAAInfo();
13978 
13979   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13980   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13981   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13982   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13983 
13984   SDValue Chain = ST->getChain();
13985   SDValue Ptr = ST->getBasePtr();
13986   // Lower value store.
13987   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13988                              ST->getAlignment(), MMOFlags, AAInfo);
13989   Ptr =
13990       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13991                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13992   // Higher value store.
13993   SDValue St1 =
13994       DAG.getStore(St0, DL, Hi, Ptr,
13995                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13996                    Alignment / 2, MMOFlags, AAInfo);
13997   return St1;
13998 }
13999 
14000 /// Convert a disguised subvector insertion into a shuffle:
14001 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
14002 /// bitcast(shuffle (bitcast V), (extended X), Mask)
14003 /// Note: We do not use an insert_subvector node because that requires a legal
14004 /// subvector type.
14005 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
14006   SDValue InsertVal = N->getOperand(1);
14007   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
14008       !InsertVal.getOperand(0).getValueType().isVector())
14009     return SDValue();
14010 
14011   SDValue SubVec = InsertVal.getOperand(0);
14012   SDValue DestVec = N->getOperand(0);
14013   EVT SubVecVT = SubVec.getValueType();
14014   EVT VT = DestVec.getValueType();
14015   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
14016   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
14017   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
14018 
14019   // Step 1: Create a shuffle mask that implements this insert operation. The
14020   // vector that we are inserting into will be operand 0 of the shuffle, so
14021   // those elements are just 'i'. The inserted subvector is in the first
14022   // positions of operand 1 of the shuffle. Example:
14023   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
14024   SmallVector<int, 16> Mask(NumMaskVals);
14025   for (unsigned i = 0; i != NumMaskVals; ++i) {
14026     if (i / NumSrcElts == InsIndex)
14027       Mask[i] = (i % NumSrcElts) + NumMaskVals;
14028     else
14029       Mask[i] = i;
14030   }
14031 
14032   // Bail out if the target can not handle the shuffle we want to create.
14033   EVT SubVecEltVT = SubVecVT.getVectorElementType();
14034   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14035   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14036     return SDValue();
14037 
14038   // Step 2: Create a wide vector from the inserted source vector by appending
14039   // undefined elements. This is the same size as our destination vector.
14040   SDLoc DL(N);
14041   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14042   ConcatOps[0] = SubVec;
14043   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14044 
14045   // Step 3: Shuffle in the padded subvector.
14046   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14047   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14048   AddToWorklist(PaddedSubV.getNode());
14049   AddToWorklist(DestVecBC.getNode());
14050   AddToWorklist(Shuf.getNode());
14051   return DAG.getBitcast(VT, Shuf);
14052 }
14053 
14054 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14055   SDValue InVec = N->getOperand(0);
14056   SDValue InVal = N->getOperand(1);
14057   SDValue EltNo = N->getOperand(2);
14058   SDLoc DL(N);
14059 
14060   // If the inserted element is an UNDEF, just use the input vector.
14061   if (InVal.isUndef())
14062     return InVec;
14063 
14064   EVT VT = InVec.getValueType();
14065 
14066   // Remove redundant insertions:
14067   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14068   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14069       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14070     return InVec;
14071 
14072   // We must know which element is being inserted for folds below here.
14073   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14074   if (!IndexC)
14075     return SDValue();
14076   unsigned Elt = IndexC->getZExtValue();
14077 
14078   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14079     return Shuf;
14080 
14081   // Canonicalize insert_vector_elt dag nodes.
14082   // Example:
14083   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14084   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14085   //
14086   // Do this only if the child insert_vector node has one use; also
14087   // do this only if indices are both constants and Idx1 < Idx0.
14088   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14089       && isa<ConstantSDNode>(InVec.getOperand(2))) {
14090     unsigned OtherElt = InVec.getConstantOperandVal(2);
14091     if (Elt < OtherElt) {
14092       // Swap nodes.
14093       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14094                                   InVec.getOperand(0), InVal, EltNo);
14095       AddToWorklist(NewOp.getNode());
14096       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14097                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14098     }
14099   }
14100 
14101   // If we can't generate a legal BUILD_VECTOR, exit
14102   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14103     return SDValue();
14104 
14105   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14106   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
14107   // vector elements.
14108   SmallVector<SDValue, 8> Ops;
14109   // Do not combine these two vectors if the output vector will not replace
14110   // the input vector.
14111   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14112     Ops.append(InVec.getNode()->op_begin(),
14113                InVec.getNode()->op_end());
14114   } else if (InVec.isUndef()) {
14115     unsigned NElts = VT.getVectorNumElements();
14116     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14117   } else {
14118     return SDValue();
14119   }
14120 
14121   // Insert the element
14122   if (Elt < Ops.size()) {
14123     // All the operands of BUILD_VECTOR must have the same type;
14124     // we enforce that here.
14125     EVT OpVT = Ops[0].getValueType();
14126     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14127   }
14128 
14129   // Return the new vector
14130   return DAG.getBuildVector(VT, DL, Ops);
14131 }
14132 
14133 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14134     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14135   assert(!OriginalLoad->isVolatile());
14136 
14137   EVT ResultVT = EVE->getValueType(0);
14138   EVT VecEltVT = InVecVT.getVectorElementType();
14139   unsigned Align = OriginalLoad->getAlignment();
14140   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14141       VecEltVT.getTypeForEVT(*DAG.getContext()));
14142 
14143   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14144     return SDValue();
14145 
14146   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14147     ISD::NON_EXTLOAD : ISD::EXTLOAD;
14148   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14149     return SDValue();
14150 
14151   Align = NewAlign;
14152 
14153   SDValue NewPtr = OriginalLoad->getBasePtr();
14154   SDValue Offset;
14155   EVT PtrType = NewPtr.getValueType();
14156   MachinePointerInfo MPI;
14157   SDLoc DL(EVE);
14158   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14159     int Elt = ConstEltNo->getZExtValue();
14160     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14161     Offset = DAG.getConstant(PtrOff, DL, PtrType);
14162     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14163   } else {
14164     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14165     Offset = DAG.getNode(
14166         ISD::MUL, DL, PtrType, Offset,
14167         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14168     MPI = OriginalLoad->getPointerInfo();
14169   }
14170   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14171 
14172   // The replacement we need to do here is a little tricky: we need to
14173   // replace an extractelement of a load with a load.
14174   // Use ReplaceAllUsesOfValuesWith to do the replacement.
14175   // Note that this replacement assumes that the extractvalue is the only
14176   // use of the load; that's okay because we don't want to perform this
14177   // transformation in other cases anyway.
14178   SDValue Load;
14179   SDValue Chain;
14180   if (ResultVT.bitsGT(VecEltVT)) {
14181     // If the result type of vextract is wider than the load, then issue an
14182     // extending load instead.
14183     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14184                                                   VecEltVT)
14185                                    ? ISD::ZEXTLOAD
14186                                    : ISD::EXTLOAD;
14187     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14188                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14189                           Align, OriginalLoad->getMemOperand()->getFlags(),
14190                           OriginalLoad->getAAInfo());
14191     Chain = Load.getValue(1);
14192   } else {
14193     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14194                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14195                        OriginalLoad->getAAInfo());
14196     Chain = Load.getValue(1);
14197     if (ResultVT.bitsLT(VecEltVT))
14198       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14199     else
14200       Load = DAG.getBitcast(ResultVT, Load);
14201   }
14202   WorklistRemover DeadNodes(*this);
14203   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14204   SDValue To[] = { Load, Chain };
14205   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14206   // Since we're explicitly calling ReplaceAllUses, add the new node to the
14207   // worklist explicitly as well.
14208   AddToWorklist(Load.getNode());
14209   AddUsersToWorklist(Load.getNode()); // Add users too
14210   // Make sure to revisit this node to clean it up; it will usually be dead.
14211   AddToWorklist(EVE);
14212   ++OpsNarrowed;
14213   return SDValue(EVE, 0);
14214 }
14215 
14216 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14217   // (vextract (scalar_to_vector val, 0) -> val
14218   SDValue InVec = N->getOperand(0);
14219   EVT VT = InVec.getValueType();
14220   EVT NVT = N->getValueType(0);
14221 
14222   if (InVec.isUndef())
14223     return DAG.getUNDEF(NVT);
14224 
14225   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14226     // Check if the result type doesn't match the inserted element type. A
14227     // SCALAR_TO_VECTOR may truncate the inserted element and the
14228     // EXTRACT_VECTOR_ELT may widen the extracted vector.
14229     SDValue InOp = InVec.getOperand(0);
14230     if (InOp.getValueType() != NVT) {
14231       assert(InOp.getValueType().isInteger() && NVT.isInteger());
14232       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14233     }
14234     return InOp;
14235   }
14236 
14237   SDValue EltNo = N->getOperand(1);
14238   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14239 
14240   // extract_vector_elt of out-of-bounds element -> UNDEF
14241   if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements()))
14242     return DAG.getUNDEF(NVT);
14243 
14244   // extract_vector_elt (build_vector x, y), 1 -> y
14245   if (ConstEltNo &&
14246       InVec.getOpcode() == ISD::BUILD_VECTOR &&
14247       TLI.isTypeLegal(VT) &&
14248       (InVec.hasOneUse() ||
14249        TLI.aggressivelyPreferBuildVectorSources(VT))) {
14250     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14251     EVT InEltVT = Elt.getValueType();
14252 
14253     // Sometimes build_vector's scalar input types do not match result type.
14254     if (NVT == InEltVT)
14255       return Elt;
14256 
14257     // TODO: It may be useful to truncate if free if the build_vector implicitly
14258     // converts.
14259   }
14260 
14261   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14262   bool isLE = DAG.getDataLayout().isLittleEndian();
14263   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14264   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14265       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14266     SDValue BCSrc = InVec.getOperand(0);
14267     if (BCSrc.getValueType().isScalarInteger())
14268       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14269   }
14270 
14271   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14272   //
14273   // This only really matters if the index is non-constant since other combines
14274   // on the constant elements already work.
14275   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14276       EltNo == InVec.getOperand(2)) {
14277     SDValue Elt = InVec.getOperand(1);
14278     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14279   }
14280 
14281   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14282   // We only perform this optimization before the op legalization phase because
14283   // we may introduce new vector instructions which are not backed by TD
14284   // patterns. For example on AVX, extracting elements from a wide vector
14285   // without using extract_subvector. However, if we can find an underlying
14286   // scalar value, then we can always use that.
14287   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14288     int NumElem = VT.getVectorNumElements();
14289     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14290     // Find the new index to extract from.
14291     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14292 
14293     // Extracting an undef index is undef.
14294     if (OrigElt == -1)
14295       return DAG.getUNDEF(NVT);
14296 
14297     // Select the right vector half to extract from.
14298     SDValue SVInVec;
14299     if (OrigElt < NumElem) {
14300       SVInVec = InVec->getOperand(0);
14301     } else {
14302       SVInVec = InVec->getOperand(1);
14303       OrigElt -= NumElem;
14304     }
14305 
14306     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14307       SDValue InOp = SVInVec.getOperand(OrigElt);
14308       if (InOp.getValueType() != NVT) {
14309         assert(InOp.getValueType().isInteger() && NVT.isInteger());
14310         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14311       }
14312 
14313       return InOp;
14314     }
14315 
14316     // FIXME: We should handle recursing on other vector shuffles and
14317     // scalar_to_vector here as well.
14318 
14319     if (!LegalOperations ||
14320         // FIXME: Should really be just isOperationLegalOrCustom.
14321         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14322         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14323       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14324       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14325                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14326     }
14327   }
14328 
14329   bool BCNumEltsChanged = false;
14330   EVT ExtVT = VT.getVectorElementType();
14331   EVT LVT = ExtVT;
14332 
14333   // If the result of load has to be truncated, then it's not necessarily
14334   // profitable.
14335   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14336     return SDValue();
14337 
14338   if (InVec.getOpcode() == ISD::BITCAST) {
14339     // Don't duplicate a load with other uses.
14340     if (!InVec.hasOneUse())
14341       return SDValue();
14342 
14343     EVT BCVT = InVec.getOperand(0).getValueType();
14344     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14345       return SDValue();
14346     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14347       BCNumEltsChanged = true;
14348     InVec = InVec.getOperand(0);
14349     ExtVT = BCVT.getVectorElementType();
14350   }
14351 
14352   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14353   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14354       ISD::isNormalLoad(InVec.getNode()) &&
14355       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14356     SDValue Index = N->getOperand(1);
14357     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14358       if (!OrigLoad->isVolatile()) {
14359         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14360                                                              OrigLoad);
14361       }
14362     }
14363   }
14364 
14365   // Perform only after legalization to ensure build_vector / vector_shuffle
14366   // optimizations have already been done.
14367   if (!LegalOperations) return SDValue();
14368 
14369   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14370   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14371   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14372 
14373   if (ConstEltNo) {
14374     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14375 
14376     LoadSDNode *LN0 = nullptr;
14377     const ShuffleVectorSDNode *SVN = nullptr;
14378     if (ISD::isNormalLoad(InVec.getNode())) {
14379       LN0 = cast<LoadSDNode>(InVec);
14380     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14381                InVec.getOperand(0).getValueType() == ExtVT &&
14382                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14383       // Don't duplicate a load with other uses.
14384       if (!InVec.hasOneUse())
14385         return SDValue();
14386 
14387       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14388     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14389       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14390       // =>
14391       // (load $addr+1*size)
14392 
14393       // Don't duplicate a load with other uses.
14394       if (!InVec.hasOneUse())
14395         return SDValue();
14396 
14397       // If the bit convert changed the number of elements, it is unsafe
14398       // to examine the mask.
14399       if (BCNumEltsChanged)
14400         return SDValue();
14401 
14402       // Select the input vector, guarding against out of range extract vector.
14403       unsigned NumElems = VT.getVectorNumElements();
14404       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14405       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14406 
14407       if (InVec.getOpcode() == ISD::BITCAST) {
14408         // Don't duplicate a load with other uses.
14409         if (!InVec.hasOneUse())
14410           return SDValue();
14411 
14412         InVec = InVec.getOperand(0);
14413       }
14414       if (ISD::isNormalLoad(InVec.getNode())) {
14415         LN0 = cast<LoadSDNode>(InVec);
14416         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14417         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14418       }
14419     }
14420 
14421     // Make sure we found a non-volatile load and the extractelement is
14422     // the only use.
14423     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14424       return SDValue();
14425 
14426     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14427     if (Elt == -1)
14428       return DAG.getUNDEF(LVT);
14429 
14430     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14431   }
14432 
14433   return SDValue();
14434 }
14435 
14436 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14437 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14438   // We perform this optimization post type-legalization because
14439   // the type-legalizer often scalarizes integer-promoted vectors.
14440   // Performing this optimization before may create bit-casts which
14441   // will be type-legalized to complex code sequences.
14442   // We perform this optimization only before the operation legalizer because we
14443   // may introduce illegal operations.
14444   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14445     return SDValue();
14446 
14447   unsigned NumInScalars = N->getNumOperands();
14448   SDLoc DL(N);
14449   EVT VT = N->getValueType(0);
14450 
14451   // Check to see if this is a BUILD_VECTOR of a bunch of values
14452   // which come from any_extend or zero_extend nodes. If so, we can create
14453   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14454   // optimizations. We do not handle sign-extend because we can't fill the sign
14455   // using shuffles.
14456   EVT SourceType = MVT::Other;
14457   bool AllAnyExt = true;
14458 
14459   for (unsigned i = 0; i != NumInScalars; ++i) {
14460     SDValue In = N->getOperand(i);
14461     // Ignore undef inputs.
14462     if (In.isUndef()) continue;
14463 
14464     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14465     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14466 
14467     // Abort if the element is not an extension.
14468     if (!ZeroExt && !AnyExt) {
14469       SourceType = MVT::Other;
14470       break;
14471     }
14472 
14473     // The input is a ZeroExt or AnyExt. Check the original type.
14474     EVT InTy = In.getOperand(0).getValueType();
14475 
14476     // Check that all of the widened source types are the same.
14477     if (SourceType == MVT::Other)
14478       // First time.
14479       SourceType = InTy;
14480     else if (InTy != SourceType) {
14481       // Multiple income types. Abort.
14482       SourceType = MVT::Other;
14483       break;
14484     }
14485 
14486     // Check if all of the extends are ANY_EXTENDs.
14487     AllAnyExt &= AnyExt;
14488   }
14489 
14490   // In order to have valid types, all of the inputs must be extended from the
14491   // same source type and all of the inputs must be any or zero extend.
14492   // Scalar sizes must be a power of two.
14493   EVT OutScalarTy = VT.getScalarType();
14494   bool ValidTypes = SourceType != MVT::Other &&
14495                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14496                  isPowerOf2_32(SourceType.getSizeInBits());
14497 
14498   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14499   // turn into a single shuffle instruction.
14500   if (!ValidTypes)
14501     return SDValue();
14502 
14503   bool isLE = DAG.getDataLayout().isLittleEndian();
14504   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14505   assert(ElemRatio > 1 && "Invalid element size ratio");
14506   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14507                                DAG.getConstant(0, DL, SourceType);
14508 
14509   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14510   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14511 
14512   // Populate the new build_vector
14513   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14514     SDValue Cast = N->getOperand(i);
14515     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14516             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14517             Cast.isUndef()) && "Invalid cast opcode");
14518     SDValue In;
14519     if (Cast.isUndef())
14520       In = DAG.getUNDEF(SourceType);
14521     else
14522       In = Cast->getOperand(0);
14523     unsigned Index = isLE ? (i * ElemRatio) :
14524                             (i * ElemRatio + (ElemRatio - 1));
14525 
14526     assert(Index < Ops.size() && "Invalid index");
14527     Ops[Index] = In;
14528   }
14529 
14530   // The type of the new BUILD_VECTOR node.
14531   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14532   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14533          "Invalid vector size");
14534   // Check if the new vector type is legal.
14535   if (!isTypeLegal(VecVT)) return SDValue();
14536 
14537   // Make the new BUILD_VECTOR.
14538   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14539 
14540   // The new BUILD_VECTOR node has the potential to be further optimized.
14541   AddToWorklist(BV.getNode());
14542   // Bitcast to the desired type.
14543   return DAG.getBitcast(VT, BV);
14544 }
14545 
14546 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14547   EVT VT = N->getValueType(0);
14548 
14549   unsigned NumInScalars = N->getNumOperands();
14550   SDLoc DL(N);
14551 
14552   EVT SrcVT = MVT::Other;
14553   unsigned Opcode = ISD::DELETED_NODE;
14554   unsigned NumDefs = 0;
14555 
14556   for (unsigned i = 0; i != NumInScalars; ++i) {
14557     SDValue In = N->getOperand(i);
14558     unsigned Opc = In.getOpcode();
14559 
14560     if (Opc == ISD::UNDEF)
14561       continue;
14562 
14563     // If all scalar values are floats and converted from integers.
14564     if (Opcode == ISD::DELETED_NODE &&
14565         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14566       Opcode = Opc;
14567     }
14568 
14569     if (Opc != Opcode)
14570       return SDValue();
14571 
14572     EVT InVT = In.getOperand(0).getValueType();
14573 
14574     // If all scalar values are typed differently, bail out. It's chosen to
14575     // simplify BUILD_VECTOR of integer types.
14576     if (SrcVT == MVT::Other)
14577       SrcVT = InVT;
14578     if (SrcVT != InVT)
14579       return SDValue();
14580     NumDefs++;
14581   }
14582 
14583   // If the vector has just one element defined, it's not worth to fold it into
14584   // a vectorized one.
14585   if (NumDefs < 2)
14586     return SDValue();
14587 
14588   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14589          && "Should only handle conversion from integer to float.");
14590   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14591 
14592   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14593 
14594   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14595     return SDValue();
14596 
14597   // Just because the floating-point vector type is legal does not necessarily
14598   // mean that the corresponding integer vector type is.
14599   if (!isTypeLegal(NVT))
14600     return SDValue();
14601 
14602   SmallVector<SDValue, 8> Opnds;
14603   for (unsigned i = 0; i != NumInScalars; ++i) {
14604     SDValue In = N->getOperand(i);
14605 
14606     if (In.isUndef())
14607       Opnds.push_back(DAG.getUNDEF(SrcVT));
14608     else
14609       Opnds.push_back(In.getOperand(0));
14610   }
14611   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14612   AddToWorklist(BV.getNode());
14613 
14614   return DAG.getNode(Opcode, DL, VT, BV);
14615 }
14616 
14617 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14618                                            ArrayRef<int> VectorMask,
14619                                            SDValue VecIn1, SDValue VecIn2,
14620                                            unsigned LeftIdx) {
14621   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14622   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14623 
14624   EVT VT = N->getValueType(0);
14625   EVT InVT1 = VecIn1.getValueType();
14626   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14627 
14628   unsigned Vec2Offset = 0;
14629   unsigned NumElems = VT.getVectorNumElements();
14630   unsigned ShuffleNumElems = NumElems;
14631 
14632   // In case both the input vectors are extracted from same base
14633   // vector we do not need extra addend (Vec2Offset) while
14634   // computing shuffle mask.
14635   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14636       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14637       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14638     Vec2Offset = InVT1.getVectorNumElements();
14639 
14640   // We can't generate a shuffle node with mismatched input and output types.
14641   // Try to make the types match the type of the output.
14642   if (InVT1 != VT || InVT2 != VT) {
14643     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14644       // If the output vector length is a multiple of both input lengths,
14645       // we can concatenate them and pad the rest with undefs.
14646       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14647       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14648       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14649       ConcatOps[0] = VecIn1;
14650       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14651       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14652       VecIn2 = SDValue();
14653     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14654       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14655         return SDValue();
14656 
14657       if (!VecIn2.getNode()) {
14658         // If we only have one input vector, and it's twice the size of the
14659         // output, split it in two.
14660         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14661                              DAG.getConstant(NumElems, DL, IdxTy));
14662         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14663         // Since we now have shorter input vectors, adjust the offset of the
14664         // second vector's start.
14665         Vec2Offset = NumElems;
14666       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14667         // VecIn1 is wider than the output, and we have another, possibly
14668         // smaller input. Pad the smaller input with undefs, shuffle at the
14669         // input vector width, and extract the output.
14670         // The shuffle type is different than VT, so check legality again.
14671         if (LegalOperations &&
14672             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14673           return SDValue();
14674 
14675         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14676         // lower it back into a BUILD_VECTOR. So if the inserted type is
14677         // illegal, don't even try.
14678         if (InVT1 != InVT2) {
14679           if (!TLI.isTypeLegal(InVT2))
14680             return SDValue();
14681           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14682                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14683         }
14684         ShuffleNumElems = NumElems * 2;
14685       } else {
14686         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14687         // than VecIn1. We can't handle this for now - this case will disappear
14688         // when we start sorting the vectors by type.
14689         return SDValue();
14690       }
14691     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14692                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14693       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14694       ConcatOps[0] = VecIn2;
14695       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14696     } else {
14697       // TODO: Support cases where the length mismatch isn't exactly by a
14698       // factor of 2.
14699       // TODO: Move this check upwards, so that if we have bad type
14700       // mismatches, we don't create any DAG nodes.
14701       return SDValue();
14702     }
14703   }
14704 
14705   // Initialize mask to undef.
14706   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14707 
14708   // Only need to run up to the number of elements actually used, not the
14709   // total number of elements in the shuffle - if we are shuffling a wider
14710   // vector, the high lanes should be set to undef.
14711   for (unsigned i = 0; i != NumElems; ++i) {
14712     if (VectorMask[i] <= 0)
14713       continue;
14714 
14715     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14716     if (VectorMask[i] == (int)LeftIdx) {
14717       Mask[i] = ExtIndex;
14718     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14719       Mask[i] = Vec2Offset + ExtIndex;
14720     }
14721   }
14722 
14723   // The type the input vectors may have changed above.
14724   InVT1 = VecIn1.getValueType();
14725 
14726   // If we already have a VecIn2, it should have the same type as VecIn1.
14727   // If we don't, get an undef/zero vector of the appropriate type.
14728   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14729   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14730 
14731   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14732   if (ShuffleNumElems > NumElems)
14733     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14734 
14735   return Shuffle;
14736 }
14737 
14738 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14739 // operations. If the types of the vectors we're extracting from allow it,
14740 // turn this into a vector_shuffle node.
14741 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14742   SDLoc DL(N);
14743   EVT VT = N->getValueType(0);
14744 
14745   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14746   if (!isTypeLegal(VT))
14747     return SDValue();
14748 
14749   // May only combine to shuffle after legalize if shuffle is legal.
14750   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14751     return SDValue();
14752 
14753   bool UsesZeroVector = false;
14754   unsigned NumElems = N->getNumOperands();
14755 
14756   // Record, for each element of the newly built vector, which input vector
14757   // that element comes from. -1 stands for undef, 0 for the zero vector,
14758   // and positive values for the input vectors.
14759   // VectorMask maps each element to its vector number, and VecIn maps vector
14760   // numbers to their initial SDValues.
14761 
14762   SmallVector<int, 8> VectorMask(NumElems, -1);
14763   SmallVector<SDValue, 8> VecIn;
14764   VecIn.push_back(SDValue());
14765 
14766   for (unsigned i = 0; i != NumElems; ++i) {
14767     SDValue Op = N->getOperand(i);
14768 
14769     if (Op.isUndef())
14770       continue;
14771 
14772     // See if we can use a blend with a zero vector.
14773     // TODO: Should we generalize this to a blend with an arbitrary constant
14774     // vector?
14775     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14776       UsesZeroVector = true;
14777       VectorMask[i] = 0;
14778       continue;
14779     }
14780 
14781     // Not an undef or zero. If the input is something other than an
14782     // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
14783     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14784         !isa<ConstantSDNode>(Op.getOperand(1)))
14785       return SDValue();
14786     SDValue ExtractedFromVec = Op.getOperand(0);
14787 
14788     APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
14789     if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
14790       return SDValue();
14791 
14792     // All inputs must have the same element type as the output.
14793     if (VT.getVectorElementType() !=
14794         ExtractedFromVec.getValueType().getVectorElementType())
14795       return SDValue();
14796 
14797     // Have we seen this input vector before?
14798     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14799     // a map back from SDValues to numbers isn't worth it.
14800     unsigned Idx = std::distance(
14801         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14802     if (Idx == VecIn.size())
14803       VecIn.push_back(ExtractedFromVec);
14804 
14805     VectorMask[i] = Idx;
14806   }
14807 
14808   // If we didn't find at least one input vector, bail out.
14809   if (VecIn.size() < 2)
14810     return SDValue();
14811 
14812   // If all the Operands of BUILD_VECTOR extract from same
14813   // vector, then split the vector efficiently based on the maximum
14814   // vector access index and adjust the VectorMask and
14815   // VecIn accordingly.
14816   if (VecIn.size() == 2) {
14817     unsigned MaxIndex = 0;
14818     unsigned NearestPow2 = 0;
14819     SDValue Vec = VecIn.back();
14820     EVT InVT = Vec.getValueType();
14821     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14822     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14823 
14824     for (unsigned i = 0; i < NumElems; i++) {
14825       if (VectorMask[i] <= 0)
14826         continue;
14827       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14828       IndexVec[i] = Index;
14829       MaxIndex = std::max(MaxIndex, Index);
14830     }
14831 
14832     NearestPow2 = PowerOf2Ceil(MaxIndex);
14833     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14834         NumElems * 2 < NearestPow2) {
14835       unsigned SplitSize = NearestPow2 / 2;
14836       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14837                                      InVT.getVectorElementType(), SplitSize);
14838       if (TLI.isTypeLegal(SplitVT)) {
14839         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14840                                      DAG.getConstant(SplitSize, DL, IdxTy));
14841         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
14842                                      DAG.getConstant(0, DL, IdxTy));
14843         VecIn.pop_back();
14844         VecIn.push_back(VecIn1);
14845         VecIn.push_back(VecIn2);
14846 
14847         for (unsigned i = 0; i < NumElems; i++) {
14848           if (VectorMask[i] <= 0)
14849             continue;
14850           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
14851         }
14852       }
14853     }
14854   }
14855 
14856   // TODO: We want to sort the vectors by descending length, so that adjacent
14857   // pairs have similar length, and the longer vector is always first in the
14858   // pair.
14859 
14860   // TODO: Should this fire if some of the input vectors has illegal type (like
14861   // it does now), or should we let legalization run its course first?
14862 
14863   // Shuffle phase:
14864   // Take pairs of vectors, and shuffle them so that the result has elements
14865   // from these vectors in the correct places.
14866   // For example, given:
14867   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14868   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14869   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14870   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14871   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14872   // We will generate:
14873   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14874   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14875   SmallVector<SDValue, 4> Shuffles;
14876   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14877     unsigned LeftIdx = 2 * In + 1;
14878     SDValue VecLeft = VecIn[LeftIdx];
14879     SDValue VecRight =
14880         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14881 
14882     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14883                                                 VecRight, LeftIdx))
14884       Shuffles.push_back(Shuffle);
14885     else
14886       return SDValue();
14887   }
14888 
14889   // If we need the zero vector as an "ingredient" in the blend tree, add it
14890   // to the list of shuffles.
14891   if (UsesZeroVector)
14892     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14893                                       : DAG.getConstantFP(0.0, DL, VT));
14894 
14895   // If we only have one shuffle, we're done.
14896   if (Shuffles.size() == 1)
14897     return Shuffles[0];
14898 
14899   // Update the vector mask to point to the post-shuffle vectors.
14900   for (int &Vec : VectorMask)
14901     if (Vec == 0)
14902       Vec = Shuffles.size() - 1;
14903     else
14904       Vec = (Vec - 1) / 2;
14905 
14906   // More than one shuffle. Generate a binary tree of blends, e.g. if from
14907   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14908   // generate:
14909   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14910   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14911   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14912   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14913   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14914   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14915   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14916 
14917   // Make sure the initial size of the shuffle list is even.
14918   if (Shuffles.size() % 2)
14919     Shuffles.push_back(DAG.getUNDEF(VT));
14920 
14921   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14922     if (CurSize % 2) {
14923       Shuffles[CurSize] = DAG.getUNDEF(VT);
14924       CurSize++;
14925     }
14926     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14927       int Left = 2 * In;
14928       int Right = 2 * In + 1;
14929       SmallVector<int, 8> Mask(NumElems, -1);
14930       for (unsigned i = 0; i != NumElems; ++i) {
14931         if (VectorMask[i] == Left) {
14932           Mask[i] = i;
14933           VectorMask[i] = In;
14934         } else if (VectorMask[i] == Right) {
14935           Mask[i] = i + NumElems;
14936           VectorMask[i] = In;
14937         }
14938       }
14939 
14940       Shuffles[In] =
14941           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14942     }
14943   }
14944   return Shuffles[0];
14945 }
14946 
14947 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14948   EVT VT = N->getValueType(0);
14949 
14950   // A vector built entirely of undefs is undef.
14951   if (ISD::allOperandsUndef(N))
14952     return DAG.getUNDEF(VT);
14953 
14954   // If this is a splat of a bitcast from another vector, change to a
14955   // concat_vector.
14956   // For example:
14957   //   (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
14958   //     (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
14959   //
14960   // If X is a build_vector itself, the concat can become a larger build_vector.
14961   // TODO: Maybe this is useful for non-splat too?
14962   if (!LegalOperations) {
14963     if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
14964       Splat = peekThroughBitcast(Splat);
14965       EVT SrcVT = Splat.getValueType();
14966       if (SrcVT.isVector()) {
14967         unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
14968         EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
14969                                      SrcVT.getVectorElementType(), NumElts);
14970         SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
14971         SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), NewVT, Ops);
14972         return DAG.getBitcast(VT, Concat);
14973       }
14974     }
14975   }
14976 
14977   // Check if we can express BUILD VECTOR via subvector extract.
14978   if (!LegalTypes && (N->getNumOperands() > 1)) {
14979     SDValue Op0 = N->getOperand(0);
14980     auto checkElem = [&](SDValue Op) -> uint64_t {
14981       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14982           (Op0.getOperand(0) == Op.getOperand(0)))
14983         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14984           return CNode->getZExtValue();
14985       return -1;
14986     };
14987 
14988     int Offset = checkElem(Op0);
14989     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14990       if (Offset + i != checkElem(N->getOperand(i))) {
14991         Offset = -1;
14992         break;
14993       }
14994     }
14995 
14996     if ((Offset == 0) &&
14997         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14998       return Op0.getOperand(0);
14999     if ((Offset != -1) &&
15000         ((Offset % N->getValueType(0).getVectorNumElements()) ==
15001          0)) // IDX must be multiple of output size.
15002       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
15003                          Op0.getOperand(0), Op0.getOperand(1));
15004   }
15005 
15006   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
15007     return V;
15008 
15009   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
15010     return V;
15011 
15012   if (SDValue V = reduceBuildVecToShuffle(N))
15013     return V;
15014 
15015   return SDValue();
15016 }
15017 
15018 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
15019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15020   EVT OpVT = N->getOperand(0).getValueType();
15021 
15022   // If the operands are legal vectors, leave them alone.
15023   if (TLI.isTypeLegal(OpVT))
15024     return SDValue();
15025 
15026   SDLoc DL(N);
15027   EVT VT = N->getValueType(0);
15028   SmallVector<SDValue, 8> Ops;
15029 
15030   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
15031   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15032 
15033   // Keep track of what we encounter.
15034   bool AnyInteger = false;
15035   bool AnyFP = false;
15036   for (const SDValue &Op : N->ops()) {
15037     if (ISD::BITCAST == Op.getOpcode() &&
15038         !Op.getOperand(0).getValueType().isVector())
15039       Ops.push_back(Op.getOperand(0));
15040     else if (ISD::UNDEF == Op.getOpcode())
15041       Ops.push_back(ScalarUndef);
15042     else
15043       return SDValue();
15044 
15045     // Note whether we encounter an integer or floating point scalar.
15046     // If it's neither, bail out, it could be something weird like x86mmx.
15047     EVT LastOpVT = Ops.back().getValueType();
15048     if (LastOpVT.isFloatingPoint())
15049       AnyFP = true;
15050     else if (LastOpVT.isInteger())
15051       AnyInteger = true;
15052     else
15053       return SDValue();
15054   }
15055 
15056   // If any of the operands is a floating point scalar bitcast to a vector,
15057   // use floating point types throughout, and bitcast everything.
15058   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
15059   if (AnyFP) {
15060     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
15061     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15062     if (AnyInteger) {
15063       for (SDValue &Op : Ops) {
15064         if (Op.getValueType() == SVT)
15065           continue;
15066         if (Op.isUndef())
15067           Op = ScalarUndef;
15068         else
15069           Op = DAG.getBitcast(SVT, Op);
15070       }
15071     }
15072   }
15073 
15074   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15075                                VT.getSizeInBits() / SVT.getSizeInBits());
15076   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15077 }
15078 
15079 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15080 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15081 // most two distinct vectors the same size as the result, attempt to turn this
15082 // into a legal shuffle.
15083 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15084   EVT VT = N->getValueType(0);
15085   EVT OpVT = N->getOperand(0).getValueType();
15086   int NumElts = VT.getVectorNumElements();
15087   int NumOpElts = OpVT.getVectorNumElements();
15088 
15089   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15090   SmallVector<int, 8> Mask;
15091 
15092   for (SDValue Op : N->ops()) {
15093     // Peek through any bitcast.
15094     Op = peekThroughBitcast(Op);
15095 
15096     // UNDEF nodes convert to UNDEF shuffle mask values.
15097     if (Op.isUndef()) {
15098       Mask.append((unsigned)NumOpElts, -1);
15099       continue;
15100     }
15101 
15102     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15103       return SDValue();
15104 
15105     // What vector are we extracting the subvector from and at what index?
15106     SDValue ExtVec = Op.getOperand(0);
15107 
15108     // We want the EVT of the original extraction to correctly scale the
15109     // extraction index.
15110     EVT ExtVT = ExtVec.getValueType();
15111 
15112     // Peek through any bitcast.
15113     ExtVec = peekThroughBitcast(ExtVec);
15114 
15115     // UNDEF nodes convert to UNDEF shuffle mask values.
15116     if (ExtVec.isUndef()) {
15117       Mask.append((unsigned)NumOpElts, -1);
15118       continue;
15119     }
15120 
15121     if (!isa<ConstantSDNode>(Op.getOperand(1)))
15122       return SDValue();
15123     int ExtIdx = Op.getConstantOperandVal(1);
15124 
15125     // Ensure that we are extracting a subvector from a vector the same
15126     // size as the result.
15127     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15128       return SDValue();
15129 
15130     // Scale the subvector index to account for any bitcast.
15131     int NumExtElts = ExtVT.getVectorNumElements();
15132     if (0 == (NumExtElts % NumElts))
15133       ExtIdx /= (NumExtElts / NumElts);
15134     else if (0 == (NumElts % NumExtElts))
15135       ExtIdx *= (NumElts / NumExtElts);
15136     else
15137       return SDValue();
15138 
15139     // At most we can reference 2 inputs in the final shuffle.
15140     if (SV0.isUndef() || SV0 == ExtVec) {
15141       SV0 = ExtVec;
15142       for (int i = 0; i != NumOpElts; ++i)
15143         Mask.push_back(i + ExtIdx);
15144     } else if (SV1.isUndef() || SV1 == ExtVec) {
15145       SV1 = ExtVec;
15146       for (int i = 0; i != NumOpElts; ++i)
15147         Mask.push_back(i + ExtIdx + NumElts);
15148     } else {
15149       return SDValue();
15150     }
15151   }
15152 
15153   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15154     return SDValue();
15155 
15156   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15157                               DAG.getBitcast(VT, SV1), Mask);
15158 }
15159 
15160 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15161   // If we only have one input vector, we don't need to do any concatenation.
15162   if (N->getNumOperands() == 1)
15163     return N->getOperand(0);
15164 
15165   // Check if all of the operands are undefs.
15166   EVT VT = N->getValueType(0);
15167   if (ISD::allOperandsUndef(N))
15168     return DAG.getUNDEF(VT);
15169 
15170   // Optimize concat_vectors where all but the first of the vectors are undef.
15171   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15172         return Op.isUndef();
15173       })) {
15174     SDValue In = N->getOperand(0);
15175     assert(In.getValueType().isVector() && "Must concat vectors");
15176 
15177     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15178     if (In->getOpcode() == ISD::BITCAST &&
15179         !In->getOperand(0).getValueType().isVector()) {
15180       SDValue Scalar = In->getOperand(0);
15181 
15182       // If the bitcast type isn't legal, it might be a trunc of a legal type;
15183       // look through the trunc so we can still do the transform:
15184       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15185       if (Scalar->getOpcode() == ISD::TRUNCATE &&
15186           !TLI.isTypeLegal(Scalar.getValueType()) &&
15187           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15188         Scalar = Scalar->getOperand(0);
15189 
15190       EVT SclTy = Scalar->getValueType(0);
15191 
15192       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15193         return SDValue();
15194 
15195       // Bail out if the vector size is not a multiple of the scalar size.
15196       if (VT.getSizeInBits() % SclTy.getSizeInBits())
15197         return SDValue();
15198 
15199       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15200       if (VNTNumElms < 2)
15201         return SDValue();
15202 
15203       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15204       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15205         return SDValue();
15206 
15207       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15208       return DAG.getBitcast(VT, Res);
15209     }
15210   }
15211 
15212   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15213   // We have already tested above for an UNDEF only concatenation.
15214   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15215   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15216   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15217     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15218   };
15219   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15220     SmallVector<SDValue, 8> Opnds;
15221     EVT SVT = VT.getScalarType();
15222 
15223     EVT MinVT = SVT;
15224     if (!SVT.isFloatingPoint()) {
15225       // If BUILD_VECTOR are from built from integer, they may have different
15226       // operand types. Get the smallest type and truncate all operands to it.
15227       bool FoundMinVT = false;
15228       for (const SDValue &Op : N->ops())
15229         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15230           EVT OpSVT = Op.getOperand(0).getValueType();
15231           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15232           FoundMinVT = true;
15233         }
15234       assert(FoundMinVT && "Concat vector type mismatch");
15235     }
15236 
15237     for (const SDValue &Op : N->ops()) {
15238       EVT OpVT = Op.getValueType();
15239       unsigned NumElts = OpVT.getVectorNumElements();
15240 
15241       if (ISD::UNDEF == Op.getOpcode())
15242         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15243 
15244       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15245         if (SVT.isFloatingPoint()) {
15246           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
15247           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15248         } else {
15249           for (unsigned i = 0; i != NumElts; ++i)
15250             Opnds.push_back(
15251                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15252         }
15253       }
15254     }
15255 
15256     assert(VT.getVectorNumElements() == Opnds.size() &&
15257            "Concat vector type mismatch");
15258     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15259   }
15260 
15261   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15262   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15263     return V;
15264 
15265   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15266   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15267     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15268       return V;
15269 
15270   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15271   // nodes often generate nop CONCAT_VECTOR nodes.
15272   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15273   // place the incoming vectors at the exact same location.
15274   SDValue SingleSource = SDValue();
15275   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15276 
15277   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15278     SDValue Op = N->getOperand(i);
15279 
15280     if (Op.isUndef())
15281       continue;
15282 
15283     // Check if this is the identity extract:
15284     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15285       return SDValue();
15286 
15287     // Find the single incoming vector for the extract_subvector.
15288     if (SingleSource.getNode()) {
15289       if (Op.getOperand(0) != SingleSource)
15290         return SDValue();
15291     } else {
15292       SingleSource = Op.getOperand(0);
15293 
15294       // Check the source type is the same as the type of the result.
15295       // If not, this concat may extend the vector, so we can not
15296       // optimize it away.
15297       if (SingleSource.getValueType() != N->getValueType(0))
15298         return SDValue();
15299     }
15300 
15301     unsigned IdentityIndex = i * PartNumElem;
15302     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15303     // The extract index must be constant.
15304     if (!CS)
15305       return SDValue();
15306 
15307     // Check that we are reading from the identity index.
15308     if (CS->getZExtValue() != IdentityIndex)
15309       return SDValue();
15310   }
15311 
15312   if (SingleSource.getNode())
15313     return SingleSource;
15314 
15315   return SDValue();
15316 }
15317 
15318 /// If we are extracting a subvector produced by a wide binary operator with at
15319 /// at least one operand that was the result of a vector concatenation, then try
15320 /// to use the narrow vector operands directly to avoid the concatenation and
15321 /// extraction.
15322 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15323   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15324   // some of these bailouts with other transforms.
15325 
15326   // The extract index must be a constant, so we can map it to a concat operand.
15327   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15328   if (!ExtractIndex)
15329     return SDValue();
15330 
15331   // Only handle the case where we are doubling and then halving. A larger ratio
15332   // may require more than two narrow binops to replace the wide binop.
15333   EVT VT = Extract->getValueType(0);
15334   unsigned NumElems = VT.getVectorNumElements();
15335   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15336          "Extract index is not a multiple of the vector length.");
15337   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15338     return SDValue();
15339 
15340   // We are looking for an optionally bitcasted wide vector binary operator
15341   // feeding an extract subvector.
15342   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15343 
15344   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15345   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15346   // flavors, but no other 256-bit integer support. This could be extended to
15347   // handle any binop, but that may require fixing/adding other folds to avoid
15348   // codegen regressions.
15349   unsigned BOpcode = BinOp.getOpcode();
15350   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15351     return SDValue();
15352 
15353   // The binop must be a vector type, so we can chop it in half.
15354   EVT WideBVT = BinOp.getValueType();
15355   if (!WideBVT.isVector())
15356     return SDValue();
15357 
15358   // Bail out if the target does not support a narrower version of the binop.
15359   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15360                                    WideBVT.getVectorNumElements() / 2);
15361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15362   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15363     return SDValue();
15364 
15365   // Peek through bitcasts of the binary operator operands if needed.
15366   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15367   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15368 
15369   // We need at least one concatenation operation of a binop operand to make
15370   // this transform worthwhile. The concat must double the input vector sizes.
15371   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15372   bool ConcatL =
15373       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15374   bool ConcatR =
15375       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15376   if (!ConcatL && !ConcatR)
15377     return SDValue();
15378 
15379   // If one of the binop operands was not the result of a concat, we must
15380   // extract a half-sized operand for our new narrow binop. We can't just reuse
15381   // the original extract index operand because we may have bitcasted.
15382   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15383   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15384   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15385   SDLoc DL(Extract);
15386 
15387   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15388   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15389   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15390   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15391                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15392                                     BinOp.getOperand(0),
15393                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15394 
15395   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15396                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15397                                     BinOp.getOperand(1),
15398                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15399 
15400   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15401   return DAG.getBitcast(VT, NarrowBinOp);
15402 }
15403 
15404 /// If we are extracting a subvector from a wide vector load, convert to a
15405 /// narrow load to eliminate the extraction:
15406 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15407 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15408   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15409   if (DAG.getDataLayout().isBigEndian())
15410     return SDValue();
15411 
15412   // TODO: The one-use check is overly conservative. Check the cost of the
15413   // extract instead or remove that condition entirely.
15414   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15415   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15416   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15417       !ExtIdx)
15418     return SDValue();
15419 
15420   // The narrow load will be offset from the base address of the old load if
15421   // we are extracting from something besides index 0 (little-endian).
15422   EVT VT = Extract->getValueType(0);
15423   SDLoc DL(Extract);
15424   SDValue BaseAddr = Ld->getOperand(1);
15425   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15426 
15427   // TODO: Use "BaseIndexOffset" to make this more effective.
15428   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15429   MachineFunction &MF = DAG.getMachineFunction();
15430   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15431                                                    VT.getStoreSize());
15432   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15433   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15434   return NewLd;
15435 }
15436 
15437 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15438   EVT NVT = N->getValueType(0);
15439   SDValue V = N->getOperand(0);
15440 
15441   // Extract from UNDEF is UNDEF.
15442   if (V.isUndef())
15443     return DAG.getUNDEF(NVT);
15444 
15445   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15446     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15447       return NarrowLoad;
15448 
15449   // Combine:
15450   //    (extract_subvec (concat V1, V2, ...), i)
15451   // Into:
15452   //    Vi if possible
15453   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15454   // type.
15455   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15456       isa<ConstantSDNode>(N->getOperand(1)) &&
15457       V->getOperand(0).getValueType() == NVT) {
15458     unsigned Idx = N->getConstantOperandVal(1);
15459     unsigned NumElems = NVT.getVectorNumElements();
15460     assert((Idx % NumElems) == 0 &&
15461            "IDX in concat is not a multiple of the result vector length.");
15462     return V->getOperand(Idx / NumElems);
15463   }
15464 
15465   // Skip bitcasting
15466   V = peekThroughBitcast(V);
15467 
15468   // If the input is a build vector. Try to make a smaller build vector.
15469   if (V->getOpcode() == ISD::BUILD_VECTOR) {
15470     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15471       EVT InVT = V->getValueType(0);
15472       unsigned ExtractSize = NVT.getSizeInBits();
15473       unsigned EltSize = InVT.getScalarSizeInBits();
15474       // Only do this if we won't split any elements.
15475       if (ExtractSize % EltSize == 0) {
15476         unsigned NumElems = ExtractSize / EltSize;
15477         EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15478                                          InVT.getVectorElementType(), NumElems);
15479         if ((!LegalOperations ||
15480              TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15481             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15482           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15483                             EltSize;
15484 
15485           // Extract the pieces from the original build_vector.
15486           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15487                                             makeArrayRef(V->op_begin() + IdxVal,
15488                                                          NumElems));
15489           return DAG.getBitcast(NVT, BuildVec);
15490         }
15491       }
15492     }
15493   }
15494 
15495   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15496     // Handle only simple case where vector being inserted and vector
15497     // being extracted are of same size.
15498     EVT SmallVT = V->getOperand(1).getValueType();
15499     if (!NVT.bitsEq(SmallVT))
15500       return SDValue();
15501 
15502     // Only handle cases where both indexes are constants.
15503     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15504     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15505 
15506     if (InsIdx && ExtIdx) {
15507       // Combine:
15508       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15509       // Into:
15510       //    indices are equal or bit offsets are equal => V1
15511       //    otherwise => (extract_subvec V1, ExtIdx)
15512       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15513           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15514         return DAG.getBitcast(NVT, V->getOperand(1));
15515       return DAG.getNode(
15516           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15517           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15518           N->getOperand(1));
15519     }
15520   }
15521 
15522   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15523     return NarrowBOp;
15524 
15525   return SDValue();
15526 }
15527 
15528 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
15529                                                  SDValue V, SelectionDAG &DAG) {
15530   SDLoc DL(V);
15531   EVT VT = V.getValueType();
15532 
15533   switch (V.getOpcode()) {
15534   default:
15535     return V;
15536 
15537   case ISD::CONCAT_VECTORS: {
15538     EVT OpVT = V->getOperand(0).getValueType();
15539     int OpSize = OpVT.getVectorNumElements();
15540     SmallBitVector OpUsedElements(OpSize, false);
15541     bool FoundSimplification = false;
15542     SmallVector<SDValue, 4> NewOps;
15543     NewOps.reserve(V->getNumOperands());
15544     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
15545       SDValue Op = V->getOperand(i);
15546       bool OpUsed = false;
15547       for (int j = 0; j < OpSize; ++j)
15548         if (UsedElements[i * OpSize + j]) {
15549           OpUsedElements[j] = true;
15550           OpUsed = true;
15551         }
15552       NewOps.push_back(
15553           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
15554                  : DAG.getUNDEF(OpVT));
15555       FoundSimplification |= Op == NewOps.back();
15556       OpUsedElements.reset();
15557     }
15558     if (FoundSimplification)
15559       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
15560     return V;
15561   }
15562 
15563   case ISD::INSERT_SUBVECTOR: {
15564     SDValue BaseV = V->getOperand(0);
15565     SDValue SubV = V->getOperand(1);
15566     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
15567     if (!IdxN)
15568       return V;
15569 
15570     int SubSize = SubV.getValueType().getVectorNumElements();
15571     int Idx = IdxN->getZExtValue();
15572     bool SubVectorUsed = false;
15573     SmallBitVector SubUsedElements(SubSize, false);
15574     for (int i = 0; i < SubSize; ++i)
15575       if (UsedElements[i + Idx]) {
15576         SubVectorUsed = true;
15577         SubUsedElements[i] = true;
15578         UsedElements[i + Idx] = false;
15579       }
15580 
15581     // Now recurse on both the base and sub vectors.
15582     SDValue SimplifiedSubV =
15583         SubVectorUsed
15584             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
15585             : DAG.getUNDEF(SubV.getValueType());
15586     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
15587     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
15588       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15589                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
15590     return V;
15591   }
15592   }
15593 }
15594 
15595 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
15596                                        SDValue N1, SelectionDAG &DAG) {
15597   EVT VT = SVN->getValueType(0);
15598   int NumElts = VT.getVectorNumElements();
15599   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
15600   for (int M : SVN->getMask())
15601     if (M >= 0 && M < NumElts)
15602       N0UsedElements[M] = true;
15603     else if (M >= NumElts)
15604       N1UsedElements[M - NumElts] = true;
15605 
15606   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
15607   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
15608   if (S0 == N0 && S1 == N1)
15609     return SDValue();
15610 
15611   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
15612 }
15613 
15614 static SDValue simplifyShuffleMask(ShuffleVectorSDNode *SVN, SDValue N0,
15615                                    SDValue N1, SelectionDAG &DAG) {
15616   auto isUndefElt = [](SDValue V, int Idx) {
15617     // TODO - handle more cases as required.
15618     if (V.getOpcode() == ISD::BUILD_VECTOR)
15619       return V.getOperand(Idx).isUndef();
15620     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
15621       return (Idx != 0) || V.getOperand(0).isUndef();
15622     return false;
15623   };
15624 
15625   EVT VT = SVN->getValueType(0);
15626   unsigned NumElts = VT.getVectorNumElements();
15627 
15628   bool Changed = false;
15629   SmallVector<int, 8> NewMask;
15630   for (unsigned i = 0; i != NumElts; ++i) {
15631     int Idx = SVN->getMaskElt(i);
15632     if ((0 <= Idx && Idx < (int)NumElts && isUndefElt(N0, Idx)) ||
15633         ((int)NumElts < Idx && isUndefElt(N1, Idx - NumElts))) {
15634       Changed = true;
15635       Idx = -1;
15636     }
15637     NewMask.push_back(Idx);
15638   }
15639   if (Changed)
15640     return DAG.getVectorShuffle(VT, SDLoc(SVN), N0, N1, NewMask);
15641 
15642   return SDValue();
15643 }
15644 
15645 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15646 // or turn a shuffle of a single concat into simpler shuffle then concat.
15647 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15648   EVT VT = N->getValueType(0);
15649   unsigned NumElts = VT.getVectorNumElements();
15650 
15651   SDValue N0 = N->getOperand(0);
15652   SDValue N1 = N->getOperand(1);
15653   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15654 
15655   SmallVector<SDValue, 4> Ops;
15656   EVT ConcatVT = N0.getOperand(0).getValueType();
15657   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15658   unsigned NumConcats = NumElts / NumElemsPerConcat;
15659 
15660   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15661   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15662   // half vector elements.
15663   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15664       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15665                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15666     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15667                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15668     N1 = DAG.getUNDEF(ConcatVT);
15669     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15670   }
15671 
15672   // Look at every vector that's inserted. We're looking for exact
15673   // subvector-sized copies from a concatenated vector
15674   for (unsigned I = 0; I != NumConcats; ++I) {
15675     // Make sure we're dealing with a copy.
15676     unsigned Begin = I * NumElemsPerConcat;
15677     bool AllUndef = true, NoUndef = true;
15678     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15679       if (SVN->getMaskElt(J) >= 0)
15680         AllUndef = false;
15681       else
15682         NoUndef = false;
15683     }
15684 
15685     if (NoUndef) {
15686       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15687         return SDValue();
15688 
15689       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15690         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15691           return SDValue();
15692 
15693       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15694       if (FirstElt < N0.getNumOperands())
15695         Ops.push_back(N0.getOperand(FirstElt));
15696       else
15697         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15698 
15699     } else if (AllUndef) {
15700       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15701     } else { // Mixed with general masks and undefs, can't do optimization.
15702       return SDValue();
15703     }
15704   }
15705 
15706   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15707 }
15708 
15709 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15710 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15711 //
15712 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15713 // a simplification in some sense, but it isn't appropriate in general: some
15714 // BUILD_VECTORs are substantially cheaper than others. The general case
15715 // of a BUILD_VECTOR requires inserting each element individually (or
15716 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15717 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15718 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15719 // are undef lowers to a small number of element insertions.
15720 //
15721 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15722 // We don't fold shuffles where one side is a non-zero constant, and we don't
15723 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15724 // non-constant operands. This seems to work out reasonably well in practice.
15725 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15726                                        SelectionDAG &DAG,
15727                                        const TargetLowering &TLI) {
15728   EVT VT = SVN->getValueType(0);
15729   unsigned NumElts = VT.getVectorNumElements();
15730   SDValue N0 = SVN->getOperand(0);
15731   SDValue N1 = SVN->getOperand(1);
15732 
15733   if (!N0->hasOneUse() || !N1->hasOneUse())
15734     return SDValue();
15735 
15736   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15737   // discussed above.
15738   if (!N1.isUndef()) {
15739     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15740     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15741     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15742       return SDValue();
15743     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15744       return SDValue();
15745   }
15746 
15747   // If both inputs are splats of the same value then we can safely merge this
15748   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
15749   bool IsSplat = false;
15750   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
15751   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
15752   if (BV0 && BV1)
15753     if (SDValue Splat0 = BV0->getSplatValue())
15754       IsSplat = (Splat0 == BV1->getSplatValue());
15755 
15756   SmallVector<SDValue, 8> Ops;
15757   SmallSet<SDValue, 16> DuplicateOps;
15758   for (int M : SVN->getMask()) {
15759     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15760     if (M >= 0) {
15761       int Idx = M < (int)NumElts ? M : M - NumElts;
15762       SDValue &S = (M < (int)NumElts ? N0 : N1);
15763       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15764         Op = S.getOperand(Idx);
15765       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15766         assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
15767         Op = S.getOperand(0);
15768       } else {
15769         // Operand can't be combined - bail out.
15770         return SDValue();
15771       }
15772     }
15773 
15774     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
15775     // generating a splat; semantically, this is fine, but it's likely to
15776     // generate low-quality code if the target can't reconstruct an appropriate
15777     // shuffle.
15778     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15779       if (!IsSplat && !DuplicateOps.insert(Op).second)
15780         return SDValue();
15781 
15782     Ops.push_back(Op);
15783   }
15784 
15785   // BUILD_VECTOR requires all inputs to be of the same type, find the
15786   // maximum type and extend them all.
15787   EVT SVT = VT.getScalarType();
15788   if (SVT.isInteger())
15789     for (SDValue &Op : Ops)
15790       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15791   if (SVT != VT.getScalarType())
15792     for (SDValue &Op : Ops)
15793       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15794                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15795                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15796   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15797 }
15798 
15799 // Match shuffles that can be converted to any_vector_extend_in_reg.
15800 // This is often generated during legalization.
15801 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15802 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15803 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15804                                             SelectionDAG &DAG,
15805                                             const TargetLowering &TLI,
15806                                             bool LegalOperations,
15807                                             bool LegalTypes) {
15808   EVT VT = SVN->getValueType(0);
15809   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15810 
15811   // TODO Add support for big-endian when we have a test case.
15812   if (!VT.isInteger() || IsBigEndian)
15813     return SDValue();
15814 
15815   unsigned NumElts = VT.getVectorNumElements();
15816   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15817   ArrayRef<int> Mask = SVN->getMask();
15818   SDValue N0 = SVN->getOperand(0);
15819 
15820   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15821   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15822     for (unsigned i = 0; i != NumElts; ++i) {
15823       if (Mask[i] < 0)
15824         continue;
15825       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15826         continue;
15827       return false;
15828     }
15829     return true;
15830   };
15831 
15832   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15833   // power-of-2 extensions as they are the most likely.
15834   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15835     // Check for non power of 2 vector sizes
15836     if (NumElts % Scale != 0)
15837       continue;
15838     if (!isAnyExtend(Scale))
15839       continue;
15840 
15841     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15842     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15843     if (!LegalTypes || TLI.isTypeLegal(OutVT))
15844       if (!LegalOperations ||
15845           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15846         return DAG.getBitcast(VT,
15847                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15848   }
15849 
15850   return SDValue();
15851 }
15852 
15853 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15854 // each source element of a large type into the lowest elements of a smaller
15855 // destination type. This is often generated during legalization.
15856 // If the source node itself was a '*_extend_vector_inreg' node then we should
15857 // then be able to remove it.
15858 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15859                                         SelectionDAG &DAG) {
15860   EVT VT = SVN->getValueType(0);
15861   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15862 
15863   // TODO Add support for big-endian when we have a test case.
15864   if (!VT.isInteger() || IsBigEndian)
15865     return SDValue();
15866 
15867   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15868 
15869   unsigned Opcode = N0.getOpcode();
15870   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15871       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15872       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15873     return SDValue();
15874 
15875   SDValue N00 = N0.getOperand(0);
15876   ArrayRef<int> Mask = SVN->getMask();
15877   unsigned NumElts = VT.getVectorNumElements();
15878   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15879   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15880   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15881 
15882   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15883     return SDValue();
15884   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15885 
15886   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15887   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15888   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15889   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15890     for (unsigned i = 0; i != NumElts; ++i) {
15891       if (Mask[i] < 0)
15892         continue;
15893       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15894         continue;
15895       return false;
15896     }
15897     return true;
15898   };
15899 
15900   // At the moment we just handle the case where we've truncated back to the
15901   // same size as before the extension.
15902   // TODO: handle more extension/truncation cases as cases arise.
15903   if (EltSizeInBits != ExtSrcSizeInBits)
15904     return SDValue();
15905 
15906   // We can remove *extend_vector_inreg only if the truncation happens at
15907   // the same scale as the extension.
15908   if (isTruncate(ExtScale))
15909     return DAG.getBitcast(VT, N00);
15910 
15911   return SDValue();
15912 }
15913 
15914 // Combine shuffles of splat-shuffles of the form:
15915 // shuffle (shuffle V, undef, splat-mask), undef, M
15916 // If splat-mask contains undef elements, we need to be careful about
15917 // introducing undef's in the folded mask which are not the result of composing
15918 // the masks of the shuffles.
15919 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15920                                      ShuffleVectorSDNode *Splat,
15921                                      SelectionDAG &DAG) {
15922   ArrayRef<int> SplatMask = Splat->getMask();
15923   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15924 
15925   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15926   // every undef mask element in the splat-shuffle has a corresponding undef
15927   // element in the user-shuffle's mask or if the composition of mask elements
15928   // would result in undef.
15929   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15930   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15931   //   In this case it is not legal to simplify to the splat-shuffle because we
15932   //   may be exposing the users of the shuffle an undef element at index 1
15933   //   which was not there before the combine.
15934   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15935   //   In this case the composition of masks yields SplatMask, so it's ok to
15936   //   simplify to the splat-shuffle.
15937   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15938   //   In this case the composed mask includes all undef elements of SplatMask
15939   //   and in addition sets element zero to undef. It is safe to simplify to
15940   //   the splat-shuffle.
15941   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15942                                        ArrayRef<int> SplatMask) {
15943     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15944       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15945           SplatMask[UserMask[i]] != -1)
15946         return false;
15947     return true;
15948   };
15949   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15950     return SDValue(Splat, 0);
15951 
15952   // Create a new shuffle with a mask that is composed of the two shuffles'
15953   // masks.
15954   SmallVector<int, 32> NewMask;
15955   for (int Idx : UserMask)
15956     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15957 
15958   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15959                               Splat->getOperand(0), Splat->getOperand(1),
15960                               NewMask);
15961 }
15962 
15963 /// If the shuffle mask is taking exactly one element from the first vector
15964 /// operand and passing through all other elements from the second vector
15965 /// operand, return the index of the mask element that is choosing an element
15966 /// from the first operand. Otherwise, return -1.
15967 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
15968   int MaskSize = Mask.size();
15969   int EltFromOp0 = -1;
15970   // TODO: This does not match if there are undef elements in the shuffle mask.
15971   // Should we ignore undefs in the shuffle mask instead? The trade-off is
15972   // removing an instruction (a shuffle), but losing the knowledge that some
15973   // vector lanes are not needed.
15974   for (int i = 0; i != MaskSize; ++i) {
15975     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
15976       // We're looking for a shuffle of exactly one element from operand 0.
15977       if (EltFromOp0 != -1)
15978         return -1;
15979       EltFromOp0 = i;
15980     } else if (Mask[i] != i + MaskSize) {
15981       // Nothing from operand 1 can change lanes.
15982       return -1;
15983     }
15984   }
15985   return EltFromOp0;
15986 }
15987 
15988 /// If a shuffle inserts exactly one element from a source vector operand into
15989 /// another vector operand and we can access the specified element as a scalar,
15990 /// then we can eliminate the shuffle.
15991 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
15992                                       SelectionDAG &DAG) {
15993   // First, check if we are taking one element of a vector and shuffling that
15994   // element into another vector.
15995   ArrayRef<int> Mask = Shuf->getMask();
15996   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
15997   SDValue Op0 = Shuf->getOperand(0);
15998   SDValue Op1 = Shuf->getOperand(1);
15999   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
16000   if (ShufOp0Index == -1) {
16001     // Commute mask and check again.
16002     ShuffleVectorSDNode::commuteMask(CommutedMask);
16003     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
16004     if (ShufOp0Index == -1)
16005       return SDValue();
16006     // Commute operands to match the commuted shuffle mask.
16007     std::swap(Op0, Op1);
16008     Mask = CommutedMask;
16009   }
16010 
16011   // The shuffle inserts exactly one element from operand 0 into operand 1.
16012   // Now see if we can access that element as a scalar via a real insert element
16013   // instruction.
16014   // TODO: We can try harder to locate the element as a scalar. Examples: it
16015   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
16016   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
16017          "Shuffle mask value must be from operand 0");
16018   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
16019     return SDValue();
16020 
16021   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
16022   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
16023     return SDValue();
16024 
16025   // There's an existing insertelement with constant insertion index, so we
16026   // don't need to check the legality/profitability of a replacement operation
16027   // that differs at most in the constant value. The target should be able to
16028   // lower any of those in a similar way. If not, legalization will expand this
16029   // to a scalar-to-vector plus shuffle.
16030   //
16031   // Note that the shuffle may move the scalar from the position that the insert
16032   // element used. Therefore, our new insert element occurs at the shuffle's
16033   // mask index value, not the insert's index value.
16034   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
16035   SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
16036                                         Op0.getOperand(2).getValueType());
16037   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
16038                      Op1, Op0.getOperand(1), NewInsIndex);
16039 }
16040 
16041 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
16042   EVT VT = N->getValueType(0);
16043   unsigned NumElts = VT.getVectorNumElements();
16044 
16045   SDValue N0 = N->getOperand(0);
16046   SDValue N1 = N->getOperand(1);
16047 
16048   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
16049 
16050   // Canonicalize shuffle undef, undef -> undef
16051   if (N0.isUndef() && N1.isUndef())
16052     return DAG.getUNDEF(VT);
16053 
16054   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16055 
16056   // Canonicalize shuffle v, v -> v, undef
16057   if (N0 == N1) {
16058     SmallVector<int, 8> NewMask;
16059     for (unsigned i = 0; i != NumElts; ++i) {
16060       int Idx = SVN->getMaskElt(i);
16061       if (Idx >= (int)NumElts) Idx -= NumElts;
16062       NewMask.push_back(Idx);
16063     }
16064     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
16065   }
16066 
16067   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
16068   if (N0.isUndef())
16069     return DAG.getCommutedVectorShuffle(*SVN);
16070 
16071   // Remove references to rhs if it is undef
16072   if (N1.isUndef()) {
16073     bool Changed = false;
16074     SmallVector<int, 8> NewMask;
16075     for (unsigned i = 0; i != NumElts; ++i) {
16076       int Idx = SVN->getMaskElt(i);
16077       if (Idx >= (int)NumElts) {
16078         Idx = -1;
16079         Changed = true;
16080       }
16081       NewMask.push_back(Idx);
16082     }
16083     if (Changed)
16084       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16085   }
16086 
16087   // Simplify shuffle mask if a referenced element is UNDEF.
16088   if (SDValue V = simplifyShuffleMask(SVN, N0, N1, DAG))
16089     return V;
16090 
16091   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16092     return InsElt;
16093 
16094   // A shuffle of a single vector that is a splat can always be folded.
16095   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16096     if (N1->isUndef() && N0Shuf->isSplat())
16097       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16098 
16099   // If it is a splat, check if the argument vector is another splat or a
16100   // build_vector.
16101   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16102     SDNode *V = N0.getNode();
16103 
16104     // If this is a bit convert that changes the element type of the vector but
16105     // not the number of vector elements, look through it.  Be careful not to
16106     // look though conversions that change things like v4f32 to v2f64.
16107     if (V->getOpcode() == ISD::BITCAST) {
16108       SDValue ConvInput = V->getOperand(0);
16109       if (ConvInput.getValueType().isVector() &&
16110           ConvInput.getValueType().getVectorNumElements() == NumElts)
16111         V = ConvInput.getNode();
16112     }
16113 
16114     if (V->getOpcode() == ISD::BUILD_VECTOR) {
16115       assert(V->getNumOperands() == NumElts &&
16116              "BUILD_VECTOR has wrong number of operands");
16117       SDValue Base;
16118       bool AllSame = true;
16119       for (unsigned i = 0; i != NumElts; ++i) {
16120         if (!V->getOperand(i).isUndef()) {
16121           Base = V->getOperand(i);
16122           break;
16123         }
16124       }
16125       // Splat of <u, u, u, u>, return <u, u, u, u>
16126       if (!Base.getNode())
16127         return N0;
16128       for (unsigned i = 0; i != NumElts; ++i) {
16129         if (V->getOperand(i) != Base) {
16130           AllSame = false;
16131           break;
16132         }
16133       }
16134       // Splat of <x, x, x, x>, return <x, x, x, x>
16135       if (AllSame)
16136         return N0;
16137 
16138       // Canonicalize any other splat as a build_vector.
16139       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16140       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16141       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16142 
16143       // We may have jumped through bitcasts, so the type of the
16144       // BUILD_VECTOR may not match the type of the shuffle.
16145       if (V->getValueType(0) != VT)
16146         NewBV = DAG.getBitcast(VT, NewBV);
16147       return NewBV;
16148     }
16149   }
16150 
16151   // There are various patterns used to build up a vector from smaller vectors,
16152   // subvectors, or elements. Scan chains of these and replace unused insertions
16153   // or components with undef.
16154   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
16155     return S;
16156 
16157   // Match shuffles that can be converted to any_vector_extend_in_reg.
16158   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16159     return V;
16160 
16161   // Combine "truncate_vector_in_reg" style shuffles.
16162   if (SDValue V = combineTruncationShuffle(SVN, DAG))
16163     return V;
16164 
16165   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16166       Level < AfterLegalizeVectorOps &&
16167       (N1.isUndef() ||
16168       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16169        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16170     if (SDValue V = partitionShuffleOfConcats(N, DAG))
16171       return V;
16172   }
16173 
16174   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16175   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16176   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16177     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16178       return Res;
16179 
16180   // If this shuffle only has a single input that is a bitcasted shuffle,
16181   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16182   // back to their original types.
16183   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16184       N1.isUndef() && Level < AfterLegalizeVectorOps &&
16185       TLI.isTypeLegal(VT)) {
16186 
16187     // Peek through the bitcast only if there is one user.
16188     SDValue BC0 = N0;
16189     while (BC0.getOpcode() == ISD::BITCAST) {
16190       if (!BC0.hasOneUse())
16191         break;
16192       BC0 = BC0.getOperand(0);
16193     }
16194 
16195     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16196       if (Scale == 1)
16197         return SmallVector<int, 8>(Mask.begin(), Mask.end());
16198 
16199       SmallVector<int, 8> NewMask;
16200       for (int M : Mask)
16201         for (int s = 0; s != Scale; ++s)
16202           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16203       return NewMask;
16204     };
16205 
16206     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16207       EVT SVT = VT.getScalarType();
16208       EVT InnerVT = BC0->getValueType(0);
16209       EVT InnerSVT = InnerVT.getScalarType();
16210 
16211       // Determine which shuffle works with the smaller scalar type.
16212       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16213       EVT ScaleSVT = ScaleVT.getScalarType();
16214 
16215       if (TLI.isTypeLegal(ScaleVT) &&
16216           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16217           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16218         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16219         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16220 
16221         // Scale the shuffle masks to the smaller scalar type.
16222         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16223         SmallVector<int, 8> InnerMask =
16224             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16225         SmallVector<int, 8> OuterMask =
16226             ScaleShuffleMask(SVN->getMask(), OuterScale);
16227 
16228         // Merge the shuffle masks.
16229         SmallVector<int, 8> NewMask;
16230         for (int M : OuterMask)
16231           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16232 
16233         // Test for shuffle mask legality over both commutations.
16234         SDValue SV0 = BC0->getOperand(0);
16235         SDValue SV1 = BC0->getOperand(1);
16236         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16237         if (!LegalMask) {
16238           std::swap(SV0, SV1);
16239           ShuffleVectorSDNode::commuteMask(NewMask);
16240           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16241         }
16242 
16243         if (LegalMask) {
16244           SV0 = DAG.getBitcast(ScaleVT, SV0);
16245           SV1 = DAG.getBitcast(ScaleVT, SV1);
16246           return DAG.getBitcast(
16247               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16248         }
16249       }
16250     }
16251   }
16252 
16253   // Canonicalize shuffles according to rules:
16254   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16255   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16256   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16257   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16258       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16259       TLI.isTypeLegal(VT)) {
16260     // The incoming shuffle must be of the same type as the result of the
16261     // current shuffle.
16262     assert(N1->getOperand(0).getValueType() == VT &&
16263            "Shuffle types don't match");
16264 
16265     SDValue SV0 = N1->getOperand(0);
16266     SDValue SV1 = N1->getOperand(1);
16267     bool HasSameOp0 = N0 == SV0;
16268     bool IsSV1Undef = SV1.isUndef();
16269     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16270       // Commute the operands of this shuffle so that next rule
16271       // will trigger.
16272       return DAG.getCommutedVectorShuffle(*SVN);
16273   }
16274 
16275   // Try to fold according to rules:
16276   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16277   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16278   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16279   // Don't try to fold shuffles with illegal type.
16280   // Only fold if this shuffle is the only user of the other shuffle.
16281   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16282       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16283     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16284 
16285     // Don't try to fold splats; they're likely to simplify somehow, or they
16286     // might be free.
16287     if (OtherSV->isSplat())
16288       return SDValue();
16289 
16290     // The incoming shuffle must be of the same type as the result of the
16291     // current shuffle.
16292     assert(OtherSV->getOperand(0).getValueType() == VT &&
16293            "Shuffle types don't match");
16294 
16295     SDValue SV0, SV1;
16296     SmallVector<int, 4> Mask;
16297     // Compute the combined shuffle mask for a shuffle with SV0 as the first
16298     // operand, and SV1 as the second operand.
16299     for (unsigned i = 0; i != NumElts; ++i) {
16300       int Idx = SVN->getMaskElt(i);
16301       if (Idx < 0) {
16302         // Propagate Undef.
16303         Mask.push_back(Idx);
16304         continue;
16305       }
16306 
16307       SDValue CurrentVec;
16308       if (Idx < (int)NumElts) {
16309         // This shuffle index refers to the inner shuffle N0. Lookup the inner
16310         // shuffle mask to identify which vector is actually referenced.
16311         Idx = OtherSV->getMaskElt(Idx);
16312         if (Idx < 0) {
16313           // Propagate Undef.
16314           Mask.push_back(Idx);
16315           continue;
16316         }
16317 
16318         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16319                                            : OtherSV->getOperand(1);
16320       } else {
16321         // This shuffle index references an element within N1.
16322         CurrentVec = N1;
16323       }
16324 
16325       // Simple case where 'CurrentVec' is UNDEF.
16326       if (CurrentVec.isUndef()) {
16327         Mask.push_back(-1);
16328         continue;
16329       }
16330 
16331       // Canonicalize the shuffle index. We don't know yet if CurrentVec
16332       // will be the first or second operand of the combined shuffle.
16333       Idx = Idx % NumElts;
16334       if (!SV0.getNode() || SV0 == CurrentVec) {
16335         // Ok. CurrentVec is the left hand side.
16336         // Update the mask accordingly.
16337         SV0 = CurrentVec;
16338         Mask.push_back(Idx);
16339         continue;
16340       }
16341 
16342       // Bail out if we cannot convert the shuffle pair into a single shuffle.
16343       if (SV1.getNode() && SV1 != CurrentVec)
16344         return SDValue();
16345 
16346       // Ok. CurrentVec is the right hand side.
16347       // Update the mask accordingly.
16348       SV1 = CurrentVec;
16349       Mask.push_back(Idx + NumElts);
16350     }
16351 
16352     // Check if all indices in Mask are Undef. In case, propagate Undef.
16353     bool isUndefMask = true;
16354     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16355       isUndefMask &= Mask[i] < 0;
16356 
16357     if (isUndefMask)
16358       return DAG.getUNDEF(VT);
16359 
16360     if (!SV0.getNode())
16361       SV0 = DAG.getUNDEF(VT);
16362     if (!SV1.getNode())
16363       SV1 = DAG.getUNDEF(VT);
16364 
16365     // Avoid introducing shuffles with illegal mask.
16366     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16367       ShuffleVectorSDNode::commuteMask(Mask);
16368 
16369       if (!TLI.isShuffleMaskLegal(Mask, VT))
16370         return SDValue();
16371 
16372       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16373       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16374       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16375       std::swap(SV0, SV1);
16376     }
16377 
16378     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16379     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16380     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16381     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16382   }
16383 
16384   return SDValue();
16385 }
16386 
16387 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16388   SDValue InVal = N->getOperand(0);
16389   EVT VT = N->getValueType(0);
16390 
16391   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16392   // with a VECTOR_SHUFFLE and possible truncate.
16393   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16394     SDValue InVec = InVal->getOperand(0);
16395     SDValue EltNo = InVal->getOperand(1);
16396     auto InVecT = InVec.getValueType();
16397     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16398       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16399       int Elt = C0->getZExtValue();
16400       NewMask[0] = Elt;
16401       SDValue Val;
16402       // If we have an implict truncate do truncate here as long as it's legal.
16403       // if it's not legal, this should
16404       if (VT.getScalarType() != InVal.getValueType() &&
16405           InVal.getValueType().isScalarInteger() &&
16406           isTypeLegal(VT.getScalarType())) {
16407         Val =
16408             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16409         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16410       }
16411       if (VT.getScalarType() == InVecT.getScalarType() &&
16412           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16413           TLI.isShuffleMaskLegal(NewMask, VT)) {
16414         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16415                                    DAG.getUNDEF(InVecT), NewMask);
16416         // If the initial vector is the correct size this shuffle is a
16417         // valid result.
16418         if (VT == InVecT)
16419           return Val;
16420         // If not we must truncate the vector.
16421         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16422           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16423           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16424           EVT SubVT =
16425               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16426                                VT.getVectorNumElements());
16427           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16428                             ZeroIdx);
16429           return Val;
16430         }
16431       }
16432     }
16433   }
16434 
16435   return SDValue();
16436 }
16437 
16438 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16439   EVT VT = N->getValueType(0);
16440   SDValue N0 = N->getOperand(0);
16441   SDValue N1 = N->getOperand(1);
16442   SDValue N2 = N->getOperand(2);
16443 
16444   // If inserting an UNDEF, just return the original vector.
16445   if (N1.isUndef())
16446     return N0;
16447 
16448   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16449   // us to pull BITCASTs from input to output.
16450   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16451     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16452       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16453 
16454   // If this is an insert of an extracted vector into an undef vector, we can
16455   // just use the input to the extract.
16456   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16457       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16458     return N1.getOperand(0);
16459 
16460   // If we are inserting a bitcast value into an undef, with the same
16461   // number of elements, just use the bitcast input of the extract.
16462   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16463   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16464   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16465       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16466       N1.getOperand(0).getOperand(1) == N2 &&
16467       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16468           VT.getVectorNumElements() &&
16469       N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
16470           VT.getSizeInBits()) {
16471     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16472   }
16473 
16474   // If both N1 and N2 are bitcast values on which insert_subvector
16475   // would makes sense, pull the bitcast through.
16476   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16477   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16478   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16479     SDValue CN0 = N0.getOperand(0);
16480     SDValue CN1 = N1.getOperand(0);
16481     if (CN0.getValueType().getVectorElementType() ==
16482             CN1.getValueType().getVectorElementType() &&
16483         CN0.getValueType().getVectorNumElements() ==
16484             VT.getVectorNumElements()) {
16485       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16486                                       CN0.getValueType(), CN0, CN1, N2);
16487       return DAG.getBitcast(VT, NewINSERT);
16488     }
16489   }
16490 
16491   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16492   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16493   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16494   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16495       N0.getOperand(1).getValueType() == N1.getValueType() &&
16496       N0.getOperand(2) == N2)
16497     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16498                        N1, N2);
16499 
16500   if (!isa<ConstantSDNode>(N2))
16501     return SDValue();
16502 
16503   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16504 
16505   // Canonicalize insert_subvector dag nodes.
16506   // Example:
16507   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16508   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16509   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16510       N1.getValueType() == N0.getOperand(1).getValueType() &&
16511       isa<ConstantSDNode>(N0.getOperand(2))) {
16512     unsigned OtherIdx = N0.getConstantOperandVal(2);
16513     if (InsIdx < OtherIdx) {
16514       // Swap nodes.
16515       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16516                                   N0.getOperand(0), N1, N2);
16517       AddToWorklist(NewOp.getNode());
16518       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16519                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16520     }
16521   }
16522 
16523   // If the input vector is a concatenation, and the insert replaces
16524   // one of the pieces, we can optimize into a single concat_vectors.
16525   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16526       N0.getOperand(0).getValueType() == N1.getValueType()) {
16527     unsigned Factor = N1.getValueType().getVectorNumElements();
16528 
16529     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16530     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16531 
16532     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16533   }
16534 
16535   return SDValue();
16536 }
16537 
16538 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16539   SDValue N0 = N->getOperand(0);
16540 
16541   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16542   if (N0->getOpcode() == ISD::FP16_TO_FP)
16543     return N0->getOperand(0);
16544 
16545   return SDValue();
16546 }
16547 
16548 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16549   SDValue N0 = N->getOperand(0);
16550 
16551   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16552   if (N0->getOpcode() == ISD::AND) {
16553     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16554     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16555       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16556                          N0.getOperand(0));
16557     }
16558   }
16559 
16560   return SDValue();
16561 }
16562 
16563 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16564 /// with the destination vector and a zero vector.
16565 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16566 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16567 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16568   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
16569 
16570   EVT VT = N->getValueType(0);
16571   SDValue LHS = N->getOperand(0);
16572   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16573   SDLoc DL(N);
16574 
16575   // Make sure we're not running after operation legalization where it
16576   // may have custom lowered the vector shuffles.
16577   if (LegalOperations)
16578     return SDValue();
16579 
16580   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16581     return SDValue();
16582 
16583   EVT RVT = RHS.getValueType();
16584   unsigned NumElts = RHS.getNumOperands();
16585 
16586   // Attempt to create a valid clear mask, splitting the mask into
16587   // sub elements and checking to see if each is
16588   // all zeros or all ones - suitable for shuffle masking.
16589   auto BuildClearMask = [&](int Split) {
16590     int NumSubElts = NumElts * Split;
16591     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16592 
16593     SmallVector<int, 8> Indices;
16594     for (int i = 0; i != NumSubElts; ++i) {
16595       int EltIdx = i / Split;
16596       int SubIdx = i % Split;
16597       SDValue Elt = RHS.getOperand(EltIdx);
16598       if (Elt.isUndef()) {
16599         Indices.push_back(-1);
16600         continue;
16601       }
16602 
16603       APInt Bits;
16604       if (isa<ConstantSDNode>(Elt))
16605         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16606       else if (isa<ConstantFPSDNode>(Elt))
16607         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16608       else
16609         return SDValue();
16610 
16611       // Extract the sub element from the constant bit mask.
16612       if (DAG.getDataLayout().isBigEndian()) {
16613         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16614       } else {
16615         Bits.lshrInPlace(SubIdx * NumSubBits);
16616       }
16617 
16618       if (Split > 1)
16619         Bits = Bits.trunc(NumSubBits);
16620 
16621       if (Bits.isAllOnesValue())
16622         Indices.push_back(i);
16623       else if (Bits == 0)
16624         Indices.push_back(i + NumSubElts);
16625       else
16626         return SDValue();
16627     }
16628 
16629     // Let's see if the target supports this vector_shuffle.
16630     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16631     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16632     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16633       return SDValue();
16634 
16635     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16636     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16637                                                    DAG.getBitcast(ClearVT, LHS),
16638                                                    Zero, Indices));
16639   };
16640 
16641   // Determine maximum split level (byte level masking).
16642   int MaxSplit = 1;
16643   if (RVT.getScalarSizeInBits() % 8 == 0)
16644     MaxSplit = RVT.getScalarSizeInBits() / 8;
16645 
16646   for (int Split = 1; Split <= MaxSplit; ++Split)
16647     if (RVT.getScalarSizeInBits() % Split == 0)
16648       if (SDValue S = BuildClearMask(Split))
16649         return S;
16650 
16651   return SDValue();
16652 }
16653 
16654 /// Visit a binary vector operation, like ADD.
16655 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16656   assert(N->getValueType(0).isVector() &&
16657          "SimplifyVBinOp only works on vectors!");
16658 
16659   SDValue LHS = N->getOperand(0);
16660   SDValue RHS = N->getOperand(1);
16661   SDValue Ops[] = {LHS, RHS};
16662 
16663   // See if we can constant fold the vector operation.
16664   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16665           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16666     return Fold;
16667 
16668   // Type legalization might introduce new shuffles in the DAG.
16669   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16670   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16671   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16672       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16673       LHS.getOperand(1).isUndef() &&
16674       RHS.getOperand(1).isUndef()) {
16675     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16676     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16677 
16678     if (SVN0->getMask().equals(SVN1->getMask())) {
16679       EVT VT = N->getValueType(0);
16680       SDValue UndefVector = LHS.getOperand(1);
16681       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16682                                      LHS.getOperand(0), RHS.getOperand(0),
16683                                      N->getFlags());
16684       AddUsersToWorklist(N);
16685       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16686                                   SVN0->getMask());
16687     }
16688   }
16689 
16690   return SDValue();
16691 }
16692 
16693 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16694                                     SDValue N2) {
16695   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16696 
16697   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16698                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16699 
16700   // If we got a simplified select_cc node back from SimplifySelectCC, then
16701   // break it down into a new SETCC node, and a new SELECT node, and then return
16702   // the SELECT node, since we were called with a SELECT node.
16703   if (SCC.getNode()) {
16704     // Check to see if we got a select_cc back (to turn into setcc/select).
16705     // Otherwise, just return whatever node we got back, like fabs.
16706     if (SCC.getOpcode() == ISD::SELECT_CC) {
16707       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16708                                   N0.getValueType(),
16709                                   SCC.getOperand(0), SCC.getOperand(1),
16710                                   SCC.getOperand(4));
16711       AddToWorklist(SETCC.getNode());
16712       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16713                            SCC.getOperand(2), SCC.getOperand(3));
16714     }
16715 
16716     return SCC;
16717   }
16718   return SDValue();
16719 }
16720 
16721 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16722 /// being selected between, see if we can simplify the select.  Callers of this
16723 /// should assume that TheSelect is deleted if this returns true.  As such, they
16724 /// should return the appropriate thing (e.g. the node) back to the top-level of
16725 /// the DAG combiner loop to avoid it being looked at.
16726 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16727                                     SDValue RHS) {
16728   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16729   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16730   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16731     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16732       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16733       SDValue Sqrt = RHS;
16734       ISD::CondCode CC;
16735       SDValue CmpLHS;
16736       const ConstantFPSDNode *Zero = nullptr;
16737 
16738       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16739         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16740         CmpLHS = TheSelect->getOperand(0);
16741         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16742       } else {
16743         // SELECT or VSELECT
16744         SDValue Cmp = TheSelect->getOperand(0);
16745         if (Cmp.getOpcode() == ISD::SETCC) {
16746           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16747           CmpLHS = Cmp.getOperand(0);
16748           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16749         }
16750       }
16751       if (Zero && Zero->isZero() &&
16752           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16753           CC == ISD::SETULT || CC == ISD::SETLT)) {
16754         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16755         CombineTo(TheSelect, Sqrt);
16756         return true;
16757       }
16758     }
16759   }
16760   // Cannot simplify select with vector condition
16761   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16762 
16763   // If this is a select from two identical things, try to pull the operation
16764   // through the select.
16765   if (LHS.getOpcode() != RHS.getOpcode() ||
16766       !LHS.hasOneUse() || !RHS.hasOneUse())
16767     return false;
16768 
16769   // If this is a load and the token chain is identical, replace the select
16770   // of two loads with a load through a select of the address to load from.
16771   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16772   // constants have been dropped into the constant pool.
16773   if (LHS.getOpcode() == ISD::LOAD) {
16774     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16775     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16776 
16777     // Token chains must be identical.
16778     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16779         // Do not let this transformation reduce the number of volatile loads.
16780         LLD->isVolatile() || RLD->isVolatile() ||
16781         // FIXME: If either is a pre/post inc/dec load,
16782         // we'd need to split out the address adjustment.
16783         LLD->isIndexed() || RLD->isIndexed() ||
16784         // If this is an EXTLOAD, the VT's must match.
16785         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16786         // If this is an EXTLOAD, the kind of extension must match.
16787         (LLD->getExtensionType() != RLD->getExtensionType() &&
16788          // The only exception is if one of the extensions is anyext.
16789          LLD->getExtensionType() != ISD::EXTLOAD &&
16790          RLD->getExtensionType() != ISD::EXTLOAD) ||
16791         // FIXME: this discards src value information.  This is
16792         // over-conservative. It would be beneficial to be able to remember
16793         // both potential memory locations.  Since we are discarding
16794         // src value info, don't do the transformation if the memory
16795         // locations are not in the default address space.
16796         LLD->getPointerInfo().getAddrSpace() != 0 ||
16797         RLD->getPointerInfo().getAddrSpace() != 0 ||
16798         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16799                                       LLD->getBasePtr().getValueType()))
16800       return false;
16801 
16802     // Check that the select condition doesn't reach either load.  If so,
16803     // folding this will induce a cycle into the DAG.  If not, this is safe to
16804     // xform, so create a select of the addresses.
16805     SDValue Addr;
16806     if (TheSelect->getOpcode() == ISD::SELECT) {
16807       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16808       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16809           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16810         return false;
16811       // The loads must not depend on one another.
16812       if (LLD->isPredecessorOf(RLD) ||
16813           RLD->isPredecessorOf(LLD))
16814         return false;
16815       Addr = DAG.getSelect(SDLoc(TheSelect),
16816                            LLD->getBasePtr().getValueType(),
16817                            TheSelect->getOperand(0), LLD->getBasePtr(),
16818                            RLD->getBasePtr());
16819     } else {  // Otherwise SELECT_CC
16820       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16821       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16822 
16823       if ((LLD->hasAnyUseOfValue(1) &&
16824            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16825           (RLD->hasAnyUseOfValue(1) &&
16826            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16827         return false;
16828 
16829       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16830                          LLD->getBasePtr().getValueType(),
16831                          TheSelect->getOperand(0),
16832                          TheSelect->getOperand(1),
16833                          LLD->getBasePtr(), RLD->getBasePtr(),
16834                          TheSelect->getOperand(4));
16835     }
16836 
16837     SDValue Load;
16838     // It is safe to replace the two loads if they have different alignments,
16839     // but the new load must be the minimum (most restrictive) alignment of the
16840     // inputs.
16841     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16842     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16843     if (!RLD->isInvariant())
16844       MMOFlags &= ~MachineMemOperand::MOInvariant;
16845     if (!RLD->isDereferenceable())
16846       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16847     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16848       // FIXME: Discards pointer and AA info.
16849       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16850                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16851                          MMOFlags);
16852     } else {
16853       // FIXME: Discards pointer and AA info.
16854       Load = DAG.getExtLoad(
16855           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16856                                                   : LLD->getExtensionType(),
16857           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16858           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16859     }
16860 
16861     // Users of the select now use the result of the load.
16862     CombineTo(TheSelect, Load);
16863 
16864     // Users of the old loads now use the new load's chain.  We know the
16865     // old-load value is dead now.
16866     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16867     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16868     return true;
16869   }
16870 
16871   return false;
16872 }
16873 
16874 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16875 /// bitwise 'and'.
16876 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16877                                             SDValue N1, SDValue N2, SDValue N3,
16878                                             ISD::CondCode CC) {
16879   // If this is a select where the false operand is zero and the compare is a
16880   // check of the sign bit, see if we can perform the "gzip trick":
16881   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16882   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16883   EVT XType = N0.getValueType();
16884   EVT AType = N2.getValueType();
16885   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16886     return SDValue();
16887 
16888   // If the comparison is testing for a positive value, we have to invert
16889   // the sign bit mask, so only do that transform if the target has a bitwise
16890   // 'and not' instruction (the invert is free).
16891   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16892     // (X > -1) ? A : 0
16893     // (X >  0) ? X : 0 <-- This is canonical signed max.
16894     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16895       return SDValue();
16896   } else if (CC == ISD::SETLT) {
16897     // (X <  0) ? A : 0
16898     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16899     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16900       return SDValue();
16901   } else {
16902     return SDValue();
16903   }
16904 
16905   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16906   // constant.
16907   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16908   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16909   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16910     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16911     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16912     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16913     AddToWorklist(Shift.getNode());
16914 
16915     if (XType.bitsGT(AType)) {
16916       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16917       AddToWorklist(Shift.getNode());
16918     }
16919 
16920     if (CC == ISD::SETGT)
16921       Shift = DAG.getNOT(DL, Shift, AType);
16922 
16923     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16924   }
16925 
16926   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16927   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16928   AddToWorklist(Shift.getNode());
16929 
16930   if (XType.bitsGT(AType)) {
16931     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16932     AddToWorklist(Shift.getNode());
16933   }
16934 
16935   if (CC == ISD::SETGT)
16936     Shift = DAG.getNOT(DL, Shift, AType);
16937 
16938   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16939 }
16940 
16941 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16942 /// where 'cond' is the comparison specified by CC.
16943 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16944                                       SDValue N2, SDValue N3, ISD::CondCode CC,
16945                                       bool NotExtCompare) {
16946   // (x ? y : y) -> y.
16947   if (N2 == N3) return N2;
16948 
16949   EVT VT = N2.getValueType();
16950   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16951   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16952 
16953   // Determine if the condition we're dealing with is constant
16954   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16955                               N0, N1, CC, DL, false);
16956   if (SCC.getNode()) AddToWorklist(SCC.getNode());
16957 
16958   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16959     // fold select_cc true, x, y -> x
16960     // fold select_cc false, x, y -> y
16961     return !SCCC->isNullValue() ? N2 : N3;
16962   }
16963 
16964   // Check to see if we can simplify the select into an fabs node
16965   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16966     // Allow either -0.0 or 0.0
16967     if (CFP->isZero()) {
16968       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16969       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16970           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16971           N2 == N3.getOperand(0))
16972         return DAG.getNode(ISD::FABS, DL, VT, N0);
16973 
16974       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16975       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16976           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16977           N2.getOperand(0) == N3)
16978         return DAG.getNode(ISD::FABS, DL, VT, N3);
16979     }
16980   }
16981 
16982   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16983   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16984   // in it.  This is a win when the constant is not otherwise available because
16985   // it replaces two constant pool loads with one.  We only do this if the FP
16986   // type is known to be legal, because if it isn't, then we are before legalize
16987   // types an we want the other legalization to happen first (e.g. to avoid
16988   // messing with soft float) and if the ConstantFP is not legal, because if
16989   // it is legal, we may not need to store the FP constant in a constant pool.
16990   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16991     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16992       if (TLI.isTypeLegal(N2.getValueType()) &&
16993           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16994                TargetLowering::Legal &&
16995            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16996            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16997           // If both constants have multiple uses, then we won't need to do an
16998           // extra load, they are likely around in registers for other users.
16999           (TV->hasOneUse() || FV->hasOneUse())) {
17000         Constant *Elts[] = {
17001           const_cast<ConstantFP*>(FV->getConstantFPValue()),
17002           const_cast<ConstantFP*>(TV->getConstantFPValue())
17003         };
17004         Type *FPTy = Elts[0]->getType();
17005         const DataLayout &TD = DAG.getDataLayout();
17006 
17007         // Create a ConstantArray of the two constants.
17008         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
17009         SDValue CPIdx =
17010             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
17011                                 TD.getPrefTypeAlignment(FPTy));
17012         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
17013 
17014         // Get the offsets to the 0 and 1 element of the array so that we can
17015         // select between them.
17016         SDValue Zero = DAG.getIntPtrConstant(0, DL);
17017         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
17018         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
17019 
17020         SDValue Cond = DAG.getSetCC(DL,
17021                                     getSetCCResultType(N0.getValueType()),
17022                                     N0, N1, CC);
17023         AddToWorklist(Cond.getNode());
17024         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
17025                                           Cond, One, Zero);
17026         AddToWorklist(CstOffset.getNode());
17027         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
17028                             CstOffset);
17029         AddToWorklist(CPIdx.getNode());
17030         return DAG.getLoad(
17031             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
17032             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17033             Alignment);
17034       }
17035     }
17036 
17037   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
17038     return V;
17039 
17040   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
17041   // where y is has a single bit set.
17042   // A plaintext description would be, we can turn the SELECT_CC into an AND
17043   // when the condition can be materialized as an all-ones register.  Any
17044   // single bit-test can be materialized as an all-ones register with
17045   // shift-left and shift-right-arith.
17046   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
17047       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
17048     SDValue AndLHS = N0->getOperand(0);
17049     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17050     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
17051       // Shift the tested bit over the sign bit.
17052       const APInt &AndMask = ConstAndRHS->getAPIntValue();
17053       SDValue ShlAmt =
17054         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
17055                         getShiftAmountTy(AndLHS.getValueType()));
17056       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
17057 
17058       // Now arithmetic right shift it all the way over, so the result is either
17059       // all-ones, or zero.
17060       SDValue ShrAmt =
17061         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
17062                         getShiftAmountTy(Shl.getValueType()));
17063       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
17064 
17065       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17066     }
17067   }
17068 
17069   // fold select C, 16, 0 -> shl C, 4
17070   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17071       TLI.getBooleanContents(N0.getValueType()) ==
17072           TargetLowering::ZeroOrOneBooleanContent) {
17073 
17074     // If the caller doesn't want us to simplify this into a zext of a compare,
17075     // don't do it.
17076     if (NotExtCompare && N2C->isOne())
17077       return SDValue();
17078 
17079     // Get a SetCC of the condition
17080     // NOTE: Don't create a SETCC if it's not legal on this target.
17081     if (!LegalOperations ||
17082         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17083       SDValue Temp, SCC;
17084       // cast from setcc result type to select result type
17085       if (LegalTypes) {
17086         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17087                             N0, N1, CC);
17088         if (N2.getValueType().bitsLT(SCC.getValueType()))
17089           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17090                                         N2.getValueType());
17091         else
17092           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17093                              N2.getValueType(), SCC);
17094       } else {
17095         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17096         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17097                            N2.getValueType(), SCC);
17098       }
17099 
17100       AddToWorklist(SCC.getNode());
17101       AddToWorklist(Temp.getNode());
17102 
17103       if (N2C->isOne())
17104         return Temp;
17105 
17106       // shl setcc result by log2 n2c
17107       return DAG.getNode(
17108           ISD::SHL, DL, N2.getValueType(), Temp,
17109           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17110                           getShiftAmountTy(Temp.getValueType())));
17111     }
17112   }
17113 
17114   // Check to see if this is an integer abs.
17115   // select_cc setg[te] X,  0,  X, -X ->
17116   // select_cc setgt    X, -1,  X, -X ->
17117   // select_cc setl[te] X,  0, -X,  X ->
17118   // select_cc setlt    X,  1, -X,  X ->
17119   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17120   if (N1C) {
17121     ConstantSDNode *SubC = nullptr;
17122     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17123          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17124         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17125       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17126     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17127               (N1C->isOne() && CC == ISD::SETLT)) &&
17128              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17129       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17130 
17131     EVT XType = N0.getValueType();
17132     if (SubC && SubC->isNullValue() && XType.isInteger()) {
17133       SDLoc DL(N0);
17134       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17135                                   N0,
17136                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
17137                                          getShiftAmountTy(N0.getValueType())));
17138       SDValue Add = DAG.getNode(ISD::ADD, DL,
17139                                 XType, N0, Shift);
17140       AddToWorklist(Shift.getNode());
17141       AddToWorklist(Add.getNode());
17142       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17143     }
17144   }
17145 
17146   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17147   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17148   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17149   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17150   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17151   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17152   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17153   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17154   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17155     SDValue ValueOnZero = N2;
17156     SDValue Count = N3;
17157     // If the condition is NE instead of E, swap the operands.
17158     if (CC == ISD::SETNE)
17159       std::swap(ValueOnZero, Count);
17160     // Check if the value on zero is a constant equal to the bits in the type.
17161     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17162       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17163         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17164         // legal, combine to just cttz.
17165         if ((Count.getOpcode() == ISD::CTTZ ||
17166              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17167             N0 == Count.getOperand(0) &&
17168             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17169           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17170         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17171         // legal, combine to just ctlz.
17172         if ((Count.getOpcode() == ISD::CTLZ ||
17173              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17174             N0 == Count.getOperand(0) &&
17175             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17176           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17177       }
17178     }
17179   }
17180 
17181   return SDValue();
17182 }
17183 
17184 /// This is a stub for TargetLowering::SimplifySetCC.
17185 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17186                                    ISD::CondCode Cond, const SDLoc &DL,
17187                                    bool foldBooleans) {
17188   TargetLowering::DAGCombinerInfo
17189     DagCombineInfo(DAG, Level, false, this);
17190   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17191 }
17192 
17193 /// Given an ISD::SDIV node expressing a divide by constant, return
17194 /// a DAG expression to select that will generate the same value by multiplying
17195 /// by a magic number.
17196 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17197 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17198   // when optimising for minimum size, we don't want to expand a div to a mul
17199   // and a shift.
17200   if (DAG.getMachineFunction().getFunction().optForMinSize())
17201     return SDValue();
17202 
17203   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17204   if (!C)
17205     return SDValue();
17206 
17207   // Avoid division by zero.
17208   if (C->isNullValue())
17209     return SDValue();
17210 
17211   std::vector<SDNode *> Built;
17212   SDValue S =
17213       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17214 
17215   for (SDNode *N : Built)
17216     AddToWorklist(N);
17217   return S;
17218 }
17219 
17220 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17221 /// DAG expression that will generate the same value by right shifting.
17222 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17223   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17224   if (!C)
17225     return SDValue();
17226 
17227   // Avoid division by zero.
17228   if (C->isNullValue())
17229     return SDValue();
17230 
17231   std::vector<SDNode *> Built;
17232   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17233 
17234   for (SDNode *N : Built)
17235     AddToWorklist(N);
17236   return S;
17237 }
17238 
17239 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17240 /// expression that will generate the same value by multiplying by a magic
17241 /// number.
17242 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17243 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17244   // when optimising for minimum size, we don't want to expand a div to a mul
17245   // and a shift.
17246   if (DAG.getMachineFunction().getFunction().optForMinSize())
17247     return SDValue();
17248 
17249   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17250   if (!C)
17251     return SDValue();
17252 
17253   // Avoid division by zero.
17254   if (C->isNullValue())
17255     return SDValue();
17256 
17257   std::vector<SDNode *> Built;
17258   SDValue S =
17259       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17260 
17261   for (SDNode *N : Built)
17262     AddToWorklist(N);
17263   return S;
17264 }
17265 
17266 /// Determines the LogBase2 value for a non-null input value using the
17267 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17268 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17269   EVT VT = V.getValueType();
17270   unsigned EltBits = VT.getScalarSizeInBits();
17271   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17272   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17273   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17274   return LogBase2;
17275 }
17276 
17277 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17278 /// For the reciprocal, we need to find the zero of the function:
17279 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
17280 ///     =>
17281 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17282 ///     does not require additional intermediate precision]
17283 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17284   if (Level >= AfterLegalizeDAG)
17285     return SDValue();
17286 
17287   // TODO: Handle half and/or extended types?
17288   EVT VT = Op.getValueType();
17289   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17290     return SDValue();
17291 
17292   // If estimates are explicitly disabled for this function, we're done.
17293   MachineFunction &MF = DAG.getMachineFunction();
17294   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17295   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17296     return SDValue();
17297 
17298   // Estimates may be explicitly enabled for this type with a custom number of
17299   // refinement steps.
17300   int Iterations = TLI.getDivRefinementSteps(VT, MF);
17301   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17302     AddToWorklist(Est.getNode());
17303 
17304     if (Iterations) {
17305       EVT VT = Op.getValueType();
17306       SDLoc DL(Op);
17307       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17308 
17309       // Newton iterations: Est = Est + Est (1 - Arg * Est)
17310       for (int i = 0; i < Iterations; ++i) {
17311         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17312         AddToWorklist(NewEst.getNode());
17313 
17314         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17315         AddToWorklist(NewEst.getNode());
17316 
17317         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17318         AddToWorklist(NewEst.getNode());
17319 
17320         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17321         AddToWorklist(Est.getNode());
17322       }
17323     }
17324     return Est;
17325   }
17326 
17327   return SDValue();
17328 }
17329 
17330 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17331 /// For the reciprocal sqrt, we need to find the zero of the function:
17332 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17333 ///     =>
17334 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17335 /// As a result, we precompute A/2 prior to the iteration loop.
17336 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17337                                          unsigned Iterations,
17338                                          SDNodeFlags Flags, bool Reciprocal) {
17339   EVT VT = Arg.getValueType();
17340   SDLoc DL(Arg);
17341   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17342 
17343   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17344   // this entire sequence requires only one FP constant.
17345   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17346   AddToWorklist(HalfArg.getNode());
17347 
17348   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17349   AddToWorklist(HalfArg.getNode());
17350 
17351   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17352   for (unsigned i = 0; i < Iterations; ++i) {
17353     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17354     AddToWorklist(NewEst.getNode());
17355 
17356     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17357     AddToWorklist(NewEst.getNode());
17358 
17359     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17360     AddToWorklist(NewEst.getNode());
17361 
17362     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17363     AddToWorklist(Est.getNode());
17364   }
17365 
17366   // If non-reciprocal square root is requested, multiply the result by Arg.
17367   if (!Reciprocal) {
17368     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17369     AddToWorklist(Est.getNode());
17370   }
17371 
17372   return Est;
17373 }
17374 
17375 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17376 /// For the reciprocal sqrt, we need to find the zero of the function:
17377 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17378 ///     =>
17379 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17380 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17381                                          unsigned Iterations,
17382                                          SDNodeFlags Flags, bool Reciprocal) {
17383   EVT VT = Arg.getValueType();
17384   SDLoc DL(Arg);
17385   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17386   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17387 
17388   // This routine must enter the loop below to work correctly
17389   // when (Reciprocal == false).
17390   assert(Iterations > 0);
17391 
17392   // Newton iterations for reciprocal square root:
17393   // E = (E * -0.5) * ((A * E) * E + -3.0)
17394   for (unsigned i = 0; i < Iterations; ++i) {
17395     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17396     AddToWorklist(AE.getNode());
17397 
17398     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17399     AddToWorklist(AEE.getNode());
17400 
17401     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17402     AddToWorklist(RHS.getNode());
17403 
17404     // When calculating a square root at the last iteration build:
17405     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17406     // (notice a common subexpression)
17407     SDValue LHS;
17408     if (Reciprocal || (i + 1) < Iterations) {
17409       // RSQRT: LHS = (E * -0.5)
17410       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17411     } else {
17412       // SQRT: LHS = (A * E) * -0.5
17413       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17414     }
17415     AddToWorklist(LHS.getNode());
17416 
17417     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17418     AddToWorklist(Est.getNode());
17419   }
17420 
17421   return Est;
17422 }
17423 
17424 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17425 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17426 /// Op can be zero.
17427 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17428                                            bool Reciprocal) {
17429   if (Level >= AfterLegalizeDAG)
17430     return SDValue();
17431 
17432   // TODO: Handle half and/or extended types?
17433   EVT VT = Op.getValueType();
17434   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17435     return SDValue();
17436 
17437   // If estimates are explicitly disabled for this function, we're done.
17438   MachineFunction &MF = DAG.getMachineFunction();
17439   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17440   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17441     return SDValue();
17442 
17443   // Estimates may be explicitly enabled for this type with a custom number of
17444   // refinement steps.
17445   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17446 
17447   bool UseOneConstNR = false;
17448   if (SDValue Est =
17449       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17450                           Reciprocal)) {
17451     AddToWorklist(Est.getNode());
17452 
17453     if (Iterations) {
17454       Est = UseOneConstNR
17455             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17456             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17457 
17458       if (!Reciprocal) {
17459         // The estimate is now completely wrong if the input was exactly 0.0 or
17460         // possibly a denormal. Force the answer to 0.0 for those cases.
17461         EVT VT = Op.getValueType();
17462         SDLoc DL(Op);
17463         EVT CCVT = getSetCCResultType(VT);
17464         ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
17465         const Function &F = DAG.getMachineFunction().getFunction();
17466         Attribute Denorms = F.getFnAttribute("denormal-fp-math");
17467         if (Denorms.getValueAsString().equals("ieee")) {
17468           // fabs(X) < SmallestNormal ? 0.0 : Est
17469           const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
17470           APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
17471           SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
17472           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17473           SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
17474           SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
17475           Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
17476           AddToWorklist(Fabs.getNode());
17477           AddToWorklist(IsDenorm.getNode());
17478           AddToWorklist(Est.getNode());
17479         } else {
17480           // X == 0.0 ? 0.0 : Est
17481           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17482           SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17483           Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
17484           AddToWorklist(IsZero.getNode());
17485           AddToWorklist(Est.getNode());
17486         }
17487       }
17488     }
17489     return Est;
17490   }
17491 
17492   return SDValue();
17493 }
17494 
17495 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17496   return buildSqrtEstimateImpl(Op, Flags, true);
17497 }
17498 
17499 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17500   return buildSqrtEstimateImpl(Op, Flags, false);
17501 }
17502 
17503 /// Return true if there is any possibility that the two addresses overlap.
17504 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17505   // If they are the same then they must be aliases.
17506   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17507 
17508   // If they are both volatile then they cannot be reordered.
17509   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17510 
17511   // If one operation reads from invariant memory, and the other may store, they
17512   // cannot alias. These should really be checking the equivalent of mayWrite,
17513   // but it only matters for memory nodes other than load /store.
17514   if (Op0->isInvariant() && Op1->writeMem())
17515     return false;
17516 
17517   if (Op1->isInvariant() && Op0->writeMem())
17518     return false;
17519 
17520   unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17521   unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17522 
17523   // Check for BaseIndexOffset matching.
17524   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG);
17525   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG);
17526   int64_t PtrDiff;
17527   if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) {
17528     if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17529       return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17530 
17531     // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17532     // able to calculate their relative offset if at least one arises
17533     // from an alloca. However, these allocas cannot overlap and we
17534     // can infer there is no alias.
17535     if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17536       if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17537         MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17538         // If the base are the same frame index but the we couldn't find a
17539         // constant offset, (indices are different) be conservative.
17540         if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17541                        !MFI.isFixedObjectIndex(B->getIndex())))
17542           return false;
17543       }
17544 
17545     bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
17546     bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
17547     bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
17548     bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
17549     bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
17550     bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
17551 
17552     // If of mismatched base types or checkable indices we can check
17553     // they do not alias.
17554     if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
17555          (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
17556         (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1))
17557       return false;
17558   }
17559 
17560   // If we know required SrcValue1 and SrcValue2 have relatively large
17561   // alignment compared to the size and offset of the access, we may be able
17562   // to prove they do not alias. This check is conservative for now to catch
17563   // cases created by splitting vector types.
17564   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17565   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17566   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17567   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17568   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17569       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17570     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17571     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17572 
17573     // There is no overlap between these relatively aligned accesses of
17574     // similar size. Return no alias.
17575     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17576         (OffAlign1 + NumBytes1) <= OffAlign0)
17577       return false;
17578   }
17579 
17580   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17581                    ? CombinerGlobalAA
17582                    : DAG.getSubtarget().useAA();
17583 #ifndef NDEBUG
17584   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17585       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17586     UseAA = false;
17587 #endif
17588 
17589   if (UseAA && AA &&
17590       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17591     // Use alias analysis information.
17592     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17593     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17594     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17595     AliasResult AAResult =
17596         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17597                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17598                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17599                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17600     if (AAResult == NoAlias)
17601       return false;
17602   }
17603 
17604   // Otherwise we have to assume they alias.
17605   return true;
17606 }
17607 
17608 /// Walk up chain skipping non-aliasing memory nodes,
17609 /// looking for aliasing nodes and adding them to the Aliases vector.
17610 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17611                                    SmallVectorImpl<SDValue> &Aliases) {
17612   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17613   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17614 
17615   // Get alias information for node.
17616   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17617 
17618   // Starting off.
17619   Chains.push_back(OriginalChain);
17620   unsigned Depth = 0;
17621 
17622   // Look at each chain and determine if it is an alias.  If so, add it to the
17623   // aliases list.  If not, then continue up the chain looking for the next
17624   // candidate.
17625   while (!Chains.empty()) {
17626     SDValue Chain = Chains.pop_back_val();
17627 
17628     // For TokenFactor nodes, look at each operand and only continue up the
17629     // chain until we reach the depth limit.
17630     //
17631     // FIXME: The depth check could be made to return the last non-aliasing
17632     // chain we found before we hit a tokenfactor rather than the original
17633     // chain.
17634     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17635       Aliases.clear();
17636       Aliases.push_back(OriginalChain);
17637       return;
17638     }
17639 
17640     // Don't bother if we've been before.
17641     if (!Visited.insert(Chain.getNode()).second)
17642       continue;
17643 
17644     switch (Chain.getOpcode()) {
17645     case ISD::EntryToken:
17646       // Entry token is ideal chain operand, but handled in FindBetterChain.
17647       break;
17648 
17649     case ISD::LOAD:
17650     case ISD::STORE: {
17651       // Get alias information for Chain.
17652       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17653           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17654 
17655       // If chain is alias then stop here.
17656       if (!(IsLoad && IsOpLoad) &&
17657           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17658         Aliases.push_back(Chain);
17659       } else {
17660         // Look further up the chain.
17661         Chains.push_back(Chain.getOperand(0));
17662         ++Depth;
17663       }
17664       break;
17665     }
17666 
17667     case ISD::TokenFactor:
17668       // We have to check each of the operands of the token factor for "small"
17669       // token factors, so we queue them up.  Adding the operands to the queue
17670       // (stack) in reverse order maintains the original order and increases the
17671       // likelihood that getNode will find a matching token factor (CSE.)
17672       if (Chain.getNumOperands() > 16) {
17673         Aliases.push_back(Chain);
17674         break;
17675       }
17676       for (unsigned n = Chain.getNumOperands(); n;)
17677         Chains.push_back(Chain.getOperand(--n));
17678       ++Depth;
17679       break;
17680 
17681     case ISD::CopyFromReg:
17682       // Forward past CopyFromReg.
17683       Chains.push_back(Chain.getOperand(0));
17684       ++Depth;
17685       break;
17686 
17687     default:
17688       // For all other instructions we will just have to take what we can get.
17689       Aliases.push_back(Chain);
17690       break;
17691     }
17692   }
17693 }
17694 
17695 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17696 /// (aliasing node.)
17697 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17698   if (OptLevel == CodeGenOpt::None)
17699     return OldChain;
17700 
17701   // Ops for replacing token factor.
17702   SmallVector<SDValue, 8> Aliases;
17703 
17704   // Accumulate all the aliases to this node.
17705   GatherAllAliases(N, OldChain, Aliases);
17706 
17707   // If no operands then chain to entry token.
17708   if (Aliases.size() == 0)
17709     return DAG.getEntryNode();
17710 
17711   // If a single operand then chain to it.  We don't need to revisit it.
17712   if (Aliases.size() == 1)
17713     return Aliases[0];
17714 
17715   // Construct a custom tailored token factor.
17716   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17717 }
17718 
17719 // This function tries to collect a bunch of potentially interesting
17720 // nodes to improve the chains of, all at once. This might seem
17721 // redundant, as this function gets called when visiting every store
17722 // node, so why not let the work be done on each store as it's visited?
17723 //
17724 // I believe this is mainly important because MergeConsecutiveStores
17725 // is unable to deal with merging stores of different sizes, so unless
17726 // we improve the chains of all the potential candidates up-front
17727 // before running MergeConsecutiveStores, it might only see some of
17728 // the nodes that will eventually be candidates, and then not be able
17729 // to go from a partially-merged state to the desired final
17730 // fully-merged state.
17731 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17732   if (OptLevel == CodeGenOpt::None)
17733     return false;
17734 
17735   // This holds the base pointer, index, and the offset in bytes from the base
17736   // pointer.
17737   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
17738 
17739   // We must have a base and an offset.
17740   if (!BasePtr.getBase().getNode())
17741     return false;
17742 
17743   // Do not handle stores to undef base pointers.
17744   if (BasePtr.getBase().isUndef())
17745     return false;
17746 
17747   SmallVector<StoreSDNode *, 8> ChainedStores;
17748   ChainedStores.push_back(St);
17749 
17750   // Walk up the chain and look for nodes with offsets from the same
17751   // base pointer. Stop when reaching an instruction with a different kind
17752   // or instruction which has a different base pointer.
17753   StoreSDNode *Index = St;
17754   while (Index) {
17755     // If the chain has more than one use, then we can't reorder the mem ops.
17756     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17757       break;
17758 
17759     if (Index->isVolatile() || Index->isIndexed())
17760       break;
17761 
17762     // Find the base pointer and offset for this memory node.
17763     BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG);
17764 
17765     // Check that the base pointer is the same as the original one.
17766     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17767       break;
17768 
17769     // Walk up the chain to find the next store node, ignoring any
17770     // intermediate loads. Any other kind of node will halt the loop.
17771     SDNode *NextInChain = Index->getChain().getNode();
17772     while (true) {
17773       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17774         // We found a store node. Use it for the next iteration.
17775         if (STn->isVolatile() || STn->isIndexed()) {
17776           Index = nullptr;
17777           break;
17778         }
17779         ChainedStores.push_back(STn);
17780         Index = STn;
17781         break;
17782       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17783         NextInChain = Ldn->getChain().getNode();
17784         continue;
17785       } else {
17786         Index = nullptr;
17787         break;
17788       }
17789     } // end while
17790   }
17791 
17792   // At this point, ChainedStores lists all of the Store nodes
17793   // reachable by iterating up through chain nodes matching the above
17794   // conditions.  For each such store identified, try to find an
17795   // earlier chain to attach the store to which won't violate the
17796   // required ordering.
17797   bool MadeChangeToSt = false;
17798   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17799 
17800   for (StoreSDNode *ChainedStore : ChainedStores) {
17801     SDValue Chain = ChainedStore->getChain();
17802     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17803 
17804     if (Chain != BetterChain) {
17805       if (ChainedStore == St)
17806         MadeChangeToSt = true;
17807       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17808     }
17809   }
17810 
17811   // Do all replacements after finding the replacements to make to avoid making
17812   // the chains more complicated by introducing new TokenFactors.
17813   for (auto Replacement : BetterChains)
17814     replaceStoreChain(Replacement.first, Replacement.second);
17815 
17816   return MadeChangeToSt;
17817 }
17818 
17819 /// This is the entry point for the file.
17820 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17821                            CodeGenOpt::Level OptLevel) {
17822   /// This is the main entry point to this class.
17823   DAGCombiner(*this, AA, OptLevel).Run(Level);
17824 }
17825