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/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAG.h"
41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
42 #include "llvm/CodeGen/SelectionDAGNodes.h"
43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constant.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CodeGen.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.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     /// Check the specified vector node value to see if it can be simplified or
236     /// if things it uses can be simplified as it only uses some of the
237     /// elements. If so, return true.
238     bool SimplifyDemandedVectorElts(SDValue Op) {
239       unsigned NumElts = Op.getValueType().getVectorNumElements();
240       APInt Demanded = APInt::getAllOnesValue(NumElts);
241       return SimplifyDemandedVectorElts(Op, Demanded);
242     }
243 
244     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
245     bool SimplifyDemandedVectorElts(SDValue Op, const APInt &Demanded);
246 
247     bool CombineToPreIndexedLoadStore(SDNode *N);
248     bool CombineToPostIndexedLoadStore(SDNode *N);
249     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
250     bool SliceUpLoad(SDNode *N);
251 
252     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
253     ///   load.
254     ///
255     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
256     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
257     /// \param EltNo index of the vector element to load.
258     /// \param OriginalLoad load that EVE came from to be replaced.
259     /// \returns EVE on success SDValue() on failure.
260     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
261         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
262     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
263     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
264     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
265     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
266     SDValue PromoteIntBinOp(SDValue Op);
267     SDValue PromoteIntShiftOp(SDValue Op);
268     SDValue PromoteExtend(SDValue Op);
269     bool PromoteLoad(SDValue Op);
270 
271     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
272                          SDValue OrigLoad, SDValue ExtLoad,
273                          const SDLoc &DL,
274                          ISD::NodeType ExtType);
275 
276     /// Call the node-specific routine that knows how to fold each
277     /// particular type of node. If that doesn't do anything, try the
278     /// target-specific DAG combines.
279     SDValue combine(SDNode *N);
280 
281     // Visitation implementation - Implement dag node combining for different
282     // node types.  The semantics are as follows:
283     // Return Value:
284     //   SDValue.getNode() == 0 - No change was made
285     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
286     //   otherwise              - N should be replaced by the returned Operand.
287     //
288     SDValue visitTokenFactor(SDNode *N);
289     SDValue visitMERGE_VALUES(SDNode *N);
290     SDValue visitADD(SDNode *N);
291     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
292     SDValue visitSUB(SDNode *N);
293     SDValue visitADDC(SDNode *N);
294     SDValue visitUADDO(SDNode *N);
295     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
296     SDValue visitSUBC(SDNode *N);
297     SDValue visitUSUBO(SDNode *N);
298     SDValue visitADDE(SDNode *N);
299     SDValue visitADDCARRY(SDNode *N);
300     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
301     SDValue visitSUBE(SDNode *N);
302     SDValue visitSUBCARRY(SDNode *N);
303     SDValue visitMUL(SDNode *N);
304     SDValue useDivRem(SDNode *N);
305     SDValue visitSDIV(SDNode *N);
306     SDValue visitUDIV(SDNode *N);
307     SDValue visitREM(SDNode *N);
308     SDValue visitMULHU(SDNode *N);
309     SDValue visitMULHS(SDNode *N);
310     SDValue visitSMUL_LOHI(SDNode *N);
311     SDValue visitUMUL_LOHI(SDNode *N);
312     SDValue visitSMULO(SDNode *N);
313     SDValue visitUMULO(SDNode *N);
314     SDValue visitIMINMAX(SDNode *N);
315     SDValue visitAND(SDNode *N);
316     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
317     SDValue visitOR(SDNode *N);
318     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
319     SDValue visitXOR(SDNode *N);
320     SDValue SimplifyVBinOp(SDNode *N);
321     SDValue visitSHL(SDNode *N);
322     SDValue visitSRA(SDNode *N);
323     SDValue visitSRL(SDNode *N);
324     SDValue visitRotate(SDNode *N);
325     SDValue visitABS(SDNode *N);
326     SDValue visitBSWAP(SDNode *N);
327     SDValue visitBITREVERSE(SDNode *N);
328     SDValue visitCTLZ(SDNode *N);
329     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
330     SDValue visitCTTZ(SDNode *N);
331     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
332     SDValue visitCTPOP(SDNode *N);
333     SDValue visitSELECT(SDNode *N);
334     SDValue visitVSELECT(SDNode *N);
335     SDValue visitSELECT_CC(SDNode *N);
336     SDValue visitSETCC(SDNode *N);
337     SDValue visitSETCCE(SDNode *N);
338     SDValue visitSETCCCARRY(SDNode *N);
339     SDValue visitSIGN_EXTEND(SDNode *N);
340     SDValue visitZERO_EXTEND(SDNode *N);
341     SDValue visitANY_EXTEND(SDNode *N);
342     SDValue visitAssertExt(SDNode *N);
343     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
344     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
345     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
346     SDValue visitTRUNCATE(SDNode *N);
347     SDValue visitBITCAST(SDNode *N);
348     SDValue visitBUILD_PAIR(SDNode *N);
349     SDValue visitFADD(SDNode *N);
350     SDValue visitFSUB(SDNode *N);
351     SDValue visitFMUL(SDNode *N);
352     SDValue visitFMA(SDNode *N);
353     SDValue visitFDIV(SDNode *N);
354     SDValue visitFREM(SDNode *N);
355     SDValue visitFSQRT(SDNode *N);
356     SDValue visitFCOPYSIGN(SDNode *N);
357     SDValue visitSINT_TO_FP(SDNode *N);
358     SDValue visitUINT_TO_FP(SDNode *N);
359     SDValue visitFP_TO_SINT(SDNode *N);
360     SDValue visitFP_TO_UINT(SDNode *N);
361     SDValue visitFP_ROUND(SDNode *N);
362     SDValue visitFP_ROUND_INREG(SDNode *N);
363     SDValue visitFP_EXTEND(SDNode *N);
364     SDValue visitFNEG(SDNode *N);
365     SDValue visitFABS(SDNode *N);
366     SDValue visitFCEIL(SDNode *N);
367     SDValue visitFTRUNC(SDNode *N);
368     SDValue visitFFLOOR(SDNode *N);
369     SDValue visitFMINNUM(SDNode *N);
370     SDValue visitFMAXNUM(SDNode *N);
371     SDValue visitBRCOND(SDNode *N);
372     SDValue visitBR_CC(SDNode *N);
373     SDValue visitLOAD(SDNode *N);
374 
375     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
376     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
377 
378     SDValue visitSTORE(SDNode *N);
379     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
380     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
381     SDValue visitBUILD_VECTOR(SDNode *N);
382     SDValue visitCONCAT_VECTORS(SDNode *N);
383     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
384     SDValue visitVECTOR_SHUFFLE(SDNode *N);
385     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
386     SDValue visitINSERT_SUBVECTOR(SDNode *N);
387     SDValue visitMLOAD(SDNode *N);
388     SDValue visitMSTORE(SDNode *N);
389     SDValue visitMGATHER(SDNode *N);
390     SDValue visitMSCATTER(SDNode *N);
391     SDValue visitFP_TO_FP16(SDNode *N);
392     SDValue visitFP16_TO_FP(SDNode *N);
393 
394     SDValue visitFADDForFMACombine(SDNode *N);
395     SDValue visitFSUBForFMACombine(SDNode *N);
396     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
397 
398     SDValue XformToShuffleWithZero(SDNode *N);
399     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
400                            SDValue RHS);
401 
402     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
403 
404     SDValue foldSelectOfConstants(SDNode *N);
405     SDValue foldVSelectOfConstants(SDNode *N);
406     SDValue foldBinOpIntoSelect(SDNode *BO);
407     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
408     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
409     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
410     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
411                              SDValue N2, SDValue N3, ISD::CondCode CC,
412                              bool NotExtCompare = false);
413     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
414                                    SDValue N2, SDValue N3, ISD::CondCode CC);
415     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
416                               const SDLoc &DL);
417     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
418                           const SDLoc &DL, bool foldBooleans);
419     SDValue rebuildSetCC(SDValue N);
420 
421     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
422                            SDValue &CC) const;
423     bool isOneUseSetCC(SDValue N) const;
424 
425     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
426                                          unsigned HiOp);
427     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
428     SDValue CombineExtLoad(SDNode *N);
429     SDValue CombineZExtLogicopShiftLoad(SDNode *N);
430     SDValue combineRepeatedFPDivisors(SDNode *N);
431     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
432     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
433     SDValue BuildSDIV(SDNode *N);
434     SDValue BuildSDIVPow2(SDNode *N);
435     SDValue BuildUDIV(SDNode *N);
436     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
437     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
438     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
439     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
440     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
441     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
442                                 SDNodeFlags Flags, bool Reciprocal);
443     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
444                                 SDNodeFlags Flags, bool Reciprocal);
445     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
446                                bool DemandHighBits = true);
447     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
448     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
449                               SDValue InnerPos, SDValue InnerNeg,
450                               unsigned PosOpcode, unsigned NegOpcode,
451                               const SDLoc &DL);
452     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
453     SDValue MatchLoadCombine(SDNode *N);
454     SDValue ReduceLoadWidth(SDNode *N);
455     SDValue ReduceLoadOpStoreWidth(SDNode *N);
456     SDValue splitMergedValStore(StoreSDNode *ST);
457     SDValue TransformFPLoadStorePair(SDNode *N);
458     SDValue convertBuildVecZextToZext(SDNode *N);
459     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
460     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
461     SDValue reduceBuildVecToShuffle(SDNode *N);
462     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
463                                   ArrayRef<int> VectorMask, SDValue VecIn1,
464                                   SDValue VecIn2, unsigned LeftIdx);
465     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
466 
467     /// Walk up chain skipping non-aliasing memory nodes,
468     /// looking for aliasing nodes and adding them to the Aliases vector.
469     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
470                           SmallVectorImpl<SDValue> &Aliases);
471 
472     /// Return true if there is any possibility that the two addresses overlap.
473     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
474 
475     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
476     /// chain (aliasing node.)
477     SDValue FindBetterChain(SDNode *N, SDValue Chain);
478 
479     /// Try to replace a store and any possibly adjacent stores on
480     /// consecutive chains with better chains. Return true only if St is
481     /// replaced.
482     ///
483     /// Notice that other chains may still be replaced even if the function
484     /// returns false.
485     bool findBetterNeighborChains(StoreSDNode *St);
486 
487     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
488     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
489 
490     /// Holds a pointer to an LSBaseSDNode as well as information on where it
491     /// is located in a sequence of memory operations connected by a chain.
492     struct MemOpLink {
493       // Ptr to the mem node.
494       LSBaseSDNode *MemNode;
495 
496       // Offset from the base ptr.
497       int64_t OffsetFromBase;
498 
499       MemOpLink(LSBaseSDNode *N, int64_t Offset)
500           : MemNode(N), OffsetFromBase(Offset) {}
501     };
502 
503     /// This is a helper function for visitMUL to check the profitability
504     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
505     /// MulNode is the original multiply, AddNode is (add x, c1),
506     /// and ConstNode is c2.
507     bool isMulAddWithConstProfitable(SDNode *MulNode,
508                                      SDValue &AddNode,
509                                      SDValue &ConstNode);
510 
511     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
512     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
513     /// the type of the loaded value to be extended.
514     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
515                           EVT LoadResultTy, EVT &ExtVT);
516 
517     /// Helper function to calculate whether the given Load can have its
518     /// width reduced to ExtVT.
519     bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
520                            EVT &ExtVT, unsigned ShAmt = 0);
521 
522     /// Used by BackwardsPropagateMask to find suitable loads.
523     bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
524                            SmallPtrSetImpl<SDNode*> &NodeWithConsts,
525                            ConstantSDNode *Mask, SDNode *&UncombinedNode);
526     /// Attempt to propagate a given AND node back to load leaves so that they
527     /// can be combined into narrow loads.
528     bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
529 
530     /// Helper function for MergeConsecutiveStores which merges the
531     /// component store chains.
532     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
533                                 unsigned NumStores);
534 
535     /// This is a helper function for MergeConsecutiveStores. When the
536     /// source elements of the consecutive stores are all constants or
537     /// all extracted vector elements, try to merge them into one
538     /// larger store introducing bitcasts if necessary.  \return True
539     /// if a merged store was created.
540     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
541                                          EVT MemVT, unsigned NumStores,
542                                          bool IsConstantSrc, bool UseVector,
543                                          bool UseTrunc);
544 
545     /// This is a helper function for MergeConsecutiveStores. Stores
546     /// that potentially may be merged with St are placed in
547     /// StoreNodes.
548     void getStoreMergeCandidates(StoreSDNode *St,
549                                  SmallVectorImpl<MemOpLink> &StoreNodes);
550 
551     /// Helper function for MergeConsecutiveStores. Checks if
552     /// candidate stores have indirect dependency through their
553     /// operands. \return True if safe to merge.
554     bool checkMergeStoreCandidatesForDependencies(
555         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
556 
557     /// Merge consecutive store operations into a wide store.
558     /// This optimization uses wide integers or vectors when possible.
559     /// \return number of stores that were merged into a merged store (the
560     /// affected nodes are stored as a prefix in \p StoreNodes).
561     bool MergeConsecutiveStores(StoreSDNode *N);
562 
563     /// \brief Try to transform a truncation where C is a constant:
564     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
565     ///
566     /// \p N needs to be a truncation and its first operand an AND. Other
567     /// requirements are checked by the function (e.g. that trunc is
568     /// single-use) and if missed an empty SDValue is returned.
569     SDValue distributeTruncateThroughAnd(SDNode *N);
570 
571   public:
572     /// Runs the dag combiner on all nodes in the work list
573     void Run(CombineLevel AtLevel);
574 
575     SelectionDAG &getDAG() const { return DAG; }
576 
577     /// Returns a type large enough to hold any valid shift amount - before type
578     /// legalization these can be huge.
579     EVT getShiftAmountTy(EVT LHSTy) {
580       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
581       return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
582     }
583 
584     /// This method returns true if we are running before type legalization or
585     /// if the specified VT is legal.
586     bool isTypeLegal(const EVT &VT) {
587       if (!LegalTypes) return true;
588       return TLI.isTypeLegal(VT);
589     }
590 
591     /// Convenience wrapper around TargetLowering::getSetCCResultType
592     EVT getSetCCResultType(EVT VT) const {
593       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
594     }
595   };
596 
597 /// This class is a DAGUpdateListener that removes any deleted
598 /// nodes from the worklist.
599 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
600   DAGCombiner &DC;
601 
602 public:
603   explicit WorklistRemover(DAGCombiner &dc)
604     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
605 
606   void NodeDeleted(SDNode *N, SDNode *E) override {
607     DC.removeFromWorklist(N);
608   }
609 };
610 
611 } // end anonymous namespace
612 
613 //===----------------------------------------------------------------------===//
614 //  TargetLowering::DAGCombinerInfo implementation
615 //===----------------------------------------------------------------------===//
616 
617 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
618   ((DAGCombiner*)DC)->AddToWorklist(N);
619 }
620 
621 SDValue TargetLowering::DAGCombinerInfo::
622 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
623   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
624 }
625 
626 SDValue TargetLowering::DAGCombinerInfo::
627 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
628   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
629 }
630 
631 SDValue TargetLowering::DAGCombinerInfo::
632 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
633   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
634 }
635 
636 void TargetLowering::DAGCombinerInfo::
637 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
638   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
639 }
640 
641 //===----------------------------------------------------------------------===//
642 // Helper Functions
643 //===----------------------------------------------------------------------===//
644 
645 void DAGCombiner::deleteAndRecombine(SDNode *N) {
646   removeFromWorklist(N);
647 
648   // If the operands of this node are only used by the node, they will now be
649   // dead. Make sure to re-visit them and recursively delete dead nodes.
650   for (const SDValue &Op : N->ops())
651     // For an operand generating multiple values, one of the values may
652     // become dead allowing further simplification (e.g. split index
653     // arithmetic from an indexed load).
654     if (Op->hasOneUse() || Op->getNumValues() > 1)
655       AddToWorklist(Op.getNode());
656 
657   DAG.DeleteNode(N);
658 }
659 
660 /// Return 1 if we can compute the negated form of the specified expression for
661 /// the same cost as the expression itself, or 2 if we can compute the negated
662 /// form more cheaply than the expression itself.
663 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
664                                const TargetLowering &TLI,
665                                const TargetOptions *Options,
666                                unsigned Depth = 0) {
667   // fneg is removable even if it has multiple uses.
668   if (Op.getOpcode() == ISD::FNEG) return 2;
669 
670   // Don't allow anything with multiple uses unless we know it is free.
671   EVT VT = Op.getValueType();
672   if (!Op.hasOneUse())
673     if (!(Op.getOpcode() == ISD::FP_EXTEND &&
674           TLI.isFPExtFree(VT, Op.getOperand(0).getValueType())))
675       return 0;
676 
677   // Don't recurse exponentially.
678   if (Depth > 6) return 0;
679 
680   switch (Op.getOpcode()) {
681   default: return false;
682   case ISD::ConstantFP: {
683     if (!LegalOperations)
684       return 1;
685 
686     // Don't invert constant FP values after legalization unless the target says
687     // the negated constant is legal.
688     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
689       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
690   }
691   case ISD::FADD:
692     // FIXME: determine better conditions for this xform.
693     if (!Options->UnsafeFPMath) return 0;
694 
695     // After operation legalization, it might not be legal to create new FSUBs.
696     if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
697       return 0;
698 
699     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
700     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
701                                     Options, Depth + 1))
702       return V;
703     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
704     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
705                               Depth + 1);
706   case ISD::FSUB:
707     // We can't turn -(A-B) into B-A when we honor signed zeros.
708     if (!Options->NoSignedZerosFPMath &&
709         !Op.getNode()->getFlags().hasNoSignedZeros())
710       return 0;
711 
712     // fold (fneg (fsub A, B)) -> (fsub B, A)
713     return 1;
714 
715   case ISD::FMUL:
716   case ISD::FDIV:
717     if (Options->HonorSignDependentRoundingFPMath()) return 0;
718 
719     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
720     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
721                                     Options, Depth + 1))
722       return V;
723 
724     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
725                               Depth + 1);
726 
727   case ISD::FP_EXTEND:
728   case ISD::FP_ROUND:
729   case ISD::FSIN:
730     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
731                               Depth + 1);
732   }
733 }
734 
735 /// If isNegatibleForFree returns true, return the newly negated expression.
736 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
737                                     bool LegalOperations, unsigned Depth = 0) {
738   const TargetOptions &Options = DAG.getTarget().Options;
739   // fneg is removable even if it has multiple uses.
740   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
741 
742   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
743 
744   const SDNodeFlags Flags = Op.getNode()->getFlags();
745 
746   switch (Op.getOpcode()) {
747   default: llvm_unreachable("Unknown code");
748   case ISD::ConstantFP: {
749     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
750     V.changeSign();
751     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
752   }
753   case ISD::FADD:
754     // FIXME: determine better conditions for this xform.
755     assert(Options.UnsafeFPMath);
756 
757     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
758     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
759                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
760       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
761                          GetNegatedExpression(Op.getOperand(0), DAG,
762                                               LegalOperations, Depth+1),
763                          Op.getOperand(1), Flags);
764     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
765     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
766                        GetNegatedExpression(Op.getOperand(1), DAG,
767                                             LegalOperations, Depth+1),
768                        Op.getOperand(0), Flags);
769   case ISD::FSUB:
770     // fold (fneg (fsub 0, B)) -> B
771     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
772       if (N0CFP->isZero())
773         return Op.getOperand(1);
774 
775     // fold (fneg (fsub A, B)) -> (fsub B, A)
776     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
777                        Op.getOperand(1), Op.getOperand(0), Flags);
778 
779   case ISD::FMUL:
780   case ISD::FDIV:
781     assert(!Options.HonorSignDependentRoundingFPMath());
782 
783     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
784     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
785                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
786       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
787                          GetNegatedExpression(Op.getOperand(0), DAG,
788                                               LegalOperations, Depth+1),
789                          Op.getOperand(1), Flags);
790 
791     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
792     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
793                        Op.getOperand(0),
794                        GetNegatedExpression(Op.getOperand(1), DAG,
795                                             LegalOperations, Depth+1), Flags);
796 
797   case ISD::FP_EXTEND:
798   case ISD::FSIN:
799     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
800                        GetNegatedExpression(Op.getOperand(0), DAG,
801                                             LegalOperations, Depth+1));
802   case ISD::FP_ROUND:
803       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
804                          GetNegatedExpression(Op.getOperand(0), DAG,
805                                               LegalOperations, Depth+1),
806                          Op.getOperand(1));
807   }
808 }
809 
810 // APInts must be the same size for most operations, this helper
811 // function zero extends the shorter of the pair so that they match.
812 // We provide an Offset so that we can create bitwidths that won't overflow.
813 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
814   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
815   LHS = LHS.zextOrSelf(Bits);
816   RHS = RHS.zextOrSelf(Bits);
817 }
818 
819 // Return true if this node is a setcc, or is a select_cc
820 // that selects between the target values used for true and false, making it
821 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
822 // the appropriate nodes based on the type of node we are checking. This
823 // simplifies life a bit for the callers.
824 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
825                                     SDValue &CC) const {
826   if (N.getOpcode() == ISD::SETCC) {
827     LHS = N.getOperand(0);
828     RHS = N.getOperand(1);
829     CC  = N.getOperand(2);
830     return true;
831   }
832 
833   if (N.getOpcode() != ISD::SELECT_CC ||
834       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
835       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
836     return false;
837 
838   if (TLI.getBooleanContents(N.getValueType()) ==
839       TargetLowering::UndefinedBooleanContent)
840     return false;
841 
842   LHS = N.getOperand(0);
843   RHS = N.getOperand(1);
844   CC  = N.getOperand(4);
845   return true;
846 }
847 
848 /// Return true if this is a SetCC-equivalent operation with only one use.
849 /// If this is true, it allows the users to invert the operation for free when
850 /// it is profitable to do so.
851 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
852   SDValue N0, N1, N2;
853   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
854     return true;
855   return false;
856 }
857 
858 // \brief Returns the SDNode if it is a constant float BuildVector
859 // or constant float.
860 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
861   if (isa<ConstantFPSDNode>(N))
862     return N.getNode();
863   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
864     return N.getNode();
865   return nullptr;
866 }
867 
868 // Determines if it is a constant integer or a build vector of constant
869 // integers (and undefs).
870 // Do not permit build vector implicit truncation.
871 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
872   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
873     return !(Const->isOpaque() && NoOpaques);
874   if (N.getOpcode() != ISD::BUILD_VECTOR)
875     return false;
876   unsigned BitWidth = N.getScalarValueSizeInBits();
877   for (const SDValue &Op : N->op_values()) {
878     if (Op.isUndef())
879       continue;
880     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
881     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
882         (Const->isOpaque() && NoOpaques))
883       return false;
884   }
885   return true;
886 }
887 
888 // Determines if it is a constant null integer or a splatted vector of a
889 // constant null integer (with no undefs).
890 // Build vector implicit truncation is not an issue for null values.
891 static bool isNullConstantOrNullSplatConstant(SDValue N) {
892   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
893     return Splat->isNullValue();
894   return false;
895 }
896 
897 // Determines if it is a constant integer of one or a splatted vector of a
898 // constant integer of one (with no undefs).
899 // Do not permit build vector implicit truncation.
900 static bool isOneConstantOrOneSplatConstant(SDValue N) {
901   unsigned BitWidth = N.getScalarValueSizeInBits();
902   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
903     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
904   return false;
905 }
906 
907 // Determines if it is a constant integer of all ones or a splatted vector of a
908 // constant integer of all ones (with no undefs).
909 // Do not permit build vector implicit truncation.
910 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
911   unsigned BitWidth = N.getScalarValueSizeInBits();
912   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
913     return Splat->isAllOnesValue() &&
914            Splat->getAPIntValue().getBitWidth() == BitWidth;
915   return false;
916 }
917 
918 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
919 // undef's.
920 static bool isAnyConstantBuildVector(const SDNode *N) {
921   return ISD::isBuildVectorOfConstantSDNodes(N) ||
922          ISD::isBuildVectorOfConstantFPSDNodes(N);
923 }
924 
925 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
926                                     SDValue N1) {
927   EVT VT = N0.getValueType();
928   if (N0.getOpcode() == Opc) {
929     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
930       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
931         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
932         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
933           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
934         return SDValue();
935       }
936       if (N0.hasOneUse()) {
937         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
938         // use
939         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
940         if (!OpNode.getNode())
941           return SDValue();
942         AddToWorklist(OpNode.getNode());
943         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
944       }
945     }
946   }
947 
948   if (N1.getOpcode() == Opc) {
949     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
950       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
951         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
952         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
953           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
954         return SDValue();
955       }
956       if (N1.hasOneUse()) {
957         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
958         // use
959         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
960         if (!OpNode.getNode())
961           return SDValue();
962         AddToWorklist(OpNode.getNode());
963         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
964       }
965     }
966   }
967 
968   return SDValue();
969 }
970 
971 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
972                                bool AddTo) {
973   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
974   ++NodesCombined;
975   DEBUG(dbgs() << "\nReplacing.1 ";
976         N->dump(&DAG);
977         dbgs() << "\nWith: ";
978         To[0].getNode()->dump(&DAG);
979         dbgs() << " and " << NumTo-1 << " other values\n");
980   for (unsigned i = 0, e = NumTo; i != e; ++i)
981     assert((!To[i].getNode() ||
982             N->getValueType(i) == To[i].getValueType()) &&
983            "Cannot combine value to value of different type!");
984 
985   WorklistRemover DeadNodes(*this);
986   DAG.ReplaceAllUsesWith(N, To);
987   if (AddTo) {
988     // Push the new nodes and any users onto the worklist
989     for (unsigned i = 0, e = NumTo; i != e; ++i) {
990       if (To[i].getNode()) {
991         AddToWorklist(To[i].getNode());
992         AddUsersToWorklist(To[i].getNode());
993       }
994     }
995   }
996 
997   // Finally, if the node is now dead, remove it from the graph.  The node
998   // may not be dead if the replacement process recursively simplified to
999   // something else needing this node.
1000   if (N->use_empty())
1001     deleteAndRecombine(N);
1002   return SDValue(N, 0);
1003 }
1004 
1005 void DAGCombiner::
1006 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1007   // Replace all uses.  If any nodes become isomorphic to other nodes and
1008   // are deleted, make sure to remove them from our worklist.
1009   WorklistRemover DeadNodes(*this);
1010   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1011 
1012   // Push the new node and any (possibly new) users onto the worklist.
1013   AddToWorklist(TLO.New.getNode());
1014   AddUsersToWorklist(TLO.New.getNode());
1015 
1016   // Finally, if the node is now dead, remove it from the graph.  The node
1017   // may not be dead if the replacement process recursively simplified to
1018   // something else needing this node.
1019   if (TLO.Old.getNode()->use_empty())
1020     deleteAndRecombine(TLO.Old.getNode());
1021 }
1022 
1023 /// Check the specified integer node value to see if it can be simplified or if
1024 /// things it uses can be simplified by bit propagation. If so, return true.
1025 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1026   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1027   KnownBits Known;
1028   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1029     return false;
1030 
1031   // Revisit the node.
1032   AddToWorklist(Op.getNode());
1033 
1034   // Replace the old value with the new one.
1035   ++NodesCombined;
1036   DEBUG(dbgs() << "\nReplacing.2 ";
1037         TLO.Old.getNode()->dump(&DAG);
1038         dbgs() << "\nWith: ";
1039         TLO.New.getNode()->dump(&DAG);
1040         dbgs() << '\n');
1041 
1042   CommitTargetLoweringOpt(TLO);
1043   return true;
1044 }
1045 
1046 /// Check the specified vector node value to see if it can be simplified or
1047 /// if things it uses can be simplified as it only uses some of the elements.
1048 /// If so, return true.
1049 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1050                                              const APInt &Demanded) {
1051   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1052   APInt KnownUndef, KnownZero;
1053   if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO))
1054     return false;
1055 
1056   // Revisit the node.
1057   AddToWorklist(Op.getNode());
1058 
1059   // Replace the old value with the new one.
1060   ++NodesCombined;
1061   DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1062         dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); dbgs() << '\n');
1063 
1064   CommitTargetLoweringOpt(TLO);
1065   return true;
1066 }
1067 
1068 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1069   SDLoc DL(Load);
1070   EVT VT = Load->getValueType(0);
1071   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1072 
1073   DEBUG(dbgs() << "\nReplacing.9 ";
1074         Load->dump(&DAG);
1075         dbgs() << "\nWith: ";
1076         Trunc.getNode()->dump(&DAG);
1077         dbgs() << '\n');
1078   WorklistRemover DeadNodes(*this);
1079   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1080   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1081   deleteAndRecombine(Load);
1082   AddToWorklist(Trunc.getNode());
1083 }
1084 
1085 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1086   Replace = false;
1087   SDLoc DL(Op);
1088   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1089     LoadSDNode *LD = cast<LoadSDNode>(Op);
1090     EVT MemVT = LD->getMemoryVT();
1091     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1093                                                        : ISD::EXTLOAD)
1094       : LD->getExtensionType();
1095     Replace = true;
1096     return DAG.getExtLoad(ExtType, DL, PVT,
1097                           LD->getChain(), LD->getBasePtr(),
1098                           MemVT, LD->getMemOperand());
1099   }
1100 
1101   unsigned Opc = Op.getOpcode();
1102   switch (Opc) {
1103   default: break;
1104   case ISD::AssertSext:
1105     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1106       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1107     break;
1108   case ISD::AssertZext:
1109     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1110       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1111     break;
1112   case ISD::Constant: {
1113     unsigned ExtOpc =
1114       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1115     return DAG.getNode(ExtOpc, DL, PVT, Op);
1116   }
1117   }
1118 
1119   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1120     return SDValue();
1121   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1122 }
1123 
1124 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1125   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1126     return SDValue();
1127   EVT OldVT = Op.getValueType();
1128   SDLoc DL(Op);
1129   bool Replace = false;
1130   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1131   if (!NewOp.getNode())
1132     return SDValue();
1133   AddToWorklist(NewOp.getNode());
1134 
1135   if (Replace)
1136     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1137   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1138                      DAG.getValueType(OldVT));
1139 }
1140 
1141 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1142   EVT OldVT = Op.getValueType();
1143   SDLoc DL(Op);
1144   bool Replace = false;
1145   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1146   if (!NewOp.getNode())
1147     return SDValue();
1148   AddToWorklist(NewOp.getNode());
1149 
1150   if (Replace)
1151     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1152   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1153 }
1154 
1155 /// Promote the specified integer binary operation if the target indicates it is
1156 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1157 /// i32 since i16 instructions are longer.
1158 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1159   if (!LegalOperations)
1160     return SDValue();
1161 
1162   EVT VT = Op.getValueType();
1163   if (VT.isVector() || !VT.isInteger())
1164     return SDValue();
1165 
1166   // If operation type is 'undesirable', e.g. i16 on x86, consider
1167   // promoting it.
1168   unsigned Opc = Op.getOpcode();
1169   if (TLI.isTypeDesirableForOp(Opc, VT))
1170     return SDValue();
1171 
1172   EVT PVT = VT;
1173   // Consult target whether it is a good idea to promote this operation and
1174   // what's the right type to promote it to.
1175   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1176     assert(PVT != VT && "Don't know what type to promote to!");
1177 
1178     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1179 
1180     bool Replace0 = false;
1181     SDValue N0 = Op.getOperand(0);
1182     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1183 
1184     bool Replace1 = false;
1185     SDValue N1 = Op.getOperand(1);
1186     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1187     SDLoc DL(Op);
1188 
1189     SDValue RV =
1190         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1191 
1192     // We are always replacing N0/N1's use in N and only need
1193     // additional replacements if there are additional uses.
1194     Replace0 &= !N0->hasOneUse();
1195     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1196 
1197     // Combine Op here so it is preserved past replacements.
1198     CombineTo(Op.getNode(), RV);
1199 
1200     // If operands have a use ordering, make sure we deal with
1201     // predecessor first.
1202     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1203       std::swap(N0, N1);
1204       std::swap(NN0, NN1);
1205     }
1206 
1207     if (Replace0) {
1208       AddToWorklist(NN0.getNode());
1209       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1210     }
1211     if (Replace1) {
1212       AddToWorklist(NN1.getNode());
1213       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1214     }
1215     return Op;
1216   }
1217   return SDValue();
1218 }
1219 
1220 /// Promote the specified integer shift operation if the target indicates it is
1221 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1222 /// i32 since i16 instructions are longer.
1223 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1224   if (!LegalOperations)
1225     return SDValue();
1226 
1227   EVT VT = Op.getValueType();
1228   if (VT.isVector() || !VT.isInteger())
1229     return SDValue();
1230 
1231   // If operation type is 'undesirable', e.g. i16 on x86, consider
1232   // promoting it.
1233   unsigned Opc = Op.getOpcode();
1234   if (TLI.isTypeDesirableForOp(Opc, VT))
1235     return SDValue();
1236 
1237   EVT PVT = VT;
1238   // Consult target whether it is a good idea to promote this operation and
1239   // what's the right type to promote it to.
1240   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1241     assert(PVT != VT && "Don't know what type to promote to!");
1242 
1243     DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1244 
1245     bool Replace = false;
1246     SDValue N0 = Op.getOperand(0);
1247     SDValue N1 = Op.getOperand(1);
1248     if (Opc == ISD::SRA)
1249       N0 = SExtPromoteOperand(N0, PVT);
1250     else if (Opc == ISD::SRL)
1251       N0 = ZExtPromoteOperand(N0, PVT);
1252     else
1253       N0 = PromoteOperand(N0, PVT, Replace);
1254 
1255     if (!N0.getNode())
1256       return SDValue();
1257 
1258     SDLoc DL(Op);
1259     SDValue RV =
1260         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1261 
1262     AddToWorklist(N0.getNode());
1263     if (Replace)
1264       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1265 
1266     // Deal with Op being deleted.
1267     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1268       return RV;
1269   }
1270   return SDValue();
1271 }
1272 
1273 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1274   if (!LegalOperations)
1275     return SDValue();
1276 
1277   EVT VT = Op.getValueType();
1278   if (VT.isVector() || !VT.isInteger())
1279     return SDValue();
1280 
1281   // If operation type is 'undesirable', e.g. i16 on x86, consider
1282   // promoting it.
1283   unsigned Opc = Op.getOpcode();
1284   if (TLI.isTypeDesirableForOp(Opc, VT))
1285     return SDValue();
1286 
1287   EVT PVT = VT;
1288   // Consult target whether it is a good idea to promote this operation and
1289   // what's the right type to promote it to.
1290   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1291     assert(PVT != VT && "Don't know what type to promote to!");
1292     // fold (aext (aext x)) -> (aext x)
1293     // fold (aext (zext x)) -> (zext x)
1294     // fold (aext (sext x)) -> (sext x)
1295     DEBUG(dbgs() << "\nPromoting ";
1296           Op.getNode()->dump(&DAG));
1297     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1298   }
1299   return SDValue();
1300 }
1301 
1302 bool DAGCombiner::PromoteLoad(SDValue Op) {
1303   if (!LegalOperations)
1304     return false;
1305 
1306   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1307     return false;
1308 
1309   EVT VT = Op.getValueType();
1310   if (VT.isVector() || !VT.isInteger())
1311     return false;
1312 
1313   // If operation type is 'undesirable', e.g. i16 on x86, consider
1314   // promoting it.
1315   unsigned Opc = Op.getOpcode();
1316   if (TLI.isTypeDesirableForOp(Opc, VT))
1317     return false;
1318 
1319   EVT PVT = VT;
1320   // Consult target whether it is a good idea to promote this operation and
1321   // what's the right type to promote it to.
1322   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1323     assert(PVT != VT && "Don't know what type to promote to!");
1324 
1325     SDLoc DL(Op);
1326     SDNode *N = Op.getNode();
1327     LoadSDNode *LD = cast<LoadSDNode>(N);
1328     EVT MemVT = LD->getMemoryVT();
1329     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1330       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1331                                                        : ISD::EXTLOAD)
1332       : LD->getExtensionType();
1333     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1334                                    LD->getChain(), LD->getBasePtr(),
1335                                    MemVT, LD->getMemOperand());
1336     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1337 
1338     DEBUG(dbgs() << "\nPromoting ";
1339           N->dump(&DAG);
1340           dbgs() << "\nTo: ";
1341           Result.getNode()->dump(&DAG);
1342           dbgs() << '\n');
1343     WorklistRemover DeadNodes(*this);
1344     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1345     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1346     deleteAndRecombine(N);
1347     AddToWorklist(Result.getNode());
1348     return true;
1349   }
1350   return false;
1351 }
1352 
1353 /// \brief Recursively delete a node which has no uses and any operands for
1354 /// which it is the only use.
1355 ///
1356 /// Note that this both deletes the nodes and removes them from the worklist.
1357 /// It also adds any nodes who have had a user deleted to the worklist as they
1358 /// may now have only one use and subject to other combines.
1359 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1360   if (!N->use_empty())
1361     return false;
1362 
1363   SmallSetVector<SDNode *, 16> Nodes;
1364   Nodes.insert(N);
1365   do {
1366     N = Nodes.pop_back_val();
1367     if (!N)
1368       continue;
1369 
1370     if (N->use_empty()) {
1371       for (const SDValue &ChildN : N->op_values())
1372         Nodes.insert(ChildN.getNode());
1373 
1374       removeFromWorklist(N);
1375       DAG.DeleteNode(N);
1376     } else {
1377       AddToWorklist(N);
1378     }
1379   } while (!Nodes.empty());
1380   return true;
1381 }
1382 
1383 //===----------------------------------------------------------------------===//
1384 //  Main DAG Combiner implementation
1385 //===----------------------------------------------------------------------===//
1386 
1387 void DAGCombiner::Run(CombineLevel AtLevel) {
1388   // set the instance variables, so that the various visit routines may use it.
1389   Level = AtLevel;
1390   LegalOperations = Level >= AfterLegalizeVectorOps;
1391   LegalTypes = Level >= AfterLegalizeTypes;
1392 
1393   // Add all the dag nodes to the worklist.
1394   for (SDNode &Node : DAG.allnodes())
1395     AddToWorklist(&Node);
1396 
1397   // Create a dummy node (which is not added to allnodes), that adds a reference
1398   // to the root node, preventing it from being deleted, and tracking any
1399   // changes of the root.
1400   HandleSDNode Dummy(DAG.getRoot());
1401 
1402   // While the worklist isn't empty, find a node and try to combine it.
1403   while (!WorklistMap.empty()) {
1404     SDNode *N;
1405     // The Worklist holds the SDNodes in order, but it may contain null entries.
1406     do {
1407       N = Worklist.pop_back_val();
1408     } while (!N);
1409 
1410     bool GoodWorklistEntry = WorklistMap.erase(N);
1411     (void)GoodWorklistEntry;
1412     assert(GoodWorklistEntry &&
1413            "Found a worklist entry without a corresponding map entry!");
1414 
1415     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1416     // N is deleted from the DAG, since they too may now be dead or may have a
1417     // reduced number of uses, allowing other xforms.
1418     if (recursivelyDeleteUnusedNodes(N))
1419       continue;
1420 
1421     WorklistRemover DeadNodes(*this);
1422 
1423     // If this combine is running after legalizing the DAG, re-legalize any
1424     // nodes pulled off the worklist.
1425     if (Level == AfterLegalizeDAG) {
1426       SmallSetVector<SDNode *, 16> UpdatedNodes;
1427       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1428 
1429       for (SDNode *LN : UpdatedNodes) {
1430         AddToWorklist(LN);
1431         AddUsersToWorklist(LN);
1432       }
1433       if (!NIsValid)
1434         continue;
1435     }
1436 
1437     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1438 
1439     // Add any operands of the new node which have not yet been combined to the
1440     // worklist as well. Because the worklist uniques things already, this
1441     // won't repeatedly process the same operand.
1442     CombinedNodes.insert(N);
1443     for (const SDValue &ChildN : N->op_values())
1444       if (!CombinedNodes.count(ChildN.getNode()))
1445         AddToWorklist(ChildN.getNode());
1446 
1447     SDValue RV = combine(N);
1448 
1449     if (!RV.getNode())
1450       continue;
1451 
1452     ++NodesCombined;
1453 
1454     // If we get back the same node we passed in, rather than a new node or
1455     // zero, we know that the node must have defined multiple values and
1456     // CombineTo was used.  Since CombineTo takes care of the worklist
1457     // mechanics for us, we have no work to do in this case.
1458     if (RV.getNode() == N)
1459       continue;
1460 
1461     assert(N->getOpcode() != ISD::DELETED_NODE &&
1462            RV.getOpcode() != ISD::DELETED_NODE &&
1463            "Node was deleted but visit returned new node!");
1464 
1465     DEBUG(dbgs() << " ... into: ";
1466           RV.getNode()->dump(&DAG));
1467 
1468     if (N->getNumValues() == RV.getNode()->getNumValues())
1469       DAG.ReplaceAllUsesWith(N, RV.getNode());
1470     else {
1471       assert(N->getValueType(0) == RV.getValueType() &&
1472              N->getNumValues() == 1 && "Type mismatch");
1473       DAG.ReplaceAllUsesWith(N, &RV);
1474     }
1475 
1476     // Push the new node and any users onto the worklist
1477     AddToWorklist(RV.getNode());
1478     AddUsersToWorklist(RV.getNode());
1479 
1480     // Finally, if the node is now dead, remove it from the graph.  The node
1481     // may not be dead if the replacement process recursively simplified to
1482     // something else needing this node. This will also take care of adding any
1483     // operands which have lost a user to the worklist.
1484     recursivelyDeleteUnusedNodes(N);
1485   }
1486 
1487   // If the root changed (e.g. it was a dead load, update the root).
1488   DAG.setRoot(Dummy.getValue());
1489   DAG.RemoveDeadNodes();
1490 }
1491 
1492 SDValue DAGCombiner::visit(SDNode *N) {
1493   switch (N->getOpcode()) {
1494   default: break;
1495   case ISD::TokenFactor:        return visitTokenFactor(N);
1496   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1497   case ISD::ADD:                return visitADD(N);
1498   case ISD::SUB:                return visitSUB(N);
1499   case ISD::ADDC:               return visitADDC(N);
1500   case ISD::UADDO:              return visitUADDO(N);
1501   case ISD::SUBC:               return visitSUBC(N);
1502   case ISD::USUBO:              return visitUSUBO(N);
1503   case ISD::ADDE:               return visitADDE(N);
1504   case ISD::ADDCARRY:           return visitADDCARRY(N);
1505   case ISD::SUBE:               return visitSUBE(N);
1506   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1507   case ISD::MUL:                return visitMUL(N);
1508   case ISD::SDIV:               return visitSDIV(N);
1509   case ISD::UDIV:               return visitUDIV(N);
1510   case ISD::SREM:
1511   case ISD::UREM:               return visitREM(N);
1512   case ISD::MULHU:              return visitMULHU(N);
1513   case ISD::MULHS:              return visitMULHS(N);
1514   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1515   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1516   case ISD::SMULO:              return visitSMULO(N);
1517   case ISD::UMULO:              return visitUMULO(N);
1518   case ISD::SMIN:
1519   case ISD::SMAX:
1520   case ISD::UMIN:
1521   case ISD::UMAX:               return visitIMINMAX(N);
1522   case ISD::AND:                return visitAND(N);
1523   case ISD::OR:                 return visitOR(N);
1524   case ISD::XOR:                return visitXOR(N);
1525   case ISD::SHL:                return visitSHL(N);
1526   case ISD::SRA:                return visitSRA(N);
1527   case ISD::SRL:                return visitSRL(N);
1528   case ISD::ROTR:
1529   case ISD::ROTL:               return visitRotate(N);
1530   case ISD::ABS:                return visitABS(N);
1531   case ISD::BSWAP:              return visitBSWAP(N);
1532   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1533   case ISD::CTLZ:               return visitCTLZ(N);
1534   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1535   case ISD::CTTZ:               return visitCTTZ(N);
1536   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1537   case ISD::CTPOP:              return visitCTPOP(N);
1538   case ISD::SELECT:             return visitSELECT(N);
1539   case ISD::VSELECT:            return visitVSELECT(N);
1540   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1541   case ISD::SETCC:              return visitSETCC(N);
1542   case ISD::SETCCE:             return visitSETCCE(N);
1543   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1544   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1545   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1546   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1547   case ISD::AssertSext:
1548   case ISD::AssertZext:         return visitAssertExt(N);
1549   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1550   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1551   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1552   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1553   case ISD::BITCAST:            return visitBITCAST(N);
1554   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1555   case ISD::FADD:               return visitFADD(N);
1556   case ISD::FSUB:               return visitFSUB(N);
1557   case ISD::FMUL:               return visitFMUL(N);
1558   case ISD::FMA:                return visitFMA(N);
1559   case ISD::FDIV:               return visitFDIV(N);
1560   case ISD::FREM:               return visitFREM(N);
1561   case ISD::FSQRT:              return visitFSQRT(N);
1562   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1563   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1564   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1565   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1566   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1567   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1568   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1569   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1570   case ISD::FNEG:               return visitFNEG(N);
1571   case ISD::FABS:               return visitFABS(N);
1572   case ISD::FFLOOR:             return visitFFLOOR(N);
1573   case ISD::FMINNUM:            return visitFMINNUM(N);
1574   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1575   case ISD::FCEIL:              return visitFCEIL(N);
1576   case ISD::FTRUNC:             return visitFTRUNC(N);
1577   case ISD::BRCOND:             return visitBRCOND(N);
1578   case ISD::BR_CC:              return visitBR_CC(N);
1579   case ISD::LOAD:               return visitLOAD(N);
1580   case ISD::STORE:              return visitSTORE(N);
1581   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1582   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1583   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1584   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1585   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1586   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1587   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1588   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1589   case ISD::MGATHER:            return visitMGATHER(N);
1590   case ISD::MLOAD:              return visitMLOAD(N);
1591   case ISD::MSCATTER:           return visitMSCATTER(N);
1592   case ISD::MSTORE:             return visitMSTORE(N);
1593   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1594   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1595   }
1596   return SDValue();
1597 }
1598 
1599 SDValue DAGCombiner::combine(SDNode *N) {
1600   SDValue RV = visit(N);
1601 
1602   // If nothing happened, try a target-specific DAG combine.
1603   if (!RV.getNode()) {
1604     assert(N->getOpcode() != ISD::DELETED_NODE &&
1605            "Node was deleted but visit returned NULL!");
1606 
1607     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1608         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1609 
1610       // Expose the DAG combiner to the target combiner impls.
1611       TargetLowering::DAGCombinerInfo
1612         DagCombineInfo(DAG, Level, false, this);
1613 
1614       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1615     }
1616   }
1617 
1618   // If nothing happened still, try promoting the operation.
1619   if (!RV.getNode()) {
1620     switch (N->getOpcode()) {
1621     default: break;
1622     case ISD::ADD:
1623     case ISD::SUB:
1624     case ISD::MUL:
1625     case ISD::AND:
1626     case ISD::OR:
1627     case ISD::XOR:
1628       RV = PromoteIntBinOp(SDValue(N, 0));
1629       break;
1630     case ISD::SHL:
1631     case ISD::SRA:
1632     case ISD::SRL:
1633       RV = PromoteIntShiftOp(SDValue(N, 0));
1634       break;
1635     case ISD::SIGN_EXTEND:
1636     case ISD::ZERO_EXTEND:
1637     case ISD::ANY_EXTEND:
1638       RV = PromoteExtend(SDValue(N, 0));
1639       break;
1640     case ISD::LOAD:
1641       if (PromoteLoad(SDValue(N, 0)))
1642         RV = SDValue(N, 0);
1643       break;
1644     }
1645   }
1646 
1647   // If N is a commutative binary node, try eliminate it if the commuted
1648   // version is already present in the DAG.
1649   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1650       N->getNumValues() == 1) {
1651     SDValue N0 = N->getOperand(0);
1652     SDValue N1 = N->getOperand(1);
1653 
1654     // Constant operands are canonicalized to RHS.
1655     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1656       SDValue Ops[] = {N1, N0};
1657       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1658                                             N->getFlags());
1659       if (CSENode)
1660         return SDValue(CSENode, 0);
1661     }
1662   }
1663 
1664   return RV;
1665 }
1666 
1667 /// Given a node, return its input chain if it has one, otherwise return a null
1668 /// sd operand.
1669 static SDValue getInputChainForNode(SDNode *N) {
1670   if (unsigned NumOps = N->getNumOperands()) {
1671     if (N->getOperand(0).getValueType() == MVT::Other)
1672       return N->getOperand(0);
1673     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1674       return N->getOperand(NumOps-1);
1675     for (unsigned i = 1; i < NumOps-1; ++i)
1676       if (N->getOperand(i).getValueType() == MVT::Other)
1677         return N->getOperand(i);
1678   }
1679   return SDValue();
1680 }
1681 
1682 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1683   // If N has two operands, where one has an input chain equal to the other,
1684   // the 'other' chain is redundant.
1685   if (N->getNumOperands() == 2) {
1686     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1687       return N->getOperand(0);
1688     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1689       return N->getOperand(1);
1690   }
1691 
1692   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1693   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1694   SmallPtrSet<SDNode*, 16> SeenOps;
1695   bool Changed = false;             // If we should replace this token factor.
1696 
1697   // Start out with this token factor.
1698   TFs.push_back(N);
1699 
1700   // Iterate through token factors.  The TFs grows when new token factors are
1701   // encountered.
1702   for (unsigned i = 0; i < TFs.size(); ++i) {
1703     SDNode *TF = TFs[i];
1704 
1705     // Check each of the operands.
1706     for (const SDValue &Op : TF->op_values()) {
1707       switch (Op.getOpcode()) {
1708       case ISD::EntryToken:
1709         // Entry tokens don't need to be added to the list. They are
1710         // redundant.
1711         Changed = true;
1712         break;
1713 
1714       case ISD::TokenFactor:
1715         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1716           // Queue up for processing.
1717           TFs.push_back(Op.getNode());
1718           // Clean up in case the token factor is removed.
1719           AddToWorklist(Op.getNode());
1720           Changed = true;
1721           break;
1722         }
1723         LLVM_FALLTHROUGH;
1724 
1725       default:
1726         // Only add if it isn't already in the list.
1727         if (SeenOps.insert(Op.getNode()).second)
1728           Ops.push_back(Op);
1729         else
1730           Changed = true;
1731         break;
1732       }
1733     }
1734   }
1735 
1736   // Remove Nodes that are chained to another node in the list. Do so
1737   // by walking up chains breath-first stopping when we've seen
1738   // another operand. In general we must climb to the EntryNode, but we can exit
1739   // early if we find all remaining work is associated with just one operand as
1740   // no further pruning is possible.
1741 
1742   // List of nodes to search through and original Ops from which they originate.
1743   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1744   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1745   SmallPtrSet<SDNode *, 16> SeenChains;
1746   bool DidPruneOps = false;
1747 
1748   unsigned NumLeftToConsider = 0;
1749   for (const SDValue &Op : Ops) {
1750     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1751     OpWorkCount.push_back(1);
1752   }
1753 
1754   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1755     // If this is an Op, we can remove the op from the list. Remark any
1756     // search associated with it as from the current OpNumber.
1757     if (SeenOps.count(Op) != 0) {
1758       Changed = true;
1759       DidPruneOps = true;
1760       unsigned OrigOpNumber = 0;
1761       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1762         OrigOpNumber++;
1763       assert((OrigOpNumber != Ops.size()) &&
1764              "expected to find TokenFactor Operand");
1765       // Re-mark worklist from OrigOpNumber to OpNumber
1766       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1767         if (Worklist[i].second == OrigOpNumber) {
1768           Worklist[i].second = OpNumber;
1769         }
1770       }
1771       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1772       OpWorkCount[OrigOpNumber] = 0;
1773       NumLeftToConsider--;
1774     }
1775     // Add if it's a new chain
1776     if (SeenChains.insert(Op).second) {
1777       OpWorkCount[OpNumber]++;
1778       Worklist.push_back(std::make_pair(Op, OpNumber));
1779     }
1780   };
1781 
1782   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1783     // We need at least be consider at least 2 Ops to prune.
1784     if (NumLeftToConsider <= 1)
1785       break;
1786     auto CurNode = Worklist[i].first;
1787     auto CurOpNumber = Worklist[i].second;
1788     assert((OpWorkCount[CurOpNumber] > 0) &&
1789            "Node should not appear in worklist");
1790     switch (CurNode->getOpcode()) {
1791     case ISD::EntryToken:
1792       // Hitting EntryToken is the only way for the search to terminate without
1793       // hitting
1794       // another operand's search. Prevent us from marking this operand
1795       // considered.
1796       NumLeftToConsider++;
1797       break;
1798     case ISD::TokenFactor:
1799       for (const SDValue &Op : CurNode->op_values())
1800         AddToWorklist(i, Op.getNode(), CurOpNumber);
1801       break;
1802     case ISD::CopyFromReg:
1803     case ISD::CopyToReg:
1804       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1805       break;
1806     default:
1807       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1808         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1809       break;
1810     }
1811     OpWorkCount[CurOpNumber]--;
1812     if (OpWorkCount[CurOpNumber] == 0)
1813       NumLeftToConsider--;
1814   }
1815 
1816   // If we've changed things around then replace token factor.
1817   if (Changed) {
1818     SDValue Result;
1819     if (Ops.empty()) {
1820       // The entry token is the only possible outcome.
1821       Result = DAG.getEntryNode();
1822     } else {
1823       if (DidPruneOps) {
1824         SmallVector<SDValue, 8> PrunedOps;
1825         //
1826         for (const SDValue &Op : Ops) {
1827           if (SeenChains.count(Op.getNode()) == 0)
1828             PrunedOps.push_back(Op);
1829         }
1830         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1831       } else {
1832         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1833       }
1834     }
1835     return Result;
1836   }
1837   return SDValue();
1838 }
1839 
1840 /// MERGE_VALUES can always be eliminated.
1841 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1842   WorklistRemover DeadNodes(*this);
1843   // Replacing results may cause a different MERGE_VALUES to suddenly
1844   // be CSE'd with N, and carry its uses with it. Iterate until no
1845   // uses remain, to ensure that the node can be safely deleted.
1846   // First add the users of this node to the work list so that they
1847   // can be tried again once they have new operands.
1848   AddUsersToWorklist(N);
1849   do {
1850     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1851       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1852   } while (!N->use_empty());
1853   deleteAndRecombine(N);
1854   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1855 }
1856 
1857 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1858 /// ConstantSDNode pointer else nullptr.
1859 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1860   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1861   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1862 }
1863 
1864 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1865   auto BinOpcode = BO->getOpcode();
1866   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1867           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1868           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1869           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1870           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1871           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1872           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1873           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1874           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1875          "Unexpected binary operator");
1876 
1877   // Bail out if any constants are opaque because we can't constant fold those.
1878   SDValue C1 = BO->getOperand(1);
1879   if (!isConstantOrConstantVector(C1, true) &&
1880       !isConstantFPBuildVectorOrConstantFP(C1))
1881     return SDValue();
1882 
1883   // Don't do this unless the old select is going away. We want to eliminate the
1884   // binary operator, not replace a binop with a select.
1885   // TODO: Handle ISD::SELECT_CC.
1886   SDValue Sel = BO->getOperand(0);
1887   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1888     return SDValue();
1889 
1890   SDValue CT = Sel.getOperand(1);
1891   if (!isConstantOrConstantVector(CT, true) &&
1892       !isConstantFPBuildVectorOrConstantFP(CT))
1893     return SDValue();
1894 
1895   SDValue CF = Sel.getOperand(2);
1896   if (!isConstantOrConstantVector(CF, true) &&
1897       !isConstantFPBuildVectorOrConstantFP(CF))
1898     return SDValue();
1899 
1900   // We have a select-of-constants followed by a binary operator with a
1901   // constant. Eliminate the binop by pulling the constant math into the select.
1902   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1903   EVT VT = Sel.getValueType();
1904   SDLoc DL(Sel);
1905   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1906   if (!NewCT.isUndef() &&
1907       !isConstantOrConstantVector(NewCT, true) &&
1908       !isConstantFPBuildVectorOrConstantFP(NewCT))
1909     return SDValue();
1910 
1911   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1912   if (!NewCF.isUndef() &&
1913       !isConstantOrConstantVector(NewCF, true) &&
1914       !isConstantFPBuildVectorOrConstantFP(NewCF))
1915     return SDValue();
1916 
1917   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1918 }
1919 
1920 SDValue DAGCombiner::visitADD(SDNode *N) {
1921   SDValue N0 = N->getOperand(0);
1922   SDValue N1 = N->getOperand(1);
1923   EVT VT = N0.getValueType();
1924   SDLoc DL(N);
1925 
1926   // fold vector ops
1927   if (VT.isVector()) {
1928     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1929       return FoldedVOp;
1930 
1931     // fold (add x, 0) -> x, vector edition
1932     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1933       return N0;
1934     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1935       return N1;
1936   }
1937 
1938   // fold (add x, undef) -> undef
1939   if (N0.isUndef())
1940     return N0;
1941 
1942   if (N1.isUndef())
1943     return N1;
1944 
1945   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1946     // canonicalize constant to RHS
1947     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1948       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1949     // fold (add c1, c2) -> c1+c2
1950     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1951                                       N1.getNode());
1952   }
1953 
1954   // fold (add x, 0) -> x
1955   if (isNullConstant(N1))
1956     return N0;
1957 
1958   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1959     // fold ((c1-A)+c2) -> (c1+c2)-A
1960     if (N0.getOpcode() == ISD::SUB &&
1961         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1962       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1963       return DAG.getNode(ISD::SUB, DL, VT,
1964                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1965                          N0.getOperand(1));
1966     }
1967 
1968     // add (sext i1 X), 1 -> zext (not i1 X)
1969     // We don't transform this pattern:
1970     //   add (zext i1 X), -1 -> sext (not i1 X)
1971     // because most (?) targets generate better code for the zext form.
1972     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1973         isOneConstantOrOneSplatConstant(N1)) {
1974       SDValue X = N0.getOperand(0);
1975       if ((!LegalOperations ||
1976            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1977             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1978           X.getScalarValueSizeInBits() == 1) {
1979         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1980         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1981       }
1982     }
1983 
1984     // Undo the add -> or combine to merge constant offsets from a frame index.
1985     if (N0.getOpcode() == ISD::OR &&
1986         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
1987         isa<ConstantSDNode>(N0.getOperand(1)) &&
1988         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
1989       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
1990       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
1991     }
1992   }
1993 
1994   if (SDValue NewSel = foldBinOpIntoSelect(N))
1995     return NewSel;
1996 
1997   // reassociate add
1998   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1999     return RADD;
2000 
2001   // fold ((0-A) + B) -> B-A
2002   if (N0.getOpcode() == ISD::SUB &&
2003       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2004     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2005 
2006   // fold (A + (0-B)) -> A-B
2007   if (N1.getOpcode() == ISD::SUB &&
2008       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2009     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2010 
2011   // fold (A+(B-A)) -> B
2012   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2013     return N1.getOperand(0);
2014 
2015   // fold ((B-A)+A) -> B
2016   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2017     return N0.getOperand(0);
2018 
2019   // fold (A+(B-(A+C))) to (B-C)
2020   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2021       N0 == N1.getOperand(1).getOperand(0))
2022     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2023                        N1.getOperand(1).getOperand(1));
2024 
2025   // fold (A+(B-(C+A))) to (B-C)
2026   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2027       N0 == N1.getOperand(1).getOperand(1))
2028     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2029                        N1.getOperand(1).getOperand(0));
2030 
2031   // fold (A+((B-A)+or-C)) to (B+or-C)
2032   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2033       N1.getOperand(0).getOpcode() == ISD::SUB &&
2034       N0 == N1.getOperand(0).getOperand(1))
2035     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2036                        N1.getOperand(1));
2037 
2038   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2039   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2040     SDValue N00 = N0.getOperand(0);
2041     SDValue N01 = N0.getOperand(1);
2042     SDValue N10 = N1.getOperand(0);
2043     SDValue N11 = N1.getOperand(1);
2044 
2045     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2046       return DAG.getNode(ISD::SUB, DL, VT,
2047                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2048                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2049   }
2050 
2051   if (SimplifyDemandedBits(SDValue(N, 0)))
2052     return SDValue(N, 0);
2053 
2054   // fold (a+b) -> (a|b) iff a and b share no bits.
2055   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2056       DAG.haveNoCommonBitsSet(N0, N1))
2057     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2058 
2059   if (SDValue Combined = visitADDLike(N0, N1, N))
2060     return Combined;
2061 
2062   if (SDValue Combined = visitADDLike(N1, N0, N))
2063     return Combined;
2064 
2065   return SDValue();
2066 }
2067 
2068 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2069   bool Masked = false;
2070 
2071   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2072   while (true) {
2073     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2074       V = V.getOperand(0);
2075       continue;
2076     }
2077 
2078     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2079       Masked = true;
2080       V = V.getOperand(0);
2081       continue;
2082     }
2083 
2084     break;
2085   }
2086 
2087   // If this is not a carry, return.
2088   if (V.getResNo() != 1)
2089     return SDValue();
2090 
2091   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2092       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2093     return SDValue();
2094 
2095   // If the result is masked, then no matter what kind of bool it is we can
2096   // return. If it isn't, then we need to make sure the bool type is either 0 or
2097   // 1 and not other values.
2098   if (Masked ||
2099       TLI.getBooleanContents(V.getValueType()) ==
2100           TargetLoweringBase::ZeroOrOneBooleanContent)
2101     return V;
2102 
2103   return SDValue();
2104 }
2105 
2106 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2107   EVT VT = N0.getValueType();
2108   SDLoc DL(LocReference);
2109 
2110   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2111   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2112       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2113     return DAG.getNode(ISD::SUB, DL, VT, N0,
2114                        DAG.getNode(ISD::SHL, DL, VT,
2115                                    N1.getOperand(0).getOperand(1),
2116                                    N1.getOperand(1)));
2117 
2118   if (N1.getOpcode() == ISD::AND) {
2119     SDValue AndOp0 = N1.getOperand(0);
2120     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2121     unsigned DestBits = VT.getScalarSizeInBits();
2122 
2123     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2124     // and similar xforms where the inner op is either ~0 or 0.
2125     if (NumSignBits == DestBits &&
2126         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2127       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2128   }
2129 
2130   // add (sext i1), X -> sub X, (zext i1)
2131   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2132       N0.getOperand(0).getValueType() == MVT::i1 &&
2133       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2134     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2135     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2136   }
2137 
2138   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2139   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2140     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2141     if (TN->getVT() == MVT::i1) {
2142       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2143                                  DAG.getConstant(1, DL, VT));
2144       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2145     }
2146   }
2147 
2148   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2149   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2150       N1.getResNo() == 0)
2151     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2152                        N0, N1.getOperand(0), N1.getOperand(2));
2153 
2154   // (add X, Carry) -> (addcarry X, 0, Carry)
2155   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2156     if (SDValue Carry = getAsCarry(TLI, N1))
2157       return DAG.getNode(ISD::ADDCARRY, DL,
2158                          DAG.getVTList(VT, Carry.getValueType()), N0,
2159                          DAG.getConstant(0, DL, VT), Carry);
2160 
2161   return SDValue();
2162 }
2163 
2164 SDValue DAGCombiner::visitADDC(SDNode *N) {
2165   SDValue N0 = N->getOperand(0);
2166   SDValue N1 = N->getOperand(1);
2167   EVT VT = N0.getValueType();
2168   SDLoc DL(N);
2169 
2170   // If the flag result is dead, turn this into an ADD.
2171   if (!N->hasAnyUseOfValue(1))
2172     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2173                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2174 
2175   // canonicalize constant to RHS.
2176   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2177   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2178   if (N0C && !N1C)
2179     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2180 
2181   // fold (addc x, 0) -> x + no carry out
2182   if (isNullConstant(N1))
2183     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2184                                         DL, MVT::Glue));
2185 
2186   // If it cannot overflow, transform into an add.
2187   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2188     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2189                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2190 
2191   return SDValue();
2192 }
2193 
2194 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2195   SDValue N0 = N->getOperand(0);
2196   SDValue N1 = N->getOperand(1);
2197   EVT VT = N0.getValueType();
2198   if (VT.isVector())
2199     return SDValue();
2200 
2201   EVT CarryVT = N->getValueType(1);
2202   SDLoc DL(N);
2203 
2204   // If the flag result is dead, turn this into an ADD.
2205   if (!N->hasAnyUseOfValue(1))
2206     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2207                      DAG.getUNDEF(CarryVT));
2208 
2209   // canonicalize constant to RHS.
2210   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2211   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2212   if (N0C && !N1C)
2213     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2214 
2215   // fold (uaddo x, 0) -> x + no carry out
2216   if (isNullConstant(N1))
2217     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2218 
2219   // If it cannot overflow, transform into an add.
2220   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2221     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2222                      DAG.getConstant(0, DL, CarryVT));
2223 
2224   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2225     return Combined;
2226 
2227   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2228     return Combined;
2229 
2230   return SDValue();
2231 }
2232 
2233 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2234   auto VT = N0.getValueType();
2235 
2236   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2237   // If Y + 1 cannot overflow.
2238   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2239     SDValue Y = N1.getOperand(0);
2240     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2241     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2242       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2243                          N1.getOperand(2));
2244   }
2245 
2246   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2247   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2248     if (SDValue Carry = getAsCarry(TLI, N1))
2249       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2250                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2251 
2252   return SDValue();
2253 }
2254 
2255 SDValue DAGCombiner::visitADDE(SDNode *N) {
2256   SDValue N0 = N->getOperand(0);
2257   SDValue N1 = N->getOperand(1);
2258   SDValue CarryIn = N->getOperand(2);
2259 
2260   // canonicalize constant to RHS
2261   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2262   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2263   if (N0C && !N1C)
2264     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2265                        N1, N0, CarryIn);
2266 
2267   // fold (adde x, y, false) -> (addc x, y)
2268   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2269     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2270 
2271   return SDValue();
2272 }
2273 
2274 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2275   SDValue N0 = N->getOperand(0);
2276   SDValue N1 = N->getOperand(1);
2277   SDValue CarryIn = N->getOperand(2);
2278   SDLoc DL(N);
2279 
2280   // canonicalize constant to RHS
2281   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2282   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2283   if (N0C && !N1C)
2284     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2285 
2286   // fold (addcarry x, y, false) -> (uaddo x, y)
2287   if (isNullConstant(CarryIn))
2288     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2289 
2290   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2291   if (isNullConstant(N0) && isNullConstant(N1)) {
2292     EVT VT = N0.getValueType();
2293     EVT CarryVT = CarryIn.getValueType();
2294     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2295     AddToWorklist(CarryExt.getNode());
2296     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2297                                     DAG.getConstant(1, DL, VT)),
2298                      DAG.getConstant(0, DL, CarryVT));
2299   }
2300 
2301   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2302     return Combined;
2303 
2304   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2305     return Combined;
2306 
2307   return SDValue();
2308 }
2309 
2310 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2311                                        SDNode *N) {
2312   // Iff the flag result is dead:
2313   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2314   if ((N0.getOpcode() == ISD::ADD ||
2315        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2316       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2317     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2318                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2319 
2320   /**
2321    * When one of the addcarry argument is itself a carry, we may be facing
2322    * a diamond carry propagation. In which case we try to transform the DAG
2323    * to ensure linear carry propagation if that is possible.
2324    *
2325    * We are trying to get:
2326    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2327    */
2328   if (auto Y = getAsCarry(TLI, N1)) {
2329     /**
2330      *            (uaddo A, B)
2331      *             /       \
2332      *          Carry      Sum
2333      *            |          \
2334      *            | (addcarry *, 0, Z)
2335      *            |       /
2336      *             \   Carry
2337      *              |   /
2338      * (addcarry X, *, *)
2339      */
2340     if (Y.getOpcode() == ISD::UADDO &&
2341         CarryIn.getResNo() == 1 &&
2342         CarryIn.getOpcode() == ISD::ADDCARRY &&
2343         isNullConstant(CarryIn.getOperand(1)) &&
2344         CarryIn.getOperand(0) == Y.getValue(0)) {
2345       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2346                               Y.getOperand(0), Y.getOperand(1),
2347                               CarryIn.getOperand(2));
2348       AddToWorklist(NewY.getNode());
2349       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2350                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2351                          NewY.getValue(1));
2352     }
2353   }
2354 
2355   return SDValue();
2356 }
2357 
2358 // Since it may not be valid to emit a fold to zero for vector initializers
2359 // check if we can before folding.
2360 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2361                              SelectionDAG &DAG, bool LegalOperations,
2362                              bool LegalTypes) {
2363   if (!VT.isVector())
2364     return DAG.getConstant(0, DL, VT);
2365   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2366     return DAG.getConstant(0, DL, VT);
2367   return SDValue();
2368 }
2369 
2370 SDValue DAGCombiner::visitSUB(SDNode *N) {
2371   SDValue N0 = N->getOperand(0);
2372   SDValue N1 = N->getOperand(1);
2373   EVT VT = N0.getValueType();
2374   SDLoc DL(N);
2375 
2376   // fold vector ops
2377   if (VT.isVector()) {
2378     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2379       return FoldedVOp;
2380 
2381     // fold (sub x, 0) -> x, vector edition
2382     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2383       return N0;
2384   }
2385 
2386   // fold (sub x, x) -> 0
2387   // FIXME: Refactor this and xor and other similar operations together.
2388   if (N0 == N1)
2389     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2390   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2391       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2392     // fold (sub c1, c2) -> c1-c2
2393     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2394                                       N1.getNode());
2395   }
2396 
2397   if (SDValue NewSel = foldBinOpIntoSelect(N))
2398     return NewSel;
2399 
2400   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2401 
2402   // fold (sub x, c) -> (add x, -c)
2403   if (N1C) {
2404     return DAG.getNode(ISD::ADD, DL, VT, N0,
2405                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2406   }
2407 
2408   if (isNullConstantOrNullSplatConstant(N0)) {
2409     unsigned BitWidth = VT.getScalarSizeInBits();
2410     // Right-shifting everything out but the sign bit followed by negation is
2411     // the same as flipping arithmetic/logical shift type without the negation:
2412     // -(X >>u 31) -> (X >>s 31)
2413     // -(X >>s 31) -> (X >>u 31)
2414     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2415       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2416       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2417         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2418         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2419           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2420       }
2421     }
2422 
2423     // 0 - X --> 0 if the sub is NUW.
2424     if (N->getFlags().hasNoUnsignedWrap())
2425       return N0;
2426 
2427     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2428       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2429       // N1 must be 0 because negating the minimum signed value is undefined.
2430       if (N->getFlags().hasNoSignedWrap())
2431         return N0;
2432 
2433       // 0 - X --> X if X is 0 or the minimum signed value.
2434       return N1;
2435     }
2436   }
2437 
2438   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2439   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2440     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2441 
2442   // fold A-(A-B) -> B
2443   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2444     return N1.getOperand(1);
2445 
2446   // fold (A+B)-A -> B
2447   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2448     return N0.getOperand(1);
2449 
2450   // fold (A+B)-B -> A
2451   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2452     return N0.getOperand(0);
2453 
2454   // fold C2-(A+C1) -> (C2-C1)-A
2455   if (N1.getOpcode() == ISD::ADD) {
2456     SDValue N11 = N1.getOperand(1);
2457     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2458         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2459       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2460       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2461     }
2462   }
2463 
2464   // fold ((A+(B+or-C))-B) -> A+or-C
2465   if (N0.getOpcode() == ISD::ADD &&
2466       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2467        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2468       N0.getOperand(1).getOperand(0) == N1)
2469     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2470                        N0.getOperand(1).getOperand(1));
2471 
2472   // fold ((A+(C+B))-B) -> A+C
2473   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2474       N0.getOperand(1).getOperand(1) == N1)
2475     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2476                        N0.getOperand(1).getOperand(0));
2477 
2478   // fold ((A-(B-C))-C) -> A-B
2479   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2480       N0.getOperand(1).getOperand(1) == N1)
2481     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2482                        N0.getOperand(1).getOperand(0));
2483 
2484   // If either operand of a sub is undef, the result is undef
2485   if (N0.isUndef())
2486     return N0;
2487   if (N1.isUndef())
2488     return N1;
2489 
2490   // If the relocation model supports it, consider symbol offsets.
2491   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2492     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2493       // fold (sub Sym, c) -> Sym-c
2494       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2495         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2496                                     GA->getOffset() -
2497                                         (uint64_t)N1C->getSExtValue());
2498       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2499       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2500         if (GA->getGlobal() == GB->getGlobal())
2501           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2502                                  DL, VT);
2503     }
2504 
2505   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2506   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2507     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2508     if (TN->getVT() == MVT::i1) {
2509       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2510                                  DAG.getConstant(1, DL, VT));
2511       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2512     }
2513   }
2514 
2515   return SDValue();
2516 }
2517 
2518 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2519   SDValue N0 = N->getOperand(0);
2520   SDValue N1 = N->getOperand(1);
2521   EVT VT = N0.getValueType();
2522   SDLoc DL(N);
2523 
2524   // If the flag result is dead, turn this into an SUB.
2525   if (!N->hasAnyUseOfValue(1))
2526     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2527                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2528 
2529   // fold (subc x, x) -> 0 + no borrow
2530   if (N0 == N1)
2531     return CombineTo(N, DAG.getConstant(0, DL, VT),
2532                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2533 
2534   // fold (subc x, 0) -> x + no borrow
2535   if (isNullConstant(N1))
2536     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2537 
2538   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2539   if (isAllOnesConstant(N0))
2540     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2541                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2542 
2543   return SDValue();
2544 }
2545 
2546 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2547   SDValue N0 = N->getOperand(0);
2548   SDValue N1 = N->getOperand(1);
2549   EVT VT = N0.getValueType();
2550   if (VT.isVector())
2551     return SDValue();
2552 
2553   EVT CarryVT = N->getValueType(1);
2554   SDLoc DL(N);
2555 
2556   // If the flag result is dead, turn this into an SUB.
2557   if (!N->hasAnyUseOfValue(1))
2558     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2559                      DAG.getUNDEF(CarryVT));
2560 
2561   // fold (usubo x, x) -> 0 + no borrow
2562   if (N0 == N1)
2563     return CombineTo(N, DAG.getConstant(0, DL, VT),
2564                      DAG.getConstant(0, DL, CarryVT));
2565 
2566   // fold (usubo x, 0) -> x + no borrow
2567   if (isNullConstant(N1))
2568     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2569 
2570   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2571   if (isAllOnesConstant(N0))
2572     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2573                      DAG.getConstant(0, DL, CarryVT));
2574 
2575   return SDValue();
2576 }
2577 
2578 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2579   SDValue N0 = N->getOperand(0);
2580   SDValue N1 = N->getOperand(1);
2581   SDValue CarryIn = N->getOperand(2);
2582 
2583   // fold (sube x, y, false) -> (subc x, y)
2584   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2585     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2586 
2587   return SDValue();
2588 }
2589 
2590 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2591   SDValue N0 = N->getOperand(0);
2592   SDValue N1 = N->getOperand(1);
2593   SDValue CarryIn = N->getOperand(2);
2594 
2595   // fold (subcarry x, y, false) -> (usubo x, y)
2596   if (isNullConstant(CarryIn))
2597     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2598 
2599   return SDValue();
2600 }
2601 
2602 SDValue DAGCombiner::visitMUL(SDNode *N) {
2603   SDValue N0 = N->getOperand(0);
2604   SDValue N1 = N->getOperand(1);
2605   EVT VT = N0.getValueType();
2606 
2607   // fold (mul x, undef) -> 0
2608   if (N0.isUndef() || N1.isUndef())
2609     return DAG.getConstant(0, SDLoc(N), VT);
2610 
2611   bool N0IsConst = false;
2612   bool N1IsConst = false;
2613   bool N1IsOpaqueConst = false;
2614   bool N0IsOpaqueConst = false;
2615   APInt ConstValue0, ConstValue1;
2616   // fold vector ops
2617   if (VT.isVector()) {
2618     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2619       return FoldedVOp;
2620 
2621     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2622     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2623     assert((!N0IsConst ||
2624             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2625            "Splat APInt should be element width");
2626     assert((!N1IsConst ||
2627             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2628            "Splat APInt should be element width");
2629   } else {
2630     N0IsConst = isa<ConstantSDNode>(N0);
2631     if (N0IsConst) {
2632       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2633       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2634     }
2635     N1IsConst = isa<ConstantSDNode>(N1);
2636     if (N1IsConst) {
2637       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2638       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2639     }
2640   }
2641 
2642   // fold (mul c1, c2) -> c1*c2
2643   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2644     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2645                                       N0.getNode(), N1.getNode());
2646 
2647   // canonicalize constant to RHS (vector doesn't have to splat)
2648   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2649      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2650     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2651   // fold (mul x, 0) -> 0
2652   if (N1IsConst && ConstValue1.isNullValue())
2653     return N1;
2654   // fold (mul x, 1) -> x
2655   if (N1IsConst && ConstValue1.isOneValue())
2656     return N0;
2657 
2658   if (SDValue NewSel = foldBinOpIntoSelect(N))
2659     return NewSel;
2660 
2661   // fold (mul x, -1) -> 0-x
2662   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2663     SDLoc DL(N);
2664     return DAG.getNode(ISD::SUB, DL, VT,
2665                        DAG.getConstant(0, DL, VT), N0);
2666   }
2667   // fold (mul x, (1 << c)) -> x << c
2668   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2669       DAG.isKnownToBeAPowerOfTwo(N1) &&
2670       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2671     SDLoc DL(N);
2672     SDValue LogBase2 = BuildLogBase2(N1, DL);
2673     AddToWorklist(LogBase2.getNode());
2674 
2675     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2676     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2677     AddToWorklist(Trunc.getNode());
2678     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2679   }
2680   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2681   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2682     unsigned Log2Val = (-ConstValue1).logBase2();
2683     SDLoc DL(N);
2684     // FIXME: If the input is something that is easily negated (e.g. a
2685     // single-use add), we should put the negate there.
2686     return DAG.getNode(ISD::SUB, DL, VT,
2687                        DAG.getConstant(0, DL, VT),
2688                        DAG.getNode(ISD::SHL, DL, VT, N0,
2689                             DAG.getConstant(Log2Val, DL,
2690                                       getShiftAmountTy(N0.getValueType()))));
2691   }
2692 
2693   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2694   if (N0.getOpcode() == ISD::SHL &&
2695       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2696       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2697     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2698     if (isConstantOrConstantVector(C3))
2699       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2700   }
2701 
2702   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2703   // use.
2704   {
2705     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2706 
2707     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2708     if (N0.getOpcode() == ISD::SHL &&
2709         isConstantOrConstantVector(N0.getOperand(1)) &&
2710         N0.getNode()->hasOneUse()) {
2711       Sh = N0; Y = N1;
2712     } else if (N1.getOpcode() == ISD::SHL &&
2713                isConstantOrConstantVector(N1.getOperand(1)) &&
2714                N1.getNode()->hasOneUse()) {
2715       Sh = N1; Y = N0;
2716     }
2717 
2718     if (Sh.getNode()) {
2719       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2720       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2721     }
2722   }
2723 
2724   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2725   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2726       N0.getOpcode() == ISD::ADD &&
2727       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2728       isMulAddWithConstProfitable(N, N0, N1))
2729       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2730                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2731                                      N0.getOperand(0), N1),
2732                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2733                                      N0.getOperand(1), N1));
2734 
2735   // reassociate mul
2736   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2737     return RMUL;
2738 
2739   return SDValue();
2740 }
2741 
2742 /// Return true if divmod libcall is available.
2743 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2744                                      const TargetLowering &TLI) {
2745   RTLIB::Libcall LC;
2746   EVT NodeType = Node->getValueType(0);
2747   if (!NodeType.isSimple())
2748     return false;
2749   switch (NodeType.getSimpleVT().SimpleTy) {
2750   default: return false; // No libcall for vector types.
2751   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2752   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2753   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2754   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2755   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2756   }
2757 
2758   return TLI.getLibcallName(LC) != nullptr;
2759 }
2760 
2761 /// Issue divrem if both quotient and remainder are needed.
2762 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2763   if (Node->use_empty())
2764     return SDValue(); // This is a dead node, leave it alone.
2765 
2766   unsigned Opcode = Node->getOpcode();
2767   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2768   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2769 
2770   // DivMod lib calls can still work on non-legal types if using lib-calls.
2771   EVT VT = Node->getValueType(0);
2772   if (VT.isVector() || !VT.isInteger())
2773     return SDValue();
2774 
2775   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2776     return SDValue();
2777 
2778   // If DIVREM is going to get expanded into a libcall,
2779   // but there is no libcall available, then don't combine.
2780   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2781       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2782     return SDValue();
2783 
2784   // If div is legal, it's better to do the normal expansion
2785   unsigned OtherOpcode = 0;
2786   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2787     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2788     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2789       return SDValue();
2790   } else {
2791     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2792     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2793       return SDValue();
2794   }
2795 
2796   SDValue Op0 = Node->getOperand(0);
2797   SDValue Op1 = Node->getOperand(1);
2798   SDValue combined;
2799   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2800          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2801     SDNode *User = *UI;
2802     if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
2803         User->use_empty())
2804       continue;
2805     // Convert the other matching node(s), too;
2806     // otherwise, the DIVREM may get target-legalized into something
2807     // target-specific that we won't be able to recognize.
2808     unsigned UserOpc = User->getOpcode();
2809     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2810         User->getOperand(0) == Op0 &&
2811         User->getOperand(1) == Op1) {
2812       if (!combined) {
2813         if (UserOpc == OtherOpcode) {
2814           SDVTList VTs = DAG.getVTList(VT, VT);
2815           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2816         } else if (UserOpc == DivRemOpc) {
2817           combined = SDValue(User, 0);
2818         } else {
2819           assert(UserOpc == Opcode);
2820           continue;
2821         }
2822       }
2823       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2824         CombineTo(User, combined);
2825       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2826         CombineTo(User, combined.getValue(1));
2827     }
2828   }
2829   return combined;
2830 }
2831 
2832 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2833   SDValue N0 = N->getOperand(0);
2834   SDValue N1 = N->getOperand(1);
2835   EVT VT = N->getValueType(0);
2836   SDLoc DL(N);
2837 
2838   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2839     return DAG.getUNDEF(VT);
2840 
2841   // undef / X -> 0
2842   // undef % X -> 0
2843   if (N0.isUndef())
2844     return DAG.getConstant(0, DL, VT);
2845 
2846   return SDValue();
2847 }
2848 
2849 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2850   SDValue N0 = N->getOperand(0);
2851   SDValue N1 = N->getOperand(1);
2852   EVT VT = N->getValueType(0);
2853 
2854   // fold vector ops
2855   if (VT.isVector())
2856     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2857       return FoldedVOp;
2858 
2859   SDLoc DL(N);
2860 
2861   // fold (sdiv c1, c2) -> c1/c2
2862   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2863   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2864   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2865     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2866   // fold (sdiv X, 1) -> X
2867   if (N1C && N1C->isOne())
2868     return N0;
2869   // fold (sdiv X, -1) -> 0-X
2870   if (N1C && N1C->isAllOnesValue())
2871     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2872 
2873   if (SDValue V = simplifyDivRem(N, DAG))
2874     return V;
2875 
2876   if (SDValue NewSel = foldBinOpIntoSelect(N))
2877     return NewSel;
2878 
2879   // If we know the sign bits of both operands are zero, strength reduce to a
2880   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2881   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2882     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2883 
2884   // Helper for determining whether a value is a power-2 constant scalar or a
2885   // vector of such elements.
2886   SmallBitVector KnownNegatives(
2887       (N1C || !VT.isVector()) ? 1 : VT.getVectorNumElements(), false);
2888   unsigned EltIndex = 0;
2889   auto IsPowerOfTwo = [&KnownNegatives, &EltIndex](ConstantSDNode *C) {
2890     unsigned Idx = EltIndex++;
2891     if (C->isNullValue() || C->isOpaque())
2892       return false;
2893     if (C->getAPIntValue().isPowerOf2())
2894       return true;
2895     if ((-C->getAPIntValue()).isPowerOf2()) {
2896       KnownNegatives.set(Idx);
2897       return true;
2898     }
2899     return false;
2900   };
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 (!N->getFlags().hasExact() &&
2907       ISD::matchUnaryPredicate(N1C ? SDValue(N1C, 0) : N1, IsPowerOfTwo)) {
2908     // Target-specific implementation of sdiv x, pow2.
2909     if (SDValue Res = BuildSDIVPow2(N))
2910       return Res;
2911 
2912     // Create constants that are functions of the shift amount value.
2913     EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
2914     SDValue Bits = DAG.getConstant(VT.getScalarSizeInBits(), DL, ShiftAmtTy);
2915     SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
2916     C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
2917     SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
2918     if (!isConstantOrConstantVector(Inexact))
2919       return SDValue();
2920     // Splat the sign bit into the register
2921     SDValue Sign = DAG.getNode(
2922         ISD::SRA, DL, VT, N0,
2923         DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, ShiftAmtTy));
2924     AddToWorklist(Sign.getNode());
2925 
2926     // Add (N0 < 0) ? abs2 - 1 : 0;
2927     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
2928     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
2929     AddToWorklist(Srl.getNode());
2930     AddToWorklist(Add.getNode()); // Divide by pow2
2931     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
2932 
2933     // If dividing by a positive value, we're done. Otherwise, the result must
2934     // be negated.
2935     if (KnownNegatives.none())
2936       return Sra;
2937 
2938     AddToWorklist(Sra.getNode());
2939     SDValue Sub =
2940         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Sra);
2941     // If all shift amount elements are negative, we're done.
2942     if (KnownNegatives.all())
2943       return Sub;
2944 
2945     // Shift amount has both positive and negative elements.
2946     assert(VT.isVector() && !N0C &&
2947            "Expecting a non-splat vector shift amount");
2948 
2949     SmallVector<SDValue, 64> VSelectMask;
2950     for (int i = 0, e = VT.getVectorNumElements(); i < e; ++i)
2951       VSelectMask.push_back(
2952           DAG.getConstant(KnownNegatives[i] ? -1 : 0, DL, MVT::i1));
2953 
2954     SDValue Mask =
2955         DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i1,
2956                                             VT.getVectorElementCount()),
2957                            DL, VSelectMask);
2958     return DAG.getNode(ISD::VSELECT, DL, VT, Mask, Sub, Sra);
2959   }
2960 
2961   // If integer divide is expensive and we satisfy the requirements, emit an
2962   // alternate sequence.  Targets may check function attributes for size/speed
2963   // trade-offs.
2964   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2965   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2966     if (SDValue Op = BuildSDIV(N))
2967       return Op;
2968 
2969   // sdiv, srem -> sdivrem
2970   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2971   // true.  Otherwise, we break the simplification logic in visitREM().
2972   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2973     if (SDValue DivRem = useDivRem(N))
2974         return DivRem;
2975 
2976   return SDValue();
2977 }
2978 
2979 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2980   SDValue N0 = N->getOperand(0);
2981   SDValue N1 = N->getOperand(1);
2982   EVT VT = N->getValueType(0);
2983 
2984   // fold vector ops
2985   if (VT.isVector())
2986     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2987       return FoldedVOp;
2988 
2989   SDLoc DL(N);
2990 
2991   // fold (udiv c1, c2) -> c1/c2
2992   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2993   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2994   if (N0C && N1C)
2995     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2996                                                     N0C, N1C))
2997       return Folded;
2998 
2999   if (SDValue V = simplifyDivRem(N, DAG))
3000     return V;
3001 
3002   if (SDValue NewSel = foldBinOpIntoSelect(N))
3003     return NewSel;
3004 
3005   // fold (udiv x, (1 << c)) -> x >>u c
3006   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3007       DAG.isKnownToBeAPowerOfTwo(N1)) {
3008     SDValue LogBase2 = BuildLogBase2(N1, DL);
3009     AddToWorklist(LogBase2.getNode());
3010 
3011     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3012     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3013     AddToWorklist(Trunc.getNode());
3014     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3015   }
3016 
3017   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3018   if (N1.getOpcode() == ISD::SHL) {
3019     SDValue N10 = N1.getOperand(0);
3020     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3021         DAG.isKnownToBeAPowerOfTwo(N10)) {
3022       SDValue LogBase2 = BuildLogBase2(N10, DL);
3023       AddToWorklist(LogBase2.getNode());
3024 
3025       EVT ADDVT = N1.getOperand(1).getValueType();
3026       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3027       AddToWorklist(Trunc.getNode());
3028       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3029       AddToWorklist(Add.getNode());
3030       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3031     }
3032   }
3033 
3034   // fold (udiv x, c) -> alternate
3035   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3036   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3037     if (SDValue Op = BuildUDIV(N))
3038       return Op;
3039 
3040   // sdiv, srem -> sdivrem
3041   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3042   // true.  Otherwise, we break the simplification logic in visitREM().
3043   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3044     if (SDValue DivRem = useDivRem(N))
3045         return DivRem;
3046 
3047   return SDValue();
3048 }
3049 
3050 // handles ISD::SREM and ISD::UREM
3051 SDValue DAGCombiner::visitREM(SDNode *N) {
3052   unsigned Opcode = N->getOpcode();
3053   SDValue N0 = N->getOperand(0);
3054   SDValue N1 = N->getOperand(1);
3055   EVT VT = N->getValueType(0);
3056   bool isSigned = (Opcode == ISD::SREM);
3057   SDLoc DL(N);
3058 
3059   // fold (rem c1, c2) -> c1%c2
3060   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3061   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3062   if (N0C && N1C)
3063     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3064       return Folded;
3065 
3066   if (SDValue V = simplifyDivRem(N, DAG))
3067     return V;
3068 
3069   if (SDValue NewSel = foldBinOpIntoSelect(N))
3070     return NewSel;
3071 
3072   if (isSigned) {
3073     // If we know the sign bits of both operands are zero, strength reduce to a
3074     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3075     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3076       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3077   } else {
3078     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3079     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3080       // fold (urem x, pow2) -> (and x, pow2-1)
3081       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3082       AddToWorklist(Add.getNode());
3083       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3084     }
3085     if (N1.getOpcode() == ISD::SHL &&
3086         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3087       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3088       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3089       AddToWorklist(Add.getNode());
3090       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3091     }
3092   }
3093 
3094   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3095 
3096   // If X/C can be simplified by the division-by-constant logic, lower
3097   // X%C to the equivalent of X-X/C*C.
3098   // To avoid mangling nodes, this simplification requires that the combine()
3099   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3100   // against this by skipping the simplification if isIntDivCheap().  When
3101   // div is not cheap, combine will not return a DIVREM.  Regardless,
3102   // checking cheapness here makes sense since the simplification results in
3103   // fatter code.
3104   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3105     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3106     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3107     AddToWorklist(Div.getNode());
3108     SDValue OptimizedDiv = combine(Div.getNode());
3109     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode() &&
3110         OptimizedDiv.getOpcode() != ISD::UDIVREM &&
3111         OptimizedDiv.getOpcode() != ISD::SDIVREM) {
3112       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3113       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3114       AddToWorklist(Mul.getNode());
3115       return Sub;
3116     }
3117   }
3118 
3119   // sdiv, srem -> sdivrem
3120   if (SDValue DivRem = useDivRem(N))
3121     return DivRem.getValue(1);
3122 
3123   return SDValue();
3124 }
3125 
3126 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3127   SDValue N0 = N->getOperand(0);
3128   SDValue N1 = N->getOperand(1);
3129   EVT VT = N->getValueType(0);
3130   SDLoc DL(N);
3131 
3132   if (VT.isVector()) {
3133     // fold (mulhs x, 0) -> 0
3134     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3135       return N1;
3136     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3137       return N0;
3138   }
3139 
3140   // fold (mulhs x, 0) -> 0
3141   if (isNullConstant(N1))
3142     return N1;
3143   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3144   if (isOneConstant(N1))
3145     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3146                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3147                                        getShiftAmountTy(N0.getValueType())));
3148 
3149   // fold (mulhs x, undef) -> 0
3150   if (N0.isUndef() || N1.isUndef())
3151     return DAG.getConstant(0, DL, VT);
3152 
3153   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3154   // plus a shift.
3155   if (VT.isSimple() && !VT.isVector()) {
3156     MVT Simple = VT.getSimpleVT();
3157     unsigned SimpleSize = Simple.getSizeInBits();
3158     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3159     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3160       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3161       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3162       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3163       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3164             DAG.getConstant(SimpleSize, DL,
3165                             getShiftAmountTy(N1.getValueType())));
3166       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3167     }
3168   }
3169 
3170   return SDValue();
3171 }
3172 
3173 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3174   SDValue N0 = N->getOperand(0);
3175   SDValue N1 = N->getOperand(1);
3176   EVT VT = N->getValueType(0);
3177   SDLoc DL(N);
3178 
3179   if (VT.isVector()) {
3180     // fold (mulhu x, 0) -> 0
3181     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3182       return N1;
3183     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3184       return N0;
3185   }
3186 
3187   // fold (mulhu x, 0) -> 0
3188   if (isNullConstant(N1))
3189     return N1;
3190   // fold (mulhu x, 1) -> 0
3191   if (isOneConstant(N1))
3192     return DAG.getConstant(0, DL, N0.getValueType());
3193   // fold (mulhu x, undef) -> 0
3194   if (N0.isUndef() || N1.isUndef())
3195     return DAG.getConstant(0, DL, VT);
3196 
3197   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3198   // plus a shift.
3199   if (VT.isSimple() && !VT.isVector()) {
3200     MVT Simple = VT.getSimpleVT();
3201     unsigned SimpleSize = Simple.getSizeInBits();
3202     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3203     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3204       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3205       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3206       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3207       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3208             DAG.getConstant(SimpleSize, DL,
3209                             getShiftAmountTy(N1.getValueType())));
3210       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3211     }
3212   }
3213 
3214   return SDValue();
3215 }
3216 
3217 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3218 /// give the opcodes for the two computations that are being performed. Return
3219 /// true if a simplification was made.
3220 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3221                                                 unsigned HiOp) {
3222   // If the high half is not needed, just compute the low half.
3223   bool HiExists = N->hasAnyUseOfValue(1);
3224   if (!HiExists &&
3225       (!LegalOperations ||
3226        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3227     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3228     return CombineTo(N, Res, Res);
3229   }
3230 
3231   // If the low half is not needed, just compute the high half.
3232   bool LoExists = N->hasAnyUseOfValue(0);
3233   if (!LoExists &&
3234       (!LegalOperations ||
3235        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3236     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3237     return CombineTo(N, Res, Res);
3238   }
3239 
3240   // If both halves are used, return as it is.
3241   if (LoExists && HiExists)
3242     return SDValue();
3243 
3244   // If the two computed results can be simplified separately, separate them.
3245   if (LoExists) {
3246     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3247     AddToWorklist(Lo.getNode());
3248     SDValue LoOpt = combine(Lo.getNode());
3249     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3250         (!LegalOperations ||
3251          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3252       return CombineTo(N, LoOpt, LoOpt);
3253   }
3254 
3255   if (HiExists) {
3256     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3257     AddToWorklist(Hi.getNode());
3258     SDValue HiOpt = combine(Hi.getNode());
3259     if (HiOpt.getNode() && HiOpt != Hi &&
3260         (!LegalOperations ||
3261          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3262       return CombineTo(N, HiOpt, HiOpt);
3263   }
3264 
3265   return SDValue();
3266 }
3267 
3268 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3269   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3270     return Res;
3271 
3272   EVT VT = N->getValueType(0);
3273   SDLoc DL(N);
3274 
3275   // If the type is twice as wide is legal, transform the mulhu to a wider
3276   // multiply plus a shift.
3277   if (VT.isSimple() && !VT.isVector()) {
3278     MVT Simple = VT.getSimpleVT();
3279     unsigned SimpleSize = Simple.getSizeInBits();
3280     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3281     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3282       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3283       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3284       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3285       // Compute the high part as N1.
3286       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3287             DAG.getConstant(SimpleSize, DL,
3288                             getShiftAmountTy(Lo.getValueType())));
3289       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3290       // Compute the low part as N0.
3291       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3292       return CombineTo(N, Lo, Hi);
3293     }
3294   }
3295 
3296   return SDValue();
3297 }
3298 
3299 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3300   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3301     return Res;
3302 
3303   EVT VT = N->getValueType(0);
3304   SDLoc DL(N);
3305 
3306   // If the type is twice as wide is legal, transform the mulhu to a wider
3307   // multiply plus a shift.
3308   if (VT.isSimple() && !VT.isVector()) {
3309     MVT Simple = VT.getSimpleVT();
3310     unsigned SimpleSize = Simple.getSizeInBits();
3311     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3312     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3313       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3314       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3315       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3316       // Compute the high part as N1.
3317       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3318             DAG.getConstant(SimpleSize, DL,
3319                             getShiftAmountTy(Lo.getValueType())));
3320       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3321       // Compute the low part as N0.
3322       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3323       return CombineTo(N, Lo, Hi);
3324     }
3325   }
3326 
3327   return SDValue();
3328 }
3329 
3330 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3331   // (smulo x, 2) -> (saddo x, x)
3332   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3333     if (C2->getAPIntValue() == 2)
3334       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3335                          N->getOperand(0), N->getOperand(0));
3336 
3337   return SDValue();
3338 }
3339 
3340 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3341   // (umulo x, 2) -> (uaddo x, x)
3342   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3343     if (C2->getAPIntValue() == 2)
3344       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3345                          N->getOperand(0), N->getOperand(0));
3346 
3347   return SDValue();
3348 }
3349 
3350 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3351   SDValue N0 = N->getOperand(0);
3352   SDValue N1 = N->getOperand(1);
3353   EVT VT = N0.getValueType();
3354 
3355   // fold vector ops
3356   if (VT.isVector())
3357     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3358       return FoldedVOp;
3359 
3360   // fold operation with constant operands.
3361   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3362   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3363   if (N0C && N1C)
3364     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3365 
3366   // canonicalize constant to RHS
3367   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3368      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3369     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3370 
3371   // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
3372   // Only do this if the current op isn't legal and the flipped is.
3373   unsigned Opcode = N->getOpcode();
3374   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3375   if (!TLI.isOperationLegal(Opcode, VT) &&
3376       (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
3377       (N1.isUndef() || DAG.SignBitIsZero(N1))) {
3378     unsigned AltOpcode;
3379     switch (Opcode) {
3380     case ISD::SMIN: AltOpcode = ISD::UMIN; break;
3381     case ISD::SMAX: AltOpcode = ISD::UMAX; break;
3382     case ISD::UMIN: AltOpcode = ISD::SMIN; break;
3383     case ISD::UMAX: AltOpcode = ISD::SMAX; break;
3384     default: llvm_unreachable("Unknown MINMAX opcode");
3385     }
3386     if (TLI.isOperationLegal(AltOpcode, VT))
3387       return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
3388   }
3389 
3390   return SDValue();
3391 }
3392 
3393 /// If this is a binary operator with two operands of the same opcode, try to
3394 /// simplify it.
3395 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3396   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3397   EVT VT = N0.getValueType();
3398   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3399 
3400   // Bail early if none of these transforms apply.
3401   if (N0.getNumOperands() == 0) return SDValue();
3402 
3403   // For each of OP in AND/OR/XOR:
3404   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3405   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3406   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3407   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3408   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3409   //
3410   // do not sink logical op inside of a vector extend, since it may combine
3411   // into a vsetcc.
3412   EVT Op0VT = N0.getOperand(0).getValueType();
3413   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3414        N0.getOpcode() == ISD::SIGN_EXTEND ||
3415        N0.getOpcode() == ISD::BSWAP ||
3416        // Avoid infinite looping with PromoteIntBinOp.
3417        (N0.getOpcode() == ISD::ANY_EXTEND &&
3418         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3419        (N0.getOpcode() == ISD::TRUNCATE &&
3420         (!TLI.isZExtFree(VT, Op0VT) ||
3421          !TLI.isTruncateFree(Op0VT, VT)) &&
3422         TLI.isTypeLegal(Op0VT))) &&
3423       !VT.isVector() &&
3424       Op0VT == N1.getOperand(0).getValueType() &&
3425       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3426     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3427                                  N0.getOperand(0).getValueType(),
3428                                  N0.getOperand(0), N1.getOperand(0));
3429     AddToWorklist(ORNode.getNode());
3430     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3431   }
3432 
3433   // For each of OP in SHL/SRL/SRA/AND...
3434   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3435   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3436   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3437   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3438        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3439       N0.getOperand(1) == N1.getOperand(1)) {
3440     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3441                                  N0.getOperand(0).getValueType(),
3442                                  N0.getOperand(0), N1.getOperand(0));
3443     AddToWorklist(ORNode.getNode());
3444     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3445                        ORNode, N0.getOperand(1));
3446   }
3447 
3448   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3449   // Only perform this optimization up until type legalization, before
3450   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3451   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3452   // we don't want to undo this promotion.
3453   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3454   // on scalars.
3455   if ((N0.getOpcode() == ISD::BITCAST ||
3456        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3457        Level <= AfterLegalizeTypes) {
3458     SDValue In0 = N0.getOperand(0);
3459     SDValue In1 = N1.getOperand(0);
3460     EVT In0Ty = In0.getValueType();
3461     EVT In1Ty = In1.getValueType();
3462     SDLoc DL(N);
3463     // If both incoming values are integers, and the original types are the
3464     // same.
3465     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3466       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3467       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3468       AddToWorklist(Op.getNode());
3469       return BC;
3470     }
3471   }
3472 
3473   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3474   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3475   // If both shuffles use the same mask, and both shuffle within a single
3476   // vector, then it is worthwhile to move the swizzle after the operation.
3477   // The type-legalizer generates this pattern when loading illegal
3478   // vector types from memory. In many cases this allows additional shuffle
3479   // optimizations.
3480   // There are other cases where moving the shuffle after the xor/and/or
3481   // is profitable even if shuffles don't perform a swizzle.
3482   // If both shuffles use the same mask, and both shuffles have the same first
3483   // or second operand, then it might still be profitable to move the shuffle
3484   // after the xor/and/or operation.
3485   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3486     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3487     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3488 
3489     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3490            "Inputs to shuffles are not the same type");
3491 
3492     // Check that both shuffles use the same mask. The masks are known to be of
3493     // the same length because the result vector type is the same.
3494     // Check also that shuffles have only one use to avoid introducing extra
3495     // instructions.
3496     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3497         SVN0->getMask().equals(SVN1->getMask())) {
3498       SDValue ShOp = N0->getOperand(1);
3499 
3500       // Don't try to fold this node if it requires introducing a
3501       // build vector of all zeros that might be illegal at this stage.
3502       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3503         if (!LegalTypes)
3504           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3505         else
3506           ShOp = SDValue();
3507       }
3508 
3509       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3510       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3511       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3512       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3513         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3514                                       N0->getOperand(0), N1->getOperand(0));
3515         AddToWorklist(NewNode.getNode());
3516         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3517                                     SVN0->getMask());
3518       }
3519 
3520       // Don't try to fold this node if it requires introducing a
3521       // build vector of all zeros that might be illegal at this stage.
3522       ShOp = N0->getOperand(0);
3523       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3524         if (!LegalTypes)
3525           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3526         else
3527           ShOp = SDValue();
3528       }
3529 
3530       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3531       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3532       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3533       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3534         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3535                                       N0->getOperand(1), N1->getOperand(1));
3536         AddToWorklist(NewNode.getNode());
3537         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3538                                     SVN0->getMask());
3539       }
3540     }
3541   }
3542 
3543   return SDValue();
3544 }
3545 
3546 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3547 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3548                                        const SDLoc &DL) {
3549   SDValue LL, LR, RL, RR, N0CC, N1CC;
3550   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3551       !isSetCCEquivalent(N1, RL, RR, N1CC))
3552     return SDValue();
3553 
3554   assert(N0.getValueType() == N1.getValueType() &&
3555          "Unexpected operand types for bitwise logic op");
3556   assert(LL.getValueType() == LR.getValueType() &&
3557          RL.getValueType() == RR.getValueType() &&
3558          "Unexpected operand types for setcc");
3559 
3560   // If we're here post-legalization or the logic op type is not i1, the logic
3561   // op type must match a setcc result type. Also, all folds require new
3562   // operations on the left and right operands, so those types must match.
3563   EVT VT = N0.getValueType();
3564   EVT OpVT = LL.getValueType();
3565   if (LegalOperations || VT.getScalarType() != MVT::i1)
3566     if (VT != getSetCCResultType(OpVT))
3567       return SDValue();
3568   if (OpVT != RL.getValueType())
3569     return SDValue();
3570 
3571   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3572   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3573   bool IsInteger = OpVT.isInteger();
3574   if (LR == RR && CC0 == CC1 && IsInteger) {
3575     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3576     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3577 
3578     // All bits clear?
3579     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3580     // All sign bits clear?
3581     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3582     // Any bits set?
3583     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3584     // Any sign bits set?
3585     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3586 
3587     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3588     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3589     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3590     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3591     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3592       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3593       AddToWorklist(Or.getNode());
3594       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3595     }
3596 
3597     // All bits set?
3598     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3599     // All sign bits set?
3600     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3601     // Any bits clear?
3602     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3603     // Any sign bits clear?
3604     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3605 
3606     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3607     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3608     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3609     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3610     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3611       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3612       AddToWorklist(And.getNode());
3613       return DAG.getSetCC(DL, VT, And, LR, CC1);
3614     }
3615   }
3616 
3617   // TODO: What is the 'or' equivalent of this fold?
3618   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3619   if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
3620       IsInteger && CC0 == ISD::SETNE &&
3621       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3622        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3623     SDValue One = DAG.getConstant(1, DL, OpVT);
3624     SDValue Two = DAG.getConstant(2, DL, OpVT);
3625     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3626     AddToWorklist(Add.getNode());
3627     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3628   }
3629 
3630   // Try more general transforms if the predicates match and the only user of
3631   // the compares is the 'and' or 'or'.
3632   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3633       N0.hasOneUse() && N1.hasOneUse()) {
3634     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3635     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3636     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3637       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3638       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3639       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3640       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3641       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3642     }
3643   }
3644 
3645   // Canonicalize equivalent operands to LL == RL.
3646   if (LL == RR && LR == RL) {
3647     CC1 = ISD::getSetCCSwappedOperands(CC1);
3648     std::swap(RL, RR);
3649   }
3650 
3651   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3652   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3653   if (LL == RL && LR == RR) {
3654     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3655                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3656     if (NewCC != ISD::SETCC_INVALID &&
3657         (!LegalOperations ||
3658          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3659           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3660       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3661   }
3662 
3663   return SDValue();
3664 }
3665 
3666 /// This contains all DAGCombine rules which reduce two values combined by
3667 /// an And operation to a single value. This makes them reusable in the context
3668 /// of visitSELECT(). Rules involving constants are not included as
3669 /// visitSELECT() already handles those cases.
3670 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3671   EVT VT = N1.getValueType();
3672   SDLoc DL(N);
3673 
3674   // fold (and x, undef) -> 0
3675   if (N0.isUndef() || N1.isUndef())
3676     return DAG.getConstant(0, DL, VT);
3677 
3678   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3679     return V;
3680 
3681   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3682       VT.getSizeInBits() <= 64) {
3683     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3684       if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3685         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3686         // immediate for an add, but it is legal if its top c2 bits are set,
3687         // transform the ADD so the immediate doesn't need to be materialized
3688         // in a register.
3689         APInt ADDC = ADDI->getAPIntValue();
3690         APInt SRLC = SRLI->getAPIntValue();
3691         if (ADDC.getMinSignedBits() <= 64 &&
3692             SRLC.ult(VT.getSizeInBits()) &&
3693             !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3694           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3695                                              SRLC.getZExtValue());
3696           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3697             ADDC |= Mask;
3698             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3699               SDLoc DL0(N0);
3700               SDValue NewAdd =
3701                 DAG.getNode(ISD::ADD, DL0, VT,
3702                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3703               CombineTo(N0.getNode(), NewAdd);
3704               // Return N so it doesn't get rechecked!
3705               return SDValue(N, 0);
3706             }
3707           }
3708         }
3709       }
3710     }
3711   }
3712 
3713   // Reduce bit extract of low half of an integer to the narrower type.
3714   // (and (srl i64:x, K), KMask) ->
3715   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3716   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3717     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3718       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3719         unsigned Size = VT.getSizeInBits();
3720         const APInt &AndMask = CAnd->getAPIntValue();
3721         unsigned ShiftBits = CShift->getZExtValue();
3722 
3723         // Bail out, this node will probably disappear anyway.
3724         if (ShiftBits == 0)
3725           return SDValue();
3726 
3727         unsigned MaskBits = AndMask.countTrailingOnes();
3728         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3729 
3730         if (AndMask.isMask() &&
3731             // Required bits must not span the two halves of the integer and
3732             // must fit in the half size type.
3733             (ShiftBits + MaskBits <= Size / 2) &&
3734             TLI.isNarrowingProfitable(VT, HalfVT) &&
3735             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3736             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3737             TLI.isTruncateFree(VT, HalfVT) &&
3738             TLI.isZExtFree(HalfVT, VT)) {
3739           // The isNarrowingProfitable is to avoid regressions on PPC and
3740           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3741           // on downstream users of this. Those patterns could probably be
3742           // extended to handle extensions mixed in.
3743 
3744           SDValue SL(N0);
3745           assert(MaskBits <= Size);
3746 
3747           // Extracting the highest bit of the low half.
3748           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3749           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3750                                       N0.getOperand(0));
3751 
3752           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3753           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3754           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3755           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3756           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3757         }
3758       }
3759     }
3760   }
3761 
3762   return SDValue();
3763 }
3764 
3765 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3766                                    EVT LoadResultTy, EVT &ExtVT) {
3767   if (!AndC->getAPIntValue().isMask())
3768     return false;
3769 
3770   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3771 
3772   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3773   EVT LoadedVT = LoadN->getMemoryVT();
3774 
3775   if (ExtVT == LoadedVT &&
3776       (!LegalOperations ||
3777        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3778     // ZEXTLOAD will match without needing to change the size of the value being
3779     // loaded.
3780     return true;
3781   }
3782 
3783   // Do not change the width of a volatile load.
3784   if (LoadN->isVolatile())
3785     return false;
3786 
3787   // Do not generate loads of non-round integer types since these can
3788   // be expensive (and would be wrong if the type is not byte sized).
3789   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3790     return false;
3791 
3792   if (LegalOperations &&
3793       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3794     return false;
3795 
3796   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3797     return false;
3798 
3799   return true;
3800 }
3801 
3802 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3803                                     EVT &ExtVT, unsigned ShAmt) {
3804   // Don't transform one with multiple uses, this would require adding a new
3805   // load.
3806   if (!SDValue(LoadN, 0).hasOneUse())
3807     return false;
3808 
3809   if (LegalOperations &&
3810       !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3811     return false;
3812 
3813   // Do not generate loads of non-round integer types since these can
3814   // be expensive (and would be wrong if the type is not byte sized).
3815   if (!ExtVT.isRound())
3816     return false;
3817 
3818   // Don't change the width of a volatile load.
3819   if (LoadN->isVolatile())
3820     return false;
3821 
3822   // Verify that we are actually reducing a load width here.
3823   if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3824     return false;
3825 
3826   // For the transform to be legal, the load must produce only two values
3827   // (the value loaded and the chain).  Don't transform a pre-increment
3828   // load, for example, which produces an extra value.  Otherwise the
3829   // transformation is not equivalent, and the downstream logic to replace
3830   // uses gets things wrong.
3831   if (LoadN->getNumValues() > 2)
3832     return false;
3833 
3834  // Only allow byte offsets.
3835   if (ShAmt % 8)
3836     return false;
3837 
3838   // Ensure that this isn't going to produce an unsupported unaligned access.
3839   if (ShAmt && !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
3840                                        ExtVT, LoadN->getAddressSpace(),
3841                                        ShAmt / 8))
3842     return false;
3843 
3844 
3845   // If the load that we're shrinking is an extload and we're not just
3846   // discarding the extension we can't simply shrink the load. Bail.
3847   // TODO: It would be possible to merge the extensions in some cases.
3848   if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3849       LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3850     return false;
3851 
3852   if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3853     return false;
3854 
3855   // It's not possible to generate a constant of extended or untyped type.
3856   EVT PtrType = LoadN->getOperand(1).getValueType();
3857   if (PtrType == MVT::Untyped || PtrType.isExtended())
3858     return false;
3859 
3860   return true;
3861 }
3862 
3863 bool DAGCombiner::SearchForAndLoads(SDNode *N,
3864                                     SmallPtrSetImpl<LoadSDNode*> &Loads,
3865                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3866                                     ConstantSDNode *Mask,
3867                                     SDNode *&NodeToMask) {
3868   // Recursively search for the operands, looking for loads which can be
3869   // narrowed.
3870   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3871     SDValue Op = N->getOperand(i);
3872 
3873     if (Op.getValueType().isVector())
3874       return false;
3875 
3876     // Some constants may need fixing up later if they are too large.
3877     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3878       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3879           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3880         NodesWithConsts.insert(N);
3881       continue;
3882     }
3883 
3884     if (!Op.hasOneUse())
3885       return false;
3886 
3887     switch(Op.getOpcode()) {
3888     case ISD::LOAD: {
3889       auto *Load = cast<LoadSDNode>(Op);
3890       EVT ExtVT;
3891       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3892           isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3893 
3894         // ZEXTLOAD is already small enough.
3895         if (Load->getExtensionType() == ISD::ZEXTLOAD &&
3896             ExtVT.bitsGE(Load->getMemoryVT()))
3897           continue;
3898 
3899         // Use LE to convert equal sized loads to zext.
3900         if (ExtVT.bitsLE(Load->getMemoryVT()))
3901           Loads.insert(Load);
3902 
3903         continue;
3904       }
3905       return false;
3906     }
3907     case ISD::ZERO_EXTEND:
3908     case ISD::AssertZext: {
3909       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3910       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3911       EVT VT = Op.getOpcode() == ISD::AssertZext ?
3912         cast<VTSDNode>(Op.getOperand(1))->getVT() :
3913         Op.getOperand(0).getValueType();
3914 
3915       // We can accept extending nodes if the mask is wider or an equal
3916       // width to the original type.
3917       if (ExtVT.bitsGE(VT))
3918         continue;
3919       break;
3920     }
3921     case ISD::OR:
3922     case ISD::XOR:
3923     case ISD::AND:
3924       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3925                              NodeToMask))
3926         return false;
3927       continue;
3928     }
3929 
3930     // Allow one node which will masked along with any loads found.
3931     if (NodeToMask)
3932       return false;
3933     NodeToMask = Op.getNode();
3934   }
3935   return true;
3936 }
3937 
3938 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3939   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3940   if (!Mask)
3941     return false;
3942 
3943   if (!Mask->getAPIntValue().isMask())
3944     return false;
3945 
3946   // No need to do anything if the and directly uses a load.
3947   if (isa<LoadSDNode>(N->getOperand(0)))
3948     return false;
3949 
3950   SmallPtrSet<LoadSDNode*, 8> Loads;
3951   SmallPtrSet<SDNode*, 2> NodesWithConsts;
3952   SDNode *FixupNode = nullptr;
3953   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3954     if (Loads.size() == 0)
3955       return false;
3956 
3957     DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
3958     SDValue MaskOp = N->getOperand(1);
3959 
3960     // If it exists, fixup the single node we allow in the tree that needs
3961     // masking.
3962     if (FixupNode) {
3963       DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
3964       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3965                                 FixupNode->getValueType(0),
3966                                 SDValue(FixupNode, 0), MaskOp);
3967       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3968       DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3969                              MaskOp);
3970     }
3971 
3972     // Narrow any constants that need it.
3973     for (auto *LogicN : NodesWithConsts) {
3974       SDValue Op0 = LogicN->getOperand(0);
3975       SDValue Op1 = LogicN->getOperand(1);
3976 
3977       if (isa<ConstantSDNode>(Op0))
3978           std::swap(Op0, Op1);
3979 
3980       SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
3981                                 Op1, MaskOp);
3982 
3983       DAG.UpdateNodeOperands(LogicN, Op0, And);
3984     }
3985 
3986     // Create narrow loads.
3987     for (auto *Load : Loads) {
3988       DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
3989       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3990                                 SDValue(Load, 0), MaskOp);
3991       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3992       DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3993       SDValue NewLoad = ReduceLoadWidth(And.getNode());
3994       assert(NewLoad &&
3995              "Shouldn't be masking the load if it can't be narrowed");
3996       CombineTo(Load, NewLoad, NewLoad.getValue(1));
3997     }
3998     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
3999     return true;
4000   }
4001   return false;
4002 }
4003 
4004 SDValue DAGCombiner::visitAND(SDNode *N) {
4005   SDValue N0 = N->getOperand(0);
4006   SDValue N1 = N->getOperand(1);
4007   EVT VT = N1.getValueType();
4008 
4009   // x & x --> x
4010   if (N0 == N1)
4011     return N0;
4012 
4013   // fold vector ops
4014   if (VT.isVector()) {
4015     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4016       return FoldedVOp;
4017 
4018     // fold (and x, 0) -> 0, vector edition
4019     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4020       // do not return N0, because undef node may exist in N0
4021       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
4022                              SDLoc(N), N0.getValueType());
4023     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4024       // do not return N1, because undef node may exist in N1
4025       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
4026                              SDLoc(N), N1.getValueType());
4027 
4028     // fold (and x, -1) -> x, vector edition
4029     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4030       return N1;
4031     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4032       return N0;
4033   }
4034 
4035   // fold (and c1, c2) -> c1&c2
4036   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4037   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4038   if (N0C && N1C && !N1C->isOpaque())
4039     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
4040   // canonicalize constant to RHS
4041   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4042      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4043     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
4044   // fold (and x, -1) -> x
4045   if (isAllOnesConstant(N1))
4046     return N0;
4047   // if (and x, c) is known to be zero, return 0
4048   unsigned BitWidth = VT.getScalarSizeInBits();
4049   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4050                                    APInt::getAllOnesValue(BitWidth)))
4051     return DAG.getConstant(0, SDLoc(N), VT);
4052 
4053   if (SDValue NewSel = foldBinOpIntoSelect(N))
4054     return NewSel;
4055 
4056   // reassociate and
4057   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
4058     return RAND;
4059 
4060   // Try to convert a constant mask AND into a shuffle clear mask.
4061   if (VT.isVector())
4062     if (SDValue Shuffle = XformToShuffleWithZero(N))
4063       return Shuffle;
4064 
4065   // fold (and (or x, C), D) -> D if (C & D) == D
4066   auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4067     return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4068   };
4069   if (N0.getOpcode() == ISD::OR &&
4070       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4071     return N1;
4072   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4073   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4074     SDValue N0Op0 = N0.getOperand(0);
4075     APInt Mask = ~N1C->getAPIntValue();
4076     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4077     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4078       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4079                                  N0.getValueType(), N0Op0);
4080 
4081       // Replace uses of the AND with uses of the Zero extend node.
4082       CombineTo(N, Zext);
4083 
4084       // We actually want to replace all uses of the any_extend with the
4085       // zero_extend, to avoid duplicating things.  This will later cause this
4086       // AND to be folded.
4087       CombineTo(N0.getNode(), Zext);
4088       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4089     }
4090   }
4091   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4092   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4093   // already be zero by virtue of the width of the base type of the load.
4094   //
4095   // the 'X' node here can either be nothing or an extract_vector_elt to catch
4096   // more cases.
4097   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4098        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4099        N0.getOperand(0).getOpcode() == ISD::LOAD &&
4100        N0.getOperand(0).getResNo() == 0) ||
4101       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4102     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4103                                          N0 : N0.getOperand(0) );
4104 
4105     // Get the constant (if applicable) the zero'th operand is being ANDed with.
4106     // This can be a pure constant or a vector splat, in which case we treat the
4107     // vector as a scalar and use the splat value.
4108     APInt Constant = APInt::getNullValue(1);
4109     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4110       Constant = C->getAPIntValue();
4111     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4112       APInt SplatValue, SplatUndef;
4113       unsigned SplatBitSize;
4114       bool HasAnyUndefs;
4115       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4116                                              SplatBitSize, HasAnyUndefs);
4117       if (IsSplat) {
4118         // Undef bits can contribute to a possible optimisation if set, so
4119         // set them.
4120         SplatValue |= SplatUndef;
4121 
4122         // The splat value may be something like "0x00FFFFFF", which means 0 for
4123         // the first vector value and FF for the rest, repeating. We need a mask
4124         // that will apply equally to all members of the vector, so AND all the
4125         // lanes of the constant together.
4126         EVT VT = Vector->getValueType(0);
4127         unsigned BitWidth = VT.getScalarSizeInBits();
4128 
4129         // If the splat value has been compressed to a bitlength lower
4130         // than the size of the vector lane, we need to re-expand it to
4131         // the lane size.
4132         if (BitWidth > SplatBitSize)
4133           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4134                SplatBitSize < BitWidth;
4135                SplatBitSize = SplatBitSize * 2)
4136             SplatValue |= SplatValue.shl(SplatBitSize);
4137 
4138         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4139         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4140         if (SplatBitSize % BitWidth == 0) {
4141           Constant = APInt::getAllOnesValue(BitWidth);
4142           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4143             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4144         }
4145       }
4146     }
4147 
4148     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4149     // actually legal and isn't going to get expanded, else this is a false
4150     // optimisation.
4151     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4152                                                     Load->getValueType(0),
4153                                                     Load->getMemoryVT());
4154 
4155     // Resize the constant to the same size as the original memory access before
4156     // extension. If it is still the AllOnesValue then this AND is completely
4157     // unneeded.
4158     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4159 
4160     bool B;
4161     switch (Load->getExtensionType()) {
4162     default: B = false; break;
4163     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4164     case ISD::ZEXTLOAD:
4165     case ISD::NON_EXTLOAD: B = true; break;
4166     }
4167 
4168     if (B && Constant.isAllOnesValue()) {
4169       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4170       // preserve semantics once we get rid of the AND.
4171       SDValue NewLoad(Load, 0);
4172 
4173       // Fold the AND away. NewLoad may get replaced immediately.
4174       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4175 
4176       if (Load->getExtensionType() == ISD::EXTLOAD) {
4177         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4178                               Load->getValueType(0), SDLoc(Load),
4179                               Load->getChain(), Load->getBasePtr(),
4180                               Load->getOffset(), Load->getMemoryVT(),
4181                               Load->getMemOperand());
4182         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4183         if (Load->getNumValues() == 3) {
4184           // PRE/POST_INC loads have 3 values.
4185           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4186                            NewLoad.getValue(2) };
4187           CombineTo(Load, To, 3, true);
4188         } else {
4189           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4190         }
4191       }
4192 
4193       return SDValue(N, 0); // Return N so it doesn't get rechecked!
4194     }
4195   }
4196 
4197   // fold (and (load x), 255) -> (zextload x, i8)
4198   // fold (and (extload x, i16), 255) -> (zextload x, i8)
4199   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4200   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4201                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
4202                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4203     if (SDValue Res = ReduceLoadWidth(N)) {
4204       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4205         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4206 
4207       AddToWorklist(N);
4208       CombineTo(LN0, Res, Res.getValue(1));
4209       return SDValue(N, 0);
4210     }
4211   }
4212 
4213   if (Level >= AfterLegalizeTypes) {
4214     // Attempt to propagate the AND back up to the leaves which, if they're
4215     // loads, can be combined to narrow loads and the AND node can be removed.
4216     // Perform after legalization so that extend nodes will already be
4217     // combined into the loads.
4218     if (BackwardsPropagateMask(N, DAG)) {
4219       return SDValue(N, 0);
4220     }
4221   }
4222 
4223   if (SDValue Combined = visitANDLike(N0, N1, N))
4224     return Combined;
4225 
4226   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
4227   if (N0.getOpcode() == N1.getOpcode())
4228     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4229       return Tmp;
4230 
4231   // Masking the negated extension of a boolean is just the zero-extended
4232   // boolean:
4233   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4234   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4235   //
4236   // Note: the SimplifyDemandedBits fold below can make an information-losing
4237   // transform, and then we have no way to find this better fold.
4238   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4239     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4240       SDValue SubRHS = N0.getOperand(1);
4241       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4242           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4243         return SubRHS;
4244       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4245           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4246         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4247     }
4248   }
4249 
4250   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4251   // fold (and (sra)) -> (and (srl)) when possible.
4252   if (SimplifyDemandedBits(SDValue(N, 0)))
4253     return SDValue(N, 0);
4254 
4255   // fold (zext_inreg (extload x)) -> (zextload x)
4256   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4257     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4258     EVT MemVT = LN0->getMemoryVT();
4259     // If we zero all the possible extended bits, then we can turn this into
4260     // a zextload if we are running before legalize or the operation is legal.
4261     unsigned BitWidth = N1.getScalarValueSizeInBits();
4262     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4263                            BitWidth - MemVT.getScalarSizeInBits())) &&
4264         ((!LegalOperations && !LN0->isVolatile()) ||
4265          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4266       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4267                                        LN0->getChain(), LN0->getBasePtr(),
4268                                        MemVT, LN0->getMemOperand());
4269       AddToWorklist(N);
4270       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4271       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4272     }
4273   }
4274   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4275   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4276       N0.hasOneUse()) {
4277     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4278     EVT MemVT = LN0->getMemoryVT();
4279     // If we zero all the possible extended bits, then we can turn this into
4280     // a zextload if we are running before legalize or the operation is legal.
4281     unsigned BitWidth = N1.getScalarValueSizeInBits();
4282     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4283                            BitWidth - MemVT.getScalarSizeInBits())) &&
4284         ((!LegalOperations && !LN0->isVolatile()) ||
4285          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4286       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4287                                        LN0->getChain(), LN0->getBasePtr(),
4288                                        MemVT, LN0->getMemOperand());
4289       AddToWorklist(N);
4290       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4291       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4292     }
4293   }
4294   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4295   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4296     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4297                                            N0.getOperand(1), false))
4298       return BSwap;
4299   }
4300 
4301   return SDValue();
4302 }
4303 
4304 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4305 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4306                                         bool DemandHighBits) {
4307   if (!LegalOperations)
4308     return SDValue();
4309 
4310   EVT VT = N->getValueType(0);
4311   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4312     return SDValue();
4313   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4314     return SDValue();
4315 
4316   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4317   bool LookPassAnd0 = false;
4318   bool LookPassAnd1 = false;
4319   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4320       std::swap(N0, N1);
4321   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4322       std::swap(N0, N1);
4323   if (N0.getOpcode() == ISD::AND) {
4324     if (!N0.getNode()->hasOneUse())
4325       return SDValue();
4326     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4327     // Also handle 0xffff since the LHS is guaranteed to have zeros there.
4328     // This is needed for X86.
4329     if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
4330                   N01C->getZExtValue() != 0xFFFF))
4331       return SDValue();
4332     N0 = N0.getOperand(0);
4333     LookPassAnd0 = true;
4334   }
4335 
4336   if (N1.getOpcode() == ISD::AND) {
4337     if (!N1.getNode()->hasOneUse())
4338       return SDValue();
4339     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4340     if (!N11C || N11C->getZExtValue() != 0xFF)
4341       return SDValue();
4342     N1 = N1.getOperand(0);
4343     LookPassAnd1 = true;
4344   }
4345 
4346   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4347     std::swap(N0, N1);
4348   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4349     return SDValue();
4350   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4351     return SDValue();
4352 
4353   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4354   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4355   if (!N01C || !N11C)
4356     return SDValue();
4357   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4358     return SDValue();
4359 
4360   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4361   SDValue N00 = N0->getOperand(0);
4362   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4363     if (!N00.getNode()->hasOneUse())
4364       return SDValue();
4365     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4366     if (!N001C || N001C->getZExtValue() != 0xFF)
4367       return SDValue();
4368     N00 = N00.getOperand(0);
4369     LookPassAnd0 = true;
4370   }
4371 
4372   SDValue N10 = N1->getOperand(0);
4373   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4374     if (!N10.getNode()->hasOneUse())
4375       return SDValue();
4376     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4377     // Also allow 0xFFFF since the bits will be shifted out. This is needed
4378     // for X86.
4379     if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
4380                    N101C->getZExtValue() != 0xFFFF))
4381       return SDValue();
4382     N10 = N10.getOperand(0);
4383     LookPassAnd1 = true;
4384   }
4385 
4386   if (N00 != N10)
4387     return SDValue();
4388 
4389   // Make sure everything beyond the low halfword gets set to zero since the SRL
4390   // 16 will clear the top bits.
4391   unsigned OpSizeInBits = VT.getSizeInBits();
4392   if (DemandHighBits && OpSizeInBits > 16) {
4393     // If the left-shift isn't masked out then the only way this is a bswap is
4394     // if all bits beyond the low 8 are 0. In that case the entire pattern
4395     // reduces to a left shift anyway: leave it for other parts of the combiner.
4396     if (!LookPassAnd0)
4397       return SDValue();
4398 
4399     // However, if the right shift isn't masked out then it might be because
4400     // it's not needed. See if we can spot that too.
4401     if (!LookPassAnd1 &&
4402         !DAG.MaskedValueIsZero(
4403             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4404       return SDValue();
4405   }
4406 
4407   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4408   if (OpSizeInBits > 16) {
4409     SDLoc DL(N);
4410     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4411                       DAG.getConstant(OpSizeInBits - 16, DL,
4412                                       getShiftAmountTy(VT)));
4413   }
4414   return Res;
4415 }
4416 
4417 /// Return true if the specified node is an element that makes up a 32-bit
4418 /// packed halfword byteswap.
4419 /// ((x & 0x000000ff) << 8) |
4420 /// ((x & 0x0000ff00) >> 8) |
4421 /// ((x & 0x00ff0000) << 8) |
4422 /// ((x & 0xff000000) >> 8)
4423 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4424   if (!N.getNode()->hasOneUse())
4425     return false;
4426 
4427   unsigned Opc = N.getOpcode();
4428   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4429     return false;
4430 
4431   SDValue N0 = N.getOperand(0);
4432   unsigned Opc0 = N0.getOpcode();
4433   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4434     return false;
4435 
4436   ConstantSDNode *N1C = nullptr;
4437   // SHL or SRL: look upstream for AND mask operand
4438   if (Opc == ISD::AND)
4439     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4440   else if (Opc0 == ISD::AND)
4441     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4442   if (!N1C)
4443     return false;
4444 
4445   unsigned MaskByteOffset;
4446   switch (N1C->getZExtValue()) {
4447   default:
4448     return false;
4449   case 0xFF:       MaskByteOffset = 0; break;
4450   case 0xFF00:     MaskByteOffset = 1; break;
4451   case 0xFFFF:
4452     // In case demanded bits didn't clear the bits that will be shifted out.
4453     // This is needed for X86.
4454     if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
4455       MaskByteOffset = 1;
4456       break;
4457     }
4458     return false;
4459   case 0xFF0000:   MaskByteOffset = 2; break;
4460   case 0xFF000000: MaskByteOffset = 3; break;
4461   }
4462 
4463   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4464   if (Opc == ISD::AND) {
4465     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4466       // (x >> 8) & 0xff
4467       // (x >> 8) & 0xff0000
4468       if (Opc0 != ISD::SRL)
4469         return false;
4470       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4471       if (!C || C->getZExtValue() != 8)
4472         return false;
4473     } else {
4474       // (x << 8) & 0xff00
4475       // (x << 8) & 0xff000000
4476       if (Opc0 != ISD::SHL)
4477         return false;
4478       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4479       if (!C || C->getZExtValue() != 8)
4480         return false;
4481     }
4482   } else if (Opc == ISD::SHL) {
4483     // (x & 0xff) << 8
4484     // (x & 0xff0000) << 8
4485     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4486       return false;
4487     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4488     if (!C || C->getZExtValue() != 8)
4489       return false;
4490   } else { // Opc == ISD::SRL
4491     // (x & 0xff00) >> 8
4492     // (x & 0xff000000) >> 8
4493     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4494       return false;
4495     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4496     if (!C || C->getZExtValue() != 8)
4497       return false;
4498   }
4499 
4500   if (Parts[MaskByteOffset])
4501     return false;
4502 
4503   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4504   return true;
4505 }
4506 
4507 /// Match a 32-bit packed halfword bswap. That is
4508 /// ((x & 0x000000ff) << 8) |
4509 /// ((x & 0x0000ff00) >> 8) |
4510 /// ((x & 0x00ff0000) << 8) |
4511 /// ((x & 0xff000000) >> 8)
4512 /// => (rotl (bswap x), 16)
4513 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4514   if (!LegalOperations)
4515     return SDValue();
4516 
4517   EVT VT = N->getValueType(0);
4518   if (VT != MVT::i32)
4519     return SDValue();
4520   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4521     return SDValue();
4522 
4523   // Look for either
4524   // (or (or (and), (and)), (or (and), (and)))
4525   // (or (or (or (and), (and)), (and)), (and))
4526   if (N0.getOpcode() != ISD::OR)
4527     return SDValue();
4528   SDValue N00 = N0.getOperand(0);
4529   SDValue N01 = N0.getOperand(1);
4530   SDNode *Parts[4] = {};
4531 
4532   if (N1.getOpcode() == ISD::OR &&
4533       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4534     // (or (or (and), (and)), (or (and), (and)))
4535     if (!isBSwapHWordElement(N00, Parts))
4536       return SDValue();
4537 
4538     if (!isBSwapHWordElement(N01, Parts))
4539       return SDValue();
4540     SDValue N10 = N1.getOperand(0);
4541     if (!isBSwapHWordElement(N10, Parts))
4542       return SDValue();
4543     SDValue N11 = N1.getOperand(1);
4544     if (!isBSwapHWordElement(N11, Parts))
4545       return SDValue();
4546   } else {
4547     // (or (or (or (and), (and)), (and)), (and))
4548     if (!isBSwapHWordElement(N1, Parts))
4549       return SDValue();
4550     if (!isBSwapHWordElement(N01, Parts))
4551       return SDValue();
4552     if (N00.getOpcode() != ISD::OR)
4553       return SDValue();
4554     SDValue N000 = N00.getOperand(0);
4555     if (!isBSwapHWordElement(N000, Parts))
4556       return SDValue();
4557     SDValue N001 = N00.getOperand(1);
4558     if (!isBSwapHWordElement(N001, Parts))
4559       return SDValue();
4560   }
4561 
4562   // Make sure the parts are all coming from the same node.
4563   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4564     return SDValue();
4565 
4566   SDLoc DL(N);
4567   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4568                               SDValue(Parts[0], 0));
4569 
4570   // Result of the bswap should be rotated by 16. If it's not legal, then
4571   // do  (x << 16) | (x >> 16).
4572   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4573   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4574     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4575   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4576     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4577   return DAG.getNode(ISD::OR, DL, VT,
4578                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4579                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4580 }
4581 
4582 /// This contains all DAGCombine rules which reduce two values combined by
4583 /// an Or operation to a single value \see visitANDLike().
4584 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4585   EVT VT = N1.getValueType();
4586   SDLoc DL(N);
4587 
4588   // fold (or x, undef) -> -1
4589   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4590     return DAG.getAllOnesConstant(DL, VT);
4591 
4592   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4593     return V;
4594 
4595   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4596   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4597       // Don't increase # computations.
4598       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4599     // We can only do this xform if we know that bits from X that are set in C2
4600     // but not in C1 are already zero.  Likewise for Y.
4601     if (const ConstantSDNode *N0O1C =
4602         getAsNonOpaqueConstant(N0.getOperand(1))) {
4603       if (const ConstantSDNode *N1O1C =
4604           getAsNonOpaqueConstant(N1.getOperand(1))) {
4605         // We can only do this xform if we know that bits from X that are set in
4606         // C2 but not in C1 are already zero.  Likewise for Y.
4607         const APInt &LHSMask = N0O1C->getAPIntValue();
4608         const APInt &RHSMask = N1O1C->getAPIntValue();
4609 
4610         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4611             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4612           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4613                                   N0.getOperand(0), N1.getOperand(0));
4614           return DAG.getNode(ISD::AND, DL, VT, X,
4615                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4616         }
4617       }
4618     }
4619   }
4620 
4621   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4622   if (N0.getOpcode() == ISD::AND &&
4623       N1.getOpcode() == ISD::AND &&
4624       N0.getOperand(0) == N1.getOperand(0) &&
4625       // Don't increase # computations.
4626       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4627     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4628                             N0.getOperand(1), N1.getOperand(1));
4629     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4630   }
4631 
4632   return SDValue();
4633 }
4634 
4635 SDValue DAGCombiner::visitOR(SDNode *N) {
4636   SDValue N0 = N->getOperand(0);
4637   SDValue N1 = N->getOperand(1);
4638   EVT VT = N1.getValueType();
4639 
4640   // x | x --> x
4641   if (N0 == N1)
4642     return N0;
4643 
4644   // fold vector ops
4645   if (VT.isVector()) {
4646     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4647       return FoldedVOp;
4648 
4649     // fold (or x, 0) -> x, vector edition
4650     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4651       return N1;
4652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4653       return N0;
4654 
4655     // fold (or x, -1) -> -1, vector edition
4656     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4657       // do not return N0, because undef node may exist in N0
4658       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4659     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4660       // do not return N1, because undef node may exist in N1
4661       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4662 
4663     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4664     // Do this only if the resulting shuffle is legal.
4665     if (isa<ShuffleVectorSDNode>(N0) &&
4666         isa<ShuffleVectorSDNode>(N1) &&
4667         // Avoid folding a node with illegal type.
4668         TLI.isTypeLegal(VT)) {
4669       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4670       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4671       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4672       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4673       // Ensure both shuffles have a zero input.
4674       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4675         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4676         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4677         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4678         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4679         bool CanFold = true;
4680         int NumElts = VT.getVectorNumElements();
4681         SmallVector<int, 4> Mask(NumElts);
4682 
4683         for (int i = 0; i != NumElts; ++i) {
4684           int M0 = SV0->getMaskElt(i);
4685           int M1 = SV1->getMaskElt(i);
4686 
4687           // Determine if either index is pointing to a zero vector.
4688           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4689           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4690 
4691           // If one element is zero and the otherside is undef, keep undef.
4692           // This also handles the case that both are undef.
4693           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4694             Mask[i] = -1;
4695             continue;
4696           }
4697 
4698           // Make sure only one of the elements is zero.
4699           if (M0Zero == M1Zero) {
4700             CanFold = false;
4701             break;
4702           }
4703 
4704           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4705 
4706           // We have a zero and non-zero element. If the non-zero came from
4707           // SV0 make the index a LHS index. If it came from SV1, make it
4708           // a RHS index. We need to mod by NumElts because we don't care
4709           // which operand it came from in the original shuffles.
4710           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4711         }
4712 
4713         if (CanFold) {
4714           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4715           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4716 
4717           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4718           if (!LegalMask) {
4719             std::swap(NewLHS, NewRHS);
4720             ShuffleVectorSDNode::commuteMask(Mask);
4721             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4722           }
4723 
4724           if (LegalMask)
4725             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4726         }
4727       }
4728     }
4729   }
4730 
4731   // fold (or c1, c2) -> c1|c2
4732   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4733   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4734   if (N0C && N1C && !N1C->isOpaque())
4735     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4736   // canonicalize constant to RHS
4737   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4738      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4739     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4740   // fold (or x, 0) -> x
4741   if (isNullConstant(N1))
4742     return N0;
4743   // fold (or x, -1) -> -1
4744   if (isAllOnesConstant(N1))
4745     return N1;
4746 
4747   if (SDValue NewSel = foldBinOpIntoSelect(N))
4748     return NewSel;
4749 
4750   // fold (or x, c) -> c iff (x & ~c) == 0
4751   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4752     return N1;
4753 
4754   if (SDValue Combined = visitORLike(N0, N1, N))
4755     return Combined;
4756 
4757   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4758   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4759     return BSwap;
4760   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4761     return BSwap;
4762 
4763   // reassociate or
4764   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4765     return ROR;
4766 
4767   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4768   // iff (c1 & c2) != 0.
4769   auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4770     return LHS->getAPIntValue().intersects(RHS->getAPIntValue());
4771   };
4772   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4773       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) {
4774     if (SDValue COR = DAG.FoldConstantArithmetic(
4775             ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
4776       SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
4777       AddToWorklist(IOR.getNode());
4778       return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
4779     }
4780   }
4781 
4782   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4783   if (N0.getOpcode() == N1.getOpcode())
4784     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4785       return Tmp;
4786 
4787   // See if this is some rotate idiom.
4788   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4789     return SDValue(Rot, 0);
4790 
4791   if (SDValue Load = MatchLoadCombine(N))
4792     return Load;
4793 
4794   // Simplify the operands using demanded-bits information.
4795   if (SimplifyDemandedBits(SDValue(N, 0)))
4796     return SDValue(N, 0);
4797 
4798   return SDValue();
4799 }
4800 
4801 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4802 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4803   if (Op.getOpcode() == ISD::AND) {
4804     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4805       Mask = Op.getOperand(1);
4806       Op = Op.getOperand(0);
4807     } else {
4808       return false;
4809     }
4810   }
4811 
4812   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4813     Shift = Op;
4814     return true;
4815   }
4816 
4817   return false;
4818 }
4819 
4820 // Return true if we can prove that, whenever Neg and Pos are both in the
4821 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4822 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4823 //
4824 //     (or (shift1 X, Neg), (shift2 X, Pos))
4825 //
4826 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4827 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4828 // to consider shift amounts with defined behavior.
4829 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4830   // If EltSize is a power of 2 then:
4831   //
4832   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4833   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4834   //
4835   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4836   // for the stronger condition:
4837   //
4838   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4839   //
4840   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4841   // we can just replace Neg with Neg' for the rest of the function.
4842   //
4843   // In other cases we check for the even stronger condition:
4844   //
4845   //     Neg == EltSize - Pos                                    [B]
4846   //
4847   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4848   // behavior if Pos == 0 (and consequently Neg == EltSize).
4849   //
4850   // We could actually use [A] whenever EltSize is a power of 2, but the
4851   // only extra cases that it would match are those uninteresting ones
4852   // where Neg and Pos are never in range at the same time.  E.g. for
4853   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4854   // as well as (sub 32, Pos), but:
4855   //
4856   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4857   //
4858   // always invokes undefined behavior for 32-bit X.
4859   //
4860   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4861   unsigned MaskLoBits = 0;
4862   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4863     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4864       if (NegC->getAPIntValue() == EltSize - 1) {
4865         Neg = Neg.getOperand(0);
4866         MaskLoBits = Log2_64(EltSize);
4867       }
4868     }
4869   }
4870 
4871   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4872   if (Neg.getOpcode() != ISD::SUB)
4873     return false;
4874   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4875   if (!NegC)
4876     return false;
4877   SDValue NegOp1 = Neg.getOperand(1);
4878 
4879   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4880   // Pos'.  The truncation is redundant for the purpose of the equality.
4881   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4882     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4883       if (PosC->getAPIntValue() == EltSize - 1)
4884         Pos = Pos.getOperand(0);
4885 
4886   // The condition we need is now:
4887   //
4888   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4889   //
4890   // If NegOp1 == Pos then we need:
4891   //
4892   //              EltSize & Mask == NegC & Mask
4893   //
4894   // (because "x & Mask" is a truncation and distributes through subtraction).
4895   APInt Width;
4896   if (Pos == NegOp1)
4897     Width = NegC->getAPIntValue();
4898 
4899   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4900   // Then the condition we want to prove becomes:
4901   //
4902   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4903   //
4904   // which, again because "x & Mask" is a truncation, becomes:
4905   //
4906   //                NegC & Mask == (EltSize - PosC) & Mask
4907   //             EltSize & Mask == (NegC + PosC) & Mask
4908   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4909     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4910       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4911     else
4912       return false;
4913   } else
4914     return false;
4915 
4916   // Now we just need to check that EltSize & Mask == Width & Mask.
4917   if (MaskLoBits)
4918     // EltSize & Mask is 0 since Mask is EltSize - 1.
4919     return Width.getLoBits(MaskLoBits) == 0;
4920   return Width == EltSize;
4921 }
4922 
4923 // A subroutine of MatchRotate used once we have found an OR of two opposite
4924 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4925 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4926 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4927 // Neg with outer conversions stripped away.
4928 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4929                                        SDValue Neg, SDValue InnerPos,
4930                                        SDValue InnerNeg, unsigned PosOpcode,
4931                                        unsigned NegOpcode, const SDLoc &DL) {
4932   // fold (or (shl x, (*ext y)),
4933   //          (srl x, (*ext (sub 32, y)))) ->
4934   //   (rotl x, y) or (rotr x, (sub 32, y))
4935   //
4936   // fold (or (shl x, (*ext (sub 32, y))),
4937   //          (srl x, (*ext y))) ->
4938   //   (rotr x, y) or (rotl x, (sub 32, y))
4939   EVT VT = Shifted.getValueType();
4940   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4941     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4942     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4943                        HasPos ? Pos : Neg).getNode();
4944   }
4945 
4946   return nullptr;
4947 }
4948 
4949 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4950 // idioms for rotate, and if the target supports rotation instructions, generate
4951 // a rot[lr].
4952 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4953   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4954   EVT VT = LHS.getValueType();
4955   if (!TLI.isTypeLegal(VT)) return nullptr;
4956 
4957   // The target must have at least one rotate flavor.
4958   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4959   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4960   if (!HasROTL && !HasROTR) return nullptr;
4961 
4962   // Check for truncated rotate.
4963   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4964       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4965     assert(LHS.getValueType() == RHS.getValueType());
4966     if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4967       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4968                          SDValue(Rot, 0)).getNode();
4969     }
4970   }
4971 
4972   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4973   SDValue LHSShift;   // The shift.
4974   SDValue LHSMask;    // AND value if any.
4975   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4976     return nullptr; // Not part of a rotate.
4977 
4978   SDValue RHSShift;   // The shift.
4979   SDValue RHSMask;    // AND value if any.
4980   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4981     return nullptr; // Not part of a rotate.
4982 
4983   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4984     return nullptr;   // Not shifting the same value.
4985 
4986   if (LHSShift.getOpcode() == RHSShift.getOpcode())
4987     return nullptr;   // Shifts must disagree.
4988 
4989   // Canonicalize shl to left side in a shl/srl pair.
4990   if (RHSShift.getOpcode() == ISD::SHL) {
4991     std::swap(LHS, RHS);
4992     std::swap(LHSShift, RHSShift);
4993     std::swap(LHSMask, RHSMask);
4994   }
4995 
4996   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4997   SDValue LHSShiftArg = LHSShift.getOperand(0);
4998   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4999   SDValue RHSShiftArg = RHSShift.getOperand(0);
5000   SDValue RHSShiftAmt = RHSShift.getOperand(1);
5001 
5002   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
5003   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
5004   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
5005                                         ConstantSDNode *RHS) {
5006     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
5007   };
5008   if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
5009     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
5010                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
5011 
5012     // If there is an AND of either shifted operand, apply it to the result.
5013     if (LHSMask.getNode() || RHSMask.getNode()) {
5014       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
5015       SDValue Mask = AllOnes;
5016 
5017       if (LHSMask.getNode()) {
5018         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
5019         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5020                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
5021       }
5022       if (RHSMask.getNode()) {
5023         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
5024         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5025                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
5026       }
5027 
5028       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
5029     }
5030 
5031     return Rot.getNode();
5032   }
5033 
5034   // If there is a mask here, and we have a variable shift, we can't be sure
5035   // that we're masking out the right stuff.
5036   if (LHSMask.getNode() || RHSMask.getNode())
5037     return nullptr;
5038 
5039   // If the shift amount is sign/zext/any-extended just peel it off.
5040   SDValue LExtOp0 = LHSShiftAmt;
5041   SDValue RExtOp0 = RHSShiftAmt;
5042   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5043        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5044        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5045        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
5046       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5047        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5048        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5049        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
5050     LExtOp0 = LHSShiftAmt.getOperand(0);
5051     RExtOp0 = RHSShiftAmt.getOperand(0);
5052   }
5053 
5054   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
5055                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
5056   if (TryL)
5057     return TryL;
5058 
5059   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
5060                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
5061   if (TryR)
5062     return TryR;
5063 
5064   return nullptr;
5065 }
5066 
5067 namespace {
5068 
5069 /// Represents known origin of an individual byte in load combine pattern. The
5070 /// value of the byte is either constant zero or comes from memory.
5071 struct ByteProvider {
5072   // For constant zero providers Load is set to nullptr. For memory providers
5073   // Load represents the node which loads the byte from memory.
5074   // ByteOffset is the offset of the byte in the value produced by the load.
5075   LoadSDNode *Load = nullptr;
5076   unsigned ByteOffset = 0;
5077 
5078   ByteProvider() = default;
5079 
5080   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
5081     return ByteProvider(Load, ByteOffset);
5082   }
5083 
5084   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
5085 
5086   bool isConstantZero() const { return !Load; }
5087   bool isMemory() const { return Load; }
5088 
5089   bool operator==(const ByteProvider &Other) const {
5090     return Other.Load == Load && Other.ByteOffset == ByteOffset;
5091   }
5092 
5093 private:
5094   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5095       : Load(Load), ByteOffset(ByteOffset) {}
5096 };
5097 
5098 } // end anonymous namespace
5099 
5100 /// Recursively traverses the expression calculating the origin of the requested
5101 /// byte of the given value. Returns None if the provider can't be calculated.
5102 ///
5103 /// For all the values except the root of the expression verifies that the value
5104 /// has exactly one use and if it's not true return None. This way if the origin
5105 /// of the byte is returned it's guaranteed that the values which contribute to
5106 /// the byte are not used outside of this expression.
5107 ///
5108 /// Because the parts of the expression are not allowed to have more than one
5109 /// use this function iterates over trees, not DAGs. So it never visits the same
5110 /// node more than once.
5111 static const Optional<ByteProvider>
5112 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5113                       bool Root = false) {
5114   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5115   if (Depth == 10)
5116     return None;
5117 
5118   if (!Root && !Op.hasOneUse())
5119     return None;
5120 
5121   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5122   unsigned BitWidth = Op.getValueSizeInBits();
5123   if (BitWidth % 8 != 0)
5124     return None;
5125   unsigned ByteWidth = BitWidth / 8;
5126   assert(Index < ByteWidth && "invalid index requested");
5127   (void) ByteWidth;
5128 
5129   switch (Op.getOpcode()) {
5130   case ISD::OR: {
5131     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5132     if (!LHS)
5133       return None;
5134     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5135     if (!RHS)
5136       return None;
5137 
5138     if (LHS->isConstantZero())
5139       return RHS;
5140     if (RHS->isConstantZero())
5141       return LHS;
5142     return None;
5143   }
5144   case ISD::SHL: {
5145     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5146     if (!ShiftOp)
5147       return None;
5148 
5149     uint64_t BitShift = ShiftOp->getZExtValue();
5150     if (BitShift % 8 != 0)
5151       return None;
5152     uint64_t ByteShift = BitShift / 8;
5153 
5154     return Index < ByteShift
5155                ? ByteProvider::getConstantZero()
5156                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5157                                        Depth + 1);
5158   }
5159   case ISD::ANY_EXTEND:
5160   case ISD::SIGN_EXTEND:
5161   case ISD::ZERO_EXTEND: {
5162     SDValue NarrowOp = Op->getOperand(0);
5163     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5164     if (NarrowBitWidth % 8 != 0)
5165       return None;
5166     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5167 
5168     if (Index >= NarrowByteWidth)
5169       return Op.getOpcode() == ISD::ZERO_EXTEND
5170                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5171                  : None;
5172     return calculateByteProvider(NarrowOp, Index, Depth + 1);
5173   }
5174   case ISD::BSWAP:
5175     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5176                                  Depth + 1);
5177   case ISD::LOAD: {
5178     auto L = cast<LoadSDNode>(Op.getNode());
5179     if (L->isVolatile() || L->isIndexed())
5180       return None;
5181 
5182     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5183     if (NarrowBitWidth % 8 != 0)
5184       return None;
5185     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5186 
5187     if (Index >= NarrowByteWidth)
5188       return L->getExtensionType() == ISD::ZEXTLOAD
5189                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5190                  : None;
5191     return ByteProvider::getMemory(L, Index);
5192   }
5193   }
5194 
5195   return None;
5196 }
5197 
5198 /// Match a pattern where a wide type scalar value is loaded by several narrow
5199 /// loads and combined by shifts and ors. Fold it into a single load or a load
5200 /// and a BSWAP if the targets supports it.
5201 ///
5202 /// Assuming little endian target:
5203 ///  i8 *a = ...
5204 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5205 /// =>
5206 ///  i32 val = *((i32)a)
5207 ///
5208 ///  i8 *a = ...
5209 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5210 /// =>
5211 ///  i32 val = BSWAP(*((i32)a))
5212 ///
5213 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5214 /// interact well with the worklist mechanism. When a part of the pattern is
5215 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5216 /// but the root node of the pattern which triggers the load combine is not
5217 /// necessarily a direct user of the changed node. For example, once the address
5218 /// of t28 load is reassociated load combine won't be triggered:
5219 ///             t25: i32 = add t4, Constant:i32<2>
5220 ///           t26: i64 = sign_extend t25
5221 ///        t27: i64 = add t2, t26
5222 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5223 ///     t29: i32 = zero_extend t28
5224 ///   t32: i32 = shl t29, Constant:i8<8>
5225 /// t33: i32 = or t23, t32
5226 /// As a possible fix visitLoad can check if the load can be a part of a load
5227 /// combine pattern and add corresponding OR roots to the worklist.
5228 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5229   assert(N->getOpcode() == ISD::OR &&
5230          "Can only match load combining against OR nodes");
5231 
5232   // Handles simple types only
5233   EVT VT = N->getValueType(0);
5234   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5235     return SDValue();
5236   unsigned ByteWidth = VT.getSizeInBits() / 8;
5237 
5238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5239   // Before legalize we can introduce too wide illegal loads which will be later
5240   // split into legal sized loads. This enables us to combine i64 load by i8
5241   // patterns to a couple of i32 loads on 32 bit targets.
5242   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5243     return SDValue();
5244 
5245   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5246     unsigned BW, unsigned i) { return i; };
5247   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5248     unsigned BW, unsigned i) { return BW - i - 1; };
5249 
5250   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5251   auto MemoryByteOffset = [&] (ByteProvider P) {
5252     assert(P.isMemory() && "Must be a memory byte provider");
5253     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5254     assert(LoadBitWidth % 8 == 0 &&
5255            "can only analyze providers for individual bytes not bit");
5256     unsigned LoadByteWidth = LoadBitWidth / 8;
5257     return IsBigEndianTarget
5258             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5259             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5260   };
5261 
5262   Optional<BaseIndexOffset> Base;
5263   SDValue Chain;
5264 
5265   SmallSet<LoadSDNode *, 8> Loads;
5266   Optional<ByteProvider> FirstByteProvider;
5267   int64_t FirstOffset = INT64_MAX;
5268 
5269   // Check if all the bytes of the OR we are looking at are loaded from the same
5270   // base address. Collect bytes offsets from Base address in ByteOffsets.
5271   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5272   for (unsigned i = 0; i < ByteWidth; i++) {
5273     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5274     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5275       return SDValue();
5276 
5277     LoadSDNode *L = P->Load;
5278     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5279            "Must be enforced by calculateByteProvider");
5280     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5281 
5282     // All loads must share the same chain
5283     SDValue LChain = L->getChain();
5284     if (!Chain)
5285       Chain = LChain;
5286     else if (Chain != LChain)
5287       return SDValue();
5288 
5289     // Loads must share the same base address
5290     BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
5291     int64_t ByteOffsetFromBase = 0;
5292     if (!Base)
5293       Base = Ptr;
5294     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5295       return SDValue();
5296 
5297     // Calculate the offset of the current byte from the base address
5298     ByteOffsetFromBase += MemoryByteOffset(*P);
5299     ByteOffsets[i] = ByteOffsetFromBase;
5300 
5301     // Remember the first byte load
5302     if (ByteOffsetFromBase < FirstOffset) {
5303       FirstByteProvider = P;
5304       FirstOffset = ByteOffsetFromBase;
5305     }
5306 
5307     Loads.insert(L);
5308   }
5309   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5310          "memory, so there must be at least one load which produces the value");
5311   assert(Base && "Base address of the accessed memory location must be set");
5312   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5313 
5314   // Check if the bytes of the OR we are looking at match with either big or
5315   // little endian value load
5316   bool BigEndian = true, LittleEndian = true;
5317   for (unsigned i = 0; i < ByteWidth; i++) {
5318     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5319     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5320     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5321     if (!BigEndian && !LittleEndian)
5322       return SDValue();
5323   }
5324   assert((BigEndian != LittleEndian) && "should be either or");
5325   assert(FirstByteProvider && "must be set");
5326 
5327   // Ensure that the first byte is loaded from zero offset of the first load.
5328   // So the combined value can be loaded from the first load address.
5329   if (MemoryByteOffset(*FirstByteProvider) != 0)
5330     return SDValue();
5331   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5332 
5333   // The node we are looking at matches with the pattern, check if we can
5334   // replace it with a single load and bswap if needed.
5335 
5336   // If the load needs byte swap check if the target supports it
5337   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5338 
5339   // Before legalize we can introduce illegal bswaps which will be later
5340   // converted to an explicit bswap sequence. This way we end up with a single
5341   // load and byte shuffling instead of several loads and byte shuffling.
5342   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5343     return SDValue();
5344 
5345   // Check that a load of the wide type is both allowed and fast on the target
5346   bool Fast = false;
5347   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5348                                         VT, FirstLoad->getAddressSpace(),
5349                                         FirstLoad->getAlignment(), &Fast);
5350   if (!Allowed || !Fast)
5351     return SDValue();
5352 
5353   SDValue NewLoad =
5354       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5355                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5356 
5357   // Transfer chain users from old loads to the new load.
5358   for (LoadSDNode *L : Loads)
5359     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5360 
5361   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5362 }
5363 
5364 SDValue DAGCombiner::visitXOR(SDNode *N) {
5365   SDValue N0 = N->getOperand(0);
5366   SDValue N1 = N->getOperand(1);
5367   EVT VT = N0.getValueType();
5368 
5369   // fold vector ops
5370   if (VT.isVector()) {
5371     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5372       return FoldedVOp;
5373 
5374     // fold (xor x, 0) -> x, vector edition
5375     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5376       return N1;
5377     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5378       return N0;
5379   }
5380 
5381   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5382   if (N0.isUndef() && N1.isUndef())
5383     return DAG.getConstant(0, SDLoc(N), VT);
5384   // fold (xor x, undef) -> undef
5385   if (N0.isUndef())
5386     return N0;
5387   if (N1.isUndef())
5388     return N1;
5389   // fold (xor c1, c2) -> c1^c2
5390   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5391   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5392   if (N0C && N1C)
5393     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5394   // canonicalize constant to RHS
5395   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5396      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5397     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5398   // fold (xor x, 0) -> x
5399   if (isNullConstant(N1))
5400     return N0;
5401 
5402   if (SDValue NewSel = foldBinOpIntoSelect(N))
5403     return NewSel;
5404 
5405   // reassociate xor
5406   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5407     return RXOR;
5408 
5409   // fold !(x cc y) -> (x !cc y)
5410   SDValue LHS, RHS, CC;
5411   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5412     bool isInt = LHS.getValueType().isInteger();
5413     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5414                                                isInt);
5415 
5416     if (!LegalOperations ||
5417         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5418       switch (N0.getOpcode()) {
5419       default:
5420         llvm_unreachable("Unhandled SetCC Equivalent!");
5421       case ISD::SETCC:
5422         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5423       case ISD::SELECT_CC:
5424         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5425                                N0.getOperand(3), NotCC);
5426       }
5427     }
5428   }
5429 
5430   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5431   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5432       N0.getNode()->hasOneUse() &&
5433       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5434     SDValue V = N0.getOperand(0);
5435     SDLoc DL(N0);
5436     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5437                     DAG.getConstant(1, DL, V.getValueType()));
5438     AddToWorklist(V.getNode());
5439     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5440   }
5441 
5442   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5443   if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
5444       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5445     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5446     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5447       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5448       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5449       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5450       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5451       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5452     }
5453   }
5454   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5455   if (isAllOnesConstant(N1) && N0.hasOneUse() &&
5456       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5457     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5458     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5459       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5460       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5461       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5462       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5463       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5464     }
5465   }
5466   // fold (xor (and x, y), y) -> (and (not x), y)
5467   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5468       N0->getOperand(1) == N1) {
5469     SDValue X = N0->getOperand(0);
5470     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5471     AddToWorklist(NotX.getNode());
5472     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5473   }
5474 
5475   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5476   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5477   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5478       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5479       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5480     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5481       if (C->getAPIntValue() == (OpSizeInBits - 1))
5482         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5483   }
5484 
5485   // fold (xor x, x) -> 0
5486   if (N0 == N1)
5487     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5488 
5489   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5490   // Here is a concrete example of this equivalence:
5491   // i16   x ==  14
5492   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5493   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5494   //
5495   // =>
5496   //
5497   // i16     ~1      == 0b1111111111111110
5498   // i16 rol(~1, 14) == 0b1011111111111111
5499   //
5500   // Some additional tips to help conceptualize this transform:
5501   // - Try to see the operation as placing a single zero in a value of all ones.
5502   // - There exists no value for x which would allow the result to contain zero.
5503   // - Values of x larger than the bitwidth are undefined and do not require a
5504   //   consistent result.
5505   // - Pushing the zero left requires shifting one bits in from the right.
5506   // A rotate left of ~1 is a nice way of achieving the desired result.
5507   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5508       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5509     SDLoc DL(N);
5510     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5511                        N0.getOperand(1));
5512   }
5513 
5514   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5515   if (N0.getOpcode() == N1.getOpcode())
5516     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5517       return Tmp;
5518 
5519   // Simplify the expression using non-local knowledge.
5520   if (SimplifyDemandedBits(SDValue(N, 0)))
5521     return SDValue(N, 0);
5522 
5523   return SDValue();
5524 }
5525 
5526 /// Handle transforms common to the three shifts, when the shift amount is a
5527 /// constant.
5528 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5529   SDNode *LHS = N->getOperand(0).getNode();
5530   if (!LHS->hasOneUse()) return SDValue();
5531 
5532   // We want to pull some binops through shifts, so that we have (and (shift))
5533   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5534   // thing happens with address calculations, so it's important to canonicalize
5535   // it.
5536   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5537 
5538   switch (LHS->getOpcode()) {
5539   default: return SDValue();
5540   case ISD::OR:
5541   case ISD::XOR:
5542     HighBitSet = false; // We can only transform sra if the high bit is clear.
5543     break;
5544   case ISD::AND:
5545     HighBitSet = true;  // We can only transform sra if the high bit is set.
5546     break;
5547   case ISD::ADD:
5548     if (N->getOpcode() != ISD::SHL)
5549       return SDValue(); // only shl(add) not sr[al](add).
5550     HighBitSet = false; // We can only transform sra if the high bit is clear.
5551     break;
5552   }
5553 
5554   // We require the RHS of the binop to be a constant and not opaque as well.
5555   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5556   if (!BinOpCst) return SDValue();
5557 
5558   // FIXME: disable this unless the input to the binop is a shift by a constant
5559   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5560   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5561   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5562                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5563                  BinOpLHSVal->getOpcode() == ISD::SRL;
5564   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5565                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5566 
5567   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5568       !isCopyOrSelect)
5569     return SDValue();
5570 
5571   if (isCopyOrSelect && N->hasOneUse())
5572     return SDValue();
5573 
5574   EVT VT = N->getValueType(0);
5575 
5576   // If this is a signed shift right, and the high bit is modified by the
5577   // logical operation, do not perform the transformation. The highBitSet
5578   // boolean indicates the value of the high bit of the constant which would
5579   // cause it to be modified for this operation.
5580   if (N->getOpcode() == ISD::SRA) {
5581     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5582     if (BinOpRHSSignSet != HighBitSet)
5583       return SDValue();
5584   }
5585 
5586   if (!TLI.isDesirableToCommuteWithShift(LHS))
5587     return SDValue();
5588 
5589   // Fold the constants, shifting the binop RHS by the shift amount.
5590   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5591                                N->getValueType(0),
5592                                LHS->getOperand(1), N->getOperand(1));
5593   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5594 
5595   // Create the new shift.
5596   SDValue NewShift = DAG.getNode(N->getOpcode(),
5597                                  SDLoc(LHS->getOperand(0)),
5598                                  VT, LHS->getOperand(0), N->getOperand(1));
5599 
5600   // Create the new binop.
5601   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5602 }
5603 
5604 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5605   assert(N->getOpcode() == ISD::TRUNCATE);
5606   assert(N->getOperand(0).getOpcode() == ISD::AND);
5607 
5608   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5609   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5610     SDValue N01 = N->getOperand(0).getOperand(1);
5611     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5612       SDLoc DL(N);
5613       EVT TruncVT = N->getValueType(0);
5614       SDValue N00 = N->getOperand(0).getOperand(0);
5615       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5616       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5617       AddToWorklist(Trunc00.getNode());
5618       AddToWorklist(Trunc01.getNode());
5619       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5620     }
5621   }
5622 
5623   return SDValue();
5624 }
5625 
5626 SDValue DAGCombiner::visitRotate(SDNode *N) {
5627   SDLoc dl(N);
5628   SDValue N0 = N->getOperand(0);
5629   SDValue N1 = N->getOperand(1);
5630   EVT VT = N->getValueType(0);
5631   unsigned Bitsize = VT.getScalarSizeInBits();
5632 
5633   // fold (rot x, 0) -> x
5634   if (isNullConstantOrNullSplatConstant(N1))
5635     return N0;
5636 
5637   // fold (rot x, c) -> (rot x, c % BitSize)
5638   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5639     if (Cst->getAPIntValue().uge(Bitsize)) {
5640       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5641       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5642                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5643     }
5644   }
5645 
5646   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5647   if (N1.getOpcode() == ISD::TRUNCATE &&
5648       N1.getOperand(0).getOpcode() == ISD::AND) {
5649     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5650       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5651   }
5652 
5653   unsigned NextOp = N0.getOpcode();
5654   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5655   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5656     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5657     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5658     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5659       EVT ShiftVT = C1->getValueType(0);
5660       bool SameSide = (N->getOpcode() == NextOp);
5661       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5662       if (SDValue CombinedShift =
5663               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5664         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5665         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5666             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5667             BitsizeC.getNode());
5668         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5669                            CombinedShiftNorm);
5670       }
5671     }
5672   }
5673   return SDValue();
5674 }
5675 
5676 SDValue DAGCombiner::visitSHL(SDNode *N) {
5677   SDValue N0 = N->getOperand(0);
5678   SDValue N1 = N->getOperand(1);
5679   EVT VT = N0.getValueType();
5680   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5681 
5682   // fold vector ops
5683   if (VT.isVector()) {
5684     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5685       return FoldedVOp;
5686 
5687     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5688     // If setcc produces all-one true value then:
5689     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5690     if (N1CV && N1CV->isConstant()) {
5691       if (N0.getOpcode() == ISD::AND) {
5692         SDValue N00 = N0->getOperand(0);
5693         SDValue N01 = N0->getOperand(1);
5694         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5695 
5696         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5697             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5698                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5699           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5700                                                      N01CV, N1CV))
5701             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5702         }
5703       }
5704     }
5705   }
5706 
5707   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5708 
5709   // fold (shl c1, c2) -> c1<<c2
5710   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5711   if (N0C && N1C && !N1C->isOpaque())
5712     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5713   // fold (shl 0, x) -> 0
5714   if (isNullConstantOrNullSplatConstant(N0))
5715     return N0;
5716   // fold (shl x, c >= size(x)) -> undef
5717   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5718   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5719     return Val->getAPIntValue().uge(OpSizeInBits);
5720   };
5721   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
5722     return DAG.getUNDEF(VT);
5723   // fold (shl x, 0) -> x
5724   if (N1C && N1C->isNullValue())
5725     return N0;
5726   // fold (shl undef, x) -> 0
5727   if (N0.isUndef())
5728     return DAG.getConstant(0, SDLoc(N), VT);
5729 
5730   if (SDValue NewSel = foldBinOpIntoSelect(N))
5731     return NewSel;
5732 
5733   // if (shl x, c) is known to be zero, return 0
5734   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5735                             APInt::getAllOnesValue(OpSizeInBits)))
5736     return DAG.getConstant(0, SDLoc(N), VT);
5737   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5738   if (N1.getOpcode() == ISD::TRUNCATE &&
5739       N1.getOperand(0).getOpcode() == ISD::AND) {
5740     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5741       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5742   }
5743 
5744   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5745     return SDValue(N, 0);
5746 
5747   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5748   if (N0.getOpcode() == ISD::SHL) {
5749     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5750                                           ConstantSDNode *RHS) {
5751       APInt c1 = LHS->getAPIntValue();
5752       APInt c2 = RHS->getAPIntValue();
5753       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5754       return (c1 + c2).uge(OpSizeInBits);
5755     };
5756     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5757       return DAG.getConstant(0, SDLoc(N), VT);
5758 
5759     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5760                                        ConstantSDNode *RHS) {
5761       APInt c1 = LHS->getAPIntValue();
5762       APInt c2 = RHS->getAPIntValue();
5763       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5764       return (c1 + c2).ult(OpSizeInBits);
5765     };
5766     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5767       SDLoc DL(N);
5768       EVT ShiftVT = N1.getValueType();
5769       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5770       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5771     }
5772   }
5773 
5774   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5775   // For this to be valid, the second form must not preserve any of the bits
5776   // that are shifted out by the inner shift in the first form.  This means
5777   // the outer shift size must be >= the number of bits added by the ext.
5778   // As a corollary, we don't care what kind of ext it is.
5779   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5780               N0.getOpcode() == ISD::ANY_EXTEND ||
5781               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5782       N0.getOperand(0).getOpcode() == ISD::SHL) {
5783     SDValue N0Op0 = N0.getOperand(0);
5784     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5785       APInt c1 = N0Op0C1->getAPIntValue();
5786       APInt c2 = N1C->getAPIntValue();
5787       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5788 
5789       EVT InnerShiftVT = N0Op0.getValueType();
5790       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5791       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5792         SDLoc DL(N0);
5793         APInt Sum = c1 + c2;
5794         if (Sum.uge(OpSizeInBits))
5795           return DAG.getConstant(0, DL, VT);
5796 
5797         return DAG.getNode(
5798             ISD::SHL, DL, VT,
5799             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5800             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5801       }
5802     }
5803   }
5804 
5805   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5806   // Only fold this if the inner zext has no other uses to avoid increasing
5807   // the total number of instructions.
5808   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5809       N0.getOperand(0).getOpcode() == ISD::SRL) {
5810     SDValue N0Op0 = N0.getOperand(0);
5811     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5812       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5813         uint64_t c1 = N0Op0C1->getZExtValue();
5814         uint64_t c2 = N1C->getZExtValue();
5815         if (c1 == c2) {
5816           SDValue NewOp0 = N0.getOperand(0);
5817           EVT CountVT = NewOp0.getOperand(1).getValueType();
5818           SDLoc DL(N);
5819           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5820                                        NewOp0,
5821                                        DAG.getConstant(c2, DL, CountVT));
5822           AddToWorklist(NewSHL.getNode());
5823           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5824         }
5825       }
5826     }
5827   }
5828 
5829   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5830   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5831   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5832       N0->getFlags().hasExact()) {
5833     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5834       uint64_t C1 = N0C1->getZExtValue();
5835       uint64_t C2 = N1C->getZExtValue();
5836       SDLoc DL(N);
5837       if (C1 <= C2)
5838         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5839                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5840       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5841                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5842     }
5843   }
5844 
5845   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5846   //                               (and (srl x, (sub c1, c2), MASK)
5847   // Only fold this if the inner shift has no other uses -- if it does, folding
5848   // this will increase the total number of instructions.
5849   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5850     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5851       uint64_t c1 = N0C1->getZExtValue();
5852       if (c1 < OpSizeInBits) {
5853         uint64_t c2 = N1C->getZExtValue();
5854         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5855         SDValue Shift;
5856         if (c2 > c1) {
5857           Mask <<= c2 - c1;
5858           SDLoc DL(N);
5859           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5860                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5861         } else {
5862           Mask.lshrInPlace(c1 - c2);
5863           SDLoc DL(N);
5864           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5865                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5866         }
5867         SDLoc DL(N0);
5868         return DAG.getNode(ISD::AND, DL, VT, Shift,
5869                            DAG.getConstant(Mask, DL, VT));
5870       }
5871     }
5872   }
5873 
5874   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5875   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5876       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5877     SDLoc DL(N);
5878     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5879     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5880     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5881   }
5882 
5883   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5884   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5885   // Variant of version done on multiply, except mul by a power of 2 is turned
5886   // into a shift.
5887   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5888       N0.getNode()->hasOneUse() &&
5889       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5890       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5891     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5892     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5893     AddToWorklist(Shl0.getNode());
5894     AddToWorklist(Shl1.getNode());
5895     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5896   }
5897 
5898   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5899   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5900       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5901       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5902     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5903     if (isConstantOrConstantVector(Shl))
5904       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5905   }
5906 
5907   if (N1C && !N1C->isOpaque())
5908     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5909       return NewSHL;
5910 
5911   return SDValue();
5912 }
5913 
5914 SDValue DAGCombiner::visitSRA(SDNode *N) {
5915   SDValue N0 = N->getOperand(0);
5916   SDValue N1 = N->getOperand(1);
5917   EVT VT = N0.getValueType();
5918   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5919 
5920   // Arithmetic shifting an all-sign-bit value is a no-op.
5921   // fold (sra 0, x) -> 0
5922   // fold (sra -1, x) -> -1
5923   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5924     return N0;
5925 
5926   // fold vector ops
5927   if (VT.isVector())
5928     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5929       return FoldedVOp;
5930 
5931   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5932 
5933   // fold (sra c1, c2) -> (sra c1, c2)
5934   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5935   if (N0C && N1C && !N1C->isOpaque())
5936     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5937   // fold (sra x, c >= size(x)) -> undef
5938   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5939   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5940     return Val->getAPIntValue().uge(OpSizeInBits);
5941   };
5942   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
5943     return DAG.getUNDEF(VT);
5944   // fold (sra x, 0) -> x
5945   if (N1C && N1C->isNullValue())
5946     return N0;
5947 
5948   if (SDValue NewSel = foldBinOpIntoSelect(N))
5949     return NewSel;
5950 
5951   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5952   // sext_inreg.
5953   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5954     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5955     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5956     if (VT.isVector())
5957       ExtVT = EVT::getVectorVT(*DAG.getContext(),
5958                                ExtVT, VT.getVectorNumElements());
5959     if ((!LegalOperations ||
5960          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5961       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5962                          N0.getOperand(0), DAG.getValueType(ExtVT));
5963   }
5964 
5965   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5966   if (N0.getOpcode() == ISD::SRA) {
5967     SDLoc DL(N);
5968     EVT ShiftVT = N1.getValueType();
5969 
5970     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5971                                           ConstantSDNode *RHS) {
5972       APInt c1 = LHS->getAPIntValue();
5973       APInt c2 = RHS->getAPIntValue();
5974       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5975       return (c1 + c2).uge(OpSizeInBits);
5976     };
5977     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5978       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
5979                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
5980 
5981     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5982                                        ConstantSDNode *RHS) {
5983       APInt c1 = LHS->getAPIntValue();
5984       APInt c2 = RHS->getAPIntValue();
5985       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5986       return (c1 + c2).ult(OpSizeInBits);
5987     };
5988     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5989       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5990       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
5991     }
5992   }
5993 
5994   // fold (sra (shl X, m), (sub result_size, n))
5995   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5996   // result_size - n != m.
5997   // If truncate is free for the target sext(shl) is likely to result in better
5998   // code.
5999   if (N0.getOpcode() == ISD::SHL && N1C) {
6000     // Get the two constanst of the shifts, CN0 = m, CN = n.
6001     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
6002     if (N01C) {
6003       LLVMContext &Ctx = *DAG.getContext();
6004       // Determine what the truncate's result bitsize and type would be.
6005       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
6006 
6007       if (VT.isVector())
6008         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
6009 
6010       // Determine the residual right-shift amount.
6011       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
6012 
6013       // If the shift is not a no-op (in which case this should be just a sign
6014       // extend already), the truncated to type is legal, sign_extend is legal
6015       // on that type, and the truncate to that type is both legal and free,
6016       // perform the transform.
6017       if ((ShiftAmt > 0) &&
6018           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
6019           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
6020           TLI.isTruncateFree(VT, TruncVT)) {
6021         SDLoc DL(N);
6022         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
6023             getShiftAmountTy(N0.getOperand(0).getValueType()));
6024         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
6025                                     N0.getOperand(0), Amt);
6026         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
6027                                     Shift);
6028         return DAG.getNode(ISD::SIGN_EXTEND, DL,
6029                            N->getValueType(0), Trunc);
6030       }
6031     }
6032   }
6033 
6034   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
6035   if (N1.getOpcode() == ISD::TRUNCATE &&
6036       N1.getOperand(0).getOpcode() == ISD::AND) {
6037     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6038       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
6039   }
6040 
6041   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
6042   //      if c1 is equal to the number of bits the trunc removes
6043   if (N0.getOpcode() == ISD::TRUNCATE &&
6044       (N0.getOperand(0).getOpcode() == ISD::SRL ||
6045        N0.getOperand(0).getOpcode() == ISD::SRA) &&
6046       N0.getOperand(0).hasOneUse() &&
6047       N0.getOperand(0).getOperand(1).hasOneUse() &&
6048       N1C) {
6049     SDValue N0Op0 = N0.getOperand(0);
6050     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
6051       unsigned LargeShiftVal = LargeShift->getZExtValue();
6052       EVT LargeVT = N0Op0.getValueType();
6053 
6054       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
6055         SDLoc DL(N);
6056         SDValue Amt =
6057           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
6058                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
6059         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
6060                                   N0Op0.getOperand(0), Amt);
6061         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
6062       }
6063     }
6064   }
6065 
6066   // Simplify, based on bits shifted out of the LHS.
6067   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6068     return SDValue(N, 0);
6069 
6070   // If the sign bit is known to be zero, switch this to a SRL.
6071   if (DAG.SignBitIsZero(N0))
6072     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
6073 
6074   if (N1C && !N1C->isOpaque())
6075     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6076       return NewSRA;
6077 
6078   return SDValue();
6079 }
6080 
6081 SDValue DAGCombiner::visitSRL(SDNode *N) {
6082   SDValue N0 = N->getOperand(0);
6083   SDValue N1 = N->getOperand(1);
6084   EVT VT = N0.getValueType();
6085   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6086 
6087   // fold vector ops
6088   if (VT.isVector())
6089     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6090       return FoldedVOp;
6091 
6092   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6093 
6094   // fold (srl c1, c2) -> c1 >>u c2
6095   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6096   if (N0C && N1C && !N1C->isOpaque())
6097     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6098   // fold (srl 0, x) -> 0
6099   if (isNullConstantOrNullSplatConstant(N0))
6100     return N0;
6101   // fold (srl x, c >= size(x)) -> undef
6102   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6103   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6104     return Val->getAPIntValue().uge(OpSizeInBits);
6105   };
6106   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6107     return DAG.getUNDEF(VT);
6108   // fold (srl x, 0) -> x
6109   if (N1C && N1C->isNullValue())
6110     return N0;
6111 
6112   if (SDValue NewSel = foldBinOpIntoSelect(N))
6113     return NewSel;
6114 
6115   // if (srl x, c) is known to be zero, return 0
6116   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6117                                    APInt::getAllOnesValue(OpSizeInBits)))
6118     return DAG.getConstant(0, SDLoc(N), VT);
6119 
6120   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6121   if (N0.getOpcode() == ISD::SRL) {
6122     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6123                                           ConstantSDNode *RHS) {
6124       APInt c1 = LHS->getAPIntValue();
6125       APInt c2 = RHS->getAPIntValue();
6126       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6127       return (c1 + c2).uge(OpSizeInBits);
6128     };
6129     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6130       return DAG.getConstant(0, SDLoc(N), VT);
6131 
6132     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6133                                        ConstantSDNode *RHS) {
6134       APInt c1 = LHS->getAPIntValue();
6135       APInt c2 = RHS->getAPIntValue();
6136       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6137       return (c1 + c2).ult(OpSizeInBits);
6138     };
6139     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6140       SDLoc DL(N);
6141       EVT ShiftVT = N1.getValueType();
6142       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6143       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6144     }
6145   }
6146 
6147   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6148   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6149       N0.getOperand(0).getOpcode() == ISD::SRL) {
6150     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6151       uint64_t c1 = N001C->getZExtValue();
6152       uint64_t c2 = N1C->getZExtValue();
6153       EVT InnerShiftVT = N0.getOperand(0).getValueType();
6154       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6155       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6156       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6157       if (c1 + OpSizeInBits == InnerShiftSize) {
6158         SDLoc DL(N0);
6159         if (c1 + c2 >= InnerShiftSize)
6160           return DAG.getConstant(0, DL, VT);
6161         return DAG.getNode(ISD::TRUNCATE, DL, VT,
6162                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6163                                        N0.getOperand(0).getOperand(0),
6164                                        DAG.getConstant(c1 + c2, DL,
6165                                                        ShiftCountVT)));
6166       }
6167     }
6168   }
6169 
6170   // fold (srl (shl x, c), c) -> (and x, cst2)
6171   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6172       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6173     SDLoc DL(N);
6174     SDValue Mask =
6175         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6176     AddToWorklist(Mask.getNode());
6177     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6178   }
6179 
6180   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6181   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6182     // Shifting in all undef bits?
6183     EVT SmallVT = N0.getOperand(0).getValueType();
6184     unsigned BitSize = SmallVT.getScalarSizeInBits();
6185     if (N1C->getZExtValue() >= BitSize)
6186       return DAG.getUNDEF(VT);
6187 
6188     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6189       uint64_t ShiftAmt = N1C->getZExtValue();
6190       SDLoc DL0(N0);
6191       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6192                                        N0.getOperand(0),
6193                           DAG.getConstant(ShiftAmt, DL0,
6194                                           getShiftAmountTy(SmallVT)));
6195       AddToWorklist(SmallShift.getNode());
6196       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6197       SDLoc DL(N);
6198       return DAG.getNode(ISD::AND, DL, VT,
6199                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6200                          DAG.getConstant(Mask, DL, VT));
6201     }
6202   }
6203 
6204   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
6205   // bit, which is unmodified by sra.
6206   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6207     if (N0.getOpcode() == ISD::SRA)
6208       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6209   }
6210 
6211   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
6212   if (N1C && N0.getOpcode() == ISD::CTLZ &&
6213       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6214     KnownBits Known;
6215     DAG.computeKnownBits(N0.getOperand(0), Known);
6216 
6217     // If any of the input bits are KnownOne, then the input couldn't be all
6218     // zeros, thus the result of the srl will always be zero.
6219     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6220 
6221     // If all of the bits input the to ctlz node are known to be zero, then
6222     // the result of the ctlz is "32" and the result of the shift is one.
6223     APInt UnknownBits = ~Known.Zero;
6224     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6225 
6226     // Otherwise, check to see if there is exactly one bit input to the ctlz.
6227     if (UnknownBits.isPowerOf2()) {
6228       // Okay, we know that only that the single bit specified by UnknownBits
6229       // could be set on input to the CTLZ node. If this bit is set, the SRL
6230       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6231       // to an SRL/XOR pair, which is likely to simplify more.
6232       unsigned ShAmt = UnknownBits.countTrailingZeros();
6233       SDValue Op = N0.getOperand(0);
6234 
6235       if (ShAmt) {
6236         SDLoc DL(N0);
6237         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6238                   DAG.getConstant(ShAmt, DL,
6239                                   getShiftAmountTy(Op.getValueType())));
6240         AddToWorklist(Op.getNode());
6241       }
6242 
6243       SDLoc DL(N);
6244       return DAG.getNode(ISD::XOR, DL, VT,
6245                          Op, DAG.getConstant(1, DL, VT));
6246     }
6247   }
6248 
6249   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6250   if (N1.getOpcode() == ISD::TRUNCATE &&
6251       N1.getOperand(0).getOpcode() == ISD::AND) {
6252     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6253       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6254   }
6255 
6256   // fold operands of srl based on knowledge that the low bits are not
6257   // demanded.
6258   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6259     return SDValue(N, 0);
6260 
6261   if (N1C && !N1C->isOpaque())
6262     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6263       return NewSRL;
6264 
6265   // Attempt to convert a srl of a load into a narrower zero-extending load.
6266   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6267     return NarrowLoad;
6268 
6269   // Here is a common situation. We want to optimize:
6270   //
6271   //   %a = ...
6272   //   %b = and i32 %a, 2
6273   //   %c = srl i32 %b, 1
6274   //   brcond i32 %c ...
6275   //
6276   // into
6277   //
6278   //   %a = ...
6279   //   %b = and %a, 2
6280   //   %c = setcc eq %b, 0
6281   //   brcond %c ...
6282   //
6283   // However when after the source operand of SRL is optimized into AND, the SRL
6284   // itself may not be optimized further. Look for it and add the BRCOND into
6285   // the worklist.
6286   if (N->hasOneUse()) {
6287     SDNode *Use = *N->use_begin();
6288     if (Use->getOpcode() == ISD::BRCOND)
6289       AddToWorklist(Use);
6290     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6291       // Also look pass the truncate.
6292       Use = *Use->use_begin();
6293       if (Use->getOpcode() == ISD::BRCOND)
6294         AddToWorklist(Use);
6295     }
6296   }
6297 
6298   return SDValue();
6299 }
6300 
6301 SDValue DAGCombiner::visitABS(SDNode *N) {
6302   SDValue N0 = N->getOperand(0);
6303   EVT VT = N->getValueType(0);
6304 
6305   // fold (abs c1) -> c2
6306   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6307     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6308   // fold (abs (abs x)) -> (abs x)
6309   if (N0.getOpcode() == ISD::ABS)
6310     return N0;
6311   // fold (abs x) -> x iff not-negative
6312   if (DAG.SignBitIsZero(N0))
6313     return N0;
6314   return SDValue();
6315 }
6316 
6317 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6318   SDValue N0 = N->getOperand(0);
6319   EVT VT = N->getValueType(0);
6320 
6321   // fold (bswap c1) -> c2
6322   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6323     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6324   // fold (bswap (bswap x)) -> x
6325   if (N0.getOpcode() == ISD::BSWAP)
6326     return N0->getOperand(0);
6327   return SDValue();
6328 }
6329 
6330 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6331   SDValue N0 = N->getOperand(0);
6332   EVT VT = N->getValueType(0);
6333 
6334   // fold (bitreverse c1) -> c2
6335   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6336     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6337   // fold (bitreverse (bitreverse x)) -> x
6338   if (N0.getOpcode() == ISD::BITREVERSE)
6339     return N0.getOperand(0);
6340   return SDValue();
6341 }
6342 
6343 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6344   SDValue N0 = N->getOperand(0);
6345   EVT VT = N->getValueType(0);
6346 
6347   // fold (ctlz c1) -> c2
6348   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6349     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6350 
6351   // If the value is known never to be zero, switch to the undef version.
6352   if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
6353     if (DAG.isKnownNeverZero(N0))
6354       return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6355   }
6356 
6357   return SDValue();
6358 }
6359 
6360 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6361   SDValue N0 = N->getOperand(0);
6362   EVT VT = N->getValueType(0);
6363 
6364   // fold (ctlz_zero_undef c1) -> c2
6365   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6366     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6367   return SDValue();
6368 }
6369 
6370 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6371   SDValue N0 = N->getOperand(0);
6372   EVT VT = N->getValueType(0);
6373 
6374   // fold (cttz c1) -> c2
6375   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6376     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6377 
6378   // If the value is known never to be zero, switch to the undef version.
6379   if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
6380     if (DAG.isKnownNeverZero(N0))
6381       return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6382   }
6383 
6384   return SDValue();
6385 }
6386 
6387 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6388   SDValue N0 = N->getOperand(0);
6389   EVT VT = N->getValueType(0);
6390 
6391   // fold (cttz_zero_undef c1) -> c2
6392   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6393     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6394   return SDValue();
6395 }
6396 
6397 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6398   SDValue N0 = N->getOperand(0);
6399   EVT VT = N->getValueType(0);
6400 
6401   // fold (ctpop c1) -> c2
6402   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6403     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6404   return SDValue();
6405 }
6406 
6407 /// \brief Generate Min/Max node
6408 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6409                                    SDValue RHS, SDValue True, SDValue False,
6410                                    ISD::CondCode CC, const TargetLowering &TLI,
6411                                    SelectionDAG &DAG) {
6412   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6413     return SDValue();
6414 
6415   switch (CC) {
6416   case ISD::SETOLT:
6417   case ISD::SETOLE:
6418   case ISD::SETLT:
6419   case ISD::SETLE:
6420   case ISD::SETULT:
6421   case ISD::SETULE: {
6422     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6423     if (TLI.isOperationLegal(Opcode, VT))
6424       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6425     return SDValue();
6426   }
6427   case ISD::SETOGT:
6428   case ISD::SETOGE:
6429   case ISD::SETGT:
6430   case ISD::SETGE:
6431   case ISD::SETUGT:
6432   case ISD::SETUGE: {
6433     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6434     if (TLI.isOperationLegal(Opcode, VT))
6435       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6436     return SDValue();
6437   }
6438   default:
6439     return SDValue();
6440   }
6441 }
6442 
6443 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6444   SDValue Cond = N->getOperand(0);
6445   SDValue N1 = N->getOperand(1);
6446   SDValue N2 = N->getOperand(2);
6447   EVT VT = N->getValueType(0);
6448   EVT CondVT = Cond.getValueType();
6449   SDLoc DL(N);
6450 
6451   if (!VT.isInteger())
6452     return SDValue();
6453 
6454   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6455   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6456   if (!C1 || !C2)
6457     return SDValue();
6458 
6459   // Only do this before legalization to avoid conflicting with target-specific
6460   // transforms in the other direction (create a select from a zext/sext). There
6461   // is also a target-independent combine here in DAGCombiner in the other
6462   // direction for (select Cond, -1, 0) when the condition is not i1.
6463   if (CondVT == MVT::i1 && !LegalOperations) {
6464     if (C1->isNullValue() && C2->isOne()) {
6465       // select Cond, 0, 1 --> zext (!Cond)
6466       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6467       if (VT != MVT::i1)
6468         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6469       return NotCond;
6470     }
6471     if (C1->isNullValue() && C2->isAllOnesValue()) {
6472       // select Cond, 0, -1 --> sext (!Cond)
6473       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6474       if (VT != MVT::i1)
6475         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6476       return NotCond;
6477     }
6478     if (C1->isOne() && C2->isNullValue()) {
6479       // select Cond, 1, 0 --> zext (Cond)
6480       if (VT != MVT::i1)
6481         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6482       return Cond;
6483     }
6484     if (C1->isAllOnesValue() && C2->isNullValue()) {
6485       // select Cond, -1, 0 --> sext (Cond)
6486       if (VT != MVT::i1)
6487         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6488       return Cond;
6489     }
6490 
6491     // For any constants that differ by 1, we can transform the select into an
6492     // extend and add. Use a target hook because some targets may prefer to
6493     // transform in the other direction.
6494     if (TLI.convertSelectOfConstantsToMath(VT)) {
6495       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6496         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6497         if (VT != MVT::i1)
6498           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6499         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6500       }
6501       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6502         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6503         if (VT != MVT::i1)
6504           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6505         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6506       }
6507     }
6508 
6509     return SDValue();
6510   }
6511 
6512   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6513   // We can't do this reliably if integer based booleans have different contents
6514   // to floating point based booleans. This is because we can't tell whether we
6515   // have an integer-based boolean or a floating-point-based boolean unless we
6516   // can find the SETCC that produced it and inspect its operands. This is
6517   // fairly easy if C is the SETCC node, but it can potentially be
6518   // undiscoverable (or not reasonably discoverable). For example, it could be
6519   // in another basic block or it could require searching a complicated
6520   // expression.
6521   if (CondVT.isInteger() &&
6522       TLI.getBooleanContents(false, true) ==
6523           TargetLowering::ZeroOrOneBooleanContent &&
6524       TLI.getBooleanContents(false, false) ==
6525           TargetLowering::ZeroOrOneBooleanContent &&
6526       C1->isNullValue() && C2->isOne()) {
6527     SDValue NotCond =
6528         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6529     if (VT.bitsEq(CondVT))
6530       return NotCond;
6531     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6532   }
6533 
6534   return SDValue();
6535 }
6536 
6537 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6538   SDValue N0 = N->getOperand(0);
6539   SDValue N1 = N->getOperand(1);
6540   SDValue N2 = N->getOperand(2);
6541   EVT VT = N->getValueType(0);
6542   EVT VT0 = N0.getValueType();
6543   SDLoc DL(N);
6544 
6545   // fold (select C, X, X) -> X
6546   if (N1 == N2)
6547     return N1;
6548 
6549   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6550     // fold (select true, X, Y) -> X
6551     // fold (select false, X, Y) -> Y
6552     return !N0C->isNullValue() ? N1 : N2;
6553   }
6554 
6555   // fold (select X, X, Y) -> (or X, Y)
6556   // fold (select X, 1, Y) -> (or C, Y)
6557   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6558     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6559 
6560   if (SDValue V = foldSelectOfConstants(N))
6561     return V;
6562 
6563   // fold (select C, 0, X) -> (and (not C), X)
6564   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6565     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6566     AddToWorklist(NOTNode.getNode());
6567     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6568   }
6569   // fold (select C, X, 1) -> (or (not C), X)
6570   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6571     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6572     AddToWorklist(NOTNode.getNode());
6573     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6574   }
6575   // fold (select X, Y, X) -> (and X, Y)
6576   // fold (select X, Y, 0) -> (and X, Y)
6577   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6578     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6579 
6580   // If we can fold this based on the true/false value, do so.
6581   if (SimplifySelectOps(N, N1, N2))
6582     return SDValue(N, 0); // Don't revisit N.
6583 
6584   if (VT0 == MVT::i1) {
6585     // The code in this block deals with the following 2 equivalences:
6586     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6587     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6588     // The target can specify its preferred form with the
6589     // shouldNormalizeToSelectSequence() callback. However we always transform
6590     // to the right anyway if we find the inner select exists in the DAG anyway
6591     // and we always transform to the left side if we know that we can further
6592     // optimize the combination of the conditions.
6593     bool normalizeToSequence =
6594         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6595     // select (and Cond0, Cond1), X, Y
6596     //   -> select Cond0, (select Cond1, X, Y), Y
6597     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6598       SDValue Cond0 = N0->getOperand(0);
6599       SDValue Cond1 = N0->getOperand(1);
6600       SDValue InnerSelect =
6601           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6602       if (normalizeToSequence || !InnerSelect.use_empty())
6603         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6604                            InnerSelect, N2);
6605     }
6606     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6607     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6608       SDValue Cond0 = N0->getOperand(0);
6609       SDValue Cond1 = N0->getOperand(1);
6610       SDValue InnerSelect =
6611           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6612       if (normalizeToSequence || !InnerSelect.use_empty())
6613         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6614                            InnerSelect);
6615     }
6616 
6617     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6618     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6619       SDValue N1_0 = N1->getOperand(0);
6620       SDValue N1_1 = N1->getOperand(1);
6621       SDValue N1_2 = N1->getOperand(2);
6622       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6623         // Create the actual and node if we can generate good code for it.
6624         if (!normalizeToSequence) {
6625           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6626           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6627         }
6628         // Otherwise see if we can optimize the "and" to a better pattern.
6629         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6630           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6631                              N2);
6632       }
6633     }
6634     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6635     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6636       SDValue N2_0 = N2->getOperand(0);
6637       SDValue N2_1 = N2->getOperand(1);
6638       SDValue N2_2 = N2->getOperand(2);
6639       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6640         // Create the actual or node if we can generate good code for it.
6641         if (!normalizeToSequence) {
6642           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6643           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6644         }
6645         // Otherwise see if we can optimize to a better pattern.
6646         if (SDValue Combined = visitORLike(N0, N2_0, N))
6647           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6648                              N2_2);
6649       }
6650     }
6651   }
6652 
6653   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6654   if (VT0 == MVT::i1) {
6655     if (N0->getOpcode() == ISD::XOR) {
6656       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6657         SDValue Cond0 = N0->getOperand(0);
6658         if (C->isOne())
6659           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6660       }
6661     }
6662   }
6663 
6664   // fold selects based on a setcc into other things, such as min/max/abs
6665   if (N0.getOpcode() == ISD::SETCC) {
6666     // select x, y (fcmp lt x, y) -> fminnum x, y
6667     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6668     //
6669     // This is OK if we don't care about what happens if either operand is a
6670     // NaN.
6671     //
6672 
6673     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6674     // no signed zeros as well as no nans.
6675     const TargetOptions &Options = DAG.getTarget().Options;
6676     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6677         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6678       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6679 
6680       if (SDValue FMinMax = combineMinNumMaxNum(
6681               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6682         return FMinMax;
6683     }
6684 
6685     if ((!LegalOperations &&
6686          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6687         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6688       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6689                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6690     return SimplifySelect(DL, N0, N1, N2);
6691   }
6692 
6693   return SDValue();
6694 }
6695 
6696 static
6697 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6698   SDLoc DL(N);
6699   EVT LoVT, HiVT;
6700   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6701 
6702   // Split the inputs.
6703   SDValue Lo, Hi, LL, LH, RL, RH;
6704   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6705   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6706 
6707   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6708   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6709 
6710   return std::make_pair(Lo, Hi);
6711 }
6712 
6713 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6714 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6715 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6716   SDLoc DL(N);
6717   SDValue Cond = N->getOperand(0);
6718   SDValue LHS = N->getOperand(1);
6719   SDValue RHS = N->getOperand(2);
6720   EVT VT = N->getValueType(0);
6721   int NumElems = VT.getVectorNumElements();
6722   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6723          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6724          Cond.getOpcode() == ISD::BUILD_VECTOR);
6725 
6726   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6727   // binary ones here.
6728   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6729     return SDValue();
6730 
6731   // We're sure we have an even number of elements due to the
6732   // concat_vectors we have as arguments to vselect.
6733   // Skip BV elements until we find one that's not an UNDEF
6734   // After we find an UNDEF element, keep looping until we get to half the
6735   // length of the BV and see if all the non-undef nodes are the same.
6736   ConstantSDNode *BottomHalf = nullptr;
6737   for (int i = 0; i < NumElems / 2; ++i) {
6738     if (Cond->getOperand(i)->isUndef())
6739       continue;
6740 
6741     if (BottomHalf == nullptr)
6742       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6743     else if (Cond->getOperand(i).getNode() != BottomHalf)
6744       return SDValue();
6745   }
6746 
6747   // Do the same for the second half of the BuildVector
6748   ConstantSDNode *TopHalf = nullptr;
6749   for (int i = NumElems / 2; i < NumElems; ++i) {
6750     if (Cond->getOperand(i)->isUndef())
6751       continue;
6752 
6753     if (TopHalf == nullptr)
6754       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6755     else if (Cond->getOperand(i).getNode() != TopHalf)
6756       return SDValue();
6757   }
6758 
6759   assert(TopHalf && BottomHalf &&
6760          "One half of the selector was all UNDEFs and the other was all the "
6761          "same value. This should have been addressed before this function.");
6762   return DAG.getNode(
6763       ISD::CONCAT_VECTORS, DL, VT,
6764       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6765       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6766 }
6767 
6768 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6769   if (Level >= AfterLegalizeTypes)
6770     return SDValue();
6771 
6772   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6773   SDValue Mask = MSC->getMask();
6774   SDValue Data  = MSC->getValue();
6775   SDLoc DL(N);
6776 
6777   // If the MSCATTER data type requires splitting and the mask is provided by a
6778   // SETCC, then split both nodes and its operands before legalization. This
6779   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6780   // and enables future optimizations (e.g. min/max pattern matching on X86).
6781   if (Mask.getOpcode() != ISD::SETCC)
6782     return SDValue();
6783 
6784   // Check if any splitting is required.
6785   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6786       TargetLowering::TypeSplitVector)
6787     return SDValue();
6788   SDValue MaskLo, MaskHi, Lo, Hi;
6789   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6790 
6791   EVT LoVT, HiVT;
6792   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6793 
6794   SDValue Chain = MSC->getChain();
6795 
6796   EVT MemoryVT = MSC->getMemoryVT();
6797   unsigned Alignment = MSC->getOriginalAlignment();
6798 
6799   EVT LoMemVT, HiMemVT;
6800   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6801 
6802   SDValue DataLo, DataHi;
6803   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6804 
6805   SDValue Scale = MSC->getScale();
6806   SDValue BasePtr = MSC->getBasePtr();
6807   SDValue IndexLo, IndexHi;
6808   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6809 
6810   MachineMemOperand *MMO = DAG.getMachineFunction().
6811     getMachineMemOperand(MSC->getPointerInfo(),
6812                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6813                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6814 
6815   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale };
6816   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6817                             DL, OpsLo, MMO);
6818 
6819   SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale };
6820   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6821                             DL, OpsHi, MMO);
6822 
6823   AddToWorklist(Lo.getNode());
6824   AddToWorklist(Hi.getNode());
6825 
6826   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6827 }
6828 
6829 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6830   if (Level >= AfterLegalizeTypes)
6831     return SDValue();
6832 
6833   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6834   SDValue Mask = MST->getMask();
6835   SDValue Data  = MST->getValue();
6836   EVT VT = Data.getValueType();
6837   SDLoc DL(N);
6838 
6839   // If the MSTORE data type requires splitting and the mask is provided by a
6840   // SETCC, then split both nodes and its operands before legalization. This
6841   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6842   // and enables future optimizations (e.g. min/max pattern matching on X86).
6843   if (Mask.getOpcode() == ISD::SETCC) {
6844     // Check if any splitting is required.
6845     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6846         TargetLowering::TypeSplitVector)
6847       return SDValue();
6848 
6849     SDValue MaskLo, MaskHi, Lo, Hi;
6850     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6851 
6852     SDValue Chain = MST->getChain();
6853     SDValue Ptr   = MST->getBasePtr();
6854 
6855     EVT MemoryVT = MST->getMemoryVT();
6856     unsigned Alignment = MST->getOriginalAlignment();
6857 
6858     // if Alignment is equal to the vector size,
6859     // take the half of it for the second part
6860     unsigned SecondHalfAlignment =
6861       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6862 
6863     EVT LoMemVT, HiMemVT;
6864     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6865 
6866     SDValue DataLo, DataHi;
6867     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6868 
6869     MachineMemOperand *MMO = DAG.getMachineFunction().
6870       getMachineMemOperand(MST->getPointerInfo(),
6871                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6872                            Alignment, MST->getAAInfo(), MST->getRanges());
6873 
6874     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6875                             MST->isTruncatingStore(),
6876                             MST->isCompressingStore());
6877 
6878     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6879                                      MST->isCompressingStore());
6880     unsigned HiOffset = LoMemVT.getStoreSize();
6881 
6882     MMO = DAG.getMachineFunction().getMachineMemOperand(
6883         MST->getPointerInfo().getWithOffset(HiOffset),
6884         MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment,
6885         MST->getAAInfo(), MST->getRanges());
6886 
6887     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6888                             MST->isTruncatingStore(),
6889                             MST->isCompressingStore());
6890 
6891     AddToWorklist(Lo.getNode());
6892     AddToWorklist(Hi.getNode());
6893 
6894     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6895   }
6896   return SDValue();
6897 }
6898 
6899 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6900   if (Level >= AfterLegalizeTypes)
6901     return SDValue();
6902 
6903   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
6904   SDValue Mask = MGT->getMask();
6905   SDLoc DL(N);
6906 
6907   // If the MGATHER result requires splitting and the mask is provided by a
6908   // SETCC, then split both nodes and its operands before legalization. This
6909   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6910   // and enables future optimizations (e.g. min/max pattern matching on X86).
6911 
6912   if (Mask.getOpcode() != ISD::SETCC)
6913     return SDValue();
6914 
6915   EVT VT = N->getValueType(0);
6916 
6917   // Check if any splitting is required.
6918   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6919       TargetLowering::TypeSplitVector)
6920     return SDValue();
6921 
6922   SDValue MaskLo, MaskHi, Lo, Hi;
6923   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6924 
6925   SDValue Src0 = MGT->getValue();
6926   SDValue Src0Lo, Src0Hi;
6927   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6928 
6929   EVT LoVT, HiVT;
6930   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6931 
6932   SDValue Chain = MGT->getChain();
6933   EVT MemoryVT = MGT->getMemoryVT();
6934   unsigned Alignment = MGT->getOriginalAlignment();
6935 
6936   EVT LoMemVT, HiMemVT;
6937   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6938 
6939   SDValue Scale = MGT->getScale();
6940   SDValue BasePtr = MGT->getBasePtr();
6941   SDValue Index = MGT->getIndex();
6942   SDValue IndexLo, IndexHi;
6943   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6944 
6945   MachineMemOperand *MMO = DAG.getMachineFunction().
6946     getMachineMemOperand(MGT->getPointerInfo(),
6947                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
6948                           Alignment, MGT->getAAInfo(), MGT->getRanges());
6949 
6950   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale };
6951   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6952                            MMO);
6953 
6954   SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale };
6955   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6956                            MMO);
6957 
6958   AddToWorklist(Lo.getNode());
6959   AddToWorklist(Hi.getNode());
6960 
6961   // Build a factor node to remember that this load is independent of the
6962   // other one.
6963   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6964                       Hi.getValue(1));
6965 
6966   // Legalized the chain result - switch anything that used the old chain to
6967   // use the new one.
6968   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6969 
6970   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6971 
6972   SDValue RetOps[] = { GatherRes, Chain };
6973   return DAG.getMergeValues(RetOps, DL);
6974 }
6975 
6976 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6977   if (Level >= AfterLegalizeTypes)
6978     return SDValue();
6979 
6980   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6981   SDValue Mask = MLD->getMask();
6982   SDLoc DL(N);
6983 
6984   // If the MLOAD result requires splitting and the mask is provided by a
6985   // SETCC, then split both nodes and its operands before legalization. This
6986   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6987   // and enables future optimizations (e.g. min/max pattern matching on X86).
6988   if (Mask.getOpcode() == ISD::SETCC) {
6989     EVT VT = N->getValueType(0);
6990 
6991     // Check if any splitting is required.
6992     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6993         TargetLowering::TypeSplitVector)
6994       return SDValue();
6995 
6996     SDValue MaskLo, MaskHi, Lo, Hi;
6997     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6998 
6999     SDValue Src0 = MLD->getSrc0();
7000     SDValue Src0Lo, Src0Hi;
7001     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
7002 
7003     EVT LoVT, HiVT;
7004     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
7005 
7006     SDValue Chain = MLD->getChain();
7007     SDValue Ptr   = MLD->getBasePtr();
7008     EVT MemoryVT = MLD->getMemoryVT();
7009     unsigned Alignment = MLD->getOriginalAlignment();
7010 
7011     // if Alignment is equal to the vector size,
7012     // take the half of it for the second part
7013     unsigned SecondHalfAlignment =
7014       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
7015          Alignment/2 : Alignment;
7016 
7017     EVT LoMemVT, HiMemVT;
7018     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7019 
7020     MachineMemOperand *MMO = DAG.getMachineFunction().
7021     getMachineMemOperand(MLD->getPointerInfo(),
7022                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
7023                          Alignment, MLD->getAAInfo(), MLD->getRanges());
7024 
7025     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
7026                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7027 
7028     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
7029                                      MLD->isExpandingLoad());
7030     unsigned HiOffset = LoMemVT.getStoreSize();
7031 
7032     MMO = DAG.getMachineFunction().getMachineMemOperand(
7033         MLD->getPointerInfo().getWithOffset(HiOffset),
7034         MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment,
7035         MLD->getAAInfo(), MLD->getRanges());
7036 
7037     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
7038                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7039 
7040     AddToWorklist(Lo.getNode());
7041     AddToWorklist(Hi.getNode());
7042 
7043     // Build a factor node to remember that this load is independent of the
7044     // other one.
7045     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7046                         Hi.getValue(1));
7047 
7048     // Legalized the chain result - switch anything that used the old chain to
7049     // use the new one.
7050     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
7051 
7052     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7053 
7054     SDValue RetOps[] = { LoadRes, Chain };
7055     return DAG.getMergeValues(RetOps, DL);
7056   }
7057   return SDValue();
7058 }
7059 
7060 /// A vector select of 2 constant vectors can be simplified to math/logic to
7061 /// avoid a variable select instruction and possibly avoid constant loads.
7062 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
7063   SDValue Cond = N->getOperand(0);
7064   SDValue N1 = N->getOperand(1);
7065   SDValue N2 = N->getOperand(2);
7066   EVT VT = N->getValueType(0);
7067   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
7068       !TLI.convertSelectOfConstantsToMath(VT) ||
7069       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
7070       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
7071     return SDValue();
7072 
7073   // Check if we can use the condition value to increment/decrement a single
7074   // constant value. This simplifies a select to an add and removes a constant
7075   // load/materialization from the general case.
7076   bool AllAddOne = true;
7077   bool AllSubOne = true;
7078   unsigned Elts = VT.getVectorNumElements();
7079   for (unsigned i = 0; i != Elts; ++i) {
7080     SDValue N1Elt = N1.getOperand(i);
7081     SDValue N2Elt = N2.getOperand(i);
7082     if (N1Elt.isUndef() || N2Elt.isUndef())
7083       continue;
7084 
7085     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
7086     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7087     if (C1 != C2 + 1)
7088       AllAddOne = false;
7089     if (C1 != C2 - 1)
7090       AllSubOne = false;
7091   }
7092 
7093   // Further simplifications for the extra-special cases where the constants are
7094   // all 0 or all -1 should be implemented as folds of these patterns.
7095   SDLoc DL(N);
7096   if (AllAddOne || AllSubOne) {
7097     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7098     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7099     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7100     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7101     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7102   }
7103 
7104   // The general case for select-of-constants:
7105   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7106   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7107   // leave that to a machine-specific pass.
7108   return SDValue();
7109 }
7110 
7111 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7112   SDValue N0 = N->getOperand(0);
7113   SDValue N1 = N->getOperand(1);
7114   SDValue N2 = N->getOperand(2);
7115   SDLoc DL(N);
7116 
7117   // fold (vselect C, X, X) -> X
7118   if (N1 == N2)
7119     return N1;
7120 
7121   // Canonicalize integer abs.
7122   // vselect (setg[te] X,  0),  X, -X ->
7123   // vselect (setgt    X, -1),  X, -X ->
7124   // vselect (setl[te] X,  0), -X,  X ->
7125   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7126   if (N0.getOpcode() == ISD::SETCC) {
7127     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7128     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7129     bool isAbs = false;
7130     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7131 
7132     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7133          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7134         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7135       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7136     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7137              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7138       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7139 
7140     if (isAbs) {
7141       EVT VT = LHS.getValueType();
7142       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7143         return DAG.getNode(ISD::ABS, DL, VT, LHS);
7144 
7145       SDValue Shift = DAG.getNode(
7146           ISD::SRA, DL, VT, LHS,
7147           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7148       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7149       AddToWorklist(Shift.getNode());
7150       AddToWorklist(Add.getNode());
7151       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7152     }
7153   }
7154 
7155   if (SimplifySelectOps(N, N1, N2))
7156     return SDValue(N, 0);  // Don't revisit N.
7157 
7158   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7159   if (ISD::isBuildVectorAllOnes(N0.getNode()))
7160     return N1;
7161   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7162   if (ISD::isBuildVectorAllZeros(N0.getNode()))
7163     return N2;
7164 
7165   // The ConvertSelectToConcatVector function is assuming both the above
7166   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7167   // and addressed.
7168   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7169       N2.getOpcode() == ISD::CONCAT_VECTORS &&
7170       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7171     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7172       return CV;
7173   }
7174 
7175   if (SDValue V = foldVSelectOfConstants(N))
7176     return V;
7177 
7178   return SDValue();
7179 }
7180 
7181 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7182   SDValue N0 = N->getOperand(0);
7183   SDValue N1 = N->getOperand(1);
7184   SDValue N2 = N->getOperand(2);
7185   SDValue N3 = N->getOperand(3);
7186   SDValue N4 = N->getOperand(4);
7187   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7188 
7189   // fold select_cc lhs, rhs, x, x, cc -> x
7190   if (N2 == N3)
7191     return N2;
7192 
7193   // Determine if the condition we're dealing with is constant
7194   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7195                                   CC, SDLoc(N), false)) {
7196     AddToWorklist(SCC.getNode());
7197 
7198     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7199       if (!SCCC->isNullValue())
7200         return N2;    // cond always true -> true val
7201       else
7202         return N3;    // cond always false -> false val
7203     } else if (SCC->isUndef()) {
7204       // When the condition is UNDEF, just return the first operand. This is
7205       // coherent the DAG creation, no setcc node is created in this case
7206       return N2;
7207     } else if (SCC.getOpcode() == ISD::SETCC) {
7208       // Fold to a simpler select_cc
7209       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7210                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7211                          SCC.getOperand(2));
7212     }
7213   }
7214 
7215   // If we can fold this based on the true/false value, do so.
7216   if (SimplifySelectOps(N, N2, N3))
7217     return SDValue(N, 0);  // Don't revisit N.
7218 
7219   // fold select_cc into other things, such as min/max/abs
7220   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7221 }
7222 
7223 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7224   // setcc is very commonly used as an argument to brcond. This pattern
7225   // also lend itself to numerous combines and, as a result, it is desired
7226   // we keep the argument to a brcond as a setcc as much as possible.
7227   bool PreferSetCC =
7228       N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
7229 
7230   SDValue Combined = SimplifySetCC(
7231       N->getValueType(0), N->getOperand(0), N->getOperand(1),
7232       cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC);
7233 
7234   if (!Combined)
7235     return SDValue();
7236 
7237   // If we prefer to have a setcc, and we don't, we'll try our best to
7238   // recreate one using rebuildSetCC.
7239   if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
7240     SDValue NewSetCC = rebuildSetCC(Combined);
7241 
7242     // We don't have anything interesting to combine to.
7243     if (NewSetCC.getNode() == N)
7244       return SDValue();
7245 
7246     if (NewSetCC)
7247       return NewSetCC;
7248   }
7249 
7250   return Combined;
7251 }
7252 
7253 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7254   SDValue LHS = N->getOperand(0);
7255   SDValue RHS = N->getOperand(1);
7256   SDValue Carry = N->getOperand(2);
7257   SDValue Cond = N->getOperand(3);
7258 
7259   // If Carry is false, fold to a regular SETCC.
7260   if (Carry.getOpcode() == ISD::CARRY_FALSE)
7261     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7262 
7263   return SDValue();
7264 }
7265 
7266 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7267   SDValue LHS = N->getOperand(0);
7268   SDValue RHS = N->getOperand(1);
7269   SDValue Carry = N->getOperand(2);
7270   SDValue Cond = N->getOperand(3);
7271 
7272   // If Carry is false, fold to a regular SETCC.
7273   if (isNullConstant(Carry))
7274     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7275 
7276   return SDValue();
7277 }
7278 
7279 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7280 /// a build_vector of constants.
7281 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7282 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7283 /// Vector extends are not folded if operations are legal; this is to
7284 /// avoid introducing illegal build_vector dag nodes.
7285 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7286                                          SelectionDAG &DAG, bool LegalTypes,
7287                                          bool LegalOperations) {
7288   unsigned Opcode = N->getOpcode();
7289   SDValue N0 = N->getOperand(0);
7290   EVT VT = N->getValueType(0);
7291 
7292   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7293          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7294          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7295          && "Expected EXTEND dag node in input!");
7296 
7297   // fold (sext c1) -> c1
7298   // fold (zext c1) -> c1
7299   // fold (aext c1) -> c1
7300   if (isa<ConstantSDNode>(N0))
7301     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7302 
7303   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7304   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7305   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7306   EVT SVT = VT.getScalarType();
7307   if (!(VT.isVector() &&
7308       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7309       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7310     return nullptr;
7311 
7312   // We can fold this node into a build_vector.
7313   unsigned VTBits = SVT.getSizeInBits();
7314   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7315   SmallVector<SDValue, 8> Elts;
7316   unsigned NumElts = VT.getVectorNumElements();
7317   SDLoc DL(N);
7318 
7319   for (unsigned i=0; i != NumElts; ++i) {
7320     SDValue Op = N0->getOperand(i);
7321     if (Op->isUndef()) {
7322       Elts.push_back(DAG.getUNDEF(SVT));
7323       continue;
7324     }
7325 
7326     SDLoc DL(Op);
7327     // Get the constant value and if needed trunc it to the size of the type.
7328     // Nodes like build_vector might have constants wider than the scalar type.
7329     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7330     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7331       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7332     else
7333       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7334   }
7335 
7336   return DAG.getBuildVector(VT, DL, Elts).getNode();
7337 }
7338 
7339 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7340 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7341 // transformation. Returns true if extension are possible and the above
7342 // mentioned transformation is profitable.
7343 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
7344                                     unsigned ExtOpc,
7345                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7346                                     const TargetLowering &TLI) {
7347   bool HasCopyToRegUses = false;
7348   bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
7349   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7350                             UE = N0.getNode()->use_end();
7351        UI != UE; ++UI) {
7352     SDNode *User = *UI;
7353     if (User == N)
7354       continue;
7355     if (UI.getUse().getResNo() != N0.getResNo())
7356       continue;
7357     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7358     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7359       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7360       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7361         // Sign bits will be lost after a zext.
7362         return false;
7363       bool Add = false;
7364       for (unsigned i = 0; i != 2; ++i) {
7365         SDValue UseOp = User->getOperand(i);
7366         if (UseOp == N0)
7367           continue;
7368         if (!isa<ConstantSDNode>(UseOp))
7369           return false;
7370         Add = true;
7371       }
7372       if (Add)
7373         ExtendNodes.push_back(User);
7374       continue;
7375     }
7376     // If truncates aren't free and there are users we can't
7377     // extend, it isn't worthwhile.
7378     if (!isTruncFree)
7379       return false;
7380     // Remember if this value is live-out.
7381     if (User->getOpcode() == ISD::CopyToReg)
7382       HasCopyToRegUses = true;
7383   }
7384 
7385   if (HasCopyToRegUses) {
7386     bool BothLiveOut = false;
7387     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7388          UI != UE; ++UI) {
7389       SDUse &Use = UI.getUse();
7390       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7391         BothLiveOut = true;
7392         break;
7393       }
7394     }
7395     if (BothLiveOut)
7396       // Both unextended and extended values are live out. There had better be
7397       // a good reason for the transformation.
7398       return ExtendNodes.size();
7399   }
7400   return true;
7401 }
7402 
7403 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7404                                   SDValue OrigLoad, SDValue ExtLoad,
7405                                   const SDLoc &DL, ISD::NodeType ExtType) {
7406   // Extend SetCC uses if necessary.
7407   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
7408     SDNode *SetCC = SetCCs[i];
7409     SmallVector<SDValue, 4> Ops;
7410 
7411     for (unsigned j = 0; j != 2; ++j) {
7412       SDValue SOp = SetCC->getOperand(j);
7413       if (SOp == OrigLoad)
7414         Ops.push_back(ExtLoad);
7415       else
7416         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7417     }
7418 
7419     Ops.push_back(SetCC->getOperand(2));
7420     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7421   }
7422 }
7423 
7424 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7425 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7426   SDValue N0 = N->getOperand(0);
7427   EVT DstVT = N->getValueType(0);
7428   EVT SrcVT = N0.getValueType();
7429 
7430   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7431           N->getOpcode() == ISD::ZERO_EXTEND) &&
7432          "Unexpected node type (not an extend)!");
7433 
7434   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7435   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7436   //   (v8i32 (sext (v8i16 (load x))))
7437   // into:
7438   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7439   //                          (v4i32 (sextload (x + 16)))))
7440   // Where uses of the original load, i.e.:
7441   //   (v8i16 (load x))
7442   // are replaced with:
7443   //   (v8i16 (truncate
7444   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7445   //                            (v4i32 (sextload (x + 16)))))))
7446   //
7447   // This combine is only applicable to illegal, but splittable, vectors.
7448   // All legal types, and illegal non-vector types, are handled elsewhere.
7449   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7450   //
7451   if (N0->getOpcode() != ISD::LOAD)
7452     return SDValue();
7453 
7454   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7455 
7456   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7457       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7458       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7459     return SDValue();
7460 
7461   SmallVector<SDNode *, 4> SetCCs;
7462   if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
7463     return SDValue();
7464 
7465   ISD::LoadExtType ExtType =
7466       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7467 
7468   // Try to split the vector types to get down to legal types.
7469   EVT SplitSrcVT = SrcVT;
7470   EVT SplitDstVT = DstVT;
7471   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7472          SplitSrcVT.getVectorNumElements() > 1) {
7473     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7474     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7475   }
7476 
7477   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7478     return SDValue();
7479 
7480   SDLoc DL(N);
7481   const unsigned NumSplits =
7482       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7483   const unsigned Stride = SplitSrcVT.getStoreSize();
7484   SmallVector<SDValue, 4> Loads;
7485   SmallVector<SDValue, 4> Chains;
7486 
7487   SDValue BasePtr = LN0->getBasePtr();
7488   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7489     const unsigned Offset = Idx * Stride;
7490     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7491 
7492     SDValue SplitLoad = DAG.getExtLoad(
7493         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7494         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7495         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7496 
7497     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7498                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7499 
7500     Loads.push_back(SplitLoad.getValue(0));
7501     Chains.push_back(SplitLoad.getValue(1));
7502   }
7503 
7504   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7505   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7506 
7507   // Simplify TF.
7508   AddToWorklist(NewChain.getNode());
7509 
7510   CombineTo(N, NewValue);
7511 
7512   // Replace uses of the original load (before extension)
7513   // with a truncate of the concatenated sextloaded vectors.
7514   SDValue Trunc =
7515       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7516   ExtendSetCCUses(SetCCs, N0, NewValue, DL,
7517                   (ISD::NodeType)N->getOpcode());
7518   CombineTo(N0.getNode(), Trunc, NewChain);
7519   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7520 }
7521 
7522 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
7523 //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
7524 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
7525   assert(N->getOpcode() == ISD::ZERO_EXTEND);
7526   EVT VT = N->getValueType(0);
7527 
7528   // and/or/xor
7529   SDValue N0 = N->getOperand(0);
7530   if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7531         N0.getOpcode() == ISD::XOR) ||
7532       N0.getOperand(1).getOpcode() != ISD::Constant ||
7533       (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
7534     return SDValue();
7535 
7536   // shl/shr
7537   SDValue N1 = N0->getOperand(0);
7538   if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
7539       N1.getOperand(1).getOpcode() != ISD::Constant ||
7540       (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
7541     return SDValue();
7542 
7543   // load
7544   if (!isa<LoadSDNode>(N1.getOperand(0)))
7545     return SDValue();
7546   LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
7547   EVT MemVT = Load->getMemoryVT();
7548   if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
7549       Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
7550     return SDValue();
7551 
7552 
7553   // If the shift op is SHL, the logic op must be AND, otherwise the result
7554   // will be wrong.
7555   if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
7556     return SDValue();
7557 
7558   if (!N0.hasOneUse() || !N1.hasOneUse())
7559     return SDValue();
7560 
7561   SmallVector<SDNode*, 4> SetCCs;
7562   if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
7563                                ISD::ZERO_EXTEND, SetCCs, TLI))
7564     return SDValue();
7565 
7566   // Actually do the transformation.
7567   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
7568                                    Load->getChain(), Load->getBasePtr(),
7569                                    Load->getMemoryVT(), Load->getMemOperand());
7570 
7571   SDLoc DL1(N1);
7572   SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
7573                               N1.getOperand(1));
7574 
7575   APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7576   Mask = Mask.zext(VT.getSizeInBits());
7577   SDLoc DL0(N0);
7578   SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
7579                             DAG.getConstant(Mask, DL0, VT));
7580 
7581   ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, SDLoc(Load),
7582                   ISD::ZERO_EXTEND);
7583   CombineTo(N, And);
7584   if (SDValue(Load, 0).hasOneUse()) {
7585     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
7586   } else {
7587     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
7588                                 Load->getValueType(0), ExtLoad);
7589     CombineTo(Load, Trunc, ExtLoad.getValue(1));
7590   }
7591   return SDValue(N,0); // Return N so it doesn't get rechecked!
7592 }
7593 
7594 /// If we're narrowing or widening the result of a vector select and the final
7595 /// size is the same size as a setcc (compare) feeding the select, then try to
7596 /// apply the cast operation to the select's operands because matching vector
7597 /// sizes for a select condition and other operands should be more efficient.
7598 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7599   unsigned CastOpcode = Cast->getOpcode();
7600   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7601           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7602           CastOpcode == ISD::FP_ROUND) &&
7603          "Unexpected opcode for vector select narrowing/widening");
7604 
7605   // We only do this transform before legal ops because the pattern may be
7606   // obfuscated by target-specific operations after legalization. Do not create
7607   // an illegal select op, however, because that may be difficult to lower.
7608   EVT VT = Cast->getValueType(0);
7609   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7610     return SDValue();
7611 
7612   SDValue VSel = Cast->getOperand(0);
7613   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7614       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7615     return SDValue();
7616 
7617   // Does the setcc have the same vector size as the casted select?
7618   SDValue SetCC = VSel.getOperand(0);
7619   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7620   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7621     return SDValue();
7622 
7623   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7624   SDValue A = VSel.getOperand(1);
7625   SDValue B = VSel.getOperand(2);
7626   SDValue CastA, CastB;
7627   SDLoc DL(Cast);
7628   if (CastOpcode == ISD::FP_ROUND) {
7629     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7630     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7631     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7632   } else {
7633     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7634     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7635   }
7636   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7637 }
7638 
7639 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7640   SDValue N0 = N->getOperand(0);
7641   EVT VT = N->getValueType(0);
7642   SDLoc DL(N);
7643 
7644   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7645                                               LegalOperations))
7646     return SDValue(Res, 0);
7647 
7648   // fold (sext (sext x)) -> (sext x)
7649   // fold (sext (aext x)) -> (sext x)
7650   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7651     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7652 
7653   if (N0.getOpcode() == ISD::TRUNCATE) {
7654     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7655     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7656     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7657       SDNode *oye = N0.getOperand(0).getNode();
7658       if (NarrowLoad.getNode() != N0.getNode()) {
7659         CombineTo(N0.getNode(), NarrowLoad);
7660         // CombineTo deleted the truncate, if needed, but not what's under it.
7661         AddToWorklist(oye);
7662       }
7663       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7664     }
7665 
7666     // See if the value being truncated is already sign extended.  If so, just
7667     // eliminate the trunc/sext pair.
7668     SDValue Op = N0.getOperand(0);
7669     unsigned OpBits   = Op.getScalarValueSizeInBits();
7670     unsigned MidBits  = N0.getScalarValueSizeInBits();
7671     unsigned DestBits = VT.getScalarSizeInBits();
7672     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7673 
7674     if (OpBits == DestBits) {
7675       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7676       // bits, it is already ready.
7677       if (NumSignBits > DestBits-MidBits)
7678         return Op;
7679     } else if (OpBits < DestBits) {
7680       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7681       // bits, just sext from i32.
7682       if (NumSignBits > OpBits-MidBits)
7683         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7684     } else {
7685       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7686       // bits, just truncate to i32.
7687       if (NumSignBits > OpBits-MidBits)
7688         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7689     }
7690 
7691     // fold (sext (truncate x)) -> (sextinreg x).
7692     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7693                                                  N0.getValueType())) {
7694       if (OpBits < DestBits)
7695         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7696       else if (OpBits > DestBits)
7697         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7698       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7699                          DAG.getValueType(N0.getValueType()));
7700     }
7701   }
7702 
7703   // fold (sext (load x)) -> (sext (truncate (sextload x)))
7704   // Only generate vector extloads when 1) they're legal, and 2) they are
7705   // deemed desirable by the target.
7706   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7707       ((!LegalOperations && !VT.isVector() &&
7708         !cast<LoadSDNode>(N0)->isVolatile()) ||
7709        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7710     bool DoXform = true;
7711     SmallVector<SDNode*, 4> SetCCs;
7712     if (!N0.hasOneUse())
7713       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::SIGN_EXTEND, SetCCs,
7714                                         TLI);
7715     if (VT.isVector())
7716       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7717     if (DoXform) {
7718       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7719       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7720                                        LN0->getBasePtr(), N0.getValueType(),
7721                                        LN0->getMemOperand());
7722       ExtendSetCCUses(SetCCs, N0, ExtLoad, DL, ISD::SIGN_EXTEND);
7723       // If the load value is used only by N, replace it via CombineTo N.
7724       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7725       CombineTo(N, ExtLoad);
7726       if (NoReplaceTrunc) {
7727         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7728       } else {
7729         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7730                                     N0.getValueType(), ExtLoad);
7731         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7732       }
7733       return SDValue(N, 0);
7734     }
7735   }
7736 
7737   // fold (sext (load x)) to multiple smaller sextloads.
7738   // Only on illegal but splittable vectors.
7739   if (SDValue ExtLoad = CombineExtLoad(N))
7740     return ExtLoad;
7741 
7742   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7743   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7744   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7745       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7746     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7747     EVT MemVT = LN0->getMemoryVT();
7748     if ((!LegalOperations && !LN0->isVolatile()) ||
7749         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7750       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7751                                        LN0->getBasePtr(), MemVT,
7752                                        LN0->getMemOperand());
7753       CombineTo(N, ExtLoad);
7754       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7755       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7756     }
7757   }
7758 
7759   // fold (sext (and/or/xor (load x), cst)) ->
7760   //      (and/or/xor (sextload x), (sext cst))
7761   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7762        N0.getOpcode() == ISD::XOR) &&
7763       isa<LoadSDNode>(N0.getOperand(0)) &&
7764       N0.getOperand(1).getOpcode() == ISD::Constant &&
7765       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7766     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
7767     EVT MemVT = LN00->getMemoryVT();
7768     if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
7769       LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
7770       SmallVector<SDNode*, 4> SetCCs;
7771       bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
7772                                              ISD::SIGN_EXTEND, SetCCs, TLI);
7773       if (DoXform) {
7774         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
7775                                          LN00->getChain(), LN00->getBasePtr(),
7776                                          LN00->getMemoryVT(),
7777                                          LN00->getMemOperand());
7778         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7779         Mask = Mask.sext(VT.getSizeInBits());
7780         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7781                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7782         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL,
7783                         ISD::SIGN_EXTEND);
7784         bool NoReplaceTruncAnd = !N0.hasOneUse();
7785         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
7786         CombineTo(N, And);
7787         // If N0 has multiple uses, change other uses as well.
7788         if (NoReplaceTruncAnd) {
7789           SDValue TruncAnd =
7790               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7791           CombineTo(N0.getNode(), TruncAnd);
7792         }
7793         if (NoReplaceTrunc) {
7794           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
7795         } else {
7796           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
7797                                       LN00->getValueType(0), ExtLoad);
7798           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
7799         }
7800         return SDValue(N,0); // Return N so it doesn't get rechecked!
7801       }
7802     }
7803   }
7804 
7805   if (N0.getOpcode() == ISD::SETCC) {
7806     SDValue N00 = N0.getOperand(0);
7807     SDValue N01 = N0.getOperand(1);
7808     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7809     EVT N00VT = N0.getOperand(0).getValueType();
7810 
7811     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7812     // Only do this before legalize for now.
7813     if (VT.isVector() && !LegalOperations &&
7814         TLI.getBooleanContents(N00VT) ==
7815             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7816       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7817       // of the same size as the compared operands. Only optimize sext(setcc())
7818       // if this is the case.
7819       EVT SVT = getSetCCResultType(N00VT);
7820 
7821       // We know that the # elements of the results is the same as the
7822       // # elements of the compare (and the # elements of the compare result
7823       // for that matter).  Check to see that they are the same size.  If so,
7824       // we know that the element size of the sext'd result matches the
7825       // element size of the compare operands.
7826       if (VT.getSizeInBits() == SVT.getSizeInBits())
7827         return DAG.getSetCC(DL, VT, N00, N01, CC);
7828 
7829       // If the desired elements are smaller or larger than the source
7830       // elements, we can use a matching integer vector type and then
7831       // truncate/sign extend.
7832       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7833       if (SVT == MatchingVecType) {
7834         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7835         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7836       }
7837     }
7838 
7839     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7840     // Here, T can be 1 or -1, depending on the type of the setcc and
7841     // getBooleanContents().
7842     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7843 
7844     // To determine the "true" side of the select, we need to know the high bit
7845     // of the value returned by the setcc if it evaluates to true.
7846     // If the type of the setcc is i1, then the true case of the select is just
7847     // sext(i1 1), that is, -1.
7848     // If the type of the setcc is larger (say, i8) then the value of the high
7849     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7850     // of the appropriate width.
7851     SDValue ExtTrueVal = (SetCCWidth == 1)
7852                              ? DAG.getAllOnesConstant(DL, VT)
7853                              : DAG.getBoolConstant(true, DL, VT, N00VT);
7854     SDValue Zero = DAG.getConstant(0, DL, VT);
7855     if (SDValue SCC =
7856             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7857       return SCC;
7858 
7859     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7860       EVT SetCCVT = getSetCCResultType(N00VT);
7861       // Don't do this transform for i1 because there's a select transform
7862       // that would reverse it.
7863       // TODO: We should not do this transform at all without a target hook
7864       // because a sext is likely cheaper than a select?
7865       if (SetCCVT.getScalarSizeInBits() != 1 &&
7866           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7867         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7868         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7869       }
7870     }
7871   }
7872 
7873   // fold (sext x) -> (zext x) if the sign bit is known zero.
7874   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7875       DAG.SignBitIsZero(N0))
7876     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7877 
7878   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7879     return NewVSel;
7880 
7881   return SDValue();
7882 }
7883 
7884 // isTruncateOf - If N is a truncate of some other value, return true, record
7885 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7886 // This function computes KnownBits to avoid a duplicated call to
7887 // computeKnownBits in the caller.
7888 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7889                          KnownBits &Known) {
7890   if (N->getOpcode() == ISD::TRUNCATE) {
7891     Op = N->getOperand(0);
7892     DAG.computeKnownBits(Op, Known);
7893     return true;
7894   }
7895 
7896   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7897       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7898     return false;
7899 
7900   SDValue Op0 = N->getOperand(0);
7901   SDValue Op1 = N->getOperand(1);
7902   assert(Op0.getValueType() == Op1.getValueType());
7903 
7904   if (isNullConstant(Op0))
7905     Op = Op1;
7906   else if (isNullConstant(Op1))
7907     Op = Op0;
7908   else
7909     return false;
7910 
7911   DAG.computeKnownBits(Op, Known);
7912 
7913   if (!(Known.Zero | 1).isAllOnesValue())
7914     return false;
7915 
7916   return true;
7917 }
7918 
7919 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7920   SDValue N0 = N->getOperand(0);
7921   EVT VT = N->getValueType(0);
7922 
7923   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7924                                               LegalOperations))
7925     return SDValue(Res, 0);
7926 
7927   // fold (zext (zext x)) -> (zext x)
7928   // fold (zext (aext x)) -> (zext x)
7929   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7930     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7931                        N0.getOperand(0));
7932 
7933   // fold (zext (truncate x)) -> (zext x) or
7934   //      (zext (truncate x)) -> (truncate x)
7935   // This is valid when the truncated bits of x are already zero.
7936   // FIXME: We should extend this to work for vectors too.
7937   SDValue Op;
7938   KnownBits Known;
7939   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7940     APInt TruncatedBits =
7941       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7942       APInt(Op.getValueSizeInBits(), 0) :
7943       APInt::getBitsSet(Op.getValueSizeInBits(),
7944                         N0.getValueSizeInBits(),
7945                         std::min(Op.getValueSizeInBits(),
7946                                  VT.getSizeInBits()));
7947     if (TruncatedBits.isSubsetOf(Known.Zero))
7948       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7949   }
7950 
7951   // fold (zext (truncate x)) -> (and x, mask)
7952   if (N0.getOpcode() == ISD::TRUNCATE) {
7953     // fold (zext (truncate (load x))) -> (zext (smaller load x))
7954     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7955     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7956       SDNode *oye = N0.getOperand(0).getNode();
7957       if (NarrowLoad.getNode() != N0.getNode()) {
7958         CombineTo(N0.getNode(), NarrowLoad);
7959         // CombineTo deleted the truncate, if needed, but not what's under it.
7960         AddToWorklist(oye);
7961       }
7962       return SDValue(N, 0); // Return N so it doesn't get rechecked!
7963     }
7964 
7965     EVT SrcVT = N0.getOperand(0).getValueType();
7966     EVT MinVT = N0.getValueType();
7967 
7968     // Try to mask before the extension to avoid having to generate a larger mask,
7969     // possibly over several sub-vectors.
7970     if (SrcVT.bitsLT(VT) && VT.isVector()) {
7971       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7972                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7973         SDValue Op = N0.getOperand(0);
7974         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7975         AddToWorklist(Op.getNode());
7976         SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7977         // Transfer the debug info; the new node is equivalent to N0.
7978         DAG.transferDbgValues(N0, ZExtOrTrunc);
7979         return ZExtOrTrunc;
7980       }
7981     }
7982 
7983     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7984       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7985       AddToWorklist(Op.getNode());
7986       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7987       // We may safely transfer the debug info describing the truncate node over
7988       // to the equivalent and operation.
7989       DAG.transferDbgValues(N0, And);
7990       return And;
7991     }
7992   }
7993 
7994   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7995   // if either of the casts is not free.
7996   if (N0.getOpcode() == ISD::AND &&
7997       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7998       N0.getOperand(1).getOpcode() == ISD::Constant &&
7999       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8000                            N0.getValueType()) ||
8001        !TLI.isZExtFree(N0.getValueType(), VT))) {
8002     SDValue X = N0.getOperand(0).getOperand(0);
8003     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
8004     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8005     Mask = Mask.zext(VT.getSizeInBits());
8006     SDLoc DL(N);
8007     return DAG.getNode(ISD::AND, DL, VT,
8008                        X, DAG.getConstant(Mask, DL, VT));
8009   }
8010 
8011   // fold (zext (load x)) -> (zext (truncate (zextload x)))
8012   // Only generate vector extloads when 1) they're legal, and 2) they are
8013   // deemed desirable by the target.
8014   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8015       ((!LegalOperations && !VT.isVector() &&
8016         !cast<LoadSDNode>(N0)->isVolatile()) ||
8017        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
8018     bool DoXform = true;
8019     SmallVector<SDNode*, 4> SetCCs;
8020     if (!N0.hasOneUse())
8021       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ZERO_EXTEND, SetCCs,
8022                                         TLI);
8023     if (VT.isVector())
8024       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
8025     if (DoXform) {
8026       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8027       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
8028                                        LN0->getChain(),
8029                                        LN0->getBasePtr(), N0.getValueType(),
8030                                        LN0->getMemOperand());
8031 
8032       ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
8033       // If the load value is used only by N, replace it via CombineTo N.
8034       bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
8035       CombineTo(N, ExtLoad);
8036       if (NoReplaceTrunc) {
8037         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8038       } else {
8039         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8040                                     N0.getValueType(), ExtLoad);
8041         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8042       }
8043       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8044     }
8045   }
8046 
8047   // fold (zext (load x)) to multiple smaller zextloads.
8048   // Only on illegal but splittable vectors.
8049   if (SDValue ExtLoad = CombineExtLoad(N))
8050     return ExtLoad;
8051 
8052   // fold (zext (and/or/xor (load x), cst)) ->
8053   //      (and/or/xor (zextload x), (zext cst))
8054   // Unless (and (load x) cst) will match as a zextload already and has
8055   // additional users.
8056   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
8057        N0.getOpcode() == ISD::XOR) &&
8058       isa<LoadSDNode>(N0.getOperand(0)) &&
8059       N0.getOperand(1).getOpcode() == ISD::Constant &&
8060       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
8061     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
8062     EVT MemVT = LN00->getMemoryVT();
8063     if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
8064         LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
8065       bool DoXform = true;
8066       SmallVector<SDNode*, 4> SetCCs;
8067       if (!N0.hasOneUse()) {
8068         if (N0.getOpcode() == ISD::AND) {
8069           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
8070           EVT LoadResultTy = AndC->getValueType(0);
8071           EVT ExtVT;
8072           if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
8073             DoXform = false;
8074         }
8075       }
8076       if (DoXform)
8077         DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
8078                                           ISD::ZERO_EXTEND, SetCCs, TLI);
8079       if (DoXform) {
8080         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
8081                                          LN00->getChain(), LN00->getBasePtr(),
8082                                          LN00->getMemoryVT(),
8083                                          LN00->getMemOperand());
8084         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8085         Mask = Mask.zext(VT.getSizeInBits());
8086         SDLoc DL(N);
8087         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
8088                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
8089         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, DL,
8090                         ISD::ZERO_EXTEND);
8091         bool NoReplaceTruncAnd = !N0.hasOneUse();
8092         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
8093         CombineTo(N, And);
8094         // If N0 has multiple uses, change other uses as well.
8095         if (NoReplaceTruncAnd) {
8096           SDValue TruncAnd =
8097               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
8098           CombineTo(N0.getNode(), TruncAnd);
8099         }
8100         if (NoReplaceTrunc) {
8101           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
8102         } else {
8103           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
8104                                       LN00->getValueType(0), ExtLoad);
8105           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
8106         }
8107         return SDValue(N,0); // Return N so it doesn't get rechecked!
8108       }
8109     }
8110   }
8111 
8112   // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
8113   //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
8114   if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
8115     return ZExtLoad;
8116 
8117   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
8118   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
8119   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
8120       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
8121     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8122     EVT MemVT = LN0->getMemoryVT();
8123     if ((!LegalOperations && !LN0->isVolatile()) ||
8124         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
8125       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
8126                                        LN0->getChain(),
8127                                        LN0->getBasePtr(), MemVT,
8128                                        LN0->getMemOperand());
8129       CombineTo(N, ExtLoad);
8130       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8131       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8132     }
8133   }
8134 
8135   if (N0.getOpcode() == ISD::SETCC) {
8136     // Only do this before legalize for now.
8137     if (!LegalOperations && VT.isVector() &&
8138         N0.getValueType().getVectorElementType() == MVT::i1) {
8139       EVT N00VT = N0.getOperand(0).getValueType();
8140       if (getSetCCResultType(N00VT) == N0.getValueType())
8141         return SDValue();
8142 
8143       // We know that the # elements of the results is the same as the #
8144       // elements of the compare (and the # elements of the compare result for
8145       // that matter). Check to see that they are the same size. If so, we know
8146       // that the element size of the sext'd result matches the element size of
8147       // the compare operands.
8148       SDLoc DL(N);
8149       SDValue VecOnes = DAG.getConstant(1, DL, VT);
8150       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
8151         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
8152         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
8153                                      N0.getOperand(1), N0.getOperand(2));
8154         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
8155       }
8156 
8157       // If the desired elements are smaller or larger than the source
8158       // elements we can use a matching integer vector type and then
8159       // truncate/sign extend.
8160       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8161       SDValue VsetCC =
8162           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
8163                       N0.getOperand(1), N0.getOperand(2));
8164       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
8165                          VecOnes);
8166     }
8167 
8168     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8169     SDLoc DL(N);
8170     if (SDValue SCC = SimplifySelectCC(
8171             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8172             DAG.getConstant(0, DL, VT),
8173             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8174       return SCC;
8175   }
8176 
8177   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
8178   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
8179       isa<ConstantSDNode>(N0.getOperand(1)) &&
8180       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
8181       N0.hasOneUse()) {
8182     SDValue ShAmt = N0.getOperand(1);
8183     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8184     if (N0.getOpcode() == ISD::SHL) {
8185       SDValue InnerZExt = N0.getOperand(0);
8186       // If the original shl may be shifting out bits, do not perform this
8187       // transformation.
8188       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
8189         InnerZExt.getOperand(0).getValueSizeInBits();
8190       if (ShAmtVal > KnownZeroBits)
8191         return SDValue();
8192     }
8193 
8194     SDLoc DL(N);
8195 
8196     // Ensure that the shift amount is wide enough for the shifted value.
8197     if (VT.getSizeInBits() >= 256)
8198       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8199 
8200     return DAG.getNode(N0.getOpcode(), DL, VT,
8201                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8202                        ShAmt);
8203   }
8204 
8205   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8206     return NewVSel;
8207 
8208   return SDValue();
8209 }
8210 
8211 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8212   SDValue N0 = N->getOperand(0);
8213   EVT VT = N->getValueType(0);
8214 
8215   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8216                                               LegalOperations))
8217     return SDValue(Res, 0);
8218 
8219   // fold (aext (aext x)) -> (aext x)
8220   // fold (aext (zext x)) -> (zext x)
8221   // fold (aext (sext x)) -> (sext x)
8222   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
8223       N0.getOpcode() == ISD::ZERO_EXTEND ||
8224       N0.getOpcode() == ISD::SIGN_EXTEND)
8225     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8226 
8227   // fold (aext (truncate (load x))) -> (aext (smaller load x))
8228   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8229   if (N0.getOpcode() == ISD::TRUNCATE) {
8230     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8231       SDNode *oye = N0.getOperand(0).getNode();
8232       if (NarrowLoad.getNode() != N0.getNode()) {
8233         CombineTo(N0.getNode(), NarrowLoad);
8234         // CombineTo deleted the truncate, if needed, but not what's under it.
8235         AddToWorklist(oye);
8236       }
8237       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8238     }
8239   }
8240 
8241   // fold (aext (truncate x))
8242   if (N0.getOpcode() == ISD::TRUNCATE)
8243     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8244 
8245   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8246   // if the trunc is not free.
8247   if (N0.getOpcode() == ISD::AND &&
8248       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8249       N0.getOperand(1).getOpcode() == ISD::Constant &&
8250       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8251                           N0.getValueType())) {
8252     SDLoc DL(N);
8253     SDValue X = N0.getOperand(0).getOperand(0);
8254     X = DAG.getAnyExtOrTrunc(X, DL, VT);
8255     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8256     Mask = Mask.zext(VT.getSizeInBits());
8257     return DAG.getNode(ISD::AND, DL, VT,
8258                        X, DAG.getConstant(Mask, DL, VT));
8259   }
8260 
8261   // fold (aext (load x)) -> (aext (truncate (extload x)))
8262   // None of the supported targets knows how to perform load and any_ext
8263   // on vectors in one instruction.  We only perform this transformation on
8264   // scalars.
8265   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8266       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8267       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8268     bool DoXform = true;
8269     SmallVector<SDNode*, 4> SetCCs;
8270     if (!N0.hasOneUse())
8271       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs,
8272                                         TLI);
8273     if (DoXform) {
8274       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8275       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8276                                        LN0->getChain(),
8277                                        LN0->getBasePtr(), N0.getValueType(),
8278                                        LN0->getMemOperand());
8279       ExtendSetCCUses(SetCCs, N0, ExtLoad, SDLoc(N),
8280                       ISD::ANY_EXTEND);
8281       // If the load value is used only by N, replace it via CombineTo N.
8282       bool NoReplaceTrunc = N0.hasOneUse();
8283       CombineTo(N, ExtLoad);
8284       if (NoReplaceTrunc) {
8285         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8286       } else {
8287         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8288                                     N0.getValueType(), ExtLoad);
8289         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8290       }
8291       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8292     }
8293   }
8294 
8295   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8296   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8297   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
8298   if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
8299       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
8300     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8301     ISD::LoadExtType ExtType = LN0->getExtensionType();
8302     EVT MemVT = LN0->getMemoryVT();
8303     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8304       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8305                                        VT, LN0->getChain(), LN0->getBasePtr(),
8306                                        MemVT, LN0->getMemOperand());
8307       CombineTo(N, ExtLoad);
8308       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8309       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8310     }
8311   }
8312 
8313   if (N0.getOpcode() == ISD::SETCC) {
8314     // For vectors:
8315     // aext(setcc) -> vsetcc
8316     // aext(setcc) -> truncate(vsetcc)
8317     // aext(setcc) -> aext(vsetcc)
8318     // Only do this before legalize for now.
8319     if (VT.isVector() && !LegalOperations) {
8320       EVT N00VT = N0.getOperand(0).getValueType();
8321       if (getSetCCResultType(N00VT) == N0.getValueType())
8322         return SDValue();
8323 
8324       // We know that the # elements of the results is the same as the
8325       // # elements of the compare (and the # elements of the compare result
8326       // for that matter).  Check to see that they are the same size.  If so,
8327       // we know that the element size of the sext'd result matches the
8328       // element size of the compare operands.
8329       if (VT.getSizeInBits() == N00VT.getSizeInBits())
8330         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8331                              N0.getOperand(1),
8332                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
8333       // If the desired elements are smaller or larger than the source
8334       // elements we can use a matching integer vector type and then
8335       // truncate/any extend
8336       else {
8337         EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8338         SDValue VsetCC =
8339           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8340                         N0.getOperand(1),
8341                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
8342         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8343       }
8344     }
8345 
8346     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8347     SDLoc DL(N);
8348     if (SDValue SCC = SimplifySelectCC(
8349             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8350             DAG.getConstant(0, DL, VT),
8351             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8352       return SCC;
8353   }
8354 
8355   return SDValue();
8356 }
8357 
8358 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8359   unsigned Opcode = N->getOpcode();
8360   SDValue N0 = N->getOperand(0);
8361   SDValue N1 = N->getOperand(1);
8362   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8363 
8364   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8365   if (N0.getOpcode() == Opcode &&
8366       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8367     return N0;
8368 
8369   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8370       N0.getOperand(0).getOpcode() == Opcode) {
8371     // We have an assert, truncate, assert sandwich. Make one stronger assert
8372     // by asserting on the smallest asserted type to the larger source type.
8373     // This eliminates the later assert:
8374     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8375     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8376     SDValue BigA = N0.getOperand(0);
8377     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8378     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8379            "Asserting zero/sign-extended bits to a type larger than the "
8380            "truncated destination does not provide information");
8381 
8382     SDLoc DL(N);
8383     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8384     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8385     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8386                                     BigA.getOperand(0), MinAssertVTVal);
8387     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8388   }
8389 
8390   return SDValue();
8391 }
8392 
8393 /// If the result of a wider load is shifted to right of N  bits and then
8394 /// truncated to a narrower type and where N is a multiple of number of bits of
8395 /// the narrower type, transform it to a narrower load from address + N / num of
8396 /// bits of new type. Also narrow the load if the result is masked with an AND
8397 /// to effectively produce a smaller type. If the result is to be extended, also
8398 /// fold the extension to form a extending load.
8399 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8400   unsigned Opc = N->getOpcode();
8401 
8402   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8403   SDValue N0 = N->getOperand(0);
8404   EVT VT = N->getValueType(0);
8405   EVT ExtVT = VT;
8406 
8407   // This transformation isn't valid for vector loads.
8408   if (VT.isVector())
8409     return SDValue();
8410 
8411   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8412   // extended to VT.
8413   if (Opc == ISD::SIGN_EXTEND_INREG) {
8414     ExtType = ISD::SEXTLOAD;
8415     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8416   } else if (Opc == ISD::SRL) {
8417     // Another special-case: SRL is basically zero-extending a narrower value,
8418     // or it maybe shifting a higher subword, half or byte into the lowest
8419     // bits.
8420     ExtType = ISD::ZEXTLOAD;
8421     N0 = SDValue(N, 0);
8422 
8423     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8424     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8425     if (!N01 || !LN0)
8426       return SDValue();
8427 
8428     uint64_t ShiftAmt = N01->getZExtValue();
8429     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8430     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8431       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8432     else
8433       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8434                                 VT.getSizeInBits() - ShiftAmt);
8435   } else if (Opc == ISD::AND) {
8436     // An AND with a constant mask is the same as a truncate + zero-extend.
8437     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8438     if (!AndC || !AndC->getAPIntValue().isMask())
8439       return SDValue();
8440 
8441     unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8442     ExtType = ISD::ZEXTLOAD;
8443     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8444   }
8445 
8446   unsigned ShAmt = 0;
8447   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8448     SDValue SRL = N0;
8449     if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) {
8450       ShAmt = ConstShift->getZExtValue();
8451       unsigned EVTBits = ExtVT.getSizeInBits();
8452       // Is the shift amount a multiple of size of VT?
8453       if ((ShAmt & (EVTBits-1)) == 0) {
8454         N0 = N0.getOperand(0);
8455         // Is the load width a multiple of size of VT?
8456         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8457           return SDValue();
8458       }
8459 
8460       // At this point, we must have a load or else we can't do the transform.
8461       if (!isa<LoadSDNode>(N0)) return SDValue();
8462 
8463       auto *LN0 = cast<LoadSDNode>(N0);
8464 
8465       // Because a SRL must be assumed to *need* to zero-extend the high bits
8466       // (as opposed to anyext the high bits), we can't combine the zextload
8467       // lowering of SRL and an sextload.
8468       if (LN0->getExtensionType() == ISD::SEXTLOAD)
8469         return SDValue();
8470 
8471       // If the shift amount is larger than the input type then we're not
8472       // accessing any of the loaded bytes.  If the load was a zextload/extload
8473       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8474       if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
8475         return SDValue();
8476 
8477       // If the SRL is only used by a masking AND, we may be able to adjust
8478       // the ExtVT to make the AND redundant.
8479       SDNode *Mask = *(SRL->use_begin());
8480       if (Mask->getOpcode() == ISD::AND &&
8481           isa<ConstantSDNode>(Mask->getOperand(1))) {
8482         const APInt &ShiftMask =
8483           cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue();
8484         if (ShiftMask.isMask()) {
8485           EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
8486                                            ShiftMask.countTrailingOnes());
8487           // Recompute the type.
8488           if (TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT))
8489             ExtVT = MaskedVT;
8490         }
8491       }
8492     }
8493   }
8494 
8495   // If the load is shifted left (and the result isn't shifted back right),
8496   // we can fold the truncate through the shift.
8497   unsigned ShLeftAmt = 0;
8498   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8499       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8500     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8501       ShLeftAmt = N01->getZExtValue();
8502       N0 = N0.getOperand(0);
8503     }
8504   }
8505 
8506   // If we haven't found a load, we can't narrow it.
8507   if (!isa<LoadSDNode>(N0))
8508     return SDValue();
8509 
8510   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8511   if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8512     return SDValue();
8513 
8514   // For big endian targets, we need to adjust the offset to the pointer to
8515   // load the correct bytes.
8516   if (DAG.getDataLayout().isBigEndian()) {
8517     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8518     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8519     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8520   }
8521 
8522   EVT PtrType = N0.getOperand(1).getValueType();
8523   uint64_t PtrOff = ShAmt / 8;
8524   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8525   SDLoc DL(LN0);
8526   // The original load itself didn't wrap, so an offset within it doesn't.
8527   SDNodeFlags Flags;
8528   Flags.setNoUnsignedWrap(true);
8529   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8530                                PtrType, LN0->getBasePtr(),
8531                                DAG.getConstant(PtrOff, DL, PtrType),
8532                                Flags);
8533   AddToWorklist(NewPtr.getNode());
8534 
8535   SDValue Load;
8536   if (ExtType == ISD::NON_EXTLOAD)
8537     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8538                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8539                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8540   else
8541     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8542                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8543                           NewAlign, LN0->getMemOperand()->getFlags(),
8544                           LN0->getAAInfo());
8545 
8546   // Replace the old load's chain with the new load's chain.
8547   WorklistRemover DeadNodes(*this);
8548   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8549 
8550   // Shift the result left, if we've swallowed a left shift.
8551   SDValue Result = Load;
8552   if (ShLeftAmt != 0) {
8553     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8554     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8555       ShImmTy = VT;
8556     // If the shift amount is as large as the result size (but, presumably,
8557     // no larger than the source) then the useful bits of the result are
8558     // zero; we can't simply return the shortened shift, because the result
8559     // of that operation is undefined.
8560     SDLoc DL(N0);
8561     if (ShLeftAmt >= VT.getSizeInBits())
8562       Result = DAG.getConstant(0, DL, VT);
8563     else
8564       Result = DAG.getNode(ISD::SHL, DL, VT,
8565                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8566   }
8567 
8568   // Return the new loaded value.
8569   return Result;
8570 }
8571 
8572 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8573   SDValue N0 = N->getOperand(0);
8574   SDValue N1 = N->getOperand(1);
8575   EVT VT = N->getValueType(0);
8576   EVT EVT = cast<VTSDNode>(N1)->getVT();
8577   unsigned VTBits = VT.getScalarSizeInBits();
8578   unsigned EVTBits = EVT.getScalarSizeInBits();
8579 
8580   if (N0.isUndef())
8581     return DAG.getUNDEF(VT);
8582 
8583   // fold (sext_in_reg c1) -> c1
8584   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8585     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8586 
8587   // If the input is already sign extended, just drop the extension.
8588   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8589     return N0;
8590 
8591   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8592   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8593       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8594     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8595                        N0.getOperand(0), N1);
8596 
8597   // fold (sext_in_reg (sext x)) -> (sext x)
8598   // fold (sext_in_reg (aext x)) -> (sext x)
8599   // if x is small enough.
8600   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8601     SDValue N00 = N0.getOperand(0);
8602     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8603         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8604       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8605   }
8606 
8607   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
8608   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8609        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8610        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8611       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8612     if (!LegalOperations ||
8613         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8614       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8615   }
8616 
8617   // fold (sext_in_reg (zext x)) -> (sext x)
8618   // iff we are extending the source sign bit.
8619   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8620     SDValue N00 = N0.getOperand(0);
8621     if (N00.getScalarValueSizeInBits() == EVTBits &&
8622         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8623       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8624   }
8625 
8626   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8627   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8628     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8629 
8630   // fold operands of sext_in_reg based on knowledge that the top bits are not
8631   // demanded.
8632   if (SimplifyDemandedBits(SDValue(N, 0)))
8633     return SDValue(N, 0);
8634 
8635   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8636   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8637   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8638     return NarrowLoad;
8639 
8640   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8641   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8642   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8643   if (N0.getOpcode() == ISD::SRL) {
8644     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8645       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8646         // We can turn this into an SRA iff the input to the SRL is already sign
8647         // extended enough.
8648         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8649         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8650           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8651                              N0.getOperand(0), N0.getOperand(1));
8652       }
8653   }
8654 
8655   // fold (sext_inreg (extload x)) -> (sextload x)
8656   // If sextload is not supported by target, we can only do the combine when
8657   // load has one use. Doing otherwise can block folding the extload with other
8658   // extends that the target does support.
8659   if (ISD::isEXTLoad(N0.getNode()) &&
8660       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8661       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8662       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8663         N0.hasOneUse()) ||
8664        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8665     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8666     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8667                                      LN0->getChain(),
8668                                      LN0->getBasePtr(), EVT,
8669                                      LN0->getMemOperand());
8670     CombineTo(N, ExtLoad);
8671     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8672     AddToWorklist(ExtLoad.getNode());
8673     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8674   }
8675   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8676   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8677       N0.hasOneUse() &&
8678       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8679       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8680        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8681     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8682     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8683                                      LN0->getChain(),
8684                                      LN0->getBasePtr(), EVT,
8685                                      LN0->getMemOperand());
8686     CombineTo(N, ExtLoad);
8687     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8688     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8689   }
8690 
8691   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8692   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8693     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8694                                            N0.getOperand(1), false))
8695       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8696                          BSwap, N1);
8697   }
8698 
8699   return SDValue();
8700 }
8701 
8702 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8703   SDValue N0 = N->getOperand(0);
8704   EVT VT = N->getValueType(0);
8705 
8706   if (N0.isUndef())
8707     return DAG.getUNDEF(VT);
8708 
8709   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8710                                               LegalOperations))
8711     return SDValue(Res, 0);
8712 
8713   return SDValue();
8714 }
8715 
8716 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8717   SDValue N0 = N->getOperand(0);
8718   EVT VT = N->getValueType(0);
8719 
8720   if (N0.isUndef())
8721     return DAG.getUNDEF(VT);
8722 
8723   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8724                                               LegalOperations))
8725     return SDValue(Res, 0);
8726 
8727   return SDValue();
8728 }
8729 
8730 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8731   SDValue N0 = N->getOperand(0);
8732   EVT VT = N->getValueType(0);
8733   bool isLE = DAG.getDataLayout().isLittleEndian();
8734 
8735   // noop truncate
8736   if (N0.getValueType() == N->getValueType(0))
8737     return N0;
8738 
8739   // fold (truncate (truncate x)) -> (truncate x)
8740   if (N0.getOpcode() == ISD::TRUNCATE)
8741     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8742 
8743   // fold (truncate c1) -> c1
8744   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8745     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8746     if (C.getNode() != N)
8747       return C;
8748   }
8749 
8750   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8751   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8752       N0.getOpcode() == ISD::SIGN_EXTEND ||
8753       N0.getOpcode() == ISD::ANY_EXTEND) {
8754     // if the source is smaller than the dest, we still need an extend.
8755     if (N0.getOperand(0).getValueType().bitsLT(VT))
8756       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8757     // if the source is larger than the dest, than we just need the truncate.
8758     if (N0.getOperand(0).getValueType().bitsGT(VT))
8759       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8760     // if the source and dest are the same type, we can drop both the extend
8761     // and the truncate.
8762     return N0.getOperand(0);
8763   }
8764 
8765   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8766   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8767     return SDValue();
8768 
8769   // Fold extract-and-trunc into a narrow extract. For example:
8770   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8771   //   i32 y = TRUNCATE(i64 x)
8772   //        -- becomes --
8773   //   v16i8 b = BITCAST (v2i64 val)
8774   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8775   //
8776   // Note: We only run this optimization after type legalization (which often
8777   // creates this pattern) and before operation legalization after which
8778   // we need to be more careful about the vector instructions that we generate.
8779   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8780       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8781     EVT VecTy = N0.getOperand(0).getValueType();
8782     EVT ExTy = N0.getValueType();
8783     EVT TrTy = N->getValueType(0);
8784 
8785     unsigned NumElem = VecTy.getVectorNumElements();
8786     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8787 
8788     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8789     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8790 
8791     SDValue EltNo = N0->getOperand(1);
8792     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8793       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8794       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8795       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8796 
8797       SDLoc DL(N);
8798       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8799                          DAG.getBitcast(NVT, N0.getOperand(0)),
8800                          DAG.getConstant(Index, DL, IndexTy));
8801     }
8802   }
8803 
8804   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8805   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8806     EVT SrcVT = N0.getValueType();
8807     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8808         TLI.isTruncateFree(SrcVT, VT)) {
8809       SDLoc SL(N0);
8810       SDValue Cond = N0.getOperand(0);
8811       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8812       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8813       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8814     }
8815   }
8816 
8817   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8818   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8819       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8820       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8821     SDValue Amt = N0.getOperand(1);
8822     KnownBits Known;
8823     DAG.computeKnownBits(Amt, Known);
8824     unsigned Size = VT.getScalarSizeInBits();
8825     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8826       SDLoc SL(N);
8827       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8828 
8829       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8830       if (AmtVT != Amt.getValueType()) {
8831         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8832         AddToWorklist(Amt.getNode());
8833       }
8834       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8835     }
8836   }
8837 
8838   // Fold a series of buildvector, bitcast, and truncate if possible.
8839   // For example fold
8840   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8841   //   (2xi32 (buildvector x, y)).
8842   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8843       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8844       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8845       N0.getOperand(0).hasOneUse()) {
8846     SDValue BuildVect = N0.getOperand(0);
8847     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8848     EVT TruncVecEltTy = VT.getVectorElementType();
8849 
8850     // Check that the element types match.
8851     if (BuildVectEltTy == TruncVecEltTy) {
8852       // Now we only need to compute the offset of the truncated elements.
8853       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8854       unsigned TruncVecNumElts = VT.getVectorNumElements();
8855       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8856 
8857       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8858              "Invalid number of elements");
8859 
8860       SmallVector<SDValue, 8> Opnds;
8861       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8862         Opnds.push_back(BuildVect.getOperand(i));
8863 
8864       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8865     }
8866   }
8867 
8868   // See if we can simplify the input to this truncate through knowledge that
8869   // only the low bits are being used.
8870   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8871   // Currently we only perform this optimization on scalars because vectors
8872   // may have different active low bits.
8873   if (!VT.isVector()) {
8874     APInt Mask =
8875         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8876     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8877       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8878   }
8879 
8880   // fold (truncate (load x)) -> (smaller load x)
8881   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8882   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8883     if (SDValue Reduced = ReduceLoadWidth(N))
8884       return Reduced;
8885 
8886     // Handle the case where the load remains an extending load even
8887     // after truncation.
8888     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8889       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8890       if (!LN0->isVolatile() &&
8891           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8892         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8893                                          VT, LN0->getChain(), LN0->getBasePtr(),
8894                                          LN0->getMemoryVT(),
8895                                          LN0->getMemOperand());
8896         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8897         return NewLoad;
8898       }
8899     }
8900   }
8901 
8902   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8903   // where ... are all 'undef'.
8904   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8905     SmallVector<EVT, 8> VTs;
8906     SDValue V;
8907     unsigned Idx = 0;
8908     unsigned NumDefs = 0;
8909 
8910     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8911       SDValue X = N0.getOperand(i);
8912       if (!X.isUndef()) {
8913         V = X;
8914         Idx = i;
8915         NumDefs++;
8916       }
8917       // Stop if more than one members are non-undef.
8918       if (NumDefs > 1)
8919         break;
8920       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8921                                      VT.getVectorElementType(),
8922                                      X.getValueType().getVectorNumElements()));
8923     }
8924 
8925     if (NumDefs == 0)
8926       return DAG.getUNDEF(VT);
8927 
8928     if (NumDefs == 1) {
8929       assert(V.getNode() && "The single defined operand is empty!");
8930       SmallVector<SDValue, 8> Opnds;
8931       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8932         if (i != Idx) {
8933           Opnds.push_back(DAG.getUNDEF(VTs[i]));
8934           continue;
8935         }
8936         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8937         AddToWorklist(NV.getNode());
8938         Opnds.push_back(NV);
8939       }
8940       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8941     }
8942   }
8943 
8944   // Fold truncate of a bitcast of a vector to an extract of the low vector
8945   // element.
8946   //
8947   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
8948   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8949     SDValue VecSrc = N0.getOperand(0);
8950     EVT SrcVT = VecSrc.getValueType();
8951     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8952         (!LegalOperations ||
8953          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8954       SDLoc SL(N);
8955 
8956       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8957       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
8958       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8959                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
8960     }
8961   }
8962 
8963   // Simplify the operands using demanded-bits information.
8964   if (!VT.isVector() &&
8965       SimplifyDemandedBits(SDValue(N, 0)))
8966     return SDValue(N, 0);
8967 
8968   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8969   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8970   // When the adde's carry is not used.
8971   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8972       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8973       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8974     SDLoc SL(N);
8975     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8976     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8977     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8978     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8979   }
8980 
8981   // fold (truncate (extract_subvector(ext x))) ->
8982   //      (extract_subvector x)
8983   // TODO: This can be generalized to cover cases where the truncate and extract
8984   // do not fully cancel each other out.
8985   if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8986     SDValue N00 = N0.getOperand(0);
8987     if (N00.getOpcode() == ISD::SIGN_EXTEND ||
8988         N00.getOpcode() == ISD::ZERO_EXTEND ||
8989         N00.getOpcode() == ISD::ANY_EXTEND) {
8990       if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
8991           VT.getVectorElementType())
8992         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
8993                            N00.getOperand(0), N0.getOperand(1));
8994     }
8995   }
8996 
8997   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8998     return NewVSel;
8999 
9000   return SDValue();
9001 }
9002 
9003 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
9004   SDValue Elt = N->getOperand(i);
9005   if (Elt.getOpcode() != ISD::MERGE_VALUES)
9006     return Elt.getNode();
9007   return Elt.getOperand(Elt.getResNo()).getNode();
9008 }
9009 
9010 /// build_pair (load, load) -> load
9011 /// if load locations are consecutive.
9012 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
9013   assert(N->getOpcode() == ISD::BUILD_PAIR);
9014 
9015   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
9016   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
9017 
9018   // A BUILD_PAIR is always having the least significant part in elt 0 and the
9019   // most significant part in elt 1. So when combining into one large load, we
9020   // need to consider the endianness.
9021   if (DAG.getDataLayout().isBigEndian())
9022     std::swap(LD1, LD2);
9023 
9024   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
9025       LD1->getAddressSpace() != LD2->getAddressSpace())
9026     return SDValue();
9027   EVT LD1VT = LD1->getValueType(0);
9028   unsigned LD1Bytes = LD1VT.getStoreSize();
9029   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
9030       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
9031     unsigned Align = LD1->getAlignment();
9032     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
9033         VT.getTypeForEVT(*DAG.getContext()));
9034 
9035     if (NewAlign <= Align &&
9036         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
9037       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
9038                          LD1->getPointerInfo(), Align);
9039   }
9040 
9041   return SDValue();
9042 }
9043 
9044 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
9045   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
9046   // and Lo parts; on big-endian machines it doesn't.
9047   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
9048 }
9049 
9050 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
9051                                     const TargetLowering &TLI) {
9052   // If this is not a bitcast to an FP type or if the target doesn't have
9053   // IEEE754-compliant FP logic, we're done.
9054   EVT VT = N->getValueType(0);
9055   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
9056     return SDValue();
9057 
9058   // TODO: Use splat values for the constant-checking below and remove this
9059   // restriction.
9060   SDValue N0 = N->getOperand(0);
9061   EVT SourceVT = N0.getValueType();
9062   if (SourceVT.isVector())
9063     return SDValue();
9064 
9065   unsigned FPOpcode;
9066   APInt SignMask;
9067   switch (N0.getOpcode()) {
9068   case ISD::AND:
9069     FPOpcode = ISD::FABS;
9070     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
9071     break;
9072   case ISD::XOR:
9073     FPOpcode = ISD::FNEG;
9074     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
9075     break;
9076   // TODO: ISD::OR --> ISD::FNABS?
9077   default:
9078     return SDValue();
9079   }
9080 
9081   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
9082   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
9083   SDValue LogicOp0 = N0.getOperand(0);
9084   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9085   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
9086       LogicOp0.getOpcode() == ISD::BITCAST &&
9087       LogicOp0->getOperand(0).getValueType() == VT)
9088     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
9089 
9090   return SDValue();
9091 }
9092 
9093 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
9094   SDValue N0 = N->getOperand(0);
9095   EVT VT = N->getValueType(0);
9096 
9097   if (N0.isUndef())
9098     return DAG.getUNDEF(VT);
9099 
9100   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
9101   // Only do this before legalize, since afterward the target may be depending
9102   // on the bitconvert.
9103   // First check to see if this is all constant.
9104   if (!LegalTypes &&
9105       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
9106       VT.isVector()) {
9107     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
9108 
9109     EVT DestEltVT = N->getValueType(0).getVectorElementType();
9110     assert(!DestEltVT.isVector() &&
9111            "Element type of vector ValueType must not be vector!");
9112     if (isSimple)
9113       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
9114   }
9115 
9116   // If the input is a constant, let getNode fold it.
9117   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
9118     // If we can't allow illegal operations, we need to check that this is just
9119     // a fp -> int or int -> conversion and that the resulting operation will
9120     // be legal.
9121     if (!LegalOperations ||
9122         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
9123          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
9124         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
9125          TLI.isOperationLegal(ISD::Constant, VT)))
9126       return DAG.getBitcast(VT, N0);
9127   }
9128 
9129   // (conv (conv x, t1), t2) -> (conv x, t2)
9130   if (N0.getOpcode() == ISD::BITCAST)
9131     return DAG.getBitcast(VT, N0.getOperand(0));
9132 
9133   // fold (conv (load x)) -> (load (conv*)x)
9134   // If the resultant load doesn't need a higher alignment than the original!
9135   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9136       // Do not change the width of a volatile load.
9137       !cast<LoadSDNode>(N0)->isVolatile() &&
9138       // Do not remove the cast if the types differ in endian layout.
9139       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
9140           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
9141       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
9142       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
9143     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9144     unsigned OrigAlign = LN0->getAlignment();
9145 
9146     bool Fast = false;
9147     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
9148                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
9149         Fast) {
9150       SDValue Load =
9151           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9152                       LN0->getPointerInfo(), OrigAlign,
9153                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
9154       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
9155       return Load;
9156     }
9157   }
9158 
9159   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
9160     return V;
9161 
9162   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
9163   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
9164   //
9165   // For ppc_fp128:
9166   // fold (bitcast (fneg x)) ->
9167   //     flipbit = signbit
9168   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9169   //
9170   // fold (bitcast (fabs x)) ->
9171   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
9172   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9173   // This often reduces constant pool loads.
9174   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
9175        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
9176       N0.getNode()->hasOneUse() && VT.isInteger() &&
9177       !VT.isVector() && !N0.getValueType().isVector()) {
9178     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
9179     AddToWorklist(NewConv.getNode());
9180 
9181     SDLoc DL(N);
9182     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9183       assert(VT.getSizeInBits() == 128);
9184       SDValue SignBit = DAG.getConstant(
9185           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
9186       SDValue FlipBit;
9187       if (N0.getOpcode() == ISD::FNEG) {
9188         FlipBit = SignBit;
9189         AddToWorklist(FlipBit.getNode());
9190       } else {
9191         assert(N0.getOpcode() == ISD::FABS);
9192         SDValue Hi =
9193             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
9194                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9195                                               SDLoc(NewConv)));
9196         AddToWorklist(Hi.getNode());
9197         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
9198         AddToWorklist(FlipBit.getNode());
9199       }
9200       SDValue FlipBits =
9201           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9202       AddToWorklist(FlipBits.getNode());
9203       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
9204     }
9205     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9206     if (N0.getOpcode() == ISD::FNEG)
9207       return DAG.getNode(ISD::XOR, DL, VT,
9208                          NewConv, DAG.getConstant(SignBit, DL, VT));
9209     assert(N0.getOpcode() == ISD::FABS);
9210     return DAG.getNode(ISD::AND, DL, VT,
9211                        NewConv, DAG.getConstant(~SignBit, DL, VT));
9212   }
9213 
9214   // fold (bitconvert (fcopysign cst, x)) ->
9215   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
9216   // Note that we don't handle (copysign x, cst) because this can always be
9217   // folded to an fneg or fabs.
9218   //
9219   // For ppc_fp128:
9220   // fold (bitcast (fcopysign cst, x)) ->
9221   //     flipbit = (and (extract_element
9222   //                     (xor (bitcast cst), (bitcast x)), 0),
9223   //                    signbit)
9224   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
9225   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
9226       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
9227       VT.isInteger() && !VT.isVector()) {
9228     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
9229     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
9230     if (isTypeLegal(IntXVT)) {
9231       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9232       AddToWorklist(X.getNode());
9233 
9234       // If X has a different width than the result/lhs, sext it or truncate it.
9235       unsigned VTWidth = VT.getSizeInBits();
9236       if (OrigXWidth < VTWidth) {
9237         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9238         AddToWorklist(X.getNode());
9239       } else if (OrigXWidth > VTWidth) {
9240         // To get the sign bit in the right place, we have to shift it right
9241         // before truncating.
9242         SDLoc DL(X);
9243         X = DAG.getNode(ISD::SRL, DL,
9244                         X.getValueType(), X,
9245                         DAG.getConstant(OrigXWidth-VTWidth, DL,
9246                                         X.getValueType()));
9247         AddToWorklist(X.getNode());
9248         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9249         AddToWorklist(X.getNode());
9250       }
9251 
9252       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9253         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9254         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9255         AddToWorklist(Cst.getNode());
9256         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9257         AddToWorklist(X.getNode());
9258         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9259         AddToWorklist(XorResult.getNode());
9260         SDValue XorResult64 = DAG.getNode(
9261             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9262             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9263                                   SDLoc(XorResult)));
9264         AddToWorklist(XorResult64.getNode());
9265         SDValue FlipBit =
9266             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9267                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9268         AddToWorklist(FlipBit.getNode());
9269         SDValue FlipBits =
9270             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9271         AddToWorklist(FlipBits.getNode());
9272         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9273       }
9274       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9275       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9276                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
9277       AddToWorklist(X.getNode());
9278 
9279       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9280       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9281                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9282       AddToWorklist(Cst.getNode());
9283 
9284       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9285     }
9286   }
9287 
9288   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9289   if (N0.getOpcode() == ISD::BUILD_PAIR)
9290     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9291       return CombineLD;
9292 
9293   // Remove double bitcasts from shuffles - this is often a legacy of
9294   // XformToShuffleWithZero being used to combine bitmaskings (of
9295   // float vectors bitcast to integer vectors) into shuffles.
9296   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9297   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9298       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9299       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9300       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9301     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9302 
9303     // If operands are a bitcast, peek through if it casts the original VT.
9304     // If operands are a constant, just bitcast back to original VT.
9305     auto PeekThroughBitcast = [&](SDValue Op) {
9306       if (Op.getOpcode() == ISD::BITCAST &&
9307           Op.getOperand(0).getValueType() == VT)
9308         return SDValue(Op.getOperand(0));
9309       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9310           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9311         return DAG.getBitcast(VT, Op);
9312       return SDValue();
9313     };
9314 
9315     // FIXME: If either input vector is bitcast, try to convert the shuffle to
9316     // the result type of this bitcast. This would eliminate at least one
9317     // bitcast. See the transform in InstCombine.
9318     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9319     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9320     if (!(SV0 && SV1))
9321       return SDValue();
9322 
9323     int MaskScale =
9324         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9325     SmallVector<int, 8> NewMask;
9326     for (int M : SVN->getMask())
9327       for (int i = 0; i != MaskScale; ++i)
9328         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9329 
9330     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9331     if (!LegalMask) {
9332       std::swap(SV0, SV1);
9333       ShuffleVectorSDNode::commuteMask(NewMask);
9334       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9335     }
9336 
9337     if (LegalMask)
9338       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9339   }
9340 
9341   return SDValue();
9342 }
9343 
9344 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9345   EVT VT = N->getValueType(0);
9346   return CombineConsecutiveLoads(N, VT);
9347 }
9348 
9349 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9350 /// operands. DstEltVT indicates the destination element value type.
9351 SDValue DAGCombiner::
9352 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9353   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9354 
9355   // If this is already the right type, we're done.
9356   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9357 
9358   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9359   unsigned DstBitSize = DstEltVT.getSizeInBits();
9360 
9361   // If this is a conversion of N elements of one type to N elements of another
9362   // type, convert each element.  This handles FP<->INT cases.
9363   if (SrcBitSize == DstBitSize) {
9364     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9365                               BV->getValueType(0).getVectorNumElements());
9366 
9367     // Due to the FP element handling below calling this routine recursively,
9368     // we can end up with a scalar-to-vector node here.
9369     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9370       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9371                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9372 
9373     SmallVector<SDValue, 8> Ops;
9374     for (SDValue Op : BV->op_values()) {
9375       // If the vector element type is not legal, the BUILD_VECTOR operands
9376       // are promoted and implicitly truncated.  Make that explicit here.
9377       if (Op.getValueType() != SrcEltVT)
9378         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9379       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9380       AddToWorklist(Ops.back().getNode());
9381     }
9382     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9383   }
9384 
9385   // Otherwise, we're growing or shrinking the elements.  To avoid having to
9386   // handle annoying details of growing/shrinking FP values, we convert them to
9387   // int first.
9388   if (SrcEltVT.isFloatingPoint()) {
9389     // Convert the input float vector to a int vector where the elements are the
9390     // same sizes.
9391     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9392     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9393     SrcEltVT = IntVT;
9394   }
9395 
9396   // Now we know the input is an integer vector.  If the output is a FP type,
9397   // convert to integer first, then to FP of the right size.
9398   if (DstEltVT.isFloatingPoint()) {
9399     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9400     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9401 
9402     // Next, convert to FP elements of the same size.
9403     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9404   }
9405 
9406   SDLoc DL(BV);
9407 
9408   // Okay, we know the src/dst types are both integers of differing types.
9409   // Handling growing first.
9410   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9411   if (SrcBitSize < DstBitSize) {
9412     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9413 
9414     SmallVector<SDValue, 8> Ops;
9415     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9416          i += NumInputsPerOutput) {
9417       bool isLE = DAG.getDataLayout().isLittleEndian();
9418       APInt NewBits = APInt(DstBitSize, 0);
9419       bool EltIsUndef = true;
9420       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9421         // Shift the previously computed bits over.
9422         NewBits <<= SrcBitSize;
9423         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9424         if (Op.isUndef()) continue;
9425         EltIsUndef = false;
9426 
9427         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9428                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9429       }
9430 
9431       if (EltIsUndef)
9432         Ops.push_back(DAG.getUNDEF(DstEltVT));
9433       else
9434         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9435     }
9436 
9437     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9438     return DAG.getBuildVector(VT, DL, Ops);
9439   }
9440 
9441   // Finally, this must be the case where we are shrinking elements: each input
9442   // turns into multiple outputs.
9443   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9444   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9445                             NumOutputsPerInput*BV->getNumOperands());
9446   SmallVector<SDValue, 8> Ops;
9447 
9448   for (const SDValue &Op : BV->op_values()) {
9449     if (Op.isUndef()) {
9450       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9451       continue;
9452     }
9453 
9454     APInt OpVal = cast<ConstantSDNode>(Op)->
9455                   getAPIntValue().zextOrTrunc(SrcBitSize);
9456 
9457     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9458       APInt ThisVal = OpVal.trunc(DstBitSize);
9459       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9460       OpVal.lshrInPlace(DstBitSize);
9461     }
9462 
9463     // For big endian targets, swap the order of the pieces of each element.
9464     if (DAG.getDataLayout().isBigEndian())
9465       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9466   }
9467 
9468   return DAG.getBuildVector(VT, DL, Ops);
9469 }
9470 
9471 static bool isContractable(SDNode *N) {
9472   SDNodeFlags F = N->getFlags();
9473   return F.hasAllowContract() || F.hasUnsafeAlgebra();
9474 }
9475 
9476 /// Try to perform FMA combining on a given FADD node.
9477 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9478   SDValue N0 = N->getOperand(0);
9479   SDValue N1 = N->getOperand(1);
9480   EVT VT = N->getValueType(0);
9481   SDLoc SL(N);
9482 
9483   const TargetOptions &Options = DAG.getTarget().Options;
9484 
9485   // Floating-point multiply-add with intermediate rounding.
9486   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9487 
9488   // Floating-point multiply-add without intermediate rounding.
9489   bool HasFMA =
9490       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9491       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9492 
9493   // No valid opcode, do not combine.
9494   if (!HasFMAD && !HasFMA)
9495     return SDValue();
9496 
9497   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9498                               Options.UnsafeFPMath || HasFMAD);
9499   // If the addition is not contractable, do not combine.
9500   if (!AllowFusionGlobally && !isContractable(N))
9501     return SDValue();
9502 
9503   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9504   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9505     return SDValue();
9506 
9507   // Always prefer FMAD to FMA for precision.
9508   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9509   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9510 
9511   // Is the node an FMUL and contractable either due to global flags or
9512   // SDNodeFlags.
9513   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9514     if (N.getOpcode() != ISD::FMUL)
9515       return false;
9516     return AllowFusionGlobally || isContractable(N.getNode());
9517   };
9518   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9519   // prefer to fold the multiply with fewer uses.
9520   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9521     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9522       std::swap(N0, N1);
9523   }
9524 
9525   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9526   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9527     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9528                        N0.getOperand(0), N0.getOperand(1), N1);
9529   }
9530 
9531   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9532   // Note: Commutes FADD operands.
9533   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9534     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9535                        N1.getOperand(0), N1.getOperand(1), N0);
9536   }
9537 
9538   // Look through FP_EXTEND nodes to do more combining.
9539 
9540   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9541   if (N0.getOpcode() == ISD::FP_EXTEND) {
9542     SDValue N00 = N0.getOperand(0);
9543     if (isContractableFMUL(N00) &&
9544         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9545       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9546                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9547                                      N00.getOperand(0)),
9548                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9549                                      N00.getOperand(1)), N1);
9550     }
9551   }
9552 
9553   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9554   // Note: Commutes FADD operands.
9555   if (N1.getOpcode() == ISD::FP_EXTEND) {
9556     SDValue N10 = N1.getOperand(0);
9557     if (isContractableFMUL(N10) &&
9558         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9559       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9560                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9561                                      N10.getOperand(0)),
9562                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9563                                      N10.getOperand(1)), N0);
9564     }
9565   }
9566 
9567   // More folding opportunities when target permits.
9568   if (Aggressive) {
9569     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9570     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9571     // are currently only supported on binary nodes.
9572     if (Options.UnsafeFPMath &&
9573         N0.getOpcode() == PreferredFusedOpcode &&
9574         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9575         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9576       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9577                          N0.getOperand(0), N0.getOperand(1),
9578                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9579                                      N0.getOperand(2).getOperand(0),
9580                                      N0.getOperand(2).getOperand(1),
9581                                      N1));
9582     }
9583 
9584     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9585     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9586     // are currently only supported on binary nodes.
9587     if (Options.UnsafeFPMath &&
9588         N1->getOpcode() == PreferredFusedOpcode &&
9589         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9590         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9591       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9592                          N1.getOperand(0), N1.getOperand(1),
9593                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9594                                      N1.getOperand(2).getOperand(0),
9595                                      N1.getOperand(2).getOperand(1),
9596                                      N0));
9597     }
9598 
9599 
9600     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9601     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9602     auto FoldFAddFMAFPExtFMul = [&] (
9603       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9604       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9605                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9606                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9607                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9608                                      Z));
9609     };
9610     if (N0.getOpcode() == PreferredFusedOpcode) {
9611       SDValue N02 = N0.getOperand(2);
9612       if (N02.getOpcode() == ISD::FP_EXTEND) {
9613         SDValue N020 = N02.getOperand(0);
9614         if (isContractableFMUL(N020) &&
9615             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9616           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9617                                       N020.getOperand(0), N020.getOperand(1),
9618                                       N1);
9619         }
9620       }
9621     }
9622 
9623     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9624     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9625     // FIXME: This turns two single-precision and one double-precision
9626     // operation into two double-precision operations, which might not be
9627     // interesting for all targets, especially GPUs.
9628     auto FoldFAddFPExtFMAFMul = [&] (
9629       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9630       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9631                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9632                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9633                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9634                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9635                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9636                                      Z));
9637     };
9638     if (N0.getOpcode() == ISD::FP_EXTEND) {
9639       SDValue N00 = N0.getOperand(0);
9640       if (N00.getOpcode() == PreferredFusedOpcode) {
9641         SDValue N002 = N00.getOperand(2);
9642         if (isContractableFMUL(N002) &&
9643             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9644           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9645                                       N002.getOperand(0), N002.getOperand(1),
9646                                       N1);
9647         }
9648       }
9649     }
9650 
9651     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9652     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9653     if (N1.getOpcode() == PreferredFusedOpcode) {
9654       SDValue N12 = N1.getOperand(2);
9655       if (N12.getOpcode() == ISD::FP_EXTEND) {
9656         SDValue N120 = N12.getOperand(0);
9657         if (isContractableFMUL(N120) &&
9658             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9659           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9660                                       N120.getOperand(0), N120.getOperand(1),
9661                                       N0);
9662         }
9663       }
9664     }
9665 
9666     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9667     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9668     // FIXME: This turns two single-precision and one double-precision
9669     // operation into two double-precision operations, which might not be
9670     // interesting for all targets, especially GPUs.
9671     if (N1.getOpcode() == ISD::FP_EXTEND) {
9672       SDValue N10 = N1.getOperand(0);
9673       if (N10.getOpcode() == PreferredFusedOpcode) {
9674         SDValue N102 = N10.getOperand(2);
9675         if (isContractableFMUL(N102) &&
9676             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9677           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9678                                       N102.getOperand(0), N102.getOperand(1),
9679                                       N0);
9680         }
9681       }
9682     }
9683   }
9684 
9685   return SDValue();
9686 }
9687 
9688 /// Try to perform FMA combining on a given FSUB node.
9689 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9690   SDValue N0 = N->getOperand(0);
9691   SDValue N1 = N->getOperand(1);
9692   EVT VT = N->getValueType(0);
9693   SDLoc SL(N);
9694 
9695   const TargetOptions &Options = DAG.getTarget().Options;
9696   // Floating-point multiply-add with intermediate rounding.
9697   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9698 
9699   // Floating-point multiply-add without intermediate rounding.
9700   bool HasFMA =
9701       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9702       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9703 
9704   // No valid opcode, do not combine.
9705   if (!HasFMAD && !HasFMA)
9706     return SDValue();
9707 
9708   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9709                               Options.UnsafeFPMath || HasFMAD);
9710   // If the subtraction is not contractable, do not combine.
9711   if (!AllowFusionGlobally && !isContractable(N))
9712     return SDValue();
9713 
9714   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9715   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9716     return SDValue();
9717 
9718   // Always prefer FMAD to FMA for precision.
9719   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9720   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9721 
9722   // Is the node an FMUL and contractable either due to global flags or
9723   // SDNodeFlags.
9724   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9725     if (N.getOpcode() != ISD::FMUL)
9726       return false;
9727     return AllowFusionGlobally || isContractable(N.getNode());
9728   };
9729 
9730   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9731   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9732     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9733                        N0.getOperand(0), N0.getOperand(1),
9734                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9735   }
9736 
9737   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9738   // Note: Commutes FSUB operands.
9739   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9740     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9741                        DAG.getNode(ISD::FNEG, SL, VT,
9742                                    N1.getOperand(0)),
9743                        N1.getOperand(1), N0);
9744 
9745   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9746   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9747       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9748     SDValue N00 = N0.getOperand(0).getOperand(0);
9749     SDValue N01 = N0.getOperand(0).getOperand(1);
9750     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9751                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9752                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9753   }
9754 
9755   // Look through FP_EXTEND nodes to do more combining.
9756 
9757   // fold (fsub (fpext (fmul x, y)), z)
9758   //   -> (fma (fpext x), (fpext y), (fneg z))
9759   if (N0.getOpcode() == ISD::FP_EXTEND) {
9760     SDValue N00 = N0.getOperand(0);
9761     if (isContractableFMUL(N00) &&
9762         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9763       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9764                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9765                                      N00.getOperand(0)),
9766                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9767                                      N00.getOperand(1)),
9768                          DAG.getNode(ISD::FNEG, SL, VT, N1));
9769     }
9770   }
9771 
9772   // fold (fsub x, (fpext (fmul y, z)))
9773   //   -> (fma (fneg (fpext y)), (fpext z), x)
9774   // Note: Commutes FSUB operands.
9775   if (N1.getOpcode() == ISD::FP_EXTEND) {
9776     SDValue N10 = N1.getOperand(0);
9777     if (isContractableFMUL(N10) &&
9778         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9779       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9780                          DAG.getNode(ISD::FNEG, SL, VT,
9781                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
9782                                                  N10.getOperand(0))),
9783                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9784                                      N10.getOperand(1)),
9785                          N0);
9786     }
9787   }
9788 
9789   // fold (fsub (fpext (fneg (fmul, x, y))), z)
9790   //   -> (fneg (fma (fpext x), (fpext y), z))
9791   // Note: This could be removed with appropriate canonicalization of the
9792   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9793   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9794   // from implementing the canonicalization in visitFSUB.
9795   if (N0.getOpcode() == ISD::FP_EXTEND) {
9796     SDValue N00 = N0.getOperand(0);
9797     if (N00.getOpcode() == ISD::FNEG) {
9798       SDValue N000 = N00.getOperand(0);
9799       if (isContractableFMUL(N000) &&
9800           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9801         return DAG.getNode(ISD::FNEG, SL, VT,
9802                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9803                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9804                                                    N000.getOperand(0)),
9805                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9806                                                    N000.getOperand(1)),
9807                                        N1));
9808       }
9809     }
9810   }
9811 
9812   // fold (fsub (fneg (fpext (fmul, x, y))), z)
9813   //   -> (fneg (fma (fpext x)), (fpext y), z)
9814   // Note: This could be removed with appropriate canonicalization of the
9815   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9816   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9817   // from implementing the canonicalization in visitFSUB.
9818   if (N0.getOpcode() == ISD::FNEG) {
9819     SDValue N00 = N0.getOperand(0);
9820     if (N00.getOpcode() == ISD::FP_EXTEND) {
9821       SDValue N000 = N00.getOperand(0);
9822       if (isContractableFMUL(N000) &&
9823           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9824         return DAG.getNode(ISD::FNEG, SL, VT,
9825                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9826                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9827                                                    N000.getOperand(0)),
9828                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9829                                                    N000.getOperand(1)),
9830                                        N1));
9831       }
9832     }
9833   }
9834 
9835   // More folding opportunities when target permits.
9836   if (Aggressive) {
9837     // fold (fsub (fma x, y, (fmul u, v)), z)
9838     //   -> (fma x, y (fma u, v, (fneg z)))
9839     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9840     // are currently only supported on binary nodes.
9841     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9842         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9843         N0.getOperand(2)->hasOneUse()) {
9844       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9845                          N0.getOperand(0), N0.getOperand(1),
9846                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9847                                      N0.getOperand(2).getOperand(0),
9848                                      N0.getOperand(2).getOperand(1),
9849                                      DAG.getNode(ISD::FNEG, SL, VT,
9850                                                  N1)));
9851     }
9852 
9853     // fold (fsub x, (fma y, z, (fmul u, v)))
9854     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9855     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9856     // are currently only supported on binary nodes.
9857     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9858         isContractableFMUL(N1.getOperand(2))) {
9859       SDValue N20 = N1.getOperand(2).getOperand(0);
9860       SDValue N21 = N1.getOperand(2).getOperand(1);
9861       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9862                          DAG.getNode(ISD::FNEG, SL, VT,
9863                                      N1.getOperand(0)),
9864                          N1.getOperand(1),
9865                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9866                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9867 
9868                                      N21, N0));
9869     }
9870 
9871 
9872     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9873     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9874     if (N0.getOpcode() == PreferredFusedOpcode) {
9875       SDValue N02 = N0.getOperand(2);
9876       if (N02.getOpcode() == ISD::FP_EXTEND) {
9877         SDValue N020 = N02.getOperand(0);
9878         if (isContractableFMUL(N020) &&
9879             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9880           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9881                              N0.getOperand(0), N0.getOperand(1),
9882                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9883                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9884                                                      N020.getOperand(0)),
9885                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9886                                                      N020.getOperand(1)),
9887                                          DAG.getNode(ISD::FNEG, SL, VT,
9888                                                      N1)));
9889         }
9890       }
9891     }
9892 
9893     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9894     //   -> (fma (fpext x), (fpext y),
9895     //           (fma (fpext u), (fpext v), (fneg z)))
9896     // FIXME: This turns two single-precision and one double-precision
9897     // operation into two double-precision operations, which might not be
9898     // interesting for all targets, especially GPUs.
9899     if (N0.getOpcode() == ISD::FP_EXTEND) {
9900       SDValue N00 = N0.getOperand(0);
9901       if (N00.getOpcode() == PreferredFusedOpcode) {
9902         SDValue N002 = N00.getOperand(2);
9903         if (isContractableFMUL(N002) &&
9904             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9905           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9906                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9907                                          N00.getOperand(0)),
9908                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9909                                          N00.getOperand(1)),
9910                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9911                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9912                                                      N002.getOperand(0)),
9913                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9914                                                      N002.getOperand(1)),
9915                                          DAG.getNode(ISD::FNEG, SL, VT,
9916                                                      N1)));
9917         }
9918       }
9919     }
9920 
9921     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9922     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9923     if (N1.getOpcode() == PreferredFusedOpcode &&
9924         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9925       SDValue N120 = N1.getOperand(2).getOperand(0);
9926       if (isContractableFMUL(N120) &&
9927           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9928         SDValue N1200 = N120.getOperand(0);
9929         SDValue N1201 = N120.getOperand(1);
9930         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9931                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9932                            N1.getOperand(1),
9933                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9934                                        DAG.getNode(ISD::FNEG, SL, VT,
9935                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9936                                                                VT, N1200)),
9937                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9938                                                    N1201),
9939                                        N0));
9940       }
9941     }
9942 
9943     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9944     //   -> (fma (fneg (fpext y)), (fpext z),
9945     //           (fma (fneg (fpext u)), (fpext v), x))
9946     // FIXME: This turns two single-precision and one double-precision
9947     // operation into two double-precision operations, which might not be
9948     // interesting for all targets, especially GPUs.
9949     if (N1.getOpcode() == ISD::FP_EXTEND &&
9950         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9951       SDValue CvtSrc = N1.getOperand(0);
9952       SDValue N100 = CvtSrc.getOperand(0);
9953       SDValue N101 = CvtSrc.getOperand(1);
9954       SDValue N102 = CvtSrc.getOperand(2);
9955       if (isContractableFMUL(N102) &&
9956           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
9957         SDValue N1020 = N102.getOperand(0);
9958         SDValue N1021 = N102.getOperand(1);
9959         return DAG.getNode(PreferredFusedOpcode, SL, VT,
9960                            DAG.getNode(ISD::FNEG, SL, VT,
9961                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9962                                                    N100)),
9963                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9964                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9965                                        DAG.getNode(ISD::FNEG, SL, VT,
9966                                                    DAG.getNode(ISD::FP_EXTEND, SL,
9967                                                                VT, N1020)),
9968                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9969                                                    N1021),
9970                                        N0));
9971       }
9972     }
9973   }
9974 
9975   return SDValue();
9976 }
9977 
9978 /// Try to perform FMA combining on a given FMUL node based on the distributive
9979 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9980 /// subtraction instead of addition).
9981 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9982   SDValue N0 = N->getOperand(0);
9983   SDValue N1 = N->getOperand(1);
9984   EVT VT = N->getValueType(0);
9985   SDLoc SL(N);
9986 
9987   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9988 
9989   const TargetOptions &Options = DAG.getTarget().Options;
9990 
9991   // The transforms below are incorrect when x == 0 and y == inf, because the
9992   // intermediate multiplication produces a nan.
9993   if (!Options.NoInfsFPMath)
9994     return SDValue();
9995 
9996   // Floating-point multiply-add without intermediate rounding.
9997   bool HasFMA =
9998       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9999       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
10000       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
10001 
10002   // Floating-point multiply-add with intermediate rounding. This can result
10003   // in a less precise result due to the changed rounding order.
10004   bool HasFMAD = Options.UnsafeFPMath &&
10005                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
10006 
10007   // No valid opcode, do not combine.
10008   if (!HasFMAD && !HasFMA)
10009     return SDValue();
10010 
10011   // Always prefer FMAD to FMA for precision.
10012   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
10013   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
10014 
10015   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
10016   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
10017   auto FuseFADD = [&](SDValue X, SDValue Y) {
10018     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
10019       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10020       if (XC1 && XC1->isExactlyValue(+1.0))
10021         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
10022       if (XC1 && XC1->isExactlyValue(-1.0))
10023         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10024                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10025     }
10026     return SDValue();
10027   };
10028 
10029   if (SDValue FMA = FuseFADD(N0, N1))
10030     return FMA;
10031   if (SDValue FMA = FuseFADD(N1, N0))
10032     return FMA;
10033 
10034   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
10035   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
10036   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
10037   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
10038   auto FuseFSUB = [&](SDValue X, SDValue Y) {
10039     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
10040       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
10041       if (XC0 && XC0->isExactlyValue(+1.0))
10042         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10043                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10044                            Y);
10045       if (XC0 && XC0->isExactlyValue(-1.0))
10046         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10047                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10048                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10049 
10050       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10051       if (XC1 && XC1->isExactlyValue(+1.0))
10052         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10053                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10054       if (XC1 && XC1->isExactlyValue(-1.0))
10055         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
10056     }
10057     return SDValue();
10058   };
10059 
10060   if (SDValue FMA = FuseFSUB(N0, N1))
10061     return FMA;
10062   if (SDValue FMA = FuseFSUB(N1, N0))
10063     return FMA;
10064 
10065   return SDValue();
10066 }
10067 
10068 static bool isFMulNegTwo(SDValue &N) {
10069   if (N.getOpcode() != ISD::FMUL)
10070     return false;
10071   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
10072     return CFP->isExactlyValue(-2.0);
10073   return false;
10074 }
10075 
10076 SDValue DAGCombiner::visitFADD(SDNode *N) {
10077   SDValue N0 = N->getOperand(0);
10078   SDValue N1 = N->getOperand(1);
10079   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
10080   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
10081   EVT VT = N->getValueType(0);
10082   SDLoc DL(N);
10083   const TargetOptions &Options = DAG.getTarget().Options;
10084   const SDNodeFlags Flags = N->getFlags();
10085 
10086   // fold vector ops
10087   if (VT.isVector())
10088     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10089       return FoldedVOp;
10090 
10091   // fold (fadd c1, c2) -> c1 + c2
10092   if (N0CFP && N1CFP)
10093     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
10094 
10095   // canonicalize constant to RHS
10096   if (N0CFP && !N1CFP)
10097     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
10098 
10099   if (SDValue NewSel = foldBinOpIntoSelect(N))
10100     return NewSel;
10101 
10102   // fold (fadd A, (fneg B)) -> (fsub A, B)
10103   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10104       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
10105     return DAG.getNode(ISD::FSUB, DL, VT, N0,
10106                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10107 
10108   // fold (fadd (fneg A), B) -> (fsub B, A)
10109   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10110       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
10111     return DAG.getNode(ISD::FSUB, DL, VT, N1,
10112                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
10113 
10114   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
10115   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
10116   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
10117       (isFMulNegTwo(N1) && N1.hasOneUse())) {
10118     bool N1IsFMul = isFMulNegTwo(N1);
10119     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
10120     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
10121     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
10122   }
10123 
10124   // FIXME: Auto-upgrade the target/function-level option.
10125   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
10126     // fold (fadd A, 0) -> A
10127     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
10128       if (N1C->isZero())
10129         return N0;
10130   }
10131 
10132   // If 'unsafe math' is enabled, fold lots of things.
10133   if (Options.UnsafeFPMath) {
10134     // No FP constant should be created after legalization as Instruction
10135     // Selection pass has a hard time dealing with FP constants.
10136     bool AllowNewConst = (Level < AfterLegalizeDAG);
10137 
10138     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
10139     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
10140         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
10141       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
10142                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
10143                                      Flags),
10144                          Flags);
10145 
10146     // If allowed, fold (fadd (fneg x), x) -> 0.0
10147     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
10148       return DAG.getConstantFP(0.0, DL, VT);
10149 
10150     // If allowed, fold (fadd x, (fneg x)) -> 0.0
10151     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
10152       return DAG.getConstantFP(0.0, DL, VT);
10153 
10154     // We can fold chains of FADD's of the same value into multiplications.
10155     // This transform is not safe in general because we are reducing the number
10156     // of rounding steps.
10157     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
10158       if (N0.getOpcode() == ISD::FMUL) {
10159         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10160         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
10161 
10162         // (fadd (fmul x, c), x) -> (fmul x, c+1)
10163         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
10164           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10165                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10166           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
10167         }
10168 
10169         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
10170         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
10171             N1.getOperand(0) == N1.getOperand(1) &&
10172             N0.getOperand(0) == N1.getOperand(0)) {
10173           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10174                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10175           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
10176         }
10177       }
10178 
10179       if (N1.getOpcode() == ISD::FMUL) {
10180         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10181         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
10182 
10183         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
10184         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
10185           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10186                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10187           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
10188         }
10189 
10190         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
10191         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
10192             N0.getOperand(0) == N0.getOperand(1) &&
10193             N1.getOperand(0) == N0.getOperand(0)) {
10194           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10195                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10196           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
10197         }
10198       }
10199 
10200       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
10201         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10202         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
10203         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
10204             (N0.getOperand(0) == N1)) {
10205           return DAG.getNode(ISD::FMUL, DL, VT,
10206                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
10207         }
10208       }
10209 
10210       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
10211         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10212         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
10213         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
10214             N1.getOperand(0) == N0) {
10215           return DAG.getNode(ISD::FMUL, DL, VT,
10216                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
10217         }
10218       }
10219 
10220       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
10221       if (AllowNewConst &&
10222           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
10223           N0.getOperand(0) == N0.getOperand(1) &&
10224           N1.getOperand(0) == N1.getOperand(1) &&
10225           N0.getOperand(0) == N1.getOperand(0)) {
10226         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
10227                            DAG.getConstantFP(4.0, DL, VT), Flags);
10228       }
10229     }
10230   } // enable-unsafe-fp-math
10231 
10232   // FADD -> FMA combines:
10233   if (SDValue Fused = visitFADDForFMACombine(N)) {
10234     AddToWorklist(Fused.getNode());
10235     return Fused;
10236   }
10237   return SDValue();
10238 }
10239 
10240 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10241   SDValue N0 = N->getOperand(0);
10242   SDValue N1 = N->getOperand(1);
10243   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10244   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10245   EVT VT = N->getValueType(0);
10246   SDLoc DL(N);
10247   const TargetOptions &Options = DAG.getTarget().Options;
10248   const SDNodeFlags Flags = N->getFlags();
10249 
10250   // fold vector ops
10251   if (VT.isVector())
10252     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10253       return FoldedVOp;
10254 
10255   // fold (fsub c1, c2) -> c1-c2
10256   if (N0CFP && N1CFP)
10257     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10258 
10259   if (SDValue NewSel = foldBinOpIntoSelect(N))
10260     return NewSel;
10261 
10262   // fold (fsub A, (fneg B)) -> (fadd A, B)
10263   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10264     return DAG.getNode(ISD::FADD, DL, VT, N0,
10265                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10266 
10267   // FIXME: Auto-upgrade the target/function-level option.
10268   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
10269     // (fsub 0, B) -> -B
10270     if (N0CFP && N0CFP->isZero()) {
10271       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10272         return GetNegatedExpression(N1, DAG, LegalOperations);
10273       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10274         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10275     }
10276   }
10277 
10278   // If 'unsafe math' is enabled, fold lots of things.
10279   if (Options.UnsafeFPMath) {
10280     // (fsub A, 0) -> A
10281     if (N1CFP && N1CFP->isZero())
10282       return N0;
10283 
10284     // (fsub x, x) -> 0.0
10285     if (N0 == N1)
10286       return DAG.getConstantFP(0.0f, DL, VT);
10287 
10288     // (fsub x, (fadd x, y)) -> (fneg y)
10289     // (fsub x, (fadd y, x)) -> (fneg y)
10290     if (N1.getOpcode() == ISD::FADD) {
10291       SDValue N10 = N1->getOperand(0);
10292       SDValue N11 = N1->getOperand(1);
10293 
10294       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10295         return GetNegatedExpression(N11, DAG, LegalOperations);
10296 
10297       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10298         return GetNegatedExpression(N10, DAG, LegalOperations);
10299     }
10300   }
10301 
10302   // FSUB -> FMA combines:
10303   if (SDValue Fused = visitFSUBForFMACombine(N)) {
10304     AddToWorklist(Fused.getNode());
10305     return Fused;
10306   }
10307 
10308   return SDValue();
10309 }
10310 
10311 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10312   SDValue N0 = N->getOperand(0);
10313   SDValue N1 = N->getOperand(1);
10314   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10315   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10316   EVT VT = N->getValueType(0);
10317   SDLoc DL(N);
10318   const TargetOptions &Options = DAG.getTarget().Options;
10319   const SDNodeFlags Flags = N->getFlags();
10320 
10321   // fold vector ops
10322   if (VT.isVector()) {
10323     // This just handles C1 * C2 for vectors. Other vector folds are below.
10324     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10325       return FoldedVOp;
10326   }
10327 
10328   // fold (fmul c1, c2) -> c1*c2
10329   if (N0CFP && N1CFP)
10330     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10331 
10332   // canonicalize constant to RHS
10333   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10334      !isConstantFPBuildVectorOrConstantFP(N1))
10335     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10336 
10337   // fold (fmul A, 1.0) -> A
10338   if (N1CFP && N1CFP->isExactlyValue(1.0))
10339     return N0;
10340 
10341   if (SDValue NewSel = foldBinOpIntoSelect(N))
10342     return NewSel;
10343 
10344   if (Options.UnsafeFPMath) {
10345     // fold (fmul A, 0) -> 0
10346     if (N1CFP && N1CFP->isZero())
10347       return N1;
10348 
10349     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10350     if (N0.getOpcode() == ISD::FMUL) {
10351       // Fold scalars or any vector constants (not just splats).
10352       // This fold is done in general by InstCombine, but extra fmul insts
10353       // may have been generated during lowering.
10354       SDValue N00 = N0.getOperand(0);
10355       SDValue N01 = N0.getOperand(1);
10356       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10357       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10358       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10359 
10360       // Check 1: Make sure that the first operand of the inner multiply is NOT
10361       // a constant. Otherwise, we may induce infinite looping.
10362       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10363         // Check 2: Make sure that the second operand of the inner multiply and
10364         // the second operand of the outer multiply are constants.
10365         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10366             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10367           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10368           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10369         }
10370       }
10371     }
10372 
10373     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10374     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10375     // during an early run of DAGCombiner can prevent folding with fmuls
10376     // inserted during lowering.
10377     if (N0.getOpcode() == ISD::FADD &&
10378         (N0.getOperand(0) == N0.getOperand(1)) &&
10379         N0.hasOneUse()) {
10380       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10381       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10382       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10383     }
10384   }
10385 
10386   // fold (fmul X, 2.0) -> (fadd X, X)
10387   if (N1CFP && N1CFP->isExactlyValue(+2.0))
10388     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10389 
10390   // fold (fmul X, -1.0) -> (fneg X)
10391   if (N1CFP && N1CFP->isExactlyValue(-1.0))
10392     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10393       return DAG.getNode(ISD::FNEG, DL, VT, N0);
10394 
10395   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10396   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10397     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10398       // Both can be negated for free, check to see if at least one is cheaper
10399       // negated.
10400       if (LHSNeg == 2 || RHSNeg == 2)
10401         return DAG.getNode(ISD::FMUL, DL, VT,
10402                            GetNegatedExpression(N0, DAG, LegalOperations),
10403                            GetNegatedExpression(N1, DAG, LegalOperations),
10404                            Flags);
10405     }
10406   }
10407 
10408   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10409   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10410   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10411       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10412       TLI.isOperationLegal(ISD::FABS, VT)) {
10413     SDValue Select = N0, X = N1;
10414     if (Select.getOpcode() != ISD::SELECT)
10415       std::swap(Select, X);
10416 
10417     SDValue Cond = Select.getOperand(0);
10418     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10419     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10420 
10421     if (TrueOpnd && FalseOpnd &&
10422         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10423         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10424         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10425       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10426       switch (CC) {
10427       default: break;
10428       case ISD::SETOLT:
10429       case ISD::SETULT:
10430       case ISD::SETOLE:
10431       case ISD::SETULE:
10432       case ISD::SETLT:
10433       case ISD::SETLE:
10434         std::swap(TrueOpnd, FalseOpnd);
10435         LLVM_FALLTHROUGH;
10436       case ISD::SETOGT:
10437       case ISD::SETUGT:
10438       case ISD::SETOGE:
10439       case ISD::SETUGE:
10440       case ISD::SETGT:
10441       case ISD::SETGE:
10442         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10443             TLI.isOperationLegal(ISD::FNEG, VT))
10444           return DAG.getNode(ISD::FNEG, DL, VT,
10445                    DAG.getNode(ISD::FABS, DL, VT, X));
10446         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10447           return DAG.getNode(ISD::FABS, DL, VT, X);
10448 
10449         break;
10450       }
10451     }
10452   }
10453 
10454   // FMUL -> FMA combines:
10455   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10456     AddToWorklist(Fused.getNode());
10457     return Fused;
10458   }
10459 
10460   return SDValue();
10461 }
10462 
10463 SDValue DAGCombiner::visitFMA(SDNode *N) {
10464   SDValue N0 = N->getOperand(0);
10465   SDValue N1 = N->getOperand(1);
10466   SDValue N2 = N->getOperand(2);
10467   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10468   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10469   EVT VT = N->getValueType(0);
10470   SDLoc DL(N);
10471   const TargetOptions &Options = DAG.getTarget().Options;
10472 
10473   // Constant fold FMA.
10474   if (isa<ConstantFPSDNode>(N0) &&
10475       isa<ConstantFPSDNode>(N1) &&
10476       isa<ConstantFPSDNode>(N2)) {
10477     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10478   }
10479 
10480   if (Options.UnsafeFPMath) {
10481     if (N0CFP && N0CFP->isZero())
10482       return N2;
10483     if (N1CFP && N1CFP->isZero())
10484       return N2;
10485   }
10486   // TODO: The FMA node should have flags that propagate to these nodes.
10487   if (N0CFP && N0CFP->isExactlyValue(1.0))
10488     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10489   if (N1CFP && N1CFP->isExactlyValue(1.0))
10490     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10491 
10492   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10493   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10494      !isConstantFPBuildVectorOrConstantFP(N1))
10495     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10496 
10497   // TODO: FMA nodes should have flags that propagate to the created nodes.
10498   // For now, create a Flags object for use with all unsafe math transforms.
10499   SDNodeFlags Flags;
10500   Flags.setUnsafeAlgebra(true);
10501 
10502   if (Options.UnsafeFPMath) {
10503     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10504     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10505         isConstantFPBuildVectorOrConstantFP(N1) &&
10506         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10507       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10508                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10509                                      Flags), Flags);
10510     }
10511 
10512     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10513     if (N0.getOpcode() == ISD::FMUL &&
10514         isConstantFPBuildVectorOrConstantFP(N1) &&
10515         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10516       return DAG.getNode(ISD::FMA, DL, VT,
10517                          N0.getOperand(0),
10518                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10519                                      Flags),
10520                          N2);
10521     }
10522   }
10523 
10524   // (fma x, 1, y) -> (fadd x, y)
10525   // (fma x, -1, y) -> (fadd (fneg x), y)
10526   if (N1CFP) {
10527     if (N1CFP->isExactlyValue(1.0))
10528       // TODO: The FMA node should have flags that propagate to this node.
10529       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10530 
10531     if (N1CFP->isExactlyValue(-1.0) &&
10532         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10533       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10534       AddToWorklist(RHSNeg.getNode());
10535       // TODO: The FMA node should have flags that propagate to this node.
10536       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10537     }
10538 
10539     // fma (fneg x), K, y -> fma x -K, y
10540     if (N0.getOpcode() == ISD::FNEG &&
10541         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10542          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10543       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10544                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10545     }
10546   }
10547 
10548   if (Options.UnsafeFPMath) {
10549     // (fma x, c, x) -> (fmul x, (c+1))
10550     if (N1CFP && N0 == N2) {
10551       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10552                          DAG.getNode(ISD::FADD, DL, VT, N1,
10553                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10554                          Flags);
10555     }
10556 
10557     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10558     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10559       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10560                          DAG.getNode(ISD::FADD, DL, VT, N1,
10561                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10562                          Flags);
10563     }
10564   }
10565 
10566   return SDValue();
10567 }
10568 
10569 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10570 // reciprocal.
10571 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10572 // Notice that this is not always beneficial. One reason is different targets
10573 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10574 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10575 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10576 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10577   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10578   const SDNodeFlags Flags = N->getFlags();
10579   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10580     return SDValue();
10581 
10582   // Skip if current node is a reciprocal.
10583   SDValue N0 = N->getOperand(0);
10584   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10585   if (N0CFP && N0CFP->isExactlyValue(1.0))
10586     return SDValue();
10587 
10588   // Exit early if the target does not want this transform or if there can't
10589   // possibly be enough uses of the divisor to make the transform worthwhile.
10590   SDValue N1 = N->getOperand(1);
10591   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10592   if (!MinUses || N1->use_size() < MinUses)
10593     return SDValue();
10594 
10595   // Find all FDIV users of the same divisor.
10596   // Use a set because duplicates may be present in the user list.
10597   SetVector<SDNode *> Users;
10598   for (auto *U : N1->uses()) {
10599     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10600       // This division is eligible for optimization only if global unsafe math
10601       // is enabled or if this division allows reciprocal formation.
10602       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10603         Users.insert(U);
10604     }
10605   }
10606 
10607   // Now that we have the actual number of divisor uses, make sure it meets
10608   // the minimum threshold specified by the target.
10609   if (Users.size() < MinUses)
10610     return SDValue();
10611 
10612   EVT VT = N->getValueType(0);
10613   SDLoc DL(N);
10614   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10615   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10616 
10617   // Dividend / Divisor -> Dividend * Reciprocal
10618   for (auto *U : Users) {
10619     SDValue Dividend = U->getOperand(0);
10620     if (Dividend != FPOne) {
10621       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10622                                     Reciprocal, Flags);
10623       CombineTo(U, NewNode);
10624     } else if (U != Reciprocal.getNode()) {
10625       // In the absence of fast-math-flags, this user node is always the
10626       // same node as Reciprocal, but with FMF they may be different nodes.
10627       CombineTo(U, Reciprocal);
10628     }
10629   }
10630   return SDValue(N, 0);  // N was replaced.
10631 }
10632 
10633 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10634   SDValue N0 = N->getOperand(0);
10635   SDValue N1 = N->getOperand(1);
10636   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10637   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10638   EVT VT = N->getValueType(0);
10639   SDLoc DL(N);
10640   const TargetOptions &Options = DAG.getTarget().Options;
10641   SDNodeFlags Flags = N->getFlags();
10642 
10643   // fold vector ops
10644   if (VT.isVector())
10645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10646       return FoldedVOp;
10647 
10648   // fold (fdiv c1, c2) -> c1/c2
10649   if (N0CFP && N1CFP)
10650     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10651 
10652   if (SDValue NewSel = foldBinOpIntoSelect(N))
10653     return NewSel;
10654 
10655   if (Options.UnsafeFPMath) {
10656     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10657     if (N1CFP) {
10658       // Compute the reciprocal 1.0 / c2.
10659       const APFloat &N1APF = N1CFP->getValueAPF();
10660       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10661       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10662       // Only do the transform if the reciprocal is a legal fp immediate that
10663       // isn't too nasty (eg NaN, denormal, ...).
10664       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10665           (!LegalOperations ||
10666            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10667            // backend)... we should handle this gracefully after Legalize.
10668            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10669            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10670            TLI.isFPImmLegal(Recip, VT)))
10671         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10672                            DAG.getConstantFP(Recip, DL, VT), Flags);
10673     }
10674 
10675     // If this FDIV is part of a reciprocal square root, it may be folded
10676     // into a target-specific square root estimate instruction.
10677     if (N1.getOpcode() == ISD::FSQRT) {
10678       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10679         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10680       }
10681     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10682                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10683       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10684                                           Flags)) {
10685         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10686         AddToWorklist(RV.getNode());
10687         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10688       }
10689     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10690                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10691       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10692                                           Flags)) {
10693         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10694         AddToWorklist(RV.getNode());
10695         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10696       }
10697     } else if (N1.getOpcode() == ISD::FMUL) {
10698       // Look through an FMUL. Even though this won't remove the FDIV directly,
10699       // it's still worthwhile to get rid of the FSQRT if possible.
10700       SDValue SqrtOp;
10701       SDValue OtherOp;
10702       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10703         SqrtOp = N1.getOperand(0);
10704         OtherOp = N1.getOperand(1);
10705       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10706         SqrtOp = N1.getOperand(1);
10707         OtherOp = N1.getOperand(0);
10708       }
10709       if (SqrtOp.getNode()) {
10710         // We found a FSQRT, so try to make this fold:
10711         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10712         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10713           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10714           AddToWorklist(RV.getNode());
10715           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10716         }
10717       }
10718     }
10719 
10720     // Fold into a reciprocal estimate and multiply instead of a real divide.
10721     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10722       AddToWorklist(RV.getNode());
10723       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10724     }
10725   }
10726 
10727   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10728   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10729     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10730       // Both can be negated for free, check to see if at least one is cheaper
10731       // negated.
10732       if (LHSNeg == 2 || RHSNeg == 2)
10733         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10734                            GetNegatedExpression(N0, DAG, LegalOperations),
10735                            GetNegatedExpression(N1, DAG, LegalOperations),
10736                            Flags);
10737     }
10738   }
10739 
10740   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10741     return CombineRepeatedDivisors;
10742 
10743   return SDValue();
10744 }
10745 
10746 SDValue DAGCombiner::visitFREM(SDNode *N) {
10747   SDValue N0 = N->getOperand(0);
10748   SDValue N1 = N->getOperand(1);
10749   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10750   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10751   EVT VT = N->getValueType(0);
10752 
10753   // fold (frem c1, c2) -> fmod(c1,c2)
10754   if (N0CFP && N1CFP)
10755     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10756 
10757   if (SDValue NewSel = foldBinOpIntoSelect(N))
10758     return NewSel;
10759 
10760   return SDValue();
10761 }
10762 
10763 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10764   if (!DAG.getTarget().Options.UnsafeFPMath)
10765     return SDValue();
10766 
10767   SDValue N0 = N->getOperand(0);
10768   if (TLI.isFsqrtCheap(N0, DAG))
10769     return SDValue();
10770 
10771   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10772   // For now, create a Flags object for use with all unsafe math transforms.
10773   SDNodeFlags Flags;
10774   Flags.setUnsafeAlgebra(true);
10775   return buildSqrtEstimate(N0, Flags);
10776 }
10777 
10778 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10779 /// copysign(x, fp_round(y)) -> copysign(x, y)
10780 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10781   SDValue N1 = N->getOperand(1);
10782   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10783        N1.getOpcode() == ISD::FP_ROUND)) {
10784     // Do not optimize out type conversion of f128 type yet.
10785     // For some targets like x86_64, configuration is changed to keep one f128
10786     // value in one SSE register, but instruction selection cannot handle
10787     // FCOPYSIGN on SSE registers yet.
10788     EVT N1VT = N1->getValueType(0);
10789     EVT N1Op0VT = N1->getOperand(0).getValueType();
10790     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10791   }
10792   return false;
10793 }
10794 
10795 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10796   SDValue N0 = N->getOperand(0);
10797   SDValue N1 = N->getOperand(1);
10798   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10799   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10800   EVT VT = N->getValueType(0);
10801 
10802   if (N0CFP && N1CFP) // Constant fold
10803     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10804 
10805   if (N1CFP) {
10806     const APFloat &V = N1CFP->getValueAPF();
10807     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10808     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10809     if (!V.isNegative()) {
10810       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10811         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10812     } else {
10813       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10814         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10815                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10816     }
10817   }
10818 
10819   // copysign(fabs(x), y) -> copysign(x, y)
10820   // copysign(fneg(x), y) -> copysign(x, y)
10821   // copysign(copysign(x,z), y) -> copysign(x, y)
10822   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10823       N0.getOpcode() == ISD::FCOPYSIGN)
10824     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10825 
10826   // copysign(x, abs(y)) -> abs(x)
10827   if (N1.getOpcode() == ISD::FABS)
10828     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10829 
10830   // copysign(x, copysign(y,z)) -> copysign(x, z)
10831   if (N1.getOpcode() == ISD::FCOPYSIGN)
10832     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10833 
10834   // copysign(x, fp_extend(y)) -> copysign(x, y)
10835   // copysign(x, fp_round(y)) -> copysign(x, y)
10836   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10837     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10838 
10839   return SDValue();
10840 }
10841 
10842 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10843   SDValue N0 = N->getOperand(0);
10844   EVT VT = N->getValueType(0);
10845   EVT OpVT = N0.getValueType();
10846 
10847   // fold (sint_to_fp c1) -> c1fp
10848   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10849       // ...but only if the target supports immediate floating-point values
10850       (!LegalOperations ||
10851        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10852     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10853 
10854   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10855   // but UINT_TO_FP is legal on this target, try to convert.
10856   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10857       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10858     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10859     if (DAG.SignBitIsZero(N0))
10860       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10861   }
10862 
10863   // The next optimizations are desirable only if SELECT_CC can be lowered.
10864   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10865     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10866     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10867         !VT.isVector() &&
10868         (!LegalOperations ||
10869          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10870       SDLoc DL(N);
10871       SDValue Ops[] =
10872         { N0.getOperand(0), N0.getOperand(1),
10873           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10874           N0.getOperand(2) };
10875       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10876     }
10877 
10878     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10879     //      (select_cc x, y, 1.0, 0.0,, cc)
10880     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10881         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10882         (!LegalOperations ||
10883          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10884       SDLoc DL(N);
10885       SDValue Ops[] =
10886         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10887           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10888           N0.getOperand(0).getOperand(2) };
10889       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10890     }
10891   }
10892 
10893   return SDValue();
10894 }
10895 
10896 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10897   SDValue N0 = N->getOperand(0);
10898   EVT VT = N->getValueType(0);
10899   EVT OpVT = N0.getValueType();
10900 
10901   // fold (uint_to_fp c1) -> c1fp
10902   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10903       // ...but only if the target supports immediate floating-point values
10904       (!LegalOperations ||
10905        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10906     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10907 
10908   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10909   // but SINT_TO_FP is legal on this target, try to convert.
10910   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10911       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10912     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10913     if (DAG.SignBitIsZero(N0))
10914       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10915   }
10916 
10917   // The next optimizations are desirable only if SELECT_CC can be lowered.
10918   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10919     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10920     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10921         (!LegalOperations ||
10922          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10923       SDLoc DL(N);
10924       SDValue Ops[] =
10925         { N0.getOperand(0), N0.getOperand(1),
10926           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10927           N0.getOperand(2) };
10928       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10929     }
10930   }
10931 
10932   return SDValue();
10933 }
10934 
10935 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10936 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10937   SDValue N0 = N->getOperand(0);
10938   EVT VT = N->getValueType(0);
10939 
10940   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10941     return SDValue();
10942 
10943   SDValue Src = N0.getOperand(0);
10944   EVT SrcVT = Src.getValueType();
10945   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10946   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10947 
10948   // We can safely assume the conversion won't overflow the output range,
10949   // because (for example) (uint8_t)18293.f is undefined behavior.
10950 
10951   // Since we can assume the conversion won't overflow, our decision as to
10952   // whether the input will fit in the float should depend on the minimum
10953   // of the input range and output range.
10954 
10955   // This means this is also safe for a signed input and unsigned output, since
10956   // a negative input would lead to undefined behavior.
10957   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10958   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10959   unsigned ActualSize = std::min(InputSize, OutputSize);
10960   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10961 
10962   // We can only fold away the float conversion if the input range can be
10963   // represented exactly in the float range.
10964   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10965     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10966       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10967                                                        : ISD::ZERO_EXTEND;
10968       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10969     }
10970     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10971       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10972     return DAG.getBitcast(VT, Src);
10973   }
10974   return SDValue();
10975 }
10976 
10977 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10978   SDValue N0 = N->getOperand(0);
10979   EVT VT = N->getValueType(0);
10980 
10981   // fold (fp_to_sint c1fp) -> c1
10982   if (isConstantFPBuildVectorOrConstantFP(N0))
10983     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10984 
10985   return FoldIntToFPToInt(N, DAG);
10986 }
10987 
10988 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10989   SDValue N0 = N->getOperand(0);
10990   EVT VT = N->getValueType(0);
10991 
10992   // fold (fp_to_uint c1fp) -> c1
10993   if (isConstantFPBuildVectorOrConstantFP(N0))
10994     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10995 
10996   return FoldIntToFPToInt(N, DAG);
10997 }
10998 
10999 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
11000   SDValue N0 = N->getOperand(0);
11001   SDValue N1 = N->getOperand(1);
11002   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11003   EVT VT = N->getValueType(0);
11004 
11005   // fold (fp_round c1fp) -> c1fp
11006   if (N0CFP)
11007     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
11008 
11009   // fold (fp_round (fp_extend x)) -> x
11010   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
11011     return N0.getOperand(0);
11012 
11013   // fold (fp_round (fp_round x)) -> (fp_round x)
11014   if (N0.getOpcode() == ISD::FP_ROUND) {
11015     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
11016     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
11017 
11018     // Skip this folding if it results in an fp_round from f80 to f16.
11019     //
11020     // f80 to f16 always generates an expensive (and as yet, unimplemented)
11021     // libcall to __truncxfhf2 instead of selecting native f16 conversion
11022     // instructions from f32 or f64.  Moreover, the first (value-preserving)
11023     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
11024     // x86.
11025     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
11026       return SDValue();
11027 
11028     // If the first fp_round isn't a value preserving truncation, it might
11029     // introduce a tie in the second fp_round, that wouldn't occur in the
11030     // single-step fp_round we want to fold to.
11031     // In other words, double rounding isn't the same as rounding.
11032     // Also, this is a value preserving truncation iff both fp_round's are.
11033     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
11034       SDLoc DL(N);
11035       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
11036                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
11037     }
11038   }
11039 
11040   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
11041   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
11042     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
11043                               N0.getOperand(0), N1);
11044     AddToWorklist(Tmp.getNode());
11045     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
11046                        Tmp, N0.getOperand(1));
11047   }
11048 
11049   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11050     return NewVSel;
11051 
11052   return SDValue();
11053 }
11054 
11055 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
11056   SDValue N0 = N->getOperand(0);
11057   EVT VT = N->getValueType(0);
11058   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
11059   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11060 
11061   // fold (fp_round_inreg c1fp) -> c1fp
11062   if (N0CFP && isTypeLegal(EVT)) {
11063     SDLoc DL(N);
11064     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
11065     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
11066   }
11067 
11068   return SDValue();
11069 }
11070 
11071 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
11072   SDValue N0 = N->getOperand(0);
11073   EVT VT = N->getValueType(0);
11074 
11075   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
11076   if (N->hasOneUse() &&
11077       N->use_begin()->getOpcode() == ISD::FP_ROUND)
11078     return SDValue();
11079 
11080   // fold (fp_extend c1fp) -> c1fp
11081   if (isConstantFPBuildVectorOrConstantFP(N0))
11082     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
11083 
11084   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
11085   if (N0.getOpcode() == ISD::FP16_TO_FP &&
11086       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
11087     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
11088 
11089   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
11090   // value of X.
11091   if (N0.getOpcode() == ISD::FP_ROUND
11092       && N0.getConstantOperandVal(1) == 1) {
11093     SDValue In = N0.getOperand(0);
11094     if (In.getValueType() == VT) return In;
11095     if (VT.bitsLT(In.getValueType()))
11096       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
11097                          In, N0.getOperand(1));
11098     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
11099   }
11100 
11101   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
11102   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11103        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
11104     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11105     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
11106                                      LN0->getChain(),
11107                                      LN0->getBasePtr(), N0.getValueType(),
11108                                      LN0->getMemOperand());
11109     CombineTo(N, ExtLoad);
11110     CombineTo(N0.getNode(),
11111               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
11112                           N0.getValueType(), ExtLoad,
11113                           DAG.getIntPtrConstant(1, SDLoc(N0))),
11114               ExtLoad.getValue(1));
11115     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11116   }
11117 
11118   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11119     return NewVSel;
11120 
11121   return SDValue();
11122 }
11123 
11124 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
11125   SDValue N0 = N->getOperand(0);
11126   EVT VT = N->getValueType(0);
11127 
11128   // fold (fceil c1) -> fceil(c1)
11129   if (isConstantFPBuildVectorOrConstantFP(N0))
11130     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
11131 
11132   return SDValue();
11133 }
11134 
11135 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
11136   SDValue N0 = N->getOperand(0);
11137   EVT VT = N->getValueType(0);
11138 
11139   // fold (ftrunc c1) -> ftrunc(c1)
11140   if (isConstantFPBuildVectorOrConstantFP(N0))
11141     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
11142 
11143   // fold ftrunc (known rounded int x) -> x
11144   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
11145   // likely to be generated to extract integer from a rounded floating value.
11146   switch (N0.getOpcode()) {
11147   default: break;
11148   case ISD::FRINT:
11149   case ISD::FTRUNC:
11150   case ISD::FNEARBYINT:
11151   case ISD::FFLOOR:
11152   case ISD::FCEIL:
11153     return N0;
11154   }
11155 
11156   return SDValue();
11157 }
11158 
11159 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
11160   SDValue N0 = N->getOperand(0);
11161   EVT VT = N->getValueType(0);
11162 
11163   // fold (ffloor c1) -> ffloor(c1)
11164   if (isConstantFPBuildVectorOrConstantFP(N0))
11165     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
11166 
11167   return SDValue();
11168 }
11169 
11170 // FIXME: FNEG and FABS have a lot in common; refactor.
11171 SDValue DAGCombiner::visitFNEG(SDNode *N) {
11172   SDValue N0 = N->getOperand(0);
11173   EVT VT = N->getValueType(0);
11174 
11175   // Constant fold FNEG.
11176   if (isConstantFPBuildVectorOrConstantFP(N0))
11177     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
11178 
11179   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
11180                          &DAG.getTarget().Options))
11181     return GetNegatedExpression(N0, DAG, LegalOperations);
11182 
11183   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
11184   // constant pool values.
11185   if (!TLI.isFNegFree(VT) &&
11186       N0.getOpcode() == ISD::BITCAST &&
11187       N0.getNode()->hasOneUse()) {
11188     SDValue Int = N0.getOperand(0);
11189     EVT IntVT = Int.getValueType();
11190     if (IntVT.isInteger() && !IntVT.isVector()) {
11191       APInt SignMask;
11192       if (N0.getValueType().isVector()) {
11193         // For a vector, get a mask such as 0x80... per scalar element
11194         // and splat it.
11195         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
11196         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11197       } else {
11198         // For a scalar, just generate 0x80...
11199         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
11200       }
11201       SDLoc DL0(N0);
11202       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
11203                         DAG.getConstant(SignMask, DL0, IntVT));
11204       AddToWorklist(Int.getNode());
11205       return DAG.getBitcast(VT, Int);
11206     }
11207   }
11208 
11209   // (fneg (fmul c, x)) -> (fmul -c, x)
11210   if (N0.getOpcode() == ISD::FMUL &&
11211       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
11212     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
11213     if (CFP1) {
11214       APFloat CVal = CFP1->getValueAPF();
11215       CVal.changeSign();
11216       if (Level >= AfterLegalizeDAG &&
11217           (TLI.isFPImmLegal(CVal, VT) ||
11218            TLI.isOperationLegal(ISD::ConstantFP, VT)))
11219         return DAG.getNode(
11220             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
11221             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
11222             N0->getFlags());
11223     }
11224   }
11225 
11226   return SDValue();
11227 }
11228 
11229 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
11230   SDValue N0 = N->getOperand(0);
11231   SDValue N1 = N->getOperand(1);
11232   EVT VT = N->getValueType(0);
11233   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11234   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11235 
11236   if (N0CFP && N1CFP) {
11237     const APFloat &C0 = N0CFP->getValueAPF();
11238     const APFloat &C1 = N1CFP->getValueAPF();
11239     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11240   }
11241 
11242   // Canonicalize to constant on RHS.
11243   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11244      !isConstantFPBuildVectorOrConstantFP(N1))
11245     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11246 
11247   return SDValue();
11248 }
11249 
11250 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11251   SDValue N0 = N->getOperand(0);
11252   SDValue N1 = N->getOperand(1);
11253   EVT VT = N->getValueType(0);
11254   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11255   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11256 
11257   if (N0CFP && N1CFP) {
11258     const APFloat &C0 = N0CFP->getValueAPF();
11259     const APFloat &C1 = N1CFP->getValueAPF();
11260     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11261   }
11262 
11263   // Canonicalize to constant on RHS.
11264   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11265      !isConstantFPBuildVectorOrConstantFP(N1))
11266     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11267 
11268   return SDValue();
11269 }
11270 
11271 SDValue DAGCombiner::visitFABS(SDNode *N) {
11272   SDValue N0 = N->getOperand(0);
11273   EVT VT = N->getValueType(0);
11274 
11275   // fold (fabs c1) -> fabs(c1)
11276   if (isConstantFPBuildVectorOrConstantFP(N0))
11277     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11278 
11279   // fold (fabs (fabs x)) -> (fabs x)
11280   if (N0.getOpcode() == ISD::FABS)
11281     return N->getOperand(0);
11282 
11283   // fold (fabs (fneg x)) -> (fabs x)
11284   // fold (fabs (fcopysign x, y)) -> (fabs x)
11285   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11286     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11287 
11288   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11289   // constant pool values.
11290   if (!TLI.isFAbsFree(VT) &&
11291       N0.getOpcode() == ISD::BITCAST &&
11292       N0.getNode()->hasOneUse()) {
11293     SDValue Int = N0.getOperand(0);
11294     EVT IntVT = Int.getValueType();
11295     if (IntVT.isInteger() && !IntVT.isVector()) {
11296       APInt SignMask;
11297       if (N0.getValueType().isVector()) {
11298         // For a vector, get a mask such as 0x7f... per scalar element
11299         // and splat it.
11300         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11301         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11302       } else {
11303         // For a scalar, just generate 0x7f...
11304         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11305       }
11306       SDLoc DL(N0);
11307       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11308                         DAG.getConstant(SignMask, DL, IntVT));
11309       AddToWorklist(Int.getNode());
11310       return DAG.getBitcast(N->getValueType(0), Int);
11311     }
11312   }
11313 
11314   return SDValue();
11315 }
11316 
11317 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11318   SDValue Chain = N->getOperand(0);
11319   SDValue N1 = N->getOperand(1);
11320   SDValue N2 = N->getOperand(2);
11321 
11322   // If N is a constant we could fold this into a fallthrough or unconditional
11323   // branch. However that doesn't happen very often in normal code, because
11324   // Instcombine/SimplifyCFG should have handled the available opportunities.
11325   // If we did this folding here, it would be necessary to update the
11326   // MachineBasicBlock CFG, which is awkward.
11327 
11328   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11329   // on the target.
11330   if (N1.getOpcode() == ISD::SETCC &&
11331       TLI.isOperationLegalOrCustom(ISD::BR_CC,
11332                                    N1.getOperand(0).getValueType())) {
11333     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11334                        Chain, N1.getOperand(2),
11335                        N1.getOperand(0), N1.getOperand(1), N2);
11336   }
11337 
11338   if (N1.hasOneUse()) {
11339     if (SDValue NewN1 = rebuildSetCC(N1))
11340       return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2);
11341   }
11342 
11343   return SDValue();
11344 }
11345 
11346 SDValue DAGCombiner::rebuildSetCC(SDValue N) {
11347   if (N.getOpcode() == ISD::SRL ||
11348       (N.getOpcode() == ISD::TRUNCATE &&
11349        (N.getOperand(0).hasOneUse() &&
11350         N.getOperand(0).getOpcode() == ISD::SRL))) {
11351     // Look pass the truncate.
11352     if (N.getOpcode() == ISD::TRUNCATE)
11353       N = N.getOperand(0);
11354 
11355     // Match this pattern so that we can generate simpler code:
11356     //
11357     //   %a = ...
11358     //   %b = and i32 %a, 2
11359     //   %c = srl i32 %b, 1
11360     //   brcond i32 %c ...
11361     //
11362     // into
11363     //
11364     //   %a = ...
11365     //   %b = and i32 %a, 2
11366     //   %c = setcc eq %b, 0
11367     //   brcond %c ...
11368     //
11369     // This applies only when the AND constant value has one bit set and the
11370     // SRL constant is equal to the log2 of the AND constant. The back-end is
11371     // smart enough to convert the result into a TEST/JMP sequence.
11372     SDValue Op0 = N.getOperand(0);
11373     SDValue Op1 = N.getOperand(1);
11374 
11375     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
11376       SDValue AndOp1 = Op0.getOperand(1);
11377 
11378       if (AndOp1.getOpcode() == ISD::Constant) {
11379         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11380 
11381         if (AndConst.isPowerOf2() &&
11382             cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
11383           SDLoc DL(N);
11384           return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
11385                               Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11386                               ISD::SETNE);
11387         }
11388       }
11389     }
11390   }
11391 
11392   // Transform br(xor(x, y)) -> br(x != y)
11393   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11394   if (N.getOpcode() == ISD::XOR) {
11395     SDNode *TheXor = N.getNode();
11396 
11397     // Avoid missing important xor optimizations.
11398     while (SDValue Tmp = visitXOR(TheXor)) {
11399       // We don't have a XOR anymore, bail.
11400       if (Tmp.getOpcode() != ISD::XOR)
11401         return Tmp;
11402 
11403       TheXor = Tmp.getNode();
11404     }
11405 
11406     SDValue Op0 = TheXor->getOperand(0);
11407     SDValue Op1 = TheXor->getOperand(1);
11408 
11409     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11410       bool Equal = false;
11411       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11412           Op0.getOpcode() == ISD::XOR) {
11413         TheXor = Op0.getNode();
11414         Equal = true;
11415       }
11416 
11417       EVT SetCCVT = N.getValueType();
11418       if (LegalTypes)
11419         SetCCVT = getSetCCResultType(SetCCVT);
11420       // Replace the uses of XOR with SETCC
11421       return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1,
11422                           Equal ? ISD::SETEQ : ISD::SETNE);
11423     }
11424   }
11425 
11426   return SDValue();
11427 }
11428 
11429 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11430 //
11431 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11432   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11433   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11434 
11435   // If N is a constant we could fold this into a fallthrough or unconditional
11436   // branch. However that doesn't happen very often in normal code, because
11437   // Instcombine/SimplifyCFG should have handled the available opportunities.
11438   // If we did this folding here, it would be necessary to update the
11439   // MachineBasicBlock CFG, which is awkward.
11440 
11441   // Use SimplifySetCC to simplify SETCC's.
11442   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11443                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11444                                false);
11445   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11446 
11447   // fold to a simpler setcc
11448   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11449     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11450                        N->getOperand(0), Simp.getOperand(2),
11451                        Simp.getOperand(0), Simp.getOperand(1),
11452                        N->getOperand(4));
11453 
11454   return SDValue();
11455 }
11456 
11457 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11458 /// and that N may be folded in the load / store addressing mode.
11459 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11460                                     SelectionDAG &DAG,
11461                                     const TargetLowering &TLI) {
11462   EVT VT;
11463   unsigned AS;
11464 
11465   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11466     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11467       return false;
11468     VT = LD->getMemoryVT();
11469     AS = LD->getAddressSpace();
11470   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11471     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11472       return false;
11473     VT = ST->getMemoryVT();
11474     AS = ST->getAddressSpace();
11475   } else
11476     return false;
11477 
11478   TargetLowering::AddrMode AM;
11479   if (N->getOpcode() == ISD::ADD) {
11480     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11481     if (Offset)
11482       // [reg +/- imm]
11483       AM.BaseOffs = Offset->getSExtValue();
11484     else
11485       // [reg +/- reg]
11486       AM.Scale = 1;
11487   } else if (N->getOpcode() == ISD::SUB) {
11488     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11489     if (Offset)
11490       // [reg +/- imm]
11491       AM.BaseOffs = -Offset->getSExtValue();
11492     else
11493       // [reg +/- reg]
11494       AM.Scale = 1;
11495   } else
11496     return false;
11497 
11498   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11499                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11500 }
11501 
11502 /// Try turning a load/store into a pre-indexed load/store when the base
11503 /// pointer is an add or subtract and it has other uses besides the load/store.
11504 /// After the transformation, the new indexed load/store has effectively folded
11505 /// the add/subtract in and all of its other uses are redirected to the
11506 /// new load/store.
11507 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11508   if (Level < AfterLegalizeDAG)
11509     return false;
11510 
11511   bool isLoad = true;
11512   SDValue Ptr;
11513   EVT VT;
11514   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11515     if (LD->isIndexed())
11516       return false;
11517     VT = LD->getMemoryVT();
11518     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11519         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11520       return false;
11521     Ptr = LD->getBasePtr();
11522   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11523     if (ST->isIndexed())
11524       return false;
11525     VT = ST->getMemoryVT();
11526     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11527         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11528       return false;
11529     Ptr = ST->getBasePtr();
11530     isLoad = false;
11531   } else {
11532     return false;
11533   }
11534 
11535   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11536   // out.  There is no reason to make this a preinc/predec.
11537   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11538       Ptr.getNode()->hasOneUse())
11539     return false;
11540 
11541   // Ask the target to do addressing mode selection.
11542   SDValue BasePtr;
11543   SDValue Offset;
11544   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11545   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11546     return false;
11547 
11548   // Backends without true r+i pre-indexed forms may need to pass a
11549   // constant base with a variable offset so that constant coercion
11550   // will work with the patterns in canonical form.
11551   bool Swapped = false;
11552   if (isa<ConstantSDNode>(BasePtr)) {
11553     std::swap(BasePtr, Offset);
11554     Swapped = true;
11555   }
11556 
11557   // Don't create a indexed load / store with zero offset.
11558   if (isNullConstant(Offset))
11559     return false;
11560 
11561   // Try turning it into a pre-indexed load / store except when:
11562   // 1) The new base ptr is a frame index.
11563   // 2) If N is a store and the new base ptr is either the same as or is a
11564   //    predecessor of the value being stored.
11565   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11566   //    that would create a cycle.
11567   // 4) All uses are load / store ops that use it as old base ptr.
11568 
11569   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11570   // (plus the implicit offset) to a register to preinc anyway.
11571   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11572     return false;
11573 
11574   // Check #2.
11575   if (!isLoad) {
11576     SDValue Val = cast<StoreSDNode>(N)->getValue();
11577     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11578       return false;
11579   }
11580 
11581   // Caches for hasPredecessorHelper.
11582   SmallPtrSet<const SDNode *, 32> Visited;
11583   SmallVector<const SDNode *, 16> Worklist;
11584   Worklist.push_back(N);
11585 
11586   // If the offset is a constant, there may be other adds of constants that
11587   // can be folded with this one. We should do this to avoid having to keep
11588   // a copy of the original base pointer.
11589   SmallVector<SDNode *, 16> OtherUses;
11590   if (isa<ConstantSDNode>(Offset))
11591     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11592                               UE = BasePtr.getNode()->use_end();
11593          UI != UE; ++UI) {
11594       SDUse &Use = UI.getUse();
11595       // Skip the use that is Ptr and uses of other results from BasePtr's
11596       // node (important for nodes that return multiple results).
11597       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11598         continue;
11599 
11600       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11601         continue;
11602 
11603       if (Use.getUser()->getOpcode() != ISD::ADD &&
11604           Use.getUser()->getOpcode() != ISD::SUB) {
11605         OtherUses.clear();
11606         break;
11607       }
11608 
11609       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11610       if (!isa<ConstantSDNode>(Op1)) {
11611         OtherUses.clear();
11612         break;
11613       }
11614 
11615       // FIXME: In some cases, we can be smarter about this.
11616       if (Op1.getValueType() != Offset.getValueType()) {
11617         OtherUses.clear();
11618         break;
11619       }
11620 
11621       OtherUses.push_back(Use.getUser());
11622     }
11623 
11624   if (Swapped)
11625     std::swap(BasePtr, Offset);
11626 
11627   // Now check for #3 and #4.
11628   bool RealUse = false;
11629 
11630   for (SDNode *Use : Ptr.getNode()->uses()) {
11631     if (Use == N)
11632       continue;
11633     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11634       return false;
11635 
11636     // If Ptr may be folded in addressing mode of other use, then it's
11637     // not profitable to do this transformation.
11638     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11639       RealUse = true;
11640   }
11641 
11642   if (!RealUse)
11643     return false;
11644 
11645   SDValue Result;
11646   if (isLoad)
11647     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11648                                 BasePtr, Offset, AM);
11649   else
11650     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11651                                  BasePtr, Offset, AM);
11652   ++PreIndexedNodes;
11653   ++NodesCombined;
11654   DEBUG(dbgs() << "\nReplacing.4 ";
11655         N->dump(&DAG);
11656         dbgs() << "\nWith: ";
11657         Result.getNode()->dump(&DAG);
11658         dbgs() << '\n');
11659   WorklistRemover DeadNodes(*this);
11660   if (isLoad) {
11661     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11662     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11663   } else {
11664     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11665   }
11666 
11667   // Finally, since the node is now dead, remove it from the graph.
11668   deleteAndRecombine(N);
11669 
11670   if (Swapped)
11671     std::swap(BasePtr, Offset);
11672 
11673   // Replace other uses of BasePtr that can be updated to use Ptr
11674   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11675     unsigned OffsetIdx = 1;
11676     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11677       OffsetIdx = 0;
11678     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11679            BasePtr.getNode() && "Expected BasePtr operand");
11680 
11681     // We need to replace ptr0 in the following expression:
11682     //   x0 * offset0 + y0 * ptr0 = t0
11683     // knowing that
11684     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11685     //
11686     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11687     // indexed load/store and the expression that needs to be re-written.
11688     //
11689     // Therefore, we have:
11690     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11691 
11692     ConstantSDNode *CN =
11693       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11694     int X0, X1, Y0, Y1;
11695     const APInt &Offset0 = CN->getAPIntValue();
11696     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11697 
11698     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11699     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11700     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11701     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11702 
11703     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11704 
11705     APInt CNV = Offset0;
11706     if (X0 < 0) CNV = -CNV;
11707     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11708     else CNV = CNV - Offset1;
11709 
11710     SDLoc DL(OtherUses[i]);
11711 
11712     // We can now generate the new expression.
11713     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11714     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11715 
11716     SDValue NewUse = DAG.getNode(Opcode,
11717                                  DL,
11718                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11719     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11720     deleteAndRecombine(OtherUses[i]);
11721   }
11722 
11723   // Replace the uses of Ptr with uses of the updated base value.
11724   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11725   deleteAndRecombine(Ptr.getNode());
11726   AddToWorklist(Result.getNode());
11727 
11728   return true;
11729 }
11730 
11731 /// Try to combine a load/store with a add/sub of the base pointer node into a
11732 /// post-indexed load/store. The transformation folded the add/subtract into the
11733 /// new indexed load/store effectively and all of its uses are redirected to the
11734 /// new load/store.
11735 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11736   if (Level < AfterLegalizeDAG)
11737     return false;
11738 
11739   bool isLoad = true;
11740   SDValue Ptr;
11741   EVT VT;
11742   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11743     if (LD->isIndexed())
11744       return false;
11745     VT = LD->getMemoryVT();
11746     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11747         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11748       return false;
11749     Ptr = LD->getBasePtr();
11750   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11751     if (ST->isIndexed())
11752       return false;
11753     VT = ST->getMemoryVT();
11754     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11755         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11756       return false;
11757     Ptr = ST->getBasePtr();
11758     isLoad = false;
11759   } else {
11760     return false;
11761   }
11762 
11763   if (Ptr.getNode()->hasOneUse())
11764     return false;
11765 
11766   for (SDNode *Op : Ptr.getNode()->uses()) {
11767     if (Op == N ||
11768         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11769       continue;
11770 
11771     SDValue BasePtr;
11772     SDValue Offset;
11773     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11774     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11775       // Don't create a indexed load / store with zero offset.
11776       if (isNullConstant(Offset))
11777         continue;
11778 
11779       // Try turning it into a post-indexed load / store except when
11780       // 1) All uses are load / store ops that use it as base ptr (and
11781       //    it may be folded as addressing mmode).
11782       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11783       //    nor a successor of N. Otherwise, if Op is folded that would
11784       //    create a cycle.
11785 
11786       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11787         continue;
11788 
11789       // Check for #1.
11790       bool TryNext = false;
11791       for (SDNode *Use : BasePtr.getNode()->uses()) {
11792         if (Use == Ptr.getNode())
11793           continue;
11794 
11795         // If all the uses are load / store addresses, then don't do the
11796         // transformation.
11797         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11798           bool RealUse = false;
11799           for (SDNode *UseUse : Use->uses()) {
11800             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11801               RealUse = true;
11802           }
11803 
11804           if (!RealUse) {
11805             TryNext = true;
11806             break;
11807           }
11808         }
11809       }
11810 
11811       if (TryNext)
11812         continue;
11813 
11814       // Check for #2
11815       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11816         SDValue Result = isLoad
11817           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11818                                BasePtr, Offset, AM)
11819           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11820                                 BasePtr, Offset, AM);
11821         ++PostIndexedNodes;
11822         ++NodesCombined;
11823         DEBUG(dbgs() << "\nReplacing.5 ";
11824               N->dump(&DAG);
11825               dbgs() << "\nWith: ";
11826               Result.getNode()->dump(&DAG);
11827               dbgs() << '\n');
11828         WorklistRemover DeadNodes(*this);
11829         if (isLoad) {
11830           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11831           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11832         } else {
11833           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11834         }
11835 
11836         // Finally, since the node is now dead, remove it from the graph.
11837         deleteAndRecombine(N);
11838 
11839         // Replace the uses of Use with uses of the updated base value.
11840         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11841                                       Result.getValue(isLoad ? 1 : 0));
11842         deleteAndRecombine(Op);
11843         return true;
11844       }
11845     }
11846   }
11847 
11848   return false;
11849 }
11850 
11851 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11852 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11853   ISD::MemIndexedMode AM = LD->getAddressingMode();
11854   assert(AM != ISD::UNINDEXED);
11855   SDValue BP = LD->getOperand(1);
11856   SDValue Inc = LD->getOperand(2);
11857 
11858   // Some backends use TargetConstants for load offsets, but don't expect
11859   // TargetConstants in general ADD nodes. We can convert these constants into
11860   // regular Constants (if the constant is not opaque).
11861   assert((Inc.getOpcode() != ISD::TargetConstant ||
11862           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11863          "Cannot split out indexing using opaque target constants");
11864   if (Inc.getOpcode() == ISD::TargetConstant) {
11865     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11866     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11867                           ConstInc->getValueType(0));
11868   }
11869 
11870   unsigned Opc =
11871       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11872   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11873 }
11874 
11875 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11876   LoadSDNode *LD  = cast<LoadSDNode>(N);
11877   SDValue Chain = LD->getChain();
11878   SDValue Ptr   = LD->getBasePtr();
11879 
11880   // If load is not volatile and there are no uses of the loaded value (and
11881   // the updated indexed value in case of indexed loads), change uses of the
11882   // chain value into uses of the chain input (i.e. delete the dead load).
11883   if (!LD->isVolatile()) {
11884     if (N->getValueType(1) == MVT::Other) {
11885       // Unindexed loads.
11886       if (!N->hasAnyUseOfValue(0)) {
11887         // It's not safe to use the two value CombineTo variant here. e.g.
11888         // v1, chain2 = load chain1, loc
11889         // v2, chain3 = load chain2, loc
11890         // v3         = add v2, c
11891         // Now we replace use of chain2 with chain1.  This makes the second load
11892         // isomorphic to the one we are deleting, and thus makes this load live.
11893         DEBUG(dbgs() << "\nReplacing.6 ";
11894               N->dump(&DAG);
11895               dbgs() << "\nWith chain: ";
11896               Chain.getNode()->dump(&DAG);
11897               dbgs() << "\n");
11898         WorklistRemover DeadNodes(*this);
11899         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11900         AddUsersToWorklist(Chain.getNode());
11901         if (N->use_empty())
11902           deleteAndRecombine(N);
11903 
11904         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11905       }
11906     } else {
11907       // Indexed loads.
11908       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11909 
11910       // If this load has an opaque TargetConstant offset, then we cannot split
11911       // the indexing into an add/sub directly (that TargetConstant may not be
11912       // valid for a different type of node, and we cannot convert an opaque
11913       // target constant into a regular constant).
11914       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11915                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11916 
11917       if (!N->hasAnyUseOfValue(0) &&
11918           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11919         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11920         SDValue Index;
11921         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11922           Index = SplitIndexingFromLoad(LD);
11923           // Try to fold the base pointer arithmetic into subsequent loads and
11924           // stores.
11925           AddUsersToWorklist(N);
11926         } else
11927           Index = DAG.getUNDEF(N->getValueType(1));
11928         DEBUG(dbgs() << "\nReplacing.7 ";
11929               N->dump(&DAG);
11930               dbgs() << "\nWith: ";
11931               Undef.getNode()->dump(&DAG);
11932               dbgs() << " and 2 other values\n");
11933         WorklistRemover DeadNodes(*this);
11934         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11935         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11936         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11937         deleteAndRecombine(N);
11938         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11939       }
11940     }
11941   }
11942 
11943   // If this load is directly stored, replace the load value with the stored
11944   // value.
11945   // TODO: Handle store large -> read small portion.
11946   // TODO: Handle TRUNCSTORE/LOADEXT
11947   if (OptLevel != CodeGenOpt::None &&
11948       ISD::isNormalLoad(N) && !LD->isVolatile()) {
11949     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11950       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11951       if (PrevST->getBasePtr() == Ptr &&
11952           PrevST->getValue().getValueType() == N->getValueType(0))
11953         return CombineTo(N, PrevST->getOperand(1), Chain);
11954     }
11955   }
11956 
11957   // Try to infer better alignment information than the load already has.
11958   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11959     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11960       if (Align > LD->getMemOperand()->getBaseAlignment()) {
11961         SDValue NewLoad = DAG.getExtLoad(
11962             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11963             LD->getPointerInfo(), LD->getMemoryVT(), Align,
11964             LD->getMemOperand()->getFlags(), LD->getAAInfo());
11965         if (NewLoad.getNode() != N)
11966           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11967       }
11968     }
11969   }
11970 
11971   if (LD->isUnindexed()) {
11972     // Walk up chain skipping non-aliasing memory nodes.
11973     SDValue BetterChain = FindBetterChain(N, Chain);
11974 
11975     // If there is a better chain.
11976     if (Chain != BetterChain) {
11977       SDValue ReplLoad;
11978 
11979       // Replace the chain to void dependency.
11980       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11981         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11982                                BetterChain, Ptr, LD->getMemOperand());
11983       } else {
11984         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11985                                   LD->getValueType(0),
11986                                   BetterChain, Ptr, LD->getMemoryVT(),
11987                                   LD->getMemOperand());
11988       }
11989 
11990       // Create token factor to keep old chain connected.
11991       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11992                                   MVT::Other, Chain, ReplLoad.getValue(1));
11993 
11994       // Replace uses with load result and token factor
11995       return CombineTo(N, ReplLoad.getValue(0), Token);
11996     }
11997   }
11998 
11999   // Try transforming N to an indexed load.
12000   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12001     return SDValue(N, 0);
12002 
12003   // Try to slice up N to more direct loads if the slices are mapped to
12004   // different register banks or pairing can take place.
12005   if (SliceUpLoad(N))
12006     return SDValue(N, 0);
12007 
12008   return SDValue();
12009 }
12010 
12011 namespace {
12012 
12013 /// \brief Helper structure used to slice a load in smaller loads.
12014 /// Basically a slice is obtained from the following sequence:
12015 /// Origin = load Ty1, Base
12016 /// Shift = srl Ty1 Origin, CstTy Amount
12017 /// Inst = trunc Shift to Ty2
12018 ///
12019 /// Then, it will be rewritten into:
12020 /// Slice = load SliceTy, Base + SliceOffset
12021 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
12022 ///
12023 /// SliceTy is deduced from the number of bits that are actually used to
12024 /// build Inst.
12025 struct LoadedSlice {
12026   /// \brief Helper structure used to compute the cost of a slice.
12027   struct Cost {
12028     /// Are we optimizing for code size.
12029     bool ForCodeSize;
12030 
12031     /// Various cost.
12032     unsigned Loads = 0;
12033     unsigned Truncates = 0;
12034     unsigned CrossRegisterBanksCopies = 0;
12035     unsigned ZExts = 0;
12036     unsigned Shift = 0;
12037 
12038     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
12039 
12040     /// \brief Get the cost of one isolated slice.
12041     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
12042         : ForCodeSize(ForCodeSize), Loads(1) {
12043       EVT TruncType = LS.Inst->getValueType(0);
12044       EVT LoadedType = LS.getLoadedType();
12045       if (TruncType != LoadedType &&
12046           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
12047         ZExts = 1;
12048     }
12049 
12050     /// \brief Account for slicing gain in the current cost.
12051     /// Slicing provide a few gains like removing a shift or a
12052     /// truncate. This method allows to grow the cost of the original
12053     /// load with the gain from this slice.
12054     void addSliceGain(const LoadedSlice &LS) {
12055       // Each slice saves a truncate.
12056       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
12057       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
12058                               LS.Inst->getValueType(0)))
12059         ++Truncates;
12060       // If there is a shift amount, this slice gets rid of it.
12061       if (LS.Shift)
12062         ++Shift;
12063       // If this slice can merge a cross register bank copy, account for it.
12064       if (LS.canMergeExpensiveCrossRegisterBankCopy())
12065         ++CrossRegisterBanksCopies;
12066     }
12067 
12068     Cost &operator+=(const Cost &RHS) {
12069       Loads += RHS.Loads;
12070       Truncates += RHS.Truncates;
12071       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
12072       ZExts += RHS.ZExts;
12073       Shift += RHS.Shift;
12074       return *this;
12075     }
12076 
12077     bool operator==(const Cost &RHS) const {
12078       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
12079              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
12080              ZExts == RHS.ZExts && Shift == RHS.Shift;
12081     }
12082 
12083     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
12084 
12085     bool operator<(const Cost &RHS) const {
12086       // Assume cross register banks copies are as expensive as loads.
12087       // FIXME: Do we want some more target hooks?
12088       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
12089       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
12090       // Unless we are optimizing for code size, consider the
12091       // expensive operation first.
12092       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
12093         return ExpensiveOpsLHS < ExpensiveOpsRHS;
12094       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
12095              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
12096     }
12097 
12098     bool operator>(const Cost &RHS) const { return RHS < *this; }
12099 
12100     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
12101 
12102     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
12103   };
12104 
12105   // The last instruction that represent the slice. This should be a
12106   // truncate instruction.
12107   SDNode *Inst;
12108 
12109   // The original load instruction.
12110   LoadSDNode *Origin;
12111 
12112   // The right shift amount in bits from the original load.
12113   unsigned Shift;
12114 
12115   // The DAG from which Origin came from.
12116   // This is used to get some contextual information about legal types, etc.
12117   SelectionDAG *DAG;
12118 
12119   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
12120               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
12121       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
12122 
12123   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
12124   /// \return Result is \p BitWidth and has used bits set to 1 and
12125   ///         not used bits set to 0.
12126   APInt getUsedBits() const {
12127     // Reproduce the trunc(lshr) sequence:
12128     // - Start from the truncated value.
12129     // - Zero extend to the desired bit width.
12130     // - Shift left.
12131     assert(Origin && "No original load to compare against.");
12132     unsigned BitWidth = Origin->getValueSizeInBits(0);
12133     assert(Inst && "This slice is not bound to an instruction");
12134     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
12135            "Extracted slice is bigger than the whole type!");
12136     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
12137     UsedBits.setAllBits();
12138     UsedBits = UsedBits.zext(BitWidth);
12139     UsedBits <<= Shift;
12140     return UsedBits;
12141   }
12142 
12143   /// \brief Get the size of the slice to be loaded in bytes.
12144   unsigned getLoadedSize() const {
12145     unsigned SliceSize = getUsedBits().countPopulation();
12146     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
12147     return SliceSize / 8;
12148   }
12149 
12150   /// \brief Get the type that will be loaded for this slice.
12151   /// Note: This may not be the final type for the slice.
12152   EVT getLoadedType() const {
12153     assert(DAG && "Missing context");
12154     LLVMContext &Ctxt = *DAG->getContext();
12155     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
12156   }
12157 
12158   /// \brief Get the alignment of the load used for this slice.
12159   unsigned getAlignment() const {
12160     unsigned Alignment = Origin->getAlignment();
12161     unsigned Offset = getOffsetFromBase();
12162     if (Offset != 0)
12163       Alignment = MinAlign(Alignment, Alignment + Offset);
12164     return Alignment;
12165   }
12166 
12167   /// \brief Check if this slice can be rewritten with legal operations.
12168   bool isLegal() const {
12169     // An invalid slice is not legal.
12170     if (!Origin || !Inst || !DAG)
12171       return false;
12172 
12173     // Offsets are for indexed load only, we do not handle that.
12174     if (!Origin->getOffset().isUndef())
12175       return false;
12176 
12177     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12178 
12179     // Check that the type is legal.
12180     EVT SliceType = getLoadedType();
12181     if (!TLI.isTypeLegal(SliceType))
12182       return false;
12183 
12184     // Check that the load is legal for this type.
12185     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
12186       return false;
12187 
12188     // Check that the offset can be computed.
12189     // 1. Check its type.
12190     EVT PtrType = Origin->getBasePtr().getValueType();
12191     if (PtrType == MVT::Untyped || PtrType.isExtended())
12192       return false;
12193 
12194     // 2. Check that it fits in the immediate.
12195     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12196       return false;
12197 
12198     // 3. Check that the computation is legal.
12199     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12200       return false;
12201 
12202     // Check that the zext is legal if it needs one.
12203     EVT TruncateType = Inst->getValueType(0);
12204     if (TruncateType != SliceType &&
12205         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12206       return false;
12207 
12208     return true;
12209   }
12210 
12211   /// \brief Get the offset in bytes of this slice in the original chunk of
12212   /// bits.
12213   /// \pre DAG != nullptr.
12214   uint64_t getOffsetFromBase() const {
12215     assert(DAG && "Missing context.");
12216     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12217     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12218     uint64_t Offset = Shift / 8;
12219     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12220     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12221            "The size of the original loaded type is not a multiple of a"
12222            " byte.");
12223     // If Offset is bigger than TySizeInBytes, it means we are loading all
12224     // zeros. This should have been optimized before in the process.
12225     assert(TySizeInBytes > Offset &&
12226            "Invalid shift amount for given loaded size");
12227     if (IsBigEndian)
12228       Offset = TySizeInBytes - Offset - getLoadedSize();
12229     return Offset;
12230   }
12231 
12232   /// \brief Generate the sequence of instructions to load the slice
12233   /// represented by this object and redirect the uses of this slice to
12234   /// this new sequence of instructions.
12235   /// \pre this->Inst && this->Origin are valid Instructions and this
12236   /// object passed the legal check: LoadedSlice::isLegal returned true.
12237   /// \return The last instruction of the sequence used to load the slice.
12238   SDValue loadSlice() const {
12239     assert(Inst && Origin && "Unable to replace a non-existing slice.");
12240     const SDValue &OldBaseAddr = Origin->getBasePtr();
12241     SDValue BaseAddr = OldBaseAddr;
12242     // Get the offset in that chunk of bytes w.r.t. the endianness.
12243     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12244     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12245     if (Offset) {
12246       // BaseAddr = BaseAddr + Offset.
12247       EVT ArithType = BaseAddr.getValueType();
12248       SDLoc DL(Origin);
12249       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12250                               DAG->getConstant(Offset, DL, ArithType));
12251     }
12252 
12253     // Create the type of the loaded slice according to its size.
12254     EVT SliceType = getLoadedType();
12255 
12256     // Create the load for the slice.
12257     SDValue LastInst =
12258         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12259                      Origin->getPointerInfo().getWithOffset(Offset),
12260                      getAlignment(), Origin->getMemOperand()->getFlags());
12261     // If the final type is not the same as the loaded type, this means that
12262     // we have to pad with zero. Create a zero extend for that.
12263     EVT FinalType = Inst->getValueType(0);
12264     if (SliceType != FinalType)
12265       LastInst =
12266           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12267     return LastInst;
12268   }
12269 
12270   /// \brief Check if this slice can be merged with an expensive cross register
12271   /// bank copy. E.g.,
12272   /// i = load i32
12273   /// f = bitcast i32 i to float
12274   bool canMergeExpensiveCrossRegisterBankCopy() const {
12275     if (!Inst || !Inst->hasOneUse())
12276       return false;
12277     SDNode *Use = *Inst->use_begin();
12278     if (Use->getOpcode() != ISD::BITCAST)
12279       return false;
12280     assert(DAG && "Missing context");
12281     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12282     EVT ResVT = Use->getValueType(0);
12283     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12284     const TargetRegisterClass *ArgRC =
12285         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12286     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12287       return false;
12288 
12289     // At this point, we know that we perform a cross-register-bank copy.
12290     // Check if it is expensive.
12291     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12292     // Assume bitcasts are cheap, unless both register classes do not
12293     // explicitly share a common sub class.
12294     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12295       return false;
12296 
12297     // Check if it will be merged with the load.
12298     // 1. Check the alignment constraint.
12299     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12300         ResVT.getTypeForEVT(*DAG->getContext()));
12301 
12302     if (RequiredAlignment > getAlignment())
12303       return false;
12304 
12305     // 2. Check that the load is a legal operation for that type.
12306     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12307       return false;
12308 
12309     // 3. Check that we do not have a zext in the way.
12310     if (Inst->getValueType(0) != getLoadedType())
12311       return false;
12312 
12313     return true;
12314   }
12315 };
12316 
12317 } // end anonymous namespace
12318 
12319 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
12320 /// \p UsedBits looks like 0..0 1..1 0..0.
12321 static bool areUsedBitsDense(const APInt &UsedBits) {
12322   // If all the bits are one, this is dense!
12323   if (UsedBits.isAllOnesValue())
12324     return true;
12325 
12326   // Get rid of the unused bits on the right.
12327   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12328   // Get rid of the unused bits on the left.
12329   if (NarrowedUsedBits.countLeadingZeros())
12330     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12331   // Check that the chunk of bits is completely used.
12332   return NarrowedUsedBits.isAllOnesValue();
12333 }
12334 
12335 /// \brief Check whether or not \p First and \p Second are next to each other
12336 /// in memory. This means that there is no hole between the bits loaded
12337 /// by \p First and the bits loaded by \p Second.
12338 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12339                                      const LoadedSlice &Second) {
12340   assert(First.Origin == Second.Origin && First.Origin &&
12341          "Unable to match different memory origins.");
12342   APInt UsedBits = First.getUsedBits();
12343   assert((UsedBits & Second.getUsedBits()) == 0 &&
12344          "Slices are not supposed to overlap.");
12345   UsedBits |= Second.getUsedBits();
12346   return areUsedBitsDense(UsedBits);
12347 }
12348 
12349 /// \brief Adjust the \p GlobalLSCost according to the target
12350 /// paring capabilities and the layout of the slices.
12351 /// \pre \p GlobalLSCost should account for at least as many loads as
12352 /// there is in the slices in \p LoadedSlices.
12353 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12354                                  LoadedSlice::Cost &GlobalLSCost) {
12355   unsigned NumberOfSlices = LoadedSlices.size();
12356   // If there is less than 2 elements, no pairing is possible.
12357   if (NumberOfSlices < 2)
12358     return;
12359 
12360   // Sort the slices so that elements that are likely to be next to each
12361   // other in memory are next to each other in the list.
12362   llvm::sort(LoadedSlices.begin(), LoadedSlices.end(),
12363              [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12364     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12365     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12366   });
12367   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12368   // First (resp. Second) is the first (resp. Second) potentially candidate
12369   // to be placed in a paired load.
12370   const LoadedSlice *First = nullptr;
12371   const LoadedSlice *Second = nullptr;
12372   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12373                 // Set the beginning of the pair.
12374                                                            First = Second) {
12375     Second = &LoadedSlices[CurrSlice];
12376 
12377     // If First is NULL, it means we start a new pair.
12378     // Get to the next slice.
12379     if (!First)
12380       continue;
12381 
12382     EVT LoadedType = First->getLoadedType();
12383 
12384     // If the types of the slices are different, we cannot pair them.
12385     if (LoadedType != Second->getLoadedType())
12386       continue;
12387 
12388     // Check if the target supplies paired loads for this type.
12389     unsigned RequiredAlignment = 0;
12390     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12391       // move to the next pair, this type is hopeless.
12392       Second = nullptr;
12393       continue;
12394     }
12395     // Check if we meet the alignment requirement.
12396     if (RequiredAlignment > First->getAlignment())
12397       continue;
12398 
12399     // Check that both loads are next to each other in memory.
12400     if (!areSlicesNextToEachOther(*First, *Second))
12401       continue;
12402 
12403     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12404     --GlobalLSCost.Loads;
12405     // Move to the next pair.
12406     Second = nullptr;
12407   }
12408 }
12409 
12410 /// \brief Check the profitability of all involved LoadedSlice.
12411 /// Currently, it is considered profitable if there is exactly two
12412 /// involved slices (1) which are (2) next to each other in memory, and
12413 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12414 ///
12415 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12416 /// the elements themselves.
12417 ///
12418 /// FIXME: When the cost model will be mature enough, we can relax
12419 /// constraints (1) and (2).
12420 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12421                                 const APInt &UsedBits, bool ForCodeSize) {
12422   unsigned NumberOfSlices = LoadedSlices.size();
12423   if (StressLoadSlicing)
12424     return NumberOfSlices > 1;
12425 
12426   // Check (1).
12427   if (NumberOfSlices != 2)
12428     return false;
12429 
12430   // Check (2).
12431   if (!areUsedBitsDense(UsedBits))
12432     return false;
12433 
12434   // Check (3).
12435   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12436   // The original code has one big load.
12437   OrigCost.Loads = 1;
12438   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12439     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12440     // Accumulate the cost of all the slices.
12441     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12442     GlobalSlicingCost += SliceCost;
12443 
12444     // Account as cost in the original configuration the gain obtained
12445     // with the current slices.
12446     OrigCost.addSliceGain(LS);
12447   }
12448 
12449   // If the target supports paired load, adjust the cost accordingly.
12450   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12451   return OrigCost > GlobalSlicingCost;
12452 }
12453 
12454 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
12455 /// operations, split it in the various pieces being extracted.
12456 ///
12457 /// This sort of thing is introduced by SROA.
12458 /// This slicing takes care not to insert overlapping loads.
12459 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12460 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12461   if (Level < AfterLegalizeDAG)
12462     return false;
12463 
12464   LoadSDNode *LD = cast<LoadSDNode>(N);
12465   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12466       !LD->getValueType(0).isInteger())
12467     return false;
12468 
12469   // Keep track of already used bits to detect overlapping values.
12470   // In that case, we will just abort the transformation.
12471   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12472 
12473   SmallVector<LoadedSlice, 4> LoadedSlices;
12474 
12475   // Check if this load is used as several smaller chunks of bits.
12476   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12477   // of computation for each trunc.
12478   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12479        UI != UIEnd; ++UI) {
12480     // Skip the uses of the chain.
12481     if (UI.getUse().getResNo() != 0)
12482       continue;
12483 
12484     SDNode *User = *UI;
12485     unsigned Shift = 0;
12486 
12487     // Check if this is a trunc(lshr).
12488     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12489         isa<ConstantSDNode>(User->getOperand(1))) {
12490       Shift = User->getConstantOperandVal(1);
12491       User = *User->use_begin();
12492     }
12493 
12494     // At this point, User is a Truncate, iff we encountered, trunc or
12495     // trunc(lshr).
12496     if (User->getOpcode() != ISD::TRUNCATE)
12497       return false;
12498 
12499     // The width of the type must be a power of 2 and greater than 8-bits.
12500     // Otherwise the load cannot be represented in LLVM IR.
12501     // Moreover, if we shifted with a non-8-bits multiple, the slice
12502     // will be across several bytes. We do not support that.
12503     unsigned Width = User->getValueSizeInBits(0);
12504     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12505       return false;
12506 
12507     // Build the slice for this chain of computations.
12508     LoadedSlice LS(User, LD, Shift, &DAG);
12509     APInt CurrentUsedBits = LS.getUsedBits();
12510 
12511     // Check if this slice overlaps with another.
12512     if ((CurrentUsedBits & UsedBits) != 0)
12513       return false;
12514     // Update the bits used globally.
12515     UsedBits |= CurrentUsedBits;
12516 
12517     // Check if the new slice would be legal.
12518     if (!LS.isLegal())
12519       return false;
12520 
12521     // Record the slice.
12522     LoadedSlices.push_back(LS);
12523   }
12524 
12525   // Abort slicing if it does not seem to be profitable.
12526   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12527     return false;
12528 
12529   ++SlicedLoads;
12530 
12531   // Rewrite each chain to use an independent load.
12532   // By construction, each chain can be represented by a unique load.
12533 
12534   // Prepare the argument for the new token factor for all the slices.
12535   SmallVector<SDValue, 8> ArgChains;
12536   for (SmallVectorImpl<LoadedSlice>::const_iterator
12537            LSIt = LoadedSlices.begin(),
12538            LSItEnd = LoadedSlices.end();
12539        LSIt != LSItEnd; ++LSIt) {
12540     SDValue SliceInst = LSIt->loadSlice();
12541     CombineTo(LSIt->Inst, SliceInst, true);
12542     if (SliceInst.getOpcode() != ISD::LOAD)
12543       SliceInst = SliceInst.getOperand(0);
12544     assert(SliceInst->getOpcode() == ISD::LOAD &&
12545            "It takes more than a zext to get to the loaded slice!!");
12546     ArgChains.push_back(SliceInst.getValue(1));
12547   }
12548 
12549   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12550                               ArgChains);
12551   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12552   AddToWorklist(Chain.getNode());
12553   return true;
12554 }
12555 
12556 /// Check to see if V is (and load (ptr), imm), where the load is having
12557 /// specific bytes cleared out.  If so, return the byte size being masked out
12558 /// and the shift amount.
12559 static std::pair<unsigned, unsigned>
12560 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12561   std::pair<unsigned, unsigned> Result(0, 0);
12562 
12563   // Check for the structure we're looking for.
12564   if (V->getOpcode() != ISD::AND ||
12565       !isa<ConstantSDNode>(V->getOperand(1)) ||
12566       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12567     return Result;
12568 
12569   // Check the chain and pointer.
12570   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12571   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12572 
12573   // The store should be chained directly to the load or be an operand of a
12574   // tokenfactor.
12575   if (LD == Chain.getNode())
12576     ; // ok.
12577   else if (Chain->getOpcode() != ISD::TokenFactor)
12578     return Result; // Fail.
12579   else {
12580     bool isOk = false;
12581     for (const SDValue &ChainOp : Chain->op_values())
12582       if (ChainOp.getNode() == LD) {
12583         isOk = true;
12584         break;
12585       }
12586     if (!isOk) return Result;
12587   }
12588 
12589   // This only handles simple types.
12590   if (V.getValueType() != MVT::i16 &&
12591       V.getValueType() != MVT::i32 &&
12592       V.getValueType() != MVT::i64)
12593     return Result;
12594 
12595   // Check the constant mask.  Invert it so that the bits being masked out are
12596   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12597   // follow the sign bit for uniformity.
12598   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12599   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12600   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12601   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12602   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12603   if (NotMaskLZ == 64) return Result;  // All zero mask.
12604 
12605   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12606   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12607     return Result;
12608 
12609   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12610   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12611     NotMaskLZ -= 64-V.getValueSizeInBits();
12612 
12613   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12614   switch (MaskedBytes) {
12615   case 1:
12616   case 2:
12617   case 4: break;
12618   default: return Result; // All one mask, or 5-byte mask.
12619   }
12620 
12621   // Verify that the first bit starts at a multiple of mask so that the access
12622   // is aligned the same as the access width.
12623   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12624 
12625   Result.first = MaskedBytes;
12626   Result.second = NotMaskTZ/8;
12627   return Result;
12628 }
12629 
12630 /// Check to see if IVal is something that provides a value as specified by
12631 /// MaskInfo. If so, replace the specified store with a narrower store of
12632 /// truncated IVal.
12633 static SDNode *
12634 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12635                                 SDValue IVal, StoreSDNode *St,
12636                                 DAGCombiner *DC) {
12637   unsigned NumBytes = MaskInfo.first;
12638   unsigned ByteShift = MaskInfo.second;
12639   SelectionDAG &DAG = DC->getDAG();
12640 
12641   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12642   // that uses this.  If not, this is not a replacement.
12643   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12644                                   ByteShift*8, (ByteShift+NumBytes)*8);
12645   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12646 
12647   // Check that it is legal on the target to do this.  It is legal if the new
12648   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12649   // legalization.
12650   MVT VT = MVT::getIntegerVT(NumBytes*8);
12651   if (!DC->isTypeLegal(VT))
12652     return nullptr;
12653 
12654   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12655   // shifted by ByteShift and truncated down to NumBytes.
12656   if (ByteShift) {
12657     SDLoc DL(IVal);
12658     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12659                        DAG.getConstant(ByteShift*8, DL,
12660                                     DC->getShiftAmountTy(IVal.getValueType())));
12661   }
12662 
12663   // Figure out the offset for the store and the alignment of the access.
12664   unsigned StOffset;
12665   unsigned NewAlign = St->getAlignment();
12666 
12667   if (DAG.getDataLayout().isLittleEndian())
12668     StOffset = ByteShift;
12669   else
12670     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12671 
12672   SDValue Ptr = St->getBasePtr();
12673   if (StOffset) {
12674     SDLoc DL(IVal);
12675     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12676                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12677     NewAlign = MinAlign(NewAlign, StOffset);
12678   }
12679 
12680   // Truncate down to the new size.
12681   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12682 
12683   ++OpsNarrowed;
12684   return DAG
12685       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12686                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12687       .getNode();
12688 }
12689 
12690 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12691 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12692 /// narrowing the load and store if it would end up being a win for performance
12693 /// or code size.
12694 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12695   StoreSDNode *ST  = cast<StoreSDNode>(N);
12696   if (ST->isVolatile())
12697     return SDValue();
12698 
12699   SDValue Chain = ST->getChain();
12700   SDValue Value = ST->getValue();
12701   SDValue Ptr   = ST->getBasePtr();
12702   EVT VT = Value.getValueType();
12703 
12704   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12705     return SDValue();
12706 
12707   unsigned Opc = Value.getOpcode();
12708 
12709   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12710   // is a byte mask indicating a consecutive number of bytes, check to see if
12711   // Y is known to provide just those bytes.  If so, we try to replace the
12712   // load + replace + store sequence with a single (narrower) store, which makes
12713   // the load dead.
12714   if (Opc == ISD::OR) {
12715     std::pair<unsigned, unsigned> MaskedLoad;
12716     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12717     if (MaskedLoad.first)
12718       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12719                                                   Value.getOperand(1), ST,this))
12720         return SDValue(NewST, 0);
12721 
12722     // Or is commutative, so try swapping X and Y.
12723     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12724     if (MaskedLoad.first)
12725       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12726                                                   Value.getOperand(0), ST,this))
12727         return SDValue(NewST, 0);
12728   }
12729 
12730   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12731       Value.getOperand(1).getOpcode() != ISD::Constant)
12732     return SDValue();
12733 
12734   SDValue N0 = Value.getOperand(0);
12735   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12736       Chain == SDValue(N0.getNode(), 1)) {
12737     LoadSDNode *LD = cast<LoadSDNode>(N0);
12738     if (LD->getBasePtr() != Ptr ||
12739         LD->getPointerInfo().getAddrSpace() !=
12740         ST->getPointerInfo().getAddrSpace())
12741       return SDValue();
12742 
12743     // Find the type to narrow it the load / op / store to.
12744     SDValue N1 = Value.getOperand(1);
12745     unsigned BitWidth = N1.getValueSizeInBits();
12746     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12747     if (Opc == ISD::AND)
12748       Imm ^= APInt::getAllOnesValue(BitWidth);
12749     if (Imm == 0 || Imm.isAllOnesValue())
12750       return SDValue();
12751     unsigned ShAmt = Imm.countTrailingZeros();
12752     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12753     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12754     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12755     // The narrowing should be profitable, the load/store operation should be
12756     // legal (or custom) and the store size should be equal to the NewVT width.
12757     while (NewBW < BitWidth &&
12758            (NewVT.getStoreSizeInBits() != NewBW ||
12759             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12760             !TLI.isNarrowingProfitable(VT, NewVT))) {
12761       NewBW = NextPowerOf2(NewBW);
12762       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12763     }
12764     if (NewBW >= BitWidth)
12765       return SDValue();
12766 
12767     // If the lsb changed does not start at the type bitwidth boundary,
12768     // start at the previous one.
12769     if (ShAmt % NewBW)
12770       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12771     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12772                                    std::min(BitWidth, ShAmt + NewBW));
12773     if ((Imm & Mask) == Imm) {
12774       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12775       if (Opc == ISD::AND)
12776         NewImm ^= APInt::getAllOnesValue(NewBW);
12777       uint64_t PtrOff = ShAmt / 8;
12778       // For big endian targets, we need to adjust the offset to the pointer to
12779       // load the correct bytes.
12780       if (DAG.getDataLayout().isBigEndian())
12781         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12782 
12783       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12784       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12785       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12786         return SDValue();
12787 
12788       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12789                                    Ptr.getValueType(), Ptr,
12790                                    DAG.getConstant(PtrOff, SDLoc(LD),
12791                                                    Ptr.getValueType()));
12792       SDValue NewLD =
12793           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12794                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12795                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12796       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12797                                    DAG.getConstant(NewImm, SDLoc(Value),
12798                                                    NewVT));
12799       SDValue NewST =
12800           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12801                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12802 
12803       AddToWorklist(NewPtr.getNode());
12804       AddToWorklist(NewLD.getNode());
12805       AddToWorklist(NewVal.getNode());
12806       WorklistRemover DeadNodes(*this);
12807       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12808       ++OpsNarrowed;
12809       return NewST;
12810     }
12811   }
12812 
12813   return SDValue();
12814 }
12815 
12816 /// For a given floating point load / store pair, if the load value isn't used
12817 /// by any other operations, then consider transforming the pair to integer
12818 /// load / store operations if the target deems the transformation profitable.
12819 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12820   StoreSDNode *ST  = cast<StoreSDNode>(N);
12821   SDValue Chain = ST->getChain();
12822   SDValue Value = ST->getValue();
12823   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12824       Value.hasOneUse() &&
12825       Chain == SDValue(Value.getNode(), 1)) {
12826     LoadSDNode *LD = cast<LoadSDNode>(Value);
12827     EVT VT = LD->getMemoryVT();
12828     if (!VT.isFloatingPoint() ||
12829         VT != ST->getMemoryVT() ||
12830         LD->isNonTemporal() ||
12831         ST->isNonTemporal() ||
12832         LD->getPointerInfo().getAddrSpace() != 0 ||
12833         ST->getPointerInfo().getAddrSpace() != 0)
12834       return SDValue();
12835 
12836     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12837     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12838         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12839         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12840         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12841       return SDValue();
12842 
12843     unsigned LDAlign = LD->getAlignment();
12844     unsigned STAlign = ST->getAlignment();
12845     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12846     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12847     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12848       return SDValue();
12849 
12850     SDValue NewLD =
12851         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12852                     LD->getPointerInfo(), LDAlign);
12853 
12854     SDValue NewST =
12855         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12856                      ST->getPointerInfo(), STAlign);
12857 
12858     AddToWorklist(NewLD.getNode());
12859     AddToWorklist(NewST.getNode());
12860     WorklistRemover DeadNodes(*this);
12861     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12862     ++LdStFP2Int;
12863     return NewST;
12864   }
12865 
12866   return SDValue();
12867 }
12868 
12869 // This is a helper function for visitMUL to check the profitability
12870 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12871 // MulNode is the original multiply, AddNode is (add x, c1),
12872 // and ConstNode is c2.
12873 //
12874 // If the (add x, c1) has multiple uses, we could increase
12875 // the number of adds if we make this transformation.
12876 // It would only be worth doing this if we can remove a
12877 // multiply in the process. Check for that here.
12878 // To illustrate:
12879 //     (A + c1) * c3
12880 //     (A + c2) * c3
12881 // We're checking for cases where we have common "c3 * A" expressions.
12882 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12883                                               SDValue &AddNode,
12884                                               SDValue &ConstNode) {
12885   APInt Val;
12886 
12887   // If the add only has one use, this would be OK to do.
12888   if (AddNode.getNode()->hasOneUse())
12889     return true;
12890 
12891   // Walk all the users of the constant with which we're multiplying.
12892   for (SDNode *Use : ConstNode->uses()) {
12893     if (Use == MulNode) // This use is the one we're on right now. Skip it.
12894       continue;
12895 
12896     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12897       SDNode *OtherOp;
12898       SDNode *MulVar = AddNode.getOperand(0).getNode();
12899 
12900       // OtherOp is what we're multiplying against the constant.
12901       if (Use->getOperand(0) == ConstNode)
12902         OtherOp = Use->getOperand(1).getNode();
12903       else
12904         OtherOp = Use->getOperand(0).getNode();
12905 
12906       // Check to see if multiply is with the same operand of our "add".
12907       //
12908       //     ConstNode  = CONST
12909       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
12910       //     ...
12911       //     AddNode  = (A + c1)  <-- MulVar is A.
12912       //         = AddNode * ConstNode   <-- current visiting instruction.
12913       //
12914       // If we make this transformation, we will have a common
12915       // multiply (ConstNode * A) that we can save.
12916       if (OtherOp == MulVar)
12917         return true;
12918 
12919       // Now check to see if a future expansion will give us a common
12920       // multiply.
12921       //
12922       //     ConstNode  = CONST
12923       //     AddNode    = (A + c1)
12924       //     ...   = AddNode * ConstNode <-- current visiting instruction.
12925       //     ...
12926       //     OtherOp = (A + c2)
12927       //     Use     = OtherOp * ConstNode <-- visiting Use.
12928       //
12929       // If we make this transformation, we will have a common
12930       // multiply (CONST * A) after we also do the same transformation
12931       // to the "t2" instruction.
12932       if (OtherOp->getOpcode() == ISD::ADD &&
12933           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12934           OtherOp->getOperand(0).getNode() == MulVar)
12935         return true;
12936     }
12937   }
12938 
12939   // Didn't find a case where this would be profitable.
12940   return false;
12941 }
12942 
12943 static SDValue peekThroughBitcast(SDValue V) {
12944   while (V.getOpcode() == ISD::BITCAST)
12945     V = V.getOperand(0);
12946   return V;
12947 }
12948 
12949 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12950                                          unsigned NumStores) {
12951   SmallVector<SDValue, 8> Chains;
12952   SmallPtrSet<const SDNode *, 8> Visited;
12953   SDLoc StoreDL(StoreNodes[0].MemNode);
12954 
12955   for (unsigned i = 0; i < NumStores; ++i) {
12956     Visited.insert(StoreNodes[i].MemNode);
12957   }
12958 
12959   // don't include nodes that are children
12960   for (unsigned i = 0; i < NumStores; ++i) {
12961     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12962       Chains.push_back(StoreNodes[i].MemNode->getChain());
12963   }
12964 
12965   assert(Chains.size() > 0 && "Chain should have generated a chain");
12966   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12967 }
12968 
12969 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12970     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12971     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12972   // Make sure we have something to merge.
12973   if (NumStores < 2)
12974     return false;
12975 
12976   // The latest Node in the DAG.
12977   SDLoc DL(StoreNodes[0].MemNode);
12978 
12979   int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
12980   unsigned SizeInBits = NumStores * ElementSizeBits;
12981   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
12982 
12983   EVT StoreTy;
12984   if (UseVector) {
12985     unsigned Elts = NumStores * NumMemElts;
12986     // Get the type for the merged vector store.
12987     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12988   } else
12989     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12990 
12991   SDValue StoredVal;
12992   if (UseVector) {
12993     if (IsConstantSrc) {
12994       SmallVector<SDValue, 8> BuildVector;
12995       for (unsigned I = 0; I != NumStores; ++I) {
12996         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12997         SDValue Val = St->getValue();
12998         // If constant is of the wrong type, convert it now.
12999         if (MemVT != Val.getValueType()) {
13000           Val = peekThroughBitcast(Val);
13001           // Deal with constants of wrong size.
13002           if (ElementSizeBits != Val.getValueSizeInBits()) {
13003             EVT IntMemVT =
13004                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13005             if (isa<ConstantFPSDNode>(Val)) {
13006               // Not clear how to truncate FP values.
13007               return false;
13008             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
13009               Val = DAG.getConstant(C->getAPIntValue()
13010                                         .zextOrTrunc(Val.getValueSizeInBits())
13011                                         .zextOrTrunc(ElementSizeBits),
13012                                     SDLoc(C), IntMemVT);
13013           }
13014           // Make sure correctly size type is the correct type.
13015           Val = DAG.getBitcast(MemVT, Val);
13016         }
13017         BuildVector.push_back(Val);
13018       }
13019       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13020                                                : ISD::BUILD_VECTOR,
13021                               DL, StoreTy, BuildVector);
13022     } else {
13023       SmallVector<SDValue, 8> Ops;
13024       for (unsigned i = 0; i < NumStores; ++i) {
13025         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13026         SDValue Val = peekThroughBitcast(St->getValue());
13027         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
13028         // type MemVT. If the underlying value is not the correct
13029         // type, but it is an extraction of an appropriate vector we
13030         // can recast Val to be of the correct type. This may require
13031         // converting between EXTRACT_VECTOR_ELT and
13032         // EXTRACT_SUBVECTOR.
13033         if ((MemVT != Val.getValueType()) &&
13034             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13035              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
13036           SDValue Vec = Val.getOperand(0);
13037           EVT MemVTScalarTy = MemVT.getScalarType();
13038           // We may need to add a bitcast here to get types to line up.
13039           if (MemVTScalarTy != Vec.getValueType()) {
13040             unsigned Elts = Vec.getValueType().getSizeInBits() /
13041                             MemVTScalarTy.getSizeInBits();
13042             EVT NewVecTy =
13043                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
13044             Vec = DAG.getBitcast(NewVecTy, Vec);
13045           }
13046           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
13047                                         : ISD::EXTRACT_VECTOR_ELT;
13048           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
13049         }
13050         Ops.push_back(Val);
13051       }
13052 
13053       // Build the extracted vector elements back into a vector.
13054       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13055                                                : ISD::BUILD_VECTOR,
13056                               DL, StoreTy, Ops);
13057     }
13058   } else {
13059     // We should always use a vector store when merging extracted vector
13060     // elements, so this path implies a store of constants.
13061     assert(IsConstantSrc && "Merged vector elements should use vector store");
13062 
13063     APInt StoreInt(SizeInBits, 0);
13064 
13065     // Construct a single integer constant which is made of the smaller
13066     // constant inputs.
13067     bool IsLE = DAG.getDataLayout().isLittleEndian();
13068     for (unsigned i = 0; i < NumStores; ++i) {
13069       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
13070       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
13071 
13072       SDValue Val = St->getValue();
13073       Val = peekThroughBitcast(Val);
13074       StoreInt <<= ElementSizeBits;
13075       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
13076         StoreInt |= C->getAPIntValue()
13077                         .zextOrTrunc(ElementSizeBits)
13078                         .zextOrTrunc(SizeInBits);
13079       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
13080         StoreInt |= C->getValueAPF()
13081                         .bitcastToAPInt()
13082                         .zextOrTrunc(ElementSizeBits)
13083                         .zextOrTrunc(SizeInBits);
13084         // If fp truncation is necessary give up for now.
13085         if (MemVT.getSizeInBits() != ElementSizeBits)
13086           return false;
13087       } else {
13088         llvm_unreachable("Invalid constant element type");
13089       }
13090     }
13091 
13092     // Create the new Load and Store operations.
13093     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
13094   }
13095 
13096   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13097   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
13098 
13099   // make sure we use trunc store if it's necessary to be legal.
13100   SDValue NewStore;
13101   if (!UseTrunc) {
13102     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
13103                             FirstInChain->getPointerInfo(),
13104                             FirstInChain->getAlignment());
13105   } else { // Must be realized as a trunc store
13106     EVT LegalizedStoredValueTy =
13107         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
13108     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
13109     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
13110     SDValue ExtendedStoreVal =
13111         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
13112                         LegalizedStoredValueTy);
13113     NewStore = DAG.getTruncStore(
13114         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
13115         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
13116         FirstInChain->getAlignment(),
13117         FirstInChain->getMemOperand()->getFlags());
13118   }
13119 
13120   // Replace all merged stores with the new store.
13121   for (unsigned i = 0; i < NumStores; ++i)
13122     CombineTo(StoreNodes[i].MemNode, NewStore);
13123 
13124   AddToWorklist(NewChain.getNode());
13125   return true;
13126 }
13127 
13128 void DAGCombiner::getStoreMergeCandidates(
13129     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
13130   // This holds the base pointer, index, and the offset in bytes from the base
13131   // pointer.
13132   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
13133   EVT MemVT = St->getMemoryVT();
13134 
13135   SDValue Val = peekThroughBitcast(St->getValue());
13136   // We must have a base and an offset.
13137   if (!BasePtr.getBase().getNode())
13138     return;
13139 
13140   // Do not handle stores to undef base pointers.
13141   if (BasePtr.getBase().isUndef())
13142     return;
13143 
13144   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
13145   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13146                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13147   bool IsLoadSrc = isa<LoadSDNode>(Val);
13148   BaseIndexOffset LBasePtr;
13149   // Match on loadbaseptr if relevant.
13150   EVT LoadVT;
13151   if (IsLoadSrc) {
13152     auto *Ld = cast<LoadSDNode>(Val);
13153     LBasePtr = BaseIndexOffset::match(Ld, DAG);
13154     LoadVT = Ld->getMemoryVT();
13155     // Load and store should be the same type.
13156     if (MemVT != LoadVT)
13157       return;
13158   }
13159   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
13160                             int64_t &Offset) -> bool {
13161     if (Other->isVolatile() || Other->isIndexed())
13162       return false;
13163     SDValue Val = peekThroughBitcast(Other->getValue());
13164     // Allow merging constants of different types as integers.
13165     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
13166                                            : Other->getMemoryVT() != MemVT;
13167     if (IsLoadSrc) {
13168       if (NoTypeMatch)
13169         return false;
13170       // The Load's Base Ptr must also match
13171       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
13172         auto LPtr = BaseIndexOffset::match(OtherLd, DAG);
13173         if (LoadVT != OtherLd->getMemoryVT())
13174           return false;
13175         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
13176           return false;
13177       } else
13178         return false;
13179     }
13180     if (IsConstantSrc) {
13181       if (NoTypeMatch)
13182         return false;
13183       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
13184         return false;
13185     }
13186     if (IsExtractVecSrc) {
13187       // Do not merge truncated stores here.
13188       if (Other->isTruncatingStore())
13189         return false;
13190       if (!MemVT.bitsEq(Val.getValueType()))
13191         return false;
13192       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13193           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13194         return false;
13195     }
13196     Ptr = BaseIndexOffset::match(Other, DAG);
13197     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13198   };
13199 
13200   // We looking for a root node which is an ancestor to all mergable
13201   // stores. We search up through a load, to our root and then down
13202   // through all children. For instance we will find Store{1,2,3} if
13203   // St is Store1, Store2. or Store3 where the root is not a load
13204   // which always true for nonvolatile ops. TODO: Expand
13205   // the search to find all valid candidates through multiple layers of loads.
13206   //
13207   // Root
13208   // |-------|-------|
13209   // Load    Load    Store3
13210   // |       |
13211   // Store1   Store2
13212   //
13213   // FIXME: We should be able to climb and
13214   // descend TokenFactors to find candidates as well.
13215 
13216   SDNode *RootNode = (St->getChain()).getNode();
13217 
13218   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13219     RootNode = Ldn->getChain().getNode();
13220     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13221       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13222         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13223           if (I2.getOperandNo() == 0)
13224             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13225               BaseIndexOffset Ptr;
13226               int64_t PtrDiff;
13227               if (CandidateMatch(OtherST, Ptr, PtrDiff))
13228                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13229             }
13230   } else
13231     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13232       if (I.getOperandNo() == 0)
13233         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13234           BaseIndexOffset Ptr;
13235           int64_t PtrDiff;
13236           if (CandidateMatch(OtherST, Ptr, PtrDiff))
13237             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13238         }
13239 }
13240 
13241 // We need to check that merging these stores does not cause a loop in
13242 // the DAG. Any store candidate may depend on another candidate
13243 // indirectly through its operand (we already consider dependencies
13244 // through the chain). Check in parallel by searching up from
13245 // non-chain operands of candidates.
13246 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13247     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
13248   // FIXME: We should be able to truncate a full search of
13249   // predecessors by doing a BFS and keeping tabs the originating
13250   // stores from which worklist nodes come from in a similar way to
13251   // TokenFactor simplfication.
13252 
13253   SmallPtrSet<const SDNode *, 16> Visited;
13254   SmallVector<const SDNode *, 8> Worklist;
13255   unsigned int Max = 8192;
13256   // Search Ops of store candidates.
13257   for (unsigned i = 0; i < NumStores; ++i) {
13258     SDNode *n = StoreNodes[i].MemNode;
13259     // Potential loops may happen only through non-chain operands
13260     for (unsigned j = 1; j < n->getNumOperands(); ++j)
13261       Worklist.push_back(n->getOperand(j).getNode());
13262   }
13263   // Search through DAG. We can stop early if we find a store node.
13264   for (unsigned i = 0; i < NumStores; ++i)
13265     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13266                                      Max))
13267       return false;
13268   return true;
13269 }
13270 
13271 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13272   if (OptLevel == CodeGenOpt::None)
13273     return false;
13274 
13275   EVT MemVT = St->getMemoryVT();
13276   int64_t ElementSizeBytes = MemVT.getStoreSize();
13277   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13278 
13279   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13280     return false;
13281 
13282   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13283       Attribute::NoImplicitFloat);
13284 
13285   // This function cannot currently deal with non-byte-sized memory sizes.
13286   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13287     return false;
13288 
13289   if (!MemVT.isSimple())
13290     return false;
13291 
13292   // Perform an early exit check. Do not bother looking at stored values that
13293   // are not constants, loads, or extracted vector elements.
13294   SDValue StoredVal = peekThroughBitcast(St->getValue());
13295   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13296   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13297                        isa<ConstantFPSDNode>(StoredVal);
13298   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13299                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13300 
13301   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13302     return false;
13303 
13304   SmallVector<MemOpLink, 8> StoreNodes;
13305   // Find potential store merge candidates by searching through chain sub-DAG
13306   getStoreMergeCandidates(St, StoreNodes);
13307 
13308   // Check if there is anything to merge.
13309   if (StoreNodes.size() < 2)
13310     return false;
13311 
13312   // Sort the memory operands according to their distance from the
13313   // base pointer.
13314   llvm::sort(StoreNodes.begin(), StoreNodes.end(),
13315              [](MemOpLink LHS, MemOpLink RHS) {
13316                return LHS.OffsetFromBase < RHS.OffsetFromBase;
13317              });
13318 
13319   // Store Merge attempts to merge the lowest stores. This generally
13320   // works out as if successful, as the remaining stores are checked
13321   // after the first collection of stores is merged. However, in the
13322   // case that a non-mergeable store is found first, e.g., {p[-2],
13323   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13324   // mergeable cases. To prevent this, we prune such stores from the
13325   // front of StoreNodes here.
13326 
13327   bool RV = false;
13328   while (StoreNodes.size() > 1) {
13329     unsigned StartIdx = 0;
13330     while ((StartIdx + 1 < StoreNodes.size()) &&
13331            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13332                StoreNodes[StartIdx + 1].OffsetFromBase)
13333       ++StartIdx;
13334 
13335     // Bail if we don't have enough candidates to merge.
13336     if (StartIdx + 1 >= StoreNodes.size())
13337       return RV;
13338 
13339     if (StartIdx)
13340       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13341 
13342     // Scan the memory operations on the chain and find the first
13343     // non-consecutive store memory address.
13344     unsigned NumConsecutiveStores = 1;
13345     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13346     // Check that the addresses are consecutive starting from the second
13347     // element in the list of stores.
13348     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13349       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13350       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13351         break;
13352       NumConsecutiveStores = i + 1;
13353     }
13354 
13355     if (NumConsecutiveStores < 2) {
13356       StoreNodes.erase(StoreNodes.begin(),
13357                        StoreNodes.begin() + NumConsecutiveStores);
13358       continue;
13359     }
13360 
13361     // Check that we can merge these candidates without causing a cycle
13362     if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
13363                                                   NumConsecutiveStores)) {
13364       StoreNodes.erase(StoreNodes.begin(),
13365                        StoreNodes.begin() + NumConsecutiveStores);
13366       continue;
13367     }
13368 
13369     // The node with the lowest store address.
13370     LLVMContext &Context = *DAG.getContext();
13371     const DataLayout &DL = DAG.getDataLayout();
13372 
13373     // Store the constants into memory as one consecutive store.
13374     if (IsConstantSrc) {
13375       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13376       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13377       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13378       unsigned LastLegalType = 1;
13379       unsigned LastLegalVectorType = 1;
13380       bool LastIntegerTrunc = false;
13381       bool NonZero = false;
13382       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13383       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13384         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13385         SDValue StoredVal = ST->getValue();
13386         bool IsElementZero = false;
13387         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13388           IsElementZero = C->isNullValue();
13389         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13390           IsElementZero = C->getConstantFPValue()->isNullValue();
13391         if (IsElementZero) {
13392           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13393             FirstZeroAfterNonZero = i;
13394         }
13395         NonZero |= !IsElementZero;
13396 
13397         // Find a legal type for the constant store.
13398         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13399         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13400         bool IsFast = false;
13401         if (TLI.isTypeLegal(StoreTy) &&
13402             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13403             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13404                                    FirstStoreAlign, &IsFast) &&
13405             IsFast) {
13406           LastIntegerTrunc = false;
13407           LastLegalType = i + 1;
13408           // Or check whether a truncstore is legal.
13409         } else if (TLI.getTypeAction(Context, StoreTy) ==
13410                    TargetLowering::TypePromoteInteger) {
13411           EVT LegalizedStoredValueTy =
13412               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13413           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13414               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13415               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13416                                      FirstStoreAlign, &IsFast) &&
13417               IsFast) {
13418             LastIntegerTrunc = true;
13419             LastLegalType = i + 1;
13420           }
13421         }
13422 
13423         // We only use vectors if the constant is known to be zero or the target
13424         // allows it and the function is not marked with the noimplicitfloat
13425         // attribute.
13426         if ((!NonZero ||
13427              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13428             !NoVectors) {
13429           // Find a legal type for the vector store.
13430           unsigned Elts = (i + 1) * NumMemElts;
13431           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13432           if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13433               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13434               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13435                                      FirstStoreAlign, &IsFast) &&
13436               IsFast)
13437             LastLegalVectorType = i + 1;
13438         }
13439       }
13440 
13441       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13442       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13443 
13444       // Check if we found a legal integer type that creates a meaningful merge.
13445       if (NumElem < 2) {
13446         // We know that candidate stores are in order and of correct
13447         // shape. While there is no mergeable sequence from the
13448         // beginning one may start later in the sequence. The only
13449         // reason a merge of size N could have failed where another of
13450         // the same size would not have, is if the alignment has
13451         // improved or we've dropped a non-zero value. Drop as many
13452         // candidates as we can here.
13453         unsigned NumSkip = 1;
13454         while (
13455             (NumSkip < NumConsecutiveStores) &&
13456             (NumSkip < FirstZeroAfterNonZero) &&
13457             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13458           NumSkip++;
13459         }
13460         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13461         continue;
13462       }
13463 
13464       bool Merged = MergeStoresOfConstantsOrVecElts(
13465           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13466       RV |= Merged;
13467 
13468       // Remove merged stores for next iteration.
13469       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13470       continue;
13471     }
13472 
13473     // When extracting multiple vector elements, try to store them
13474     // in one vector store rather than a sequence of scalar stores.
13475     if (IsExtractVecSrc) {
13476       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13477       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13478       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13479       unsigned NumStoresToMerge = 1;
13480       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13481         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13482         SDValue StVal = peekThroughBitcast(St->getValue());
13483         // This restriction could be loosened.
13484         // Bail out if any stored values are not elements extracted from a
13485         // vector. It should be possible to handle mixed sources, but load
13486         // sources need more careful handling (see the block of code below that
13487         // handles consecutive loads).
13488         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13489             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13490           return RV;
13491 
13492         // Find a legal type for the vector store.
13493         unsigned Elts = (i + 1) * NumMemElts;
13494         EVT Ty =
13495             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13496         bool IsFast;
13497         if (TLI.isTypeLegal(Ty) &&
13498             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13499             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13500                                    FirstStoreAlign, &IsFast) &&
13501             IsFast)
13502           NumStoresToMerge = i + 1;
13503       }
13504 
13505       // Check if we found a legal integer type that creates a meaningful merge.
13506       if (NumStoresToMerge < 2) {
13507         // We know that candidate stores are in order and of correct
13508         // shape. While there is no mergeable sequence from the
13509         // beginning one may start later in the sequence. The only
13510         // reason a merge of size N could have failed where another of
13511         // the same size would not have, is if the alignment has
13512         // improved. Drop as many candidates as we can here.
13513         unsigned NumSkip = 1;
13514         while ((NumSkip < NumConsecutiveStores) &&
13515                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13516           NumSkip++;
13517 
13518         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13519         continue;
13520       }
13521 
13522       bool Merged = MergeStoresOfConstantsOrVecElts(
13523           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13524       if (!Merged) {
13525         StoreNodes.erase(StoreNodes.begin(),
13526                          StoreNodes.begin() + NumStoresToMerge);
13527         continue;
13528       }
13529       // Remove merged stores for next iteration.
13530       StoreNodes.erase(StoreNodes.begin(),
13531                        StoreNodes.begin() + NumStoresToMerge);
13532       RV = true;
13533       continue;
13534     }
13535 
13536     // Below we handle the case of multiple consecutive stores that
13537     // come from multiple consecutive loads. We merge them into a single
13538     // wide load and a single wide store.
13539 
13540     // Look for load nodes which are used by the stored values.
13541     SmallVector<MemOpLink, 8> LoadNodes;
13542 
13543     // Find acceptable loads. Loads need to have the same chain (token factor),
13544     // must not be zext, volatile, indexed, and they must be consecutive.
13545     BaseIndexOffset LdBasePtr;
13546     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13547       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13548       SDValue Val = peekThroughBitcast(St->getValue());
13549       LoadSDNode *Ld = dyn_cast<LoadSDNode>(Val);
13550       if (!Ld)
13551         break;
13552 
13553       // Loads must only have one use.
13554       if (!Ld->hasNUsesOfValue(1, 0))
13555         break;
13556 
13557       // The memory operands must not be volatile.
13558       if (Ld->isVolatile() || Ld->isIndexed())
13559         break;
13560 
13561       // The stored memory type must be the same.
13562       if (Ld->getMemoryVT() != MemVT)
13563         break;
13564 
13565       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
13566       // If this is not the first ptr that we check.
13567       int64_t LdOffset = 0;
13568       if (LdBasePtr.getBase().getNode()) {
13569         // The base ptr must be the same.
13570         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13571           break;
13572       } else {
13573         // Check that all other base pointers are the same as this one.
13574         LdBasePtr = LdPtr;
13575       }
13576 
13577       // We found a potential memory operand to merge.
13578       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13579     }
13580 
13581     if (LoadNodes.size() < 2) {
13582       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13583       continue;
13584     }
13585 
13586     // If we have load/store pair instructions and we only have two values,
13587     // don't bother merging.
13588     unsigned RequiredAlignment;
13589     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13590         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13591       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13592       continue;
13593     }
13594     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13595     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13596     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13597     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13598     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13599     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13600 
13601     // Scan the memory operations on the chain and find the first
13602     // non-consecutive load memory address. These variables hold the index in
13603     // the store node array.
13604     unsigned LastConsecutiveLoad = 1;
13605     // This variable refers to the size and not index in the array.
13606     unsigned LastLegalVectorType = 1;
13607     unsigned LastLegalIntegerType = 1;
13608     bool isDereferenceable = true;
13609     bool DoIntegerTruncate = false;
13610     StartAddress = LoadNodes[0].OffsetFromBase;
13611     SDValue FirstChain = FirstLoad->getChain();
13612     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13613       // All loads must share the same chain.
13614       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13615         break;
13616 
13617       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13618       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13619         break;
13620       LastConsecutiveLoad = i;
13621 
13622       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13623         isDereferenceable = false;
13624 
13625       // Find a legal type for the vector store.
13626       unsigned Elts = (i + 1) * NumMemElts;
13627       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13628 
13629       bool IsFastSt, IsFastLd;
13630       if (TLI.isTypeLegal(StoreTy) &&
13631           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13632           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13633                                  FirstStoreAlign, &IsFastSt) &&
13634           IsFastSt &&
13635           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13636                                  FirstLoadAlign, &IsFastLd) &&
13637           IsFastLd) {
13638         LastLegalVectorType = i + 1;
13639       }
13640 
13641       // Find a legal type for the integer store.
13642       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13643       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13644       if (TLI.isTypeLegal(StoreTy) &&
13645           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13646           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13647                                  FirstStoreAlign, &IsFastSt) &&
13648           IsFastSt &&
13649           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13650                                  FirstLoadAlign, &IsFastLd) &&
13651           IsFastLd) {
13652         LastLegalIntegerType = i + 1;
13653         DoIntegerTruncate = false;
13654         // Or check whether a truncstore and extload is legal.
13655       } else if (TLI.getTypeAction(Context, StoreTy) ==
13656                  TargetLowering::TypePromoteInteger) {
13657         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13658         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13659             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13660             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13661                                StoreTy) &&
13662             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13663                                StoreTy) &&
13664             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13665             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13666                                    FirstStoreAlign, &IsFastSt) &&
13667             IsFastSt &&
13668             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13669                                    FirstLoadAlign, &IsFastLd) &&
13670             IsFastLd) {
13671           LastLegalIntegerType = i + 1;
13672           DoIntegerTruncate = true;
13673         }
13674       }
13675     }
13676 
13677     // Only use vector types if the vector type is larger than the integer type.
13678     // If they are the same, use integers.
13679     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13680     unsigned LastLegalType =
13681         std::max(LastLegalVectorType, LastLegalIntegerType);
13682 
13683     // We add +1 here because the LastXXX variables refer to location while
13684     // the NumElem refers to array/index size.
13685     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13686     NumElem = std::min(LastLegalType, NumElem);
13687 
13688     if (NumElem < 2) {
13689       // We know that candidate stores are in order and of correct
13690       // shape. While there is no mergeable sequence from the
13691       // beginning one may start later in the sequence. The only
13692       // reason a merge of size N could have failed where another of
13693       // the same size would not have is if the alignment or either
13694       // the load or store has improved. Drop as many candidates as we
13695       // can here.
13696       unsigned NumSkip = 1;
13697       while ((NumSkip < LoadNodes.size()) &&
13698              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13699              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13700         NumSkip++;
13701       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13702       continue;
13703     }
13704 
13705     // Find if it is better to use vectors or integers to load and store
13706     // to memory.
13707     EVT JointMemOpVT;
13708     if (UseVectorTy) {
13709       // Find a legal type for the vector store.
13710       unsigned Elts = NumElem * NumMemElts;
13711       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13712     } else {
13713       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13714       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13715     }
13716 
13717     SDLoc LoadDL(LoadNodes[0].MemNode);
13718     SDLoc StoreDL(StoreNodes[0].MemNode);
13719 
13720     // The merged loads are required to have the same incoming chain, so
13721     // using the first's chain is acceptable.
13722 
13723     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13724     AddToWorklist(NewStoreChain.getNode());
13725 
13726     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13727                                           MachineMemOperand::MODereferenceable:
13728                                           MachineMemOperand::MONone;
13729 
13730     SDValue NewLoad, NewStore;
13731     if (UseVectorTy || !DoIntegerTruncate) {
13732       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13733                             FirstLoad->getBasePtr(),
13734                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13735                             MMOFlags);
13736       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13737                               FirstInChain->getBasePtr(),
13738                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13739     } else { // This must be the truncstore/extload case
13740       EVT ExtendedTy =
13741           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13742       NewLoad =
13743           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13744                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13745                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13746       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13747                                    FirstInChain->getBasePtr(),
13748                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13749                                    FirstInChain->getAlignment(),
13750                                    FirstInChain->getMemOperand()->getFlags());
13751     }
13752 
13753     // Transfer chain users from old loads to the new load.
13754     for (unsigned i = 0; i < NumElem; ++i) {
13755       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13756       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13757                                     SDValue(NewLoad.getNode(), 1));
13758     }
13759 
13760     // Replace the all stores with the new store. Recursively remove
13761     // corresponding value if its no longer used.
13762     for (unsigned i = 0; i < NumElem; ++i) {
13763       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13764       CombineTo(StoreNodes[i].MemNode, NewStore);
13765       if (Val.getNode()->use_empty())
13766         recursivelyDeleteUnusedNodes(Val.getNode());
13767     }
13768 
13769     RV = true;
13770     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13771   }
13772   return RV;
13773 }
13774 
13775 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13776   SDLoc SL(ST);
13777   SDValue ReplStore;
13778 
13779   // Replace the chain to avoid dependency.
13780   if (ST->isTruncatingStore()) {
13781     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13782                                   ST->getBasePtr(), ST->getMemoryVT(),
13783                                   ST->getMemOperand());
13784   } else {
13785     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13786                              ST->getMemOperand());
13787   }
13788 
13789   // Create token to keep both nodes around.
13790   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13791                               MVT::Other, ST->getChain(), ReplStore);
13792 
13793   // Make sure the new and old chains are cleaned up.
13794   AddToWorklist(Token.getNode());
13795 
13796   // Don't add users to work list.
13797   return CombineTo(ST, Token, false);
13798 }
13799 
13800 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13801   SDValue Value = ST->getValue();
13802   if (Value.getOpcode() == ISD::TargetConstantFP)
13803     return SDValue();
13804 
13805   SDLoc DL(ST);
13806 
13807   SDValue Chain = ST->getChain();
13808   SDValue Ptr = ST->getBasePtr();
13809 
13810   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13811 
13812   // NOTE: If the original store is volatile, this transform must not increase
13813   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13814   // processor operation but an i64 (which is not legal) requires two.  So the
13815   // transform should not be done in this case.
13816 
13817   SDValue Tmp;
13818   switch (CFP->getSimpleValueType(0).SimpleTy) {
13819   default:
13820     llvm_unreachable("Unknown FP type");
13821   case MVT::f16:    // We don't do this for these yet.
13822   case MVT::f80:
13823   case MVT::f128:
13824   case MVT::ppcf128:
13825     return SDValue();
13826   case MVT::f32:
13827     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13828         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13829       ;
13830       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13831                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13832                             MVT::i32);
13833       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13834     }
13835 
13836     return SDValue();
13837   case MVT::f64:
13838     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13839          !ST->isVolatile()) ||
13840         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13841       ;
13842       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13843                             getZExtValue(), SDLoc(CFP), MVT::i64);
13844       return DAG.getStore(Chain, DL, Tmp,
13845                           Ptr, ST->getMemOperand());
13846     }
13847 
13848     if (!ST->isVolatile() &&
13849         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13850       // Many FP stores are not made apparent until after legalize, e.g. for
13851       // argument passing.  Since this is so common, custom legalize the
13852       // 64-bit integer store into two 32-bit stores.
13853       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13854       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13855       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13856       if (DAG.getDataLayout().isBigEndian())
13857         std::swap(Lo, Hi);
13858 
13859       unsigned Alignment = ST->getAlignment();
13860       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13861       AAMDNodes AAInfo = ST->getAAInfo();
13862 
13863       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13864                                  ST->getAlignment(), MMOFlags, AAInfo);
13865       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13866                         DAG.getConstant(4, DL, Ptr.getValueType()));
13867       Alignment = MinAlign(Alignment, 4U);
13868       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13869                                  ST->getPointerInfo().getWithOffset(4),
13870                                  Alignment, MMOFlags, AAInfo);
13871       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13872                          St0, St1);
13873     }
13874 
13875     return SDValue();
13876   }
13877 }
13878 
13879 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13880   StoreSDNode *ST  = cast<StoreSDNode>(N);
13881   SDValue Chain = ST->getChain();
13882   SDValue Value = ST->getValue();
13883   SDValue Ptr   = ST->getBasePtr();
13884 
13885   // If this is a store of a bit convert, store the input value if the
13886   // resultant store does not need a higher alignment than the original.
13887   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13888       ST->isUnindexed()) {
13889     EVT SVT = Value.getOperand(0).getValueType();
13890     if (((!LegalOperations && !ST->isVolatile()) ||
13891          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13892         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13893       unsigned OrigAlign = ST->getAlignment();
13894       bool Fast = false;
13895       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13896                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
13897           Fast) {
13898         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13899                             ST->getPointerInfo(), OrigAlign,
13900                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
13901       }
13902     }
13903   }
13904 
13905   // Turn 'store undef, Ptr' -> nothing.
13906   if (Value.isUndef() && ST->isUnindexed())
13907     return Chain;
13908 
13909   // Try to infer better alignment information than the store already has.
13910   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13911     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13912       if (Align > ST->getAlignment()) {
13913         SDValue NewStore =
13914             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13915                               ST->getMemoryVT(), Align,
13916                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
13917         if (NewStore.getNode() != N)
13918           return CombineTo(ST, NewStore, true);
13919       }
13920     }
13921   }
13922 
13923   // Try transforming a pair floating point load / store ops to integer
13924   // load / store ops.
13925   if (SDValue NewST = TransformFPLoadStorePair(N))
13926     return NewST;
13927 
13928   if (ST->isUnindexed()) {
13929     // Walk up chain skipping non-aliasing memory nodes, on this store and any
13930     // adjacent stores.
13931     if (findBetterNeighborChains(ST)) {
13932       // replaceStoreChain uses CombineTo, which handled all of the worklist
13933       // manipulation. Return the original node to not do anything else.
13934       return SDValue(ST, 0);
13935     }
13936     Chain = ST->getChain();
13937   }
13938 
13939   // FIXME: is there such a thing as a truncating indexed store?
13940   if (ST->isTruncatingStore() && ST->isUnindexed() &&
13941       Value.getValueType().isInteger()) {
13942     // See if we can simplify the input to this truncstore with knowledge that
13943     // only the low bits are being used.  For example:
13944     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
13945     SDValue Shorter = DAG.GetDemandedBits(
13946         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13947                                     ST->getMemoryVT().getScalarSizeInBits()));
13948     AddToWorklist(Value.getNode());
13949     if (Shorter.getNode())
13950       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13951                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
13952 
13953     // Otherwise, see if we can simplify the operation with
13954     // SimplifyDemandedBits, which only works if the value has a single use.
13955     if (SimplifyDemandedBits(
13956             Value,
13957             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13958                                  ST->getMemoryVT().getScalarSizeInBits()))) {
13959       // Re-visit the store if anything changed and the store hasn't been merged
13960       // with another node (N is deleted) SimplifyDemandedBits will add Value's
13961       // node back to the worklist if necessary, but we also need to re-visit
13962       // the Store node itself.
13963       if (N->getOpcode() != ISD::DELETED_NODE)
13964         AddToWorklist(N);
13965       return SDValue(N, 0);
13966     }
13967   }
13968 
13969   // If this is a load followed by a store to the same location, then the store
13970   // is dead/noop.
13971   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13972     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13973         ST->isUnindexed() && !ST->isVolatile() &&
13974         // There can't be any side effects between the load and store, such as
13975         // a call or store.
13976         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13977       // The store is dead, remove it.
13978       return Chain;
13979     }
13980   }
13981 
13982   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13983     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13984         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13985         ST->getMemoryVT() == ST1->getMemoryVT()) {
13986       // If this is a store followed by a store with the same value to the same
13987       // location, then the store is dead/noop.
13988       if (ST1->getValue() == Value) {
13989         // The store is dead, remove it.
13990         return Chain;
13991       }
13992 
13993       // If this is a store who's preceeding store to the same location
13994       // and no one other node is chained to that store we can effectively
13995       // drop the store. Do not remove stores to undef as they may be used as
13996       // data sinks.
13997       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13998           !ST1->getBasePtr().isUndef()) {
13999         // ST1 is fully overwritten and can be elided. Combine with it's chain
14000         // value.
14001         CombineTo(ST1, ST1->getChain());
14002         return SDValue();
14003       }
14004     }
14005   }
14006 
14007   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
14008   // truncating store.  We can do this even if this is already a truncstore.
14009   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
14010       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
14011       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
14012                             ST->getMemoryVT())) {
14013     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
14014                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
14015   }
14016 
14017   // Always perform this optimization before types are legal. If the target
14018   // prefers, also try this after legalization to catch stores that were created
14019   // by intrinsics or other nodes.
14020   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
14021     while (true) {
14022       // There can be multiple store sequences on the same chain.
14023       // Keep trying to merge store sequences until we are unable to do so
14024       // or until we merge the last store on the chain.
14025       bool Changed = MergeConsecutiveStores(ST);
14026       if (!Changed) break;
14027       // Return N as merge only uses CombineTo and no worklist clean
14028       // up is necessary.
14029       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
14030         return SDValue(N, 0);
14031     }
14032   }
14033 
14034   // Try transforming N to an indexed store.
14035   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14036     return SDValue(N, 0);
14037 
14038   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
14039   //
14040   // Make sure to do this only after attempting to merge stores in order to
14041   //  avoid changing the types of some subset of stores due to visit order,
14042   //  preventing their merging.
14043   if (isa<ConstantFPSDNode>(ST->getValue())) {
14044     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
14045       return NewSt;
14046   }
14047 
14048   if (SDValue NewSt = splitMergedValStore(ST))
14049     return NewSt;
14050 
14051   return ReduceLoadOpStoreWidth(N);
14052 }
14053 
14054 /// For the instruction sequence of store below, F and I values
14055 /// are bundled together as an i64 value before being stored into memory.
14056 /// Sometimes it is more efficent to generate separate stores for F and I,
14057 /// which can remove the bitwise instructions or sink them to colder places.
14058 ///
14059 ///   (store (or (zext (bitcast F to i32) to i64),
14060 ///              (shl (zext I to i64), 32)), addr)  -->
14061 ///   (store F, addr) and (store I, addr+4)
14062 ///
14063 /// Similarly, splitting for other merged store can also be beneficial, like:
14064 /// For pair of {i32, i32}, i64 store --> two i32 stores.
14065 /// For pair of {i32, i16}, i64 store --> two i32 stores.
14066 /// For pair of {i16, i16}, i32 store --> two i16 stores.
14067 /// For pair of {i16, i8},  i32 store --> two i16 stores.
14068 /// For pair of {i8, i8},   i16 store --> two i8 stores.
14069 ///
14070 /// We allow each target to determine specifically which kind of splitting is
14071 /// supported.
14072 ///
14073 /// The store patterns are commonly seen from the simple code snippet below
14074 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
14075 ///   void goo(const std::pair<int, float> &);
14076 ///   hoo() {
14077 ///     ...
14078 ///     goo(std::make_pair(tmp, ftmp));
14079 ///     ...
14080 ///   }
14081 ///
14082 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
14083   if (OptLevel == CodeGenOpt::None)
14084     return SDValue();
14085 
14086   SDValue Val = ST->getValue();
14087   SDLoc DL(ST);
14088 
14089   // Match OR operand.
14090   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
14091     return SDValue();
14092 
14093   // Match SHL operand and get Lower and Higher parts of Val.
14094   SDValue Op1 = Val.getOperand(0);
14095   SDValue Op2 = Val.getOperand(1);
14096   SDValue Lo, Hi;
14097   if (Op1.getOpcode() != ISD::SHL) {
14098     std::swap(Op1, Op2);
14099     if (Op1.getOpcode() != ISD::SHL)
14100       return SDValue();
14101   }
14102   Lo = Op2;
14103   Hi = Op1.getOperand(0);
14104   if (!Op1.hasOneUse())
14105     return SDValue();
14106 
14107   // Match shift amount to HalfValBitSize.
14108   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
14109   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
14110   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
14111     return SDValue();
14112 
14113   // Lo and Hi are zero-extended from int with size less equal than 32
14114   // to i64.
14115   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
14116       !Lo.getOperand(0).getValueType().isScalarInteger() ||
14117       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
14118       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
14119       !Hi.getOperand(0).getValueType().isScalarInteger() ||
14120       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
14121     return SDValue();
14122 
14123   // Use the EVT of low and high parts before bitcast as the input
14124   // of target query.
14125   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
14126                   ? Lo.getOperand(0).getValueType()
14127                   : Lo.getValueType();
14128   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
14129                    ? Hi.getOperand(0).getValueType()
14130                    : Hi.getValueType();
14131   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
14132     return SDValue();
14133 
14134   // Start to split store.
14135   unsigned Alignment = ST->getAlignment();
14136   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14137   AAMDNodes AAInfo = ST->getAAInfo();
14138 
14139   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
14140   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
14141   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
14142   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
14143 
14144   SDValue Chain = ST->getChain();
14145   SDValue Ptr = ST->getBasePtr();
14146   // Lower value store.
14147   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14148                              ST->getAlignment(), MMOFlags, AAInfo);
14149   Ptr =
14150       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14151                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
14152   // Higher value store.
14153   SDValue St1 =
14154       DAG.getStore(St0, DL, Hi, Ptr,
14155                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
14156                    Alignment / 2, MMOFlags, AAInfo);
14157   return St1;
14158 }
14159 
14160 /// Convert a disguised subvector insertion into a shuffle:
14161 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
14162 /// bitcast(shuffle (bitcast V), (extended X), Mask)
14163 /// Note: We do not use an insert_subvector node because that requires a legal
14164 /// subvector type.
14165 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
14166   SDValue InsertVal = N->getOperand(1);
14167   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
14168       !InsertVal.getOperand(0).getValueType().isVector())
14169     return SDValue();
14170 
14171   SDValue SubVec = InsertVal.getOperand(0);
14172   SDValue DestVec = N->getOperand(0);
14173   EVT SubVecVT = SubVec.getValueType();
14174   EVT VT = DestVec.getValueType();
14175   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
14176   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
14177   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
14178 
14179   // Step 1: Create a shuffle mask that implements this insert operation. The
14180   // vector that we are inserting into will be operand 0 of the shuffle, so
14181   // those elements are just 'i'. The inserted subvector is in the first
14182   // positions of operand 1 of the shuffle. Example:
14183   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
14184   SmallVector<int, 16> Mask(NumMaskVals);
14185   for (unsigned i = 0; i != NumMaskVals; ++i) {
14186     if (i / NumSrcElts == InsIndex)
14187       Mask[i] = (i % NumSrcElts) + NumMaskVals;
14188     else
14189       Mask[i] = i;
14190   }
14191 
14192   // Bail out if the target can not handle the shuffle we want to create.
14193   EVT SubVecEltVT = SubVecVT.getVectorElementType();
14194   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14195   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14196     return SDValue();
14197 
14198   // Step 2: Create a wide vector from the inserted source vector by appending
14199   // undefined elements. This is the same size as our destination vector.
14200   SDLoc DL(N);
14201   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14202   ConcatOps[0] = SubVec;
14203   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14204 
14205   // Step 3: Shuffle in the padded subvector.
14206   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14207   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14208   AddToWorklist(PaddedSubV.getNode());
14209   AddToWorklist(DestVecBC.getNode());
14210   AddToWorklist(Shuf.getNode());
14211   return DAG.getBitcast(VT, Shuf);
14212 }
14213 
14214 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14215   SDValue InVec = N->getOperand(0);
14216   SDValue InVal = N->getOperand(1);
14217   SDValue EltNo = N->getOperand(2);
14218   SDLoc DL(N);
14219 
14220   // If the inserted element is an UNDEF, just use the input vector.
14221   if (InVal.isUndef())
14222     return InVec;
14223 
14224   EVT VT = InVec.getValueType();
14225 
14226   // Remove redundant insertions:
14227   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14228   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14229       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14230     return InVec;
14231 
14232   // We must know which element is being inserted for folds below here.
14233   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14234   if (!IndexC)
14235     return SDValue();
14236   unsigned Elt = IndexC->getZExtValue();
14237 
14238   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14239     return Shuf;
14240 
14241   // Canonicalize insert_vector_elt dag nodes.
14242   // Example:
14243   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14244   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14245   //
14246   // Do this only if the child insert_vector node has one use; also
14247   // do this only if indices are both constants and Idx1 < Idx0.
14248   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14249       && isa<ConstantSDNode>(InVec.getOperand(2))) {
14250     unsigned OtherElt = InVec.getConstantOperandVal(2);
14251     if (Elt < OtherElt) {
14252       // Swap nodes.
14253       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14254                                   InVec.getOperand(0), InVal, EltNo);
14255       AddToWorklist(NewOp.getNode());
14256       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14257                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14258     }
14259   }
14260 
14261   // If we can't generate a legal BUILD_VECTOR, exit
14262   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14263     return SDValue();
14264 
14265   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14266   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
14267   // vector elements.
14268   SmallVector<SDValue, 8> Ops;
14269   // Do not combine these two vectors if the output vector will not replace
14270   // the input vector.
14271   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14272     Ops.append(InVec.getNode()->op_begin(),
14273                InVec.getNode()->op_end());
14274   } else if (InVec.isUndef()) {
14275     unsigned NElts = VT.getVectorNumElements();
14276     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14277   } else {
14278     return SDValue();
14279   }
14280 
14281   // Insert the element
14282   if (Elt < Ops.size()) {
14283     // All the operands of BUILD_VECTOR must have the same type;
14284     // we enforce that here.
14285     EVT OpVT = Ops[0].getValueType();
14286     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14287   }
14288 
14289   // Return the new vector
14290   return DAG.getBuildVector(VT, DL, Ops);
14291 }
14292 
14293 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14294     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14295   assert(!OriginalLoad->isVolatile());
14296 
14297   EVT ResultVT = EVE->getValueType(0);
14298   EVT VecEltVT = InVecVT.getVectorElementType();
14299   unsigned Align = OriginalLoad->getAlignment();
14300   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14301       VecEltVT.getTypeForEVT(*DAG.getContext()));
14302 
14303   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14304     return SDValue();
14305 
14306   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14307     ISD::NON_EXTLOAD : ISD::EXTLOAD;
14308   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14309     return SDValue();
14310 
14311   Align = NewAlign;
14312 
14313   SDValue NewPtr = OriginalLoad->getBasePtr();
14314   SDValue Offset;
14315   EVT PtrType = NewPtr.getValueType();
14316   MachinePointerInfo MPI;
14317   SDLoc DL(EVE);
14318   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14319     int Elt = ConstEltNo->getZExtValue();
14320     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14321     Offset = DAG.getConstant(PtrOff, DL, PtrType);
14322     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14323   } else {
14324     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14325     Offset = DAG.getNode(
14326         ISD::MUL, DL, PtrType, Offset,
14327         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14328     MPI = OriginalLoad->getPointerInfo();
14329   }
14330   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14331 
14332   // The replacement we need to do here is a little tricky: we need to
14333   // replace an extractelement of a load with a load.
14334   // Use ReplaceAllUsesOfValuesWith to do the replacement.
14335   // Note that this replacement assumes that the extractvalue is the only
14336   // use of the load; that's okay because we don't want to perform this
14337   // transformation in other cases anyway.
14338   SDValue Load;
14339   SDValue Chain;
14340   if (ResultVT.bitsGT(VecEltVT)) {
14341     // If the result type of vextract is wider than the load, then issue an
14342     // extending load instead.
14343     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14344                                                   VecEltVT)
14345                                    ? ISD::ZEXTLOAD
14346                                    : ISD::EXTLOAD;
14347     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14348                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14349                           Align, OriginalLoad->getMemOperand()->getFlags(),
14350                           OriginalLoad->getAAInfo());
14351     Chain = Load.getValue(1);
14352   } else {
14353     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14354                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14355                        OriginalLoad->getAAInfo());
14356     Chain = Load.getValue(1);
14357     if (ResultVT.bitsLT(VecEltVT))
14358       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14359     else
14360       Load = DAG.getBitcast(ResultVT, Load);
14361   }
14362   WorklistRemover DeadNodes(*this);
14363   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14364   SDValue To[] = { Load, Chain };
14365   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14366   // Since we're explicitly calling ReplaceAllUses, add the new node to the
14367   // worklist explicitly as well.
14368   AddToWorklist(Load.getNode());
14369   AddUsersToWorklist(Load.getNode()); // Add users too
14370   // Make sure to revisit this node to clean it up; it will usually be dead.
14371   AddToWorklist(EVE);
14372   ++OpsNarrowed;
14373   return SDValue(EVE, 0);
14374 }
14375 
14376 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14377   // (vextract (scalar_to_vector val, 0) -> val
14378   SDValue InVec = N->getOperand(0);
14379   EVT VT = InVec.getValueType();
14380   EVT NVT = N->getValueType(0);
14381 
14382   if (InVec.isUndef())
14383     return DAG.getUNDEF(NVT);
14384 
14385   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14386     // Check if the result type doesn't match the inserted element type. A
14387     // SCALAR_TO_VECTOR may truncate the inserted element and the
14388     // EXTRACT_VECTOR_ELT may widen the extracted vector.
14389     SDValue InOp = InVec.getOperand(0);
14390     if (InOp.getValueType() != NVT) {
14391       assert(InOp.getValueType().isInteger() && NVT.isInteger());
14392       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14393     }
14394     return InOp;
14395   }
14396 
14397   SDValue EltNo = N->getOperand(1);
14398   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14399 
14400   // extract_vector_elt of out-of-bounds element -> UNDEF
14401   if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements()))
14402     return DAG.getUNDEF(NVT);
14403 
14404   // extract_vector_elt (build_vector x, y), 1 -> y
14405   if (ConstEltNo &&
14406       InVec.getOpcode() == ISD::BUILD_VECTOR &&
14407       TLI.isTypeLegal(VT) &&
14408       (InVec.hasOneUse() ||
14409        TLI.aggressivelyPreferBuildVectorSources(VT))) {
14410     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14411     EVT InEltVT = Elt.getValueType();
14412 
14413     // Sometimes build_vector's scalar input types do not match result type.
14414     if (NVT == InEltVT)
14415       return Elt;
14416 
14417     // TODO: It may be useful to truncate if free if the build_vector implicitly
14418     // converts.
14419   }
14420 
14421   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14422   bool isLE = DAG.getDataLayout().isLittleEndian();
14423   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14424   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14425       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14426     SDValue BCSrc = InVec.getOperand(0);
14427     if (BCSrc.getValueType().isScalarInteger())
14428       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14429   }
14430 
14431   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14432   //
14433   // This only really matters if the index is non-constant since other combines
14434   // on the constant elements already work.
14435   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14436       EltNo == InVec.getOperand(2)) {
14437     SDValue Elt = InVec.getOperand(1);
14438     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14439   }
14440 
14441   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14442   // We only perform this optimization before the op legalization phase because
14443   // we may introduce new vector instructions which are not backed by TD
14444   // patterns. For example on AVX, extracting elements from a wide vector
14445   // without using extract_subvector. However, if we can find an underlying
14446   // scalar value, then we can always use that.
14447   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14448     int NumElem = VT.getVectorNumElements();
14449     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14450     // Find the new index to extract from.
14451     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14452 
14453     // Extracting an undef index is undef.
14454     if (OrigElt == -1)
14455       return DAG.getUNDEF(NVT);
14456 
14457     // Select the right vector half to extract from.
14458     SDValue SVInVec;
14459     if (OrigElt < NumElem) {
14460       SVInVec = InVec->getOperand(0);
14461     } else {
14462       SVInVec = InVec->getOperand(1);
14463       OrigElt -= NumElem;
14464     }
14465 
14466     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14467       SDValue InOp = SVInVec.getOperand(OrigElt);
14468       if (InOp.getValueType() != NVT) {
14469         assert(InOp.getValueType().isInteger() && NVT.isInteger());
14470         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14471       }
14472 
14473       return InOp;
14474     }
14475 
14476     // FIXME: We should handle recursing on other vector shuffles and
14477     // scalar_to_vector here as well.
14478 
14479     if (!LegalOperations ||
14480         // FIXME: Should really be just isOperationLegalOrCustom.
14481         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14482         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14483       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14484       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14485                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14486     }
14487   }
14488 
14489   bool BCNumEltsChanged = false;
14490   EVT ExtVT = VT.getVectorElementType();
14491   EVT LVT = ExtVT;
14492 
14493   // If the result of load has to be truncated, then it's not necessarily
14494   // profitable.
14495   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14496     return SDValue();
14497 
14498   if (InVec.getOpcode() == ISD::BITCAST) {
14499     // Don't duplicate a load with other uses.
14500     if (!InVec.hasOneUse())
14501       return SDValue();
14502 
14503     EVT BCVT = InVec.getOperand(0).getValueType();
14504     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14505       return SDValue();
14506     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14507       BCNumEltsChanged = true;
14508     InVec = InVec.getOperand(0);
14509     ExtVT = BCVT.getVectorElementType();
14510   }
14511 
14512   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14513   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14514       ISD::isNormalLoad(InVec.getNode()) &&
14515       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14516     SDValue Index = N->getOperand(1);
14517     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14518       if (!OrigLoad->isVolatile()) {
14519         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14520                                                              OrigLoad);
14521       }
14522     }
14523   }
14524 
14525   // Perform only after legalization to ensure build_vector / vector_shuffle
14526   // optimizations have already been done.
14527   if (!LegalOperations) return SDValue();
14528 
14529   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14530   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14531   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14532 
14533   if (ConstEltNo) {
14534     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14535 
14536     LoadSDNode *LN0 = nullptr;
14537     const ShuffleVectorSDNode *SVN = nullptr;
14538     if (ISD::isNormalLoad(InVec.getNode())) {
14539       LN0 = cast<LoadSDNode>(InVec);
14540     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14541                InVec.getOperand(0).getValueType() == ExtVT &&
14542                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14543       // Don't duplicate a load with other uses.
14544       if (!InVec.hasOneUse())
14545         return SDValue();
14546 
14547       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14548     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14549       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14550       // =>
14551       // (load $addr+1*size)
14552 
14553       // Don't duplicate a load with other uses.
14554       if (!InVec.hasOneUse())
14555         return SDValue();
14556 
14557       // If the bit convert changed the number of elements, it is unsafe
14558       // to examine the mask.
14559       if (BCNumEltsChanged)
14560         return SDValue();
14561 
14562       // Select the input vector, guarding against out of range extract vector.
14563       unsigned NumElems = VT.getVectorNumElements();
14564       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14565       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14566 
14567       if (InVec.getOpcode() == ISD::BITCAST) {
14568         // Don't duplicate a load with other uses.
14569         if (!InVec.hasOneUse())
14570           return SDValue();
14571 
14572         InVec = InVec.getOperand(0);
14573       }
14574       if (ISD::isNormalLoad(InVec.getNode())) {
14575         LN0 = cast<LoadSDNode>(InVec);
14576         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14577         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14578       }
14579     }
14580 
14581     // Make sure we found a non-volatile load and the extractelement is
14582     // the only use.
14583     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14584       return SDValue();
14585 
14586     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14587     if (Elt == -1)
14588       return DAG.getUNDEF(LVT);
14589 
14590     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14591   }
14592 
14593   return SDValue();
14594 }
14595 
14596 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14597 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14598   // We perform this optimization post type-legalization because
14599   // the type-legalizer often scalarizes integer-promoted vectors.
14600   // Performing this optimization before may create bit-casts which
14601   // will be type-legalized to complex code sequences.
14602   // We perform this optimization only before the operation legalizer because we
14603   // may introduce illegal operations.
14604   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14605     return SDValue();
14606 
14607   unsigned NumInScalars = N->getNumOperands();
14608   SDLoc DL(N);
14609   EVT VT = N->getValueType(0);
14610 
14611   // Check to see if this is a BUILD_VECTOR of a bunch of values
14612   // which come from any_extend or zero_extend nodes. If so, we can create
14613   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14614   // optimizations. We do not handle sign-extend because we can't fill the sign
14615   // using shuffles.
14616   EVT SourceType = MVT::Other;
14617   bool AllAnyExt = true;
14618 
14619   for (unsigned i = 0; i != NumInScalars; ++i) {
14620     SDValue In = N->getOperand(i);
14621     // Ignore undef inputs.
14622     if (In.isUndef()) continue;
14623 
14624     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14625     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14626 
14627     // Abort if the element is not an extension.
14628     if (!ZeroExt && !AnyExt) {
14629       SourceType = MVT::Other;
14630       break;
14631     }
14632 
14633     // The input is a ZeroExt or AnyExt. Check the original type.
14634     EVT InTy = In.getOperand(0).getValueType();
14635 
14636     // Check that all of the widened source types are the same.
14637     if (SourceType == MVT::Other)
14638       // First time.
14639       SourceType = InTy;
14640     else if (InTy != SourceType) {
14641       // Multiple income types. Abort.
14642       SourceType = MVT::Other;
14643       break;
14644     }
14645 
14646     // Check if all of the extends are ANY_EXTENDs.
14647     AllAnyExt &= AnyExt;
14648   }
14649 
14650   // In order to have valid types, all of the inputs must be extended from the
14651   // same source type and all of the inputs must be any or zero extend.
14652   // Scalar sizes must be a power of two.
14653   EVT OutScalarTy = VT.getScalarType();
14654   bool ValidTypes = SourceType != MVT::Other &&
14655                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14656                  isPowerOf2_32(SourceType.getSizeInBits());
14657 
14658   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14659   // turn into a single shuffle instruction.
14660   if (!ValidTypes)
14661     return SDValue();
14662 
14663   bool isLE = DAG.getDataLayout().isLittleEndian();
14664   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14665   assert(ElemRatio > 1 && "Invalid element size ratio");
14666   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14667                                DAG.getConstant(0, DL, SourceType);
14668 
14669   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14670   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14671 
14672   // Populate the new build_vector
14673   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14674     SDValue Cast = N->getOperand(i);
14675     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14676             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14677             Cast.isUndef()) && "Invalid cast opcode");
14678     SDValue In;
14679     if (Cast.isUndef())
14680       In = DAG.getUNDEF(SourceType);
14681     else
14682       In = Cast->getOperand(0);
14683     unsigned Index = isLE ? (i * ElemRatio) :
14684                             (i * ElemRatio + (ElemRatio - 1));
14685 
14686     assert(Index < Ops.size() && "Invalid index");
14687     Ops[Index] = In;
14688   }
14689 
14690   // The type of the new BUILD_VECTOR node.
14691   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14692   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14693          "Invalid vector size");
14694   // Check if the new vector type is legal.
14695   if (!isTypeLegal(VecVT)) return SDValue();
14696 
14697   // Make the new BUILD_VECTOR.
14698   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14699 
14700   // The new BUILD_VECTOR node has the potential to be further optimized.
14701   AddToWorklist(BV.getNode());
14702   // Bitcast to the desired type.
14703   return DAG.getBitcast(VT, BV);
14704 }
14705 
14706 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14707   EVT VT = N->getValueType(0);
14708 
14709   unsigned NumInScalars = N->getNumOperands();
14710   SDLoc DL(N);
14711 
14712   EVT SrcVT = MVT::Other;
14713   unsigned Opcode = ISD::DELETED_NODE;
14714   unsigned NumDefs = 0;
14715 
14716   for (unsigned i = 0; i != NumInScalars; ++i) {
14717     SDValue In = N->getOperand(i);
14718     unsigned Opc = In.getOpcode();
14719 
14720     if (Opc == ISD::UNDEF)
14721       continue;
14722 
14723     // If all scalar values are floats and converted from integers.
14724     if (Opcode == ISD::DELETED_NODE &&
14725         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14726       Opcode = Opc;
14727     }
14728 
14729     if (Opc != Opcode)
14730       return SDValue();
14731 
14732     EVT InVT = In.getOperand(0).getValueType();
14733 
14734     // If all scalar values are typed differently, bail out. It's chosen to
14735     // simplify BUILD_VECTOR of integer types.
14736     if (SrcVT == MVT::Other)
14737       SrcVT = InVT;
14738     if (SrcVT != InVT)
14739       return SDValue();
14740     NumDefs++;
14741   }
14742 
14743   // If the vector has just one element defined, it's not worth to fold it into
14744   // a vectorized one.
14745   if (NumDefs < 2)
14746     return SDValue();
14747 
14748   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14749          && "Should only handle conversion from integer to float.");
14750   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14751 
14752   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14753 
14754   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14755     return SDValue();
14756 
14757   // Just because the floating-point vector type is legal does not necessarily
14758   // mean that the corresponding integer vector type is.
14759   if (!isTypeLegal(NVT))
14760     return SDValue();
14761 
14762   SmallVector<SDValue, 8> Opnds;
14763   for (unsigned i = 0; i != NumInScalars; ++i) {
14764     SDValue In = N->getOperand(i);
14765 
14766     if (In.isUndef())
14767       Opnds.push_back(DAG.getUNDEF(SrcVT));
14768     else
14769       Opnds.push_back(In.getOperand(0));
14770   }
14771   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14772   AddToWorklist(BV.getNode());
14773 
14774   return DAG.getNode(Opcode, DL, VT, BV);
14775 }
14776 
14777 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14778                                            ArrayRef<int> VectorMask,
14779                                            SDValue VecIn1, SDValue VecIn2,
14780                                            unsigned LeftIdx) {
14781   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14782   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14783 
14784   EVT VT = N->getValueType(0);
14785   EVT InVT1 = VecIn1.getValueType();
14786   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14787 
14788   unsigned Vec2Offset = 0;
14789   unsigned NumElems = VT.getVectorNumElements();
14790   unsigned ShuffleNumElems = NumElems;
14791 
14792   // In case both the input vectors are extracted from same base
14793   // vector we do not need extra addend (Vec2Offset) while
14794   // computing shuffle mask.
14795   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14796       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14797       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14798     Vec2Offset = InVT1.getVectorNumElements();
14799 
14800   // We can't generate a shuffle node with mismatched input and output types.
14801   // Try to make the types match the type of the output.
14802   if (InVT1 != VT || InVT2 != VT) {
14803     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14804       // If the output vector length is a multiple of both input lengths,
14805       // we can concatenate them and pad the rest with undefs.
14806       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14807       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14808       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14809       ConcatOps[0] = VecIn1;
14810       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14811       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14812       VecIn2 = SDValue();
14813     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14814       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14815         return SDValue();
14816 
14817       if (!VecIn2.getNode()) {
14818         // If we only have one input vector, and it's twice the size of the
14819         // output, split it in two.
14820         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14821                              DAG.getConstant(NumElems, DL, IdxTy));
14822         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14823         // Since we now have shorter input vectors, adjust the offset of the
14824         // second vector's start.
14825         Vec2Offset = NumElems;
14826       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14827         // VecIn1 is wider than the output, and we have another, possibly
14828         // smaller input. Pad the smaller input with undefs, shuffle at the
14829         // input vector width, and extract the output.
14830         // The shuffle type is different than VT, so check legality again.
14831         if (LegalOperations &&
14832             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14833           return SDValue();
14834 
14835         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14836         // lower it back into a BUILD_VECTOR. So if the inserted type is
14837         // illegal, don't even try.
14838         if (InVT1 != InVT2) {
14839           if (!TLI.isTypeLegal(InVT2))
14840             return SDValue();
14841           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14842                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14843         }
14844         ShuffleNumElems = NumElems * 2;
14845       } else {
14846         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14847         // than VecIn1. We can't handle this for now - this case will disappear
14848         // when we start sorting the vectors by type.
14849         return SDValue();
14850       }
14851     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14852                InVT1.getSizeInBits() == VT.getSizeInBits()) {
14853       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14854       ConcatOps[0] = VecIn2;
14855       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14856     } else {
14857       // TODO: Support cases where the length mismatch isn't exactly by a
14858       // factor of 2.
14859       // TODO: Move this check upwards, so that if we have bad type
14860       // mismatches, we don't create any DAG nodes.
14861       return SDValue();
14862     }
14863   }
14864 
14865   // Initialize mask to undef.
14866   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14867 
14868   // Only need to run up to the number of elements actually used, not the
14869   // total number of elements in the shuffle - if we are shuffling a wider
14870   // vector, the high lanes should be set to undef.
14871   for (unsigned i = 0; i != NumElems; ++i) {
14872     if (VectorMask[i] <= 0)
14873       continue;
14874 
14875     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14876     if (VectorMask[i] == (int)LeftIdx) {
14877       Mask[i] = ExtIndex;
14878     } else if (VectorMask[i] == (int)LeftIdx + 1) {
14879       Mask[i] = Vec2Offset + ExtIndex;
14880     }
14881   }
14882 
14883   // The type the input vectors may have changed above.
14884   InVT1 = VecIn1.getValueType();
14885 
14886   // If we already have a VecIn2, it should have the same type as VecIn1.
14887   // If we don't, get an undef/zero vector of the appropriate type.
14888   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14889   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14890 
14891   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14892   if (ShuffleNumElems > NumElems)
14893     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14894 
14895   return Shuffle;
14896 }
14897 
14898 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14899 // operations. If the types of the vectors we're extracting from allow it,
14900 // turn this into a vector_shuffle node.
14901 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14902   SDLoc DL(N);
14903   EVT VT = N->getValueType(0);
14904 
14905   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14906   if (!isTypeLegal(VT))
14907     return SDValue();
14908 
14909   // May only combine to shuffle after legalize if shuffle is legal.
14910   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14911     return SDValue();
14912 
14913   bool UsesZeroVector = false;
14914   unsigned NumElems = N->getNumOperands();
14915 
14916   // Record, for each element of the newly built vector, which input vector
14917   // that element comes from. -1 stands for undef, 0 for the zero vector,
14918   // and positive values for the input vectors.
14919   // VectorMask maps each element to its vector number, and VecIn maps vector
14920   // numbers to their initial SDValues.
14921 
14922   SmallVector<int, 8> VectorMask(NumElems, -1);
14923   SmallVector<SDValue, 8> VecIn;
14924   VecIn.push_back(SDValue());
14925 
14926   for (unsigned i = 0; i != NumElems; ++i) {
14927     SDValue Op = N->getOperand(i);
14928 
14929     if (Op.isUndef())
14930       continue;
14931 
14932     // See if we can use a blend with a zero vector.
14933     // TODO: Should we generalize this to a blend with an arbitrary constant
14934     // vector?
14935     if (isNullConstant(Op) || isNullFPConstant(Op)) {
14936       UsesZeroVector = true;
14937       VectorMask[i] = 0;
14938       continue;
14939     }
14940 
14941     // Not an undef or zero. If the input is something other than an
14942     // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
14943     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14944         !isa<ConstantSDNode>(Op.getOperand(1)))
14945       return SDValue();
14946     SDValue ExtractedFromVec = Op.getOperand(0);
14947 
14948     APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
14949     if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
14950       return SDValue();
14951 
14952     // All inputs must have the same element type as the output.
14953     if (VT.getVectorElementType() !=
14954         ExtractedFromVec.getValueType().getVectorElementType())
14955       return SDValue();
14956 
14957     // Have we seen this input vector before?
14958     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14959     // a map back from SDValues to numbers isn't worth it.
14960     unsigned Idx = std::distance(
14961         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14962     if (Idx == VecIn.size())
14963       VecIn.push_back(ExtractedFromVec);
14964 
14965     VectorMask[i] = Idx;
14966   }
14967 
14968   // If we didn't find at least one input vector, bail out.
14969   if (VecIn.size() < 2)
14970     return SDValue();
14971 
14972   // If all the Operands of BUILD_VECTOR extract from same
14973   // vector, then split the vector efficiently based on the maximum
14974   // vector access index and adjust the VectorMask and
14975   // VecIn accordingly.
14976   if (VecIn.size() == 2) {
14977     unsigned MaxIndex = 0;
14978     unsigned NearestPow2 = 0;
14979     SDValue Vec = VecIn.back();
14980     EVT InVT = Vec.getValueType();
14981     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14982     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
14983 
14984     for (unsigned i = 0; i < NumElems; i++) {
14985       if (VectorMask[i] <= 0)
14986         continue;
14987       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
14988       IndexVec[i] = Index;
14989       MaxIndex = std::max(MaxIndex, Index);
14990     }
14991 
14992     NearestPow2 = PowerOf2Ceil(MaxIndex);
14993     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
14994         NumElems * 2 < NearestPow2) {
14995       unsigned SplitSize = NearestPow2 / 2;
14996       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
14997                                      InVT.getVectorElementType(), SplitSize);
14998       if (TLI.isTypeLegal(SplitVT)) {
14999         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15000                                      DAG.getConstant(SplitSize, DL, IdxTy));
15001         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15002                                      DAG.getConstant(0, DL, IdxTy));
15003         VecIn.pop_back();
15004         VecIn.push_back(VecIn1);
15005         VecIn.push_back(VecIn2);
15006 
15007         for (unsigned i = 0; i < NumElems; i++) {
15008           if (VectorMask[i] <= 0)
15009             continue;
15010           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
15011         }
15012       }
15013     }
15014   }
15015 
15016   // TODO: We want to sort the vectors by descending length, so that adjacent
15017   // pairs have similar length, and the longer vector is always first in the
15018   // pair.
15019 
15020   // TODO: Should this fire if some of the input vectors has illegal type (like
15021   // it does now), or should we let legalization run its course first?
15022 
15023   // Shuffle phase:
15024   // Take pairs of vectors, and shuffle them so that the result has elements
15025   // from these vectors in the correct places.
15026   // For example, given:
15027   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
15028   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
15029   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
15030   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
15031   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
15032   // We will generate:
15033   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
15034   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
15035   SmallVector<SDValue, 4> Shuffles;
15036   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
15037     unsigned LeftIdx = 2 * In + 1;
15038     SDValue VecLeft = VecIn[LeftIdx];
15039     SDValue VecRight =
15040         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
15041 
15042     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
15043                                                 VecRight, LeftIdx))
15044       Shuffles.push_back(Shuffle);
15045     else
15046       return SDValue();
15047   }
15048 
15049   // If we need the zero vector as an "ingredient" in the blend tree, add it
15050   // to the list of shuffles.
15051   if (UsesZeroVector)
15052     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
15053                                       : DAG.getConstantFP(0.0, DL, VT));
15054 
15055   // If we only have one shuffle, we're done.
15056   if (Shuffles.size() == 1)
15057     return Shuffles[0];
15058 
15059   // Update the vector mask to point to the post-shuffle vectors.
15060   for (int &Vec : VectorMask)
15061     if (Vec == 0)
15062       Vec = Shuffles.size() - 1;
15063     else
15064       Vec = (Vec - 1) / 2;
15065 
15066   // More than one shuffle. Generate a binary tree of blends, e.g. if from
15067   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
15068   // generate:
15069   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
15070   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
15071   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
15072   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
15073   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
15074   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
15075   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
15076 
15077   // Make sure the initial size of the shuffle list is even.
15078   if (Shuffles.size() % 2)
15079     Shuffles.push_back(DAG.getUNDEF(VT));
15080 
15081   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
15082     if (CurSize % 2) {
15083       Shuffles[CurSize] = DAG.getUNDEF(VT);
15084       CurSize++;
15085     }
15086     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
15087       int Left = 2 * In;
15088       int Right = 2 * In + 1;
15089       SmallVector<int, 8> Mask(NumElems, -1);
15090       for (unsigned i = 0; i != NumElems; ++i) {
15091         if (VectorMask[i] == Left) {
15092           Mask[i] = i;
15093           VectorMask[i] = In;
15094         } else if (VectorMask[i] == Right) {
15095           Mask[i] = i + NumElems;
15096           VectorMask[i] = In;
15097         }
15098       }
15099 
15100       Shuffles[In] =
15101           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
15102     }
15103   }
15104   return Shuffles[0];
15105 }
15106 
15107 // Try to turn a build vector of zero extends of extract vector elts into a
15108 // a vector zero extend and possibly an extract subvector.
15109 // TODO: Support sign extend or any extend?
15110 // TODO: Allow undef elements?
15111 // TODO: Don't require the extracts to start at element 0.
15112 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
15113   if (LegalOperations)
15114     return SDValue();
15115 
15116   EVT VT = N->getValueType(0);
15117 
15118   SDValue Op0 = N->getOperand(0);
15119   auto checkElem = [&](SDValue Op) -> int64_t {
15120     if (Op.getOpcode() == ISD::ZERO_EXTEND &&
15121         Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15122         Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
15123       if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
15124         return C->getZExtValue();
15125     return -1;
15126   };
15127 
15128   // Make sure the first element matches
15129   // (zext (extract_vector_elt X, C))
15130   int64_t Offset = checkElem(Op0);
15131   if (Offset < 0)
15132     return SDValue();
15133 
15134   unsigned NumElems = N->getNumOperands();
15135   SDValue In = Op0.getOperand(0).getOperand(0);
15136   EVT InSVT = In.getValueType().getScalarType();
15137   EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
15138 
15139   // Don't create an illegal input type after type legalization.
15140   if (LegalTypes && !TLI.isTypeLegal(InVT))
15141     return SDValue();
15142 
15143   // Ensure all the elements come from the same vector and are adjacent.
15144   for (unsigned i = 1; i != NumElems; ++i) {
15145     if ((Offset + i) != checkElem(N->getOperand(i)))
15146       return SDValue();
15147   }
15148 
15149   SDLoc DL(N);
15150   In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
15151                    Op0.getOperand(0).getOperand(1));
15152   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In);
15153 }
15154 
15155 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
15156   EVT VT = N->getValueType(0);
15157 
15158   // A vector built entirely of undefs is undef.
15159   if (ISD::allOperandsUndef(N))
15160     return DAG.getUNDEF(VT);
15161 
15162   // If this is a splat of a bitcast from another vector, change to a
15163   // concat_vector.
15164   // For example:
15165   //   (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
15166   //     (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
15167   //
15168   // If X is a build_vector itself, the concat can become a larger build_vector.
15169   // TODO: Maybe this is useful for non-splat too?
15170   if (!LegalOperations) {
15171     if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
15172       Splat = peekThroughBitcast(Splat);
15173       EVT SrcVT = Splat.getValueType();
15174       if (SrcVT.isVector()) {
15175         unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
15176         EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
15177                                      SrcVT.getVectorElementType(), NumElts);
15178         SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
15179         SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), NewVT, Ops);
15180         return DAG.getBitcast(VT, Concat);
15181       }
15182     }
15183   }
15184 
15185   // Check if we can express BUILD VECTOR via subvector extract.
15186   if (!LegalTypes && (N->getNumOperands() > 1)) {
15187     SDValue Op0 = N->getOperand(0);
15188     auto checkElem = [&](SDValue Op) -> uint64_t {
15189       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
15190           (Op0.getOperand(0) == Op.getOperand(0)))
15191         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
15192           return CNode->getZExtValue();
15193       return -1;
15194     };
15195 
15196     int Offset = checkElem(Op0);
15197     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
15198       if (Offset + i != checkElem(N->getOperand(i))) {
15199         Offset = -1;
15200         break;
15201       }
15202     }
15203 
15204     if ((Offset == 0) &&
15205         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
15206       return Op0.getOperand(0);
15207     if ((Offset != -1) &&
15208         ((Offset % N->getValueType(0).getVectorNumElements()) ==
15209          0)) // IDX must be multiple of output size.
15210       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
15211                          Op0.getOperand(0), Op0.getOperand(1));
15212   }
15213 
15214   if (SDValue V = convertBuildVecZextToZext(N))
15215     return V;
15216 
15217   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
15218     return V;
15219 
15220   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
15221     return V;
15222 
15223   if (SDValue V = reduceBuildVecToShuffle(N))
15224     return V;
15225 
15226   return SDValue();
15227 }
15228 
15229 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
15230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15231   EVT OpVT = N->getOperand(0).getValueType();
15232 
15233   // If the operands are legal vectors, leave them alone.
15234   if (TLI.isTypeLegal(OpVT))
15235     return SDValue();
15236 
15237   SDLoc DL(N);
15238   EVT VT = N->getValueType(0);
15239   SmallVector<SDValue, 8> Ops;
15240 
15241   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
15242   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15243 
15244   // Keep track of what we encounter.
15245   bool AnyInteger = false;
15246   bool AnyFP = false;
15247   for (const SDValue &Op : N->ops()) {
15248     if (ISD::BITCAST == Op.getOpcode() &&
15249         !Op.getOperand(0).getValueType().isVector())
15250       Ops.push_back(Op.getOperand(0));
15251     else if (ISD::UNDEF == Op.getOpcode())
15252       Ops.push_back(ScalarUndef);
15253     else
15254       return SDValue();
15255 
15256     // Note whether we encounter an integer or floating point scalar.
15257     // If it's neither, bail out, it could be something weird like x86mmx.
15258     EVT LastOpVT = Ops.back().getValueType();
15259     if (LastOpVT.isFloatingPoint())
15260       AnyFP = true;
15261     else if (LastOpVT.isInteger())
15262       AnyInteger = true;
15263     else
15264       return SDValue();
15265   }
15266 
15267   // If any of the operands is a floating point scalar bitcast to a vector,
15268   // use floating point types throughout, and bitcast everything.
15269   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
15270   if (AnyFP) {
15271     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
15272     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15273     if (AnyInteger) {
15274       for (SDValue &Op : Ops) {
15275         if (Op.getValueType() == SVT)
15276           continue;
15277         if (Op.isUndef())
15278           Op = ScalarUndef;
15279         else
15280           Op = DAG.getBitcast(SVT, Op);
15281       }
15282     }
15283   }
15284 
15285   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15286                                VT.getSizeInBits() / SVT.getSizeInBits());
15287   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15288 }
15289 
15290 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15291 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15292 // most two distinct vectors the same size as the result, attempt to turn this
15293 // into a legal shuffle.
15294 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15295   EVT VT = N->getValueType(0);
15296   EVT OpVT = N->getOperand(0).getValueType();
15297   int NumElts = VT.getVectorNumElements();
15298   int NumOpElts = OpVT.getVectorNumElements();
15299 
15300   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15301   SmallVector<int, 8> Mask;
15302 
15303   for (SDValue Op : N->ops()) {
15304     // Peek through any bitcast.
15305     Op = peekThroughBitcast(Op);
15306 
15307     // UNDEF nodes convert to UNDEF shuffle mask values.
15308     if (Op.isUndef()) {
15309       Mask.append((unsigned)NumOpElts, -1);
15310       continue;
15311     }
15312 
15313     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15314       return SDValue();
15315 
15316     // What vector are we extracting the subvector from and at what index?
15317     SDValue ExtVec = Op.getOperand(0);
15318 
15319     // We want the EVT of the original extraction to correctly scale the
15320     // extraction index.
15321     EVT ExtVT = ExtVec.getValueType();
15322 
15323     // Peek through any bitcast.
15324     ExtVec = peekThroughBitcast(ExtVec);
15325 
15326     // UNDEF nodes convert to UNDEF shuffle mask values.
15327     if (ExtVec.isUndef()) {
15328       Mask.append((unsigned)NumOpElts, -1);
15329       continue;
15330     }
15331 
15332     if (!isa<ConstantSDNode>(Op.getOperand(1)))
15333       return SDValue();
15334     int ExtIdx = Op.getConstantOperandVal(1);
15335 
15336     // Ensure that we are extracting a subvector from a vector the same
15337     // size as the result.
15338     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15339       return SDValue();
15340 
15341     // Scale the subvector index to account for any bitcast.
15342     int NumExtElts = ExtVT.getVectorNumElements();
15343     if (0 == (NumExtElts % NumElts))
15344       ExtIdx /= (NumExtElts / NumElts);
15345     else if (0 == (NumElts % NumExtElts))
15346       ExtIdx *= (NumElts / NumExtElts);
15347     else
15348       return SDValue();
15349 
15350     // At most we can reference 2 inputs in the final shuffle.
15351     if (SV0.isUndef() || SV0 == ExtVec) {
15352       SV0 = ExtVec;
15353       for (int i = 0; i != NumOpElts; ++i)
15354         Mask.push_back(i + ExtIdx);
15355     } else if (SV1.isUndef() || SV1 == ExtVec) {
15356       SV1 = ExtVec;
15357       for (int i = 0; i != NumOpElts; ++i)
15358         Mask.push_back(i + ExtIdx + NumElts);
15359     } else {
15360       return SDValue();
15361     }
15362   }
15363 
15364   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15365     return SDValue();
15366 
15367   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15368                               DAG.getBitcast(VT, SV1), Mask);
15369 }
15370 
15371 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15372   // If we only have one input vector, we don't need to do any concatenation.
15373   if (N->getNumOperands() == 1)
15374     return N->getOperand(0);
15375 
15376   // Check if all of the operands are undefs.
15377   EVT VT = N->getValueType(0);
15378   if (ISD::allOperandsUndef(N))
15379     return DAG.getUNDEF(VT);
15380 
15381   // Optimize concat_vectors where all but the first of the vectors are undef.
15382   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15383         return Op.isUndef();
15384       })) {
15385     SDValue In = N->getOperand(0);
15386     assert(In.getValueType().isVector() && "Must concat vectors");
15387 
15388     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15389     if (In->getOpcode() == ISD::BITCAST &&
15390         !In->getOperand(0).getValueType().isVector()) {
15391       SDValue Scalar = In->getOperand(0);
15392 
15393       // If the bitcast type isn't legal, it might be a trunc of a legal type;
15394       // look through the trunc so we can still do the transform:
15395       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15396       if (Scalar->getOpcode() == ISD::TRUNCATE &&
15397           !TLI.isTypeLegal(Scalar.getValueType()) &&
15398           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15399         Scalar = Scalar->getOperand(0);
15400 
15401       EVT SclTy = Scalar->getValueType(0);
15402 
15403       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15404         return SDValue();
15405 
15406       // Bail out if the vector size is not a multiple of the scalar size.
15407       if (VT.getSizeInBits() % SclTy.getSizeInBits())
15408         return SDValue();
15409 
15410       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15411       if (VNTNumElms < 2)
15412         return SDValue();
15413 
15414       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15415       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15416         return SDValue();
15417 
15418       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15419       return DAG.getBitcast(VT, Res);
15420     }
15421   }
15422 
15423   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15424   // We have already tested above for an UNDEF only concatenation.
15425   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15426   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15427   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15428     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15429   };
15430   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15431     SmallVector<SDValue, 8> Opnds;
15432     EVT SVT = VT.getScalarType();
15433 
15434     EVT MinVT = SVT;
15435     if (!SVT.isFloatingPoint()) {
15436       // If BUILD_VECTOR are from built from integer, they may have different
15437       // operand types. Get the smallest type and truncate all operands to it.
15438       bool FoundMinVT = false;
15439       for (const SDValue &Op : N->ops())
15440         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15441           EVT OpSVT = Op.getOperand(0).getValueType();
15442           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15443           FoundMinVT = true;
15444         }
15445       assert(FoundMinVT && "Concat vector type mismatch");
15446     }
15447 
15448     for (const SDValue &Op : N->ops()) {
15449       EVT OpVT = Op.getValueType();
15450       unsigned NumElts = OpVT.getVectorNumElements();
15451 
15452       if (ISD::UNDEF == Op.getOpcode())
15453         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15454 
15455       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15456         if (SVT.isFloatingPoint()) {
15457           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
15458           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15459         } else {
15460           for (unsigned i = 0; i != NumElts; ++i)
15461             Opnds.push_back(
15462                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15463         }
15464       }
15465     }
15466 
15467     assert(VT.getVectorNumElements() == Opnds.size() &&
15468            "Concat vector type mismatch");
15469     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15470   }
15471 
15472   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15473   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15474     return V;
15475 
15476   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15477   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15478     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15479       return V;
15480 
15481   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15482   // nodes often generate nop CONCAT_VECTOR nodes.
15483   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15484   // place the incoming vectors at the exact same location.
15485   SDValue SingleSource = SDValue();
15486   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15487 
15488   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15489     SDValue Op = N->getOperand(i);
15490 
15491     if (Op.isUndef())
15492       continue;
15493 
15494     // Check if this is the identity extract:
15495     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15496       return SDValue();
15497 
15498     // Find the single incoming vector for the extract_subvector.
15499     if (SingleSource.getNode()) {
15500       if (Op.getOperand(0) != SingleSource)
15501         return SDValue();
15502     } else {
15503       SingleSource = Op.getOperand(0);
15504 
15505       // Check the source type is the same as the type of the result.
15506       // If not, this concat may extend the vector, so we can not
15507       // optimize it away.
15508       if (SingleSource.getValueType() != N->getValueType(0))
15509         return SDValue();
15510     }
15511 
15512     unsigned IdentityIndex = i * PartNumElem;
15513     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15514     // The extract index must be constant.
15515     if (!CS)
15516       return SDValue();
15517 
15518     // Check that we are reading from the identity index.
15519     if (CS->getZExtValue() != IdentityIndex)
15520       return SDValue();
15521   }
15522 
15523   if (SingleSource.getNode())
15524     return SingleSource;
15525 
15526   return SDValue();
15527 }
15528 
15529 /// If we are extracting a subvector produced by a wide binary operator with at
15530 /// at least one operand that was the result of a vector concatenation, then try
15531 /// to use the narrow vector operands directly to avoid the concatenation and
15532 /// extraction.
15533 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15534   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15535   // some of these bailouts with other transforms.
15536 
15537   // The extract index must be a constant, so we can map it to a concat operand.
15538   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15539   if (!ExtractIndex)
15540     return SDValue();
15541 
15542   // Only handle the case where we are doubling and then halving. A larger ratio
15543   // may require more than two narrow binops to replace the wide binop.
15544   EVT VT = Extract->getValueType(0);
15545   unsigned NumElems = VT.getVectorNumElements();
15546   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15547          "Extract index is not a multiple of the vector length.");
15548   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15549     return SDValue();
15550 
15551   // We are looking for an optionally bitcasted wide vector binary operator
15552   // feeding an extract subvector.
15553   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15554 
15555   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15556   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15557   // flavors, but no other 256-bit integer support. This could be extended to
15558   // handle any binop, but that may require fixing/adding other folds to avoid
15559   // codegen regressions.
15560   unsigned BOpcode = BinOp.getOpcode();
15561   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15562     return SDValue();
15563 
15564   // The binop must be a vector type, so we can chop it in half.
15565   EVT WideBVT = BinOp.getValueType();
15566   if (!WideBVT.isVector())
15567     return SDValue();
15568 
15569   // Bail out if the target does not support a narrower version of the binop.
15570   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15571                                    WideBVT.getVectorNumElements() / 2);
15572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15573   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15574     return SDValue();
15575 
15576   // Peek through bitcasts of the binary operator operands if needed.
15577   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15578   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15579 
15580   // We need at least one concatenation operation of a binop operand to make
15581   // this transform worthwhile. The concat must double the input vector sizes.
15582   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15583   bool ConcatL =
15584       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15585   bool ConcatR =
15586       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15587   if (!ConcatL && !ConcatR)
15588     return SDValue();
15589 
15590   // If one of the binop operands was not the result of a concat, we must
15591   // extract a half-sized operand for our new narrow binop. We can't just reuse
15592   // the original extract index operand because we may have bitcasted.
15593   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15594   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15595   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15596   SDLoc DL(Extract);
15597 
15598   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15599   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15600   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15601   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15602                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15603                                     BinOp.getOperand(0),
15604                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15605 
15606   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15607                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15608                                     BinOp.getOperand(1),
15609                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15610 
15611   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15612   return DAG.getBitcast(VT, NarrowBinOp);
15613 }
15614 
15615 /// If we are extracting a subvector from a wide vector load, convert to a
15616 /// narrow load to eliminate the extraction:
15617 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15618 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15619   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15620   if (DAG.getDataLayout().isBigEndian())
15621     return SDValue();
15622 
15623   // TODO: The one-use check is overly conservative. Check the cost of the
15624   // extract instead or remove that condition entirely.
15625   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15626   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15627   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15628       !ExtIdx)
15629     return SDValue();
15630 
15631   // The narrow load will be offset from the base address of the old load if
15632   // we are extracting from something besides index 0 (little-endian).
15633   EVT VT = Extract->getValueType(0);
15634   SDLoc DL(Extract);
15635   SDValue BaseAddr = Ld->getOperand(1);
15636   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15637 
15638   // TODO: Use "BaseIndexOffset" to make this more effective.
15639   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15640   MachineFunction &MF = DAG.getMachineFunction();
15641   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15642                                                    VT.getStoreSize());
15643   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15644   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15645   return NewLd;
15646 }
15647 
15648 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15649   EVT NVT = N->getValueType(0);
15650   SDValue V = N->getOperand(0);
15651 
15652   // Extract from UNDEF is UNDEF.
15653   if (V.isUndef())
15654     return DAG.getUNDEF(NVT);
15655 
15656   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15657     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15658       return NarrowLoad;
15659 
15660   // Combine:
15661   //    (extract_subvec (concat V1, V2, ...), i)
15662   // Into:
15663   //    Vi if possible
15664   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15665   // type.
15666   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15667       isa<ConstantSDNode>(N->getOperand(1)) &&
15668       V->getOperand(0).getValueType() == NVT) {
15669     unsigned Idx = N->getConstantOperandVal(1);
15670     unsigned NumElems = NVT.getVectorNumElements();
15671     assert((Idx % NumElems) == 0 &&
15672            "IDX in concat is not a multiple of the result vector length.");
15673     return V->getOperand(Idx / NumElems);
15674   }
15675 
15676   // Skip bitcasting
15677   V = peekThroughBitcast(V);
15678 
15679   // If the input is a build vector. Try to make a smaller build vector.
15680   if (V->getOpcode() == ISD::BUILD_VECTOR) {
15681     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15682       EVT InVT = V->getValueType(0);
15683       unsigned ExtractSize = NVT.getSizeInBits();
15684       unsigned EltSize = InVT.getScalarSizeInBits();
15685       // Only do this if we won't split any elements.
15686       if (ExtractSize % EltSize == 0) {
15687         unsigned NumElems = ExtractSize / EltSize;
15688         EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15689                                          InVT.getVectorElementType(), NumElems);
15690         if ((Level < AfterLegalizeDAG ||
15691              TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15692             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15693           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15694                             EltSize;
15695 
15696           // Extract the pieces from the original build_vector.
15697           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15698                                             makeArrayRef(V->op_begin() + IdxVal,
15699                                                          NumElems));
15700           return DAG.getBitcast(NVT, BuildVec);
15701         }
15702       }
15703     }
15704   }
15705 
15706   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15707     // Handle only simple case where vector being inserted and vector
15708     // being extracted are of same size.
15709     EVT SmallVT = V->getOperand(1).getValueType();
15710     if (!NVT.bitsEq(SmallVT))
15711       return SDValue();
15712 
15713     // Only handle cases where both indexes are constants.
15714     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15715     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15716 
15717     if (InsIdx && ExtIdx) {
15718       // Combine:
15719       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15720       // Into:
15721       //    indices are equal or bit offsets are equal => V1
15722       //    otherwise => (extract_subvec V1, ExtIdx)
15723       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15724           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15725         return DAG.getBitcast(NVT, V->getOperand(1));
15726       return DAG.getNode(
15727           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15728           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15729           N->getOperand(1));
15730     }
15731   }
15732 
15733   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15734     return NarrowBOp;
15735 
15736   return SDValue();
15737 }
15738 
15739 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15740 // or turn a shuffle of a single concat into simpler shuffle then concat.
15741 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15742   EVT VT = N->getValueType(0);
15743   unsigned NumElts = VT.getVectorNumElements();
15744 
15745   SDValue N0 = N->getOperand(0);
15746   SDValue N1 = N->getOperand(1);
15747   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15748 
15749   SmallVector<SDValue, 4> Ops;
15750   EVT ConcatVT = N0.getOperand(0).getValueType();
15751   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15752   unsigned NumConcats = NumElts / NumElemsPerConcat;
15753 
15754   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15755   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15756   // half vector elements.
15757   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15758       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15759                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15760     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15761                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15762     N1 = DAG.getUNDEF(ConcatVT);
15763     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15764   }
15765 
15766   // Look at every vector that's inserted. We're looking for exact
15767   // subvector-sized copies from a concatenated vector
15768   for (unsigned I = 0; I != NumConcats; ++I) {
15769     // Make sure we're dealing with a copy.
15770     unsigned Begin = I * NumElemsPerConcat;
15771     bool AllUndef = true, NoUndef = true;
15772     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15773       if (SVN->getMaskElt(J) >= 0)
15774         AllUndef = false;
15775       else
15776         NoUndef = false;
15777     }
15778 
15779     if (NoUndef) {
15780       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15781         return SDValue();
15782 
15783       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15784         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15785           return SDValue();
15786 
15787       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15788       if (FirstElt < N0.getNumOperands())
15789         Ops.push_back(N0.getOperand(FirstElt));
15790       else
15791         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15792 
15793     } else if (AllUndef) {
15794       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15795     } else { // Mixed with general masks and undefs, can't do optimization.
15796       return SDValue();
15797     }
15798   }
15799 
15800   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15801 }
15802 
15803 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15804 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15805 //
15806 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15807 // a simplification in some sense, but it isn't appropriate in general: some
15808 // BUILD_VECTORs are substantially cheaper than others. The general case
15809 // of a BUILD_VECTOR requires inserting each element individually (or
15810 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15811 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15812 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15813 // are undef lowers to a small number of element insertions.
15814 //
15815 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15816 // We don't fold shuffles where one side is a non-zero constant, and we don't
15817 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15818 // non-constant operands. This seems to work out reasonably well in practice.
15819 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15820                                        SelectionDAG &DAG,
15821                                        const TargetLowering &TLI) {
15822   EVT VT = SVN->getValueType(0);
15823   unsigned NumElts = VT.getVectorNumElements();
15824   SDValue N0 = SVN->getOperand(0);
15825   SDValue N1 = SVN->getOperand(1);
15826 
15827   if (!N0->hasOneUse() || !N1->hasOneUse())
15828     return SDValue();
15829 
15830   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15831   // discussed above.
15832   if (!N1.isUndef()) {
15833     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15834     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15835     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15836       return SDValue();
15837     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15838       return SDValue();
15839   }
15840 
15841   // If both inputs are splats of the same value then we can safely merge this
15842   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
15843   bool IsSplat = false;
15844   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
15845   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
15846   if (BV0 && BV1)
15847     if (SDValue Splat0 = BV0->getSplatValue())
15848       IsSplat = (Splat0 == BV1->getSplatValue());
15849 
15850   SmallVector<SDValue, 8> Ops;
15851   SmallSet<SDValue, 16> DuplicateOps;
15852   for (int M : SVN->getMask()) {
15853     SDValue Op = DAG.getUNDEF(VT.getScalarType());
15854     if (M >= 0) {
15855       int Idx = M < (int)NumElts ? M : M - NumElts;
15856       SDValue &S = (M < (int)NumElts ? N0 : N1);
15857       if (S.getOpcode() == ISD::BUILD_VECTOR) {
15858         Op = S.getOperand(Idx);
15859       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15860         assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
15861         Op = S.getOperand(0);
15862       } else {
15863         // Operand can't be combined - bail out.
15864         return SDValue();
15865       }
15866     }
15867 
15868     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
15869     // generating a splat; semantically, this is fine, but it's likely to
15870     // generate low-quality code if the target can't reconstruct an appropriate
15871     // shuffle.
15872     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15873       if (!IsSplat && !DuplicateOps.insert(Op).second)
15874         return SDValue();
15875 
15876     Ops.push_back(Op);
15877   }
15878 
15879   // BUILD_VECTOR requires all inputs to be of the same type, find the
15880   // maximum type and extend them all.
15881   EVT SVT = VT.getScalarType();
15882   if (SVT.isInteger())
15883     for (SDValue &Op : Ops)
15884       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15885   if (SVT != VT.getScalarType())
15886     for (SDValue &Op : Ops)
15887       Op = TLI.isZExtFree(Op.getValueType(), SVT)
15888                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15889                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15890   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15891 }
15892 
15893 // Match shuffles that can be converted to any_vector_extend_in_reg.
15894 // This is often generated during legalization.
15895 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15896 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15897 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15898                                             SelectionDAG &DAG,
15899                                             const TargetLowering &TLI,
15900                                             bool LegalOperations,
15901                                             bool LegalTypes) {
15902   EVT VT = SVN->getValueType(0);
15903   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15904 
15905   // TODO Add support for big-endian when we have a test case.
15906   if (!VT.isInteger() || IsBigEndian)
15907     return SDValue();
15908 
15909   unsigned NumElts = VT.getVectorNumElements();
15910   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15911   ArrayRef<int> Mask = SVN->getMask();
15912   SDValue N0 = SVN->getOperand(0);
15913 
15914   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15915   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15916     for (unsigned i = 0; i != NumElts; ++i) {
15917       if (Mask[i] < 0)
15918         continue;
15919       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15920         continue;
15921       return false;
15922     }
15923     return true;
15924   };
15925 
15926   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15927   // power-of-2 extensions as they are the most likely.
15928   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15929     // Check for non power of 2 vector sizes
15930     if (NumElts % Scale != 0)
15931       continue;
15932     if (!isAnyExtend(Scale))
15933       continue;
15934 
15935     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15936     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15937     if (!LegalTypes || TLI.isTypeLegal(OutVT))
15938       if (!LegalOperations ||
15939           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15940         return DAG.getBitcast(VT,
15941                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15942   }
15943 
15944   return SDValue();
15945 }
15946 
15947 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15948 // each source element of a large type into the lowest elements of a smaller
15949 // destination type. This is often generated during legalization.
15950 // If the source node itself was a '*_extend_vector_inreg' node then we should
15951 // then be able to remove it.
15952 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15953                                         SelectionDAG &DAG) {
15954   EVT VT = SVN->getValueType(0);
15955   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15956 
15957   // TODO Add support for big-endian when we have a test case.
15958   if (!VT.isInteger() || IsBigEndian)
15959     return SDValue();
15960 
15961   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
15962 
15963   unsigned Opcode = N0.getOpcode();
15964   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15965       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15966       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15967     return SDValue();
15968 
15969   SDValue N00 = N0.getOperand(0);
15970   ArrayRef<int> Mask = SVN->getMask();
15971   unsigned NumElts = VT.getVectorNumElements();
15972   unsigned EltSizeInBits = VT.getScalarSizeInBits();
15973   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15974   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15975 
15976   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15977     return SDValue();
15978   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15979 
15980   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15981   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15982   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15983   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15984     for (unsigned i = 0; i != NumElts; ++i) {
15985       if (Mask[i] < 0)
15986         continue;
15987       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15988         continue;
15989       return false;
15990     }
15991     return true;
15992   };
15993 
15994   // At the moment we just handle the case where we've truncated back to the
15995   // same size as before the extension.
15996   // TODO: handle more extension/truncation cases as cases arise.
15997   if (EltSizeInBits != ExtSrcSizeInBits)
15998     return SDValue();
15999 
16000   // We can remove *extend_vector_inreg only if the truncation happens at
16001   // the same scale as the extension.
16002   if (isTruncate(ExtScale))
16003     return DAG.getBitcast(VT, N00);
16004 
16005   return SDValue();
16006 }
16007 
16008 // Combine shuffles of splat-shuffles of the form:
16009 // shuffle (shuffle V, undef, splat-mask), undef, M
16010 // If splat-mask contains undef elements, we need to be careful about
16011 // introducing undef's in the folded mask which are not the result of composing
16012 // the masks of the shuffles.
16013 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
16014                                      ShuffleVectorSDNode *Splat,
16015                                      SelectionDAG &DAG) {
16016   ArrayRef<int> SplatMask = Splat->getMask();
16017   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
16018 
16019   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
16020   // every undef mask element in the splat-shuffle has a corresponding undef
16021   // element in the user-shuffle's mask or if the composition of mask elements
16022   // would result in undef.
16023   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
16024   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
16025   //   In this case it is not legal to simplify to the splat-shuffle because we
16026   //   may be exposing the users of the shuffle an undef element at index 1
16027   //   which was not there before the combine.
16028   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
16029   //   In this case the composition of masks yields SplatMask, so it's ok to
16030   //   simplify to the splat-shuffle.
16031   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
16032   //   In this case the composed mask includes all undef elements of SplatMask
16033   //   and in addition sets element zero to undef. It is safe to simplify to
16034   //   the splat-shuffle.
16035   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
16036                                        ArrayRef<int> SplatMask) {
16037     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
16038       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
16039           SplatMask[UserMask[i]] != -1)
16040         return false;
16041     return true;
16042   };
16043   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
16044     return SDValue(Splat, 0);
16045 
16046   // Create a new shuffle with a mask that is composed of the two shuffles'
16047   // masks.
16048   SmallVector<int, 32> NewMask;
16049   for (int Idx : UserMask)
16050     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
16051 
16052   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
16053                               Splat->getOperand(0), Splat->getOperand(1),
16054                               NewMask);
16055 }
16056 
16057 /// If the shuffle mask is taking exactly one element from the first vector
16058 /// operand and passing through all other elements from the second vector
16059 /// operand, return the index of the mask element that is choosing an element
16060 /// from the first operand. Otherwise, return -1.
16061 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
16062   int MaskSize = Mask.size();
16063   int EltFromOp0 = -1;
16064   // TODO: This does not match if there are undef elements in the shuffle mask.
16065   // Should we ignore undefs in the shuffle mask instead? The trade-off is
16066   // removing an instruction (a shuffle), but losing the knowledge that some
16067   // vector lanes are not needed.
16068   for (int i = 0; i != MaskSize; ++i) {
16069     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
16070       // We're looking for a shuffle of exactly one element from operand 0.
16071       if (EltFromOp0 != -1)
16072         return -1;
16073       EltFromOp0 = i;
16074     } else if (Mask[i] != i + MaskSize) {
16075       // Nothing from operand 1 can change lanes.
16076       return -1;
16077     }
16078   }
16079   return EltFromOp0;
16080 }
16081 
16082 /// If a shuffle inserts exactly one element from a source vector operand into
16083 /// another vector operand and we can access the specified element as a scalar,
16084 /// then we can eliminate the shuffle.
16085 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
16086                                       SelectionDAG &DAG) {
16087   // First, check if we are taking one element of a vector and shuffling that
16088   // element into another vector.
16089   ArrayRef<int> Mask = Shuf->getMask();
16090   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
16091   SDValue Op0 = Shuf->getOperand(0);
16092   SDValue Op1 = Shuf->getOperand(1);
16093   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
16094   if (ShufOp0Index == -1) {
16095     // Commute mask and check again.
16096     ShuffleVectorSDNode::commuteMask(CommutedMask);
16097     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
16098     if (ShufOp0Index == -1)
16099       return SDValue();
16100     // Commute operands to match the commuted shuffle mask.
16101     std::swap(Op0, Op1);
16102     Mask = CommutedMask;
16103   }
16104 
16105   // The shuffle inserts exactly one element from operand 0 into operand 1.
16106   // Now see if we can access that element as a scalar via a real insert element
16107   // instruction.
16108   // TODO: We can try harder to locate the element as a scalar. Examples: it
16109   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
16110   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
16111          "Shuffle mask value must be from operand 0");
16112   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
16113     return SDValue();
16114 
16115   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
16116   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
16117     return SDValue();
16118 
16119   // There's an existing insertelement with constant insertion index, so we
16120   // don't need to check the legality/profitability of a replacement operation
16121   // that differs at most in the constant value. The target should be able to
16122   // lower any of those in a similar way. If not, legalization will expand this
16123   // to a scalar-to-vector plus shuffle.
16124   //
16125   // Note that the shuffle may move the scalar from the position that the insert
16126   // element used. Therefore, our new insert element occurs at the shuffle's
16127   // mask index value, not the insert's index value.
16128   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
16129   SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
16130                                         Op0.getOperand(2).getValueType());
16131   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
16132                      Op1, Op0.getOperand(1), NewInsIndex);
16133 }
16134 
16135 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
16136   EVT VT = N->getValueType(0);
16137   unsigned NumElts = VT.getVectorNumElements();
16138 
16139   SDValue N0 = N->getOperand(0);
16140   SDValue N1 = N->getOperand(1);
16141 
16142   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
16143 
16144   // Canonicalize shuffle undef, undef -> undef
16145   if (N0.isUndef() && N1.isUndef())
16146     return DAG.getUNDEF(VT);
16147 
16148   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16149 
16150   // Canonicalize shuffle v, v -> v, undef
16151   if (N0 == N1) {
16152     SmallVector<int, 8> NewMask;
16153     for (unsigned i = 0; i != NumElts; ++i) {
16154       int Idx = SVN->getMaskElt(i);
16155       if (Idx >= (int)NumElts) Idx -= NumElts;
16156       NewMask.push_back(Idx);
16157     }
16158     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
16159   }
16160 
16161   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
16162   if (N0.isUndef())
16163     return DAG.getCommutedVectorShuffle(*SVN);
16164 
16165   // Remove references to rhs if it is undef
16166   if (N1.isUndef()) {
16167     bool Changed = false;
16168     SmallVector<int, 8> NewMask;
16169     for (unsigned i = 0; i != NumElts; ++i) {
16170       int Idx = SVN->getMaskElt(i);
16171       if (Idx >= (int)NumElts) {
16172         Idx = -1;
16173         Changed = true;
16174       }
16175       NewMask.push_back(Idx);
16176     }
16177     if (Changed)
16178       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16179   }
16180 
16181   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16182     return InsElt;
16183 
16184   // A shuffle of a single vector that is a splat can always be folded.
16185   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16186     if (N1->isUndef() && N0Shuf->isSplat())
16187       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16188 
16189   // If it is a splat, check if the argument vector is another splat or a
16190   // build_vector.
16191   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16192     SDNode *V = N0.getNode();
16193 
16194     // If this is a bit convert that changes the element type of the vector but
16195     // not the number of vector elements, look through it.  Be careful not to
16196     // look though conversions that change things like v4f32 to v2f64.
16197     if (V->getOpcode() == ISD::BITCAST) {
16198       SDValue ConvInput = V->getOperand(0);
16199       if (ConvInput.getValueType().isVector() &&
16200           ConvInput.getValueType().getVectorNumElements() == NumElts)
16201         V = ConvInput.getNode();
16202     }
16203 
16204     if (V->getOpcode() == ISD::BUILD_VECTOR) {
16205       assert(V->getNumOperands() == NumElts &&
16206              "BUILD_VECTOR has wrong number of operands");
16207       SDValue Base;
16208       bool AllSame = true;
16209       for (unsigned i = 0; i != NumElts; ++i) {
16210         if (!V->getOperand(i).isUndef()) {
16211           Base = V->getOperand(i);
16212           break;
16213         }
16214       }
16215       // Splat of <u, u, u, u>, return <u, u, u, u>
16216       if (!Base.getNode())
16217         return N0;
16218       for (unsigned i = 0; i != NumElts; ++i) {
16219         if (V->getOperand(i) != Base) {
16220           AllSame = false;
16221           break;
16222         }
16223       }
16224       // Splat of <x, x, x, x>, return <x, x, x, x>
16225       if (AllSame)
16226         return N0;
16227 
16228       // Canonicalize any other splat as a build_vector.
16229       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16230       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16231       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16232 
16233       // We may have jumped through bitcasts, so the type of the
16234       // BUILD_VECTOR may not match the type of the shuffle.
16235       if (V->getValueType(0) != VT)
16236         NewBV = DAG.getBitcast(VT, NewBV);
16237       return NewBV;
16238     }
16239   }
16240 
16241   // Simplify source operands based on shuffle mask.
16242   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
16243     return SDValue(N, 0);
16244 
16245   // Match shuffles that can be converted to any_vector_extend_in_reg.
16246   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16247     return V;
16248 
16249   // Combine "truncate_vector_in_reg" style shuffles.
16250   if (SDValue V = combineTruncationShuffle(SVN, DAG))
16251     return V;
16252 
16253   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16254       Level < AfterLegalizeVectorOps &&
16255       (N1.isUndef() ||
16256       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16257        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16258     if (SDValue V = partitionShuffleOfConcats(N, DAG))
16259       return V;
16260   }
16261 
16262   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16263   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16264   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16265     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16266       return Res;
16267 
16268   // If this shuffle only has a single input that is a bitcasted shuffle,
16269   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16270   // back to their original types.
16271   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16272       N1.isUndef() && Level < AfterLegalizeVectorOps &&
16273       TLI.isTypeLegal(VT)) {
16274 
16275     // Peek through the bitcast only if there is one user.
16276     SDValue BC0 = N0;
16277     while (BC0.getOpcode() == ISD::BITCAST) {
16278       if (!BC0.hasOneUse())
16279         break;
16280       BC0 = BC0.getOperand(0);
16281     }
16282 
16283     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16284       if (Scale == 1)
16285         return SmallVector<int, 8>(Mask.begin(), Mask.end());
16286 
16287       SmallVector<int, 8> NewMask;
16288       for (int M : Mask)
16289         for (int s = 0; s != Scale; ++s)
16290           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16291       return NewMask;
16292     };
16293 
16294     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16295       EVT SVT = VT.getScalarType();
16296       EVT InnerVT = BC0->getValueType(0);
16297       EVT InnerSVT = InnerVT.getScalarType();
16298 
16299       // Determine which shuffle works with the smaller scalar type.
16300       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16301       EVT ScaleSVT = ScaleVT.getScalarType();
16302 
16303       if (TLI.isTypeLegal(ScaleVT) &&
16304           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16305           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16306         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16307         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16308 
16309         // Scale the shuffle masks to the smaller scalar type.
16310         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16311         SmallVector<int, 8> InnerMask =
16312             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16313         SmallVector<int, 8> OuterMask =
16314             ScaleShuffleMask(SVN->getMask(), OuterScale);
16315 
16316         // Merge the shuffle masks.
16317         SmallVector<int, 8> NewMask;
16318         for (int M : OuterMask)
16319           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16320 
16321         // Test for shuffle mask legality over both commutations.
16322         SDValue SV0 = BC0->getOperand(0);
16323         SDValue SV1 = BC0->getOperand(1);
16324         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16325         if (!LegalMask) {
16326           std::swap(SV0, SV1);
16327           ShuffleVectorSDNode::commuteMask(NewMask);
16328           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16329         }
16330 
16331         if (LegalMask) {
16332           SV0 = DAG.getBitcast(ScaleVT, SV0);
16333           SV1 = DAG.getBitcast(ScaleVT, SV1);
16334           return DAG.getBitcast(
16335               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16336         }
16337       }
16338     }
16339   }
16340 
16341   // Canonicalize shuffles according to rules:
16342   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16343   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16344   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16345   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16346       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16347       TLI.isTypeLegal(VT)) {
16348     // The incoming shuffle must be of the same type as the result of the
16349     // current shuffle.
16350     assert(N1->getOperand(0).getValueType() == VT &&
16351            "Shuffle types don't match");
16352 
16353     SDValue SV0 = N1->getOperand(0);
16354     SDValue SV1 = N1->getOperand(1);
16355     bool HasSameOp0 = N0 == SV0;
16356     bool IsSV1Undef = SV1.isUndef();
16357     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16358       // Commute the operands of this shuffle so that next rule
16359       // will trigger.
16360       return DAG.getCommutedVectorShuffle(*SVN);
16361   }
16362 
16363   // Try to fold according to rules:
16364   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16365   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16366   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16367   // Don't try to fold shuffles with illegal type.
16368   // Only fold if this shuffle is the only user of the other shuffle.
16369   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16370       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16371     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16372 
16373     // Don't try to fold splats; they're likely to simplify somehow, or they
16374     // might be free.
16375     if (OtherSV->isSplat())
16376       return SDValue();
16377 
16378     // The incoming shuffle must be of the same type as the result of the
16379     // current shuffle.
16380     assert(OtherSV->getOperand(0).getValueType() == VT &&
16381            "Shuffle types don't match");
16382 
16383     SDValue SV0, SV1;
16384     SmallVector<int, 4> Mask;
16385     // Compute the combined shuffle mask for a shuffle with SV0 as the first
16386     // operand, and SV1 as the second operand.
16387     for (unsigned i = 0; i != NumElts; ++i) {
16388       int Idx = SVN->getMaskElt(i);
16389       if (Idx < 0) {
16390         // Propagate Undef.
16391         Mask.push_back(Idx);
16392         continue;
16393       }
16394 
16395       SDValue CurrentVec;
16396       if (Idx < (int)NumElts) {
16397         // This shuffle index refers to the inner shuffle N0. Lookup the inner
16398         // shuffle mask to identify which vector is actually referenced.
16399         Idx = OtherSV->getMaskElt(Idx);
16400         if (Idx < 0) {
16401           // Propagate Undef.
16402           Mask.push_back(Idx);
16403           continue;
16404         }
16405 
16406         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16407                                            : OtherSV->getOperand(1);
16408       } else {
16409         // This shuffle index references an element within N1.
16410         CurrentVec = N1;
16411       }
16412 
16413       // Simple case where 'CurrentVec' is UNDEF.
16414       if (CurrentVec.isUndef()) {
16415         Mask.push_back(-1);
16416         continue;
16417       }
16418 
16419       // Canonicalize the shuffle index. We don't know yet if CurrentVec
16420       // will be the first or second operand of the combined shuffle.
16421       Idx = Idx % NumElts;
16422       if (!SV0.getNode() || SV0 == CurrentVec) {
16423         // Ok. CurrentVec is the left hand side.
16424         // Update the mask accordingly.
16425         SV0 = CurrentVec;
16426         Mask.push_back(Idx);
16427         continue;
16428       }
16429 
16430       // Bail out if we cannot convert the shuffle pair into a single shuffle.
16431       if (SV1.getNode() && SV1 != CurrentVec)
16432         return SDValue();
16433 
16434       // Ok. CurrentVec is the right hand side.
16435       // Update the mask accordingly.
16436       SV1 = CurrentVec;
16437       Mask.push_back(Idx + NumElts);
16438     }
16439 
16440     // Check if all indices in Mask are Undef. In case, propagate Undef.
16441     bool isUndefMask = true;
16442     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16443       isUndefMask &= Mask[i] < 0;
16444 
16445     if (isUndefMask)
16446       return DAG.getUNDEF(VT);
16447 
16448     if (!SV0.getNode())
16449       SV0 = DAG.getUNDEF(VT);
16450     if (!SV1.getNode())
16451       SV1 = DAG.getUNDEF(VT);
16452 
16453     // Avoid introducing shuffles with illegal mask.
16454     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16455       ShuffleVectorSDNode::commuteMask(Mask);
16456 
16457       if (!TLI.isShuffleMaskLegal(Mask, VT))
16458         return SDValue();
16459 
16460       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16461       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16462       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16463       std::swap(SV0, SV1);
16464     }
16465 
16466     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16467     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16468     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16469     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16470   }
16471 
16472   return SDValue();
16473 }
16474 
16475 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16476   SDValue InVal = N->getOperand(0);
16477   EVT VT = N->getValueType(0);
16478 
16479   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16480   // with a VECTOR_SHUFFLE and possible truncate.
16481   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16482     SDValue InVec = InVal->getOperand(0);
16483     SDValue EltNo = InVal->getOperand(1);
16484     auto InVecT = InVec.getValueType();
16485     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16486       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16487       int Elt = C0->getZExtValue();
16488       NewMask[0] = Elt;
16489       SDValue Val;
16490       // If we have an implict truncate do truncate here as long as it's legal.
16491       // if it's not legal, this should
16492       if (VT.getScalarType() != InVal.getValueType() &&
16493           InVal.getValueType().isScalarInteger() &&
16494           isTypeLegal(VT.getScalarType())) {
16495         Val =
16496             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16497         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16498       }
16499       if (VT.getScalarType() == InVecT.getScalarType() &&
16500           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16501           TLI.isShuffleMaskLegal(NewMask, VT)) {
16502         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16503                                    DAG.getUNDEF(InVecT), NewMask);
16504         // If the initial vector is the correct size this shuffle is a
16505         // valid result.
16506         if (VT == InVecT)
16507           return Val;
16508         // If not we must truncate the vector.
16509         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16510           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16511           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16512           EVT SubVT =
16513               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16514                                VT.getVectorNumElements());
16515           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16516                             ZeroIdx);
16517           return Val;
16518         }
16519       }
16520     }
16521   }
16522 
16523   return SDValue();
16524 }
16525 
16526 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16527   EVT VT = N->getValueType(0);
16528   SDValue N0 = N->getOperand(0);
16529   SDValue N1 = N->getOperand(1);
16530   SDValue N2 = N->getOperand(2);
16531 
16532   // If inserting an UNDEF, just return the original vector.
16533   if (N1.isUndef())
16534     return N0;
16535 
16536   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16537   // us to pull BITCASTs from input to output.
16538   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16539     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16540       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16541 
16542   // If this is an insert of an extracted vector into an undef vector, we can
16543   // just use the input to the extract.
16544   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16545       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16546     return N1.getOperand(0);
16547 
16548   // If we are inserting a bitcast value into an undef, with the same
16549   // number of elements, just use the bitcast input of the extract.
16550   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16551   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16552   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16553       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16554       N1.getOperand(0).getOperand(1) == N2 &&
16555       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16556           VT.getVectorNumElements() &&
16557       N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
16558           VT.getSizeInBits()) {
16559     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16560   }
16561 
16562   // If both N1 and N2 are bitcast values on which insert_subvector
16563   // would makes sense, pull the bitcast through.
16564   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16565   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16566   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16567     SDValue CN0 = N0.getOperand(0);
16568     SDValue CN1 = N1.getOperand(0);
16569     EVT CN0VT = CN0.getValueType();
16570     EVT CN1VT = CN1.getValueType();
16571     if (CN0VT.isVector() && CN1VT.isVector() &&
16572         CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
16573         CN0VT.getVectorNumElements() == VT.getVectorNumElements()) {
16574       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16575                                       CN0.getValueType(), CN0, CN1, N2);
16576       return DAG.getBitcast(VT, NewINSERT);
16577     }
16578   }
16579 
16580   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16581   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16582   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16583   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16584       N0.getOperand(1).getValueType() == N1.getValueType() &&
16585       N0.getOperand(2) == N2)
16586     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16587                        N1, N2);
16588 
16589   if (!isa<ConstantSDNode>(N2))
16590     return SDValue();
16591 
16592   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16593 
16594   // Canonicalize insert_subvector dag nodes.
16595   // Example:
16596   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16597   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16598   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16599       N1.getValueType() == N0.getOperand(1).getValueType() &&
16600       isa<ConstantSDNode>(N0.getOperand(2))) {
16601     unsigned OtherIdx = N0.getConstantOperandVal(2);
16602     if (InsIdx < OtherIdx) {
16603       // Swap nodes.
16604       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16605                                   N0.getOperand(0), N1, N2);
16606       AddToWorklist(NewOp.getNode());
16607       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16608                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16609     }
16610   }
16611 
16612   // If the input vector is a concatenation, and the insert replaces
16613   // one of the pieces, we can optimize into a single concat_vectors.
16614   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16615       N0.getOperand(0).getValueType() == N1.getValueType()) {
16616     unsigned Factor = N1.getValueType().getVectorNumElements();
16617 
16618     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16619     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16620 
16621     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16622   }
16623 
16624   return SDValue();
16625 }
16626 
16627 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16628   SDValue N0 = N->getOperand(0);
16629 
16630   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16631   if (N0->getOpcode() == ISD::FP16_TO_FP)
16632     return N0->getOperand(0);
16633 
16634   return SDValue();
16635 }
16636 
16637 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16638   SDValue N0 = N->getOperand(0);
16639 
16640   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16641   if (N0->getOpcode() == ISD::AND) {
16642     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16643     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16644       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16645                          N0.getOperand(0));
16646     }
16647   }
16648 
16649   return SDValue();
16650 }
16651 
16652 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16653 /// with the destination vector and a zero vector.
16654 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16655 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16656 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16657   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
16658 
16659   EVT VT = N->getValueType(0);
16660   SDValue LHS = N->getOperand(0);
16661   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16662   SDLoc DL(N);
16663 
16664   // Make sure we're not running after operation legalization where it
16665   // may have custom lowered the vector shuffles.
16666   if (LegalOperations)
16667     return SDValue();
16668 
16669   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16670     return SDValue();
16671 
16672   EVT RVT = RHS.getValueType();
16673   unsigned NumElts = RHS.getNumOperands();
16674 
16675   // Attempt to create a valid clear mask, splitting the mask into
16676   // sub elements and checking to see if each is
16677   // all zeros or all ones - suitable for shuffle masking.
16678   auto BuildClearMask = [&](int Split) {
16679     int NumSubElts = NumElts * Split;
16680     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16681 
16682     SmallVector<int, 8> Indices;
16683     for (int i = 0; i != NumSubElts; ++i) {
16684       int EltIdx = i / Split;
16685       int SubIdx = i % Split;
16686       SDValue Elt = RHS.getOperand(EltIdx);
16687       if (Elt.isUndef()) {
16688         Indices.push_back(-1);
16689         continue;
16690       }
16691 
16692       APInt Bits;
16693       if (isa<ConstantSDNode>(Elt))
16694         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16695       else if (isa<ConstantFPSDNode>(Elt))
16696         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16697       else
16698         return SDValue();
16699 
16700       // Extract the sub element from the constant bit mask.
16701       if (DAG.getDataLayout().isBigEndian()) {
16702         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16703       } else {
16704         Bits.lshrInPlace(SubIdx * NumSubBits);
16705       }
16706 
16707       if (Split > 1)
16708         Bits = Bits.trunc(NumSubBits);
16709 
16710       if (Bits.isAllOnesValue())
16711         Indices.push_back(i);
16712       else if (Bits == 0)
16713         Indices.push_back(i + NumSubElts);
16714       else
16715         return SDValue();
16716     }
16717 
16718     // Let's see if the target supports this vector_shuffle.
16719     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16720     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16721     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16722       return SDValue();
16723 
16724     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16725     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16726                                                    DAG.getBitcast(ClearVT, LHS),
16727                                                    Zero, Indices));
16728   };
16729 
16730   // Determine maximum split level (byte level masking).
16731   int MaxSplit = 1;
16732   if (RVT.getScalarSizeInBits() % 8 == 0)
16733     MaxSplit = RVT.getScalarSizeInBits() / 8;
16734 
16735   for (int Split = 1; Split <= MaxSplit; ++Split)
16736     if (RVT.getScalarSizeInBits() % Split == 0)
16737       if (SDValue S = BuildClearMask(Split))
16738         return S;
16739 
16740   return SDValue();
16741 }
16742 
16743 /// Visit a binary vector operation, like ADD.
16744 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16745   assert(N->getValueType(0).isVector() &&
16746          "SimplifyVBinOp only works on vectors!");
16747 
16748   SDValue LHS = N->getOperand(0);
16749   SDValue RHS = N->getOperand(1);
16750   SDValue Ops[] = {LHS, RHS};
16751 
16752   // See if we can constant fold the vector operation.
16753   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16754           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16755     return Fold;
16756 
16757   // Type legalization might introduce new shuffles in the DAG.
16758   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16759   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16760   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16761       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16762       LHS.getOperand(1).isUndef() &&
16763       RHS.getOperand(1).isUndef()) {
16764     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16765     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16766 
16767     if (SVN0->getMask().equals(SVN1->getMask())) {
16768       EVT VT = N->getValueType(0);
16769       SDValue UndefVector = LHS.getOperand(1);
16770       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16771                                      LHS.getOperand(0), RHS.getOperand(0),
16772                                      N->getFlags());
16773       AddUsersToWorklist(N);
16774       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16775                                   SVN0->getMask());
16776     }
16777   }
16778 
16779   return SDValue();
16780 }
16781 
16782 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16783                                     SDValue N2) {
16784   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16785 
16786   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16787                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16788 
16789   // If we got a simplified select_cc node back from SimplifySelectCC, then
16790   // break it down into a new SETCC node, and a new SELECT node, and then return
16791   // the SELECT node, since we were called with a SELECT node.
16792   if (SCC.getNode()) {
16793     // Check to see if we got a select_cc back (to turn into setcc/select).
16794     // Otherwise, just return whatever node we got back, like fabs.
16795     if (SCC.getOpcode() == ISD::SELECT_CC) {
16796       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16797                                   N0.getValueType(),
16798                                   SCC.getOperand(0), SCC.getOperand(1),
16799                                   SCC.getOperand(4));
16800       AddToWorklist(SETCC.getNode());
16801       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16802                            SCC.getOperand(2), SCC.getOperand(3));
16803     }
16804 
16805     return SCC;
16806   }
16807   return SDValue();
16808 }
16809 
16810 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16811 /// being selected between, see if we can simplify the select.  Callers of this
16812 /// should assume that TheSelect is deleted if this returns true.  As such, they
16813 /// should return the appropriate thing (e.g. the node) back to the top-level of
16814 /// the DAG combiner loop to avoid it being looked at.
16815 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16816                                     SDValue RHS) {
16817   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16818   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16819   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16820     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16821       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16822       SDValue Sqrt = RHS;
16823       ISD::CondCode CC;
16824       SDValue CmpLHS;
16825       const ConstantFPSDNode *Zero = nullptr;
16826 
16827       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16828         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16829         CmpLHS = TheSelect->getOperand(0);
16830         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16831       } else {
16832         // SELECT or VSELECT
16833         SDValue Cmp = TheSelect->getOperand(0);
16834         if (Cmp.getOpcode() == ISD::SETCC) {
16835           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16836           CmpLHS = Cmp.getOperand(0);
16837           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16838         }
16839       }
16840       if (Zero && Zero->isZero() &&
16841           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
16842           CC == ISD::SETULT || CC == ISD::SETLT)) {
16843         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16844         CombineTo(TheSelect, Sqrt);
16845         return true;
16846       }
16847     }
16848   }
16849   // Cannot simplify select with vector condition
16850   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
16851 
16852   // If this is a select from two identical things, try to pull the operation
16853   // through the select.
16854   if (LHS.getOpcode() != RHS.getOpcode() ||
16855       !LHS.hasOneUse() || !RHS.hasOneUse())
16856     return false;
16857 
16858   // If this is a load and the token chain is identical, replace the select
16859   // of two loads with a load through a select of the address to load from.
16860   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
16861   // constants have been dropped into the constant pool.
16862   if (LHS.getOpcode() == ISD::LOAD) {
16863     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
16864     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
16865 
16866     // Token chains must be identical.
16867     if (LHS.getOperand(0) != RHS.getOperand(0) ||
16868         // Do not let this transformation reduce the number of volatile loads.
16869         LLD->isVolatile() || RLD->isVolatile() ||
16870         // FIXME: If either is a pre/post inc/dec load,
16871         // we'd need to split out the address adjustment.
16872         LLD->isIndexed() || RLD->isIndexed() ||
16873         // If this is an EXTLOAD, the VT's must match.
16874         LLD->getMemoryVT() != RLD->getMemoryVT() ||
16875         // If this is an EXTLOAD, the kind of extension must match.
16876         (LLD->getExtensionType() != RLD->getExtensionType() &&
16877          // The only exception is if one of the extensions is anyext.
16878          LLD->getExtensionType() != ISD::EXTLOAD &&
16879          RLD->getExtensionType() != ISD::EXTLOAD) ||
16880         // FIXME: this discards src value information.  This is
16881         // over-conservative. It would be beneficial to be able to remember
16882         // both potential memory locations.  Since we are discarding
16883         // src value info, don't do the transformation if the memory
16884         // locations are not in the default address space.
16885         LLD->getPointerInfo().getAddrSpace() != 0 ||
16886         RLD->getPointerInfo().getAddrSpace() != 0 ||
16887         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16888                                       LLD->getBasePtr().getValueType()))
16889       return false;
16890 
16891     // Check that the select condition doesn't reach either load.  If so,
16892     // folding this will induce a cycle into the DAG.  If not, this is safe to
16893     // xform, so create a select of the addresses.
16894     SDValue Addr;
16895     if (TheSelect->getOpcode() == ISD::SELECT) {
16896       SDNode *CondNode = TheSelect->getOperand(0).getNode();
16897       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16898           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16899         return false;
16900       // The loads must not depend on one another.
16901       if (LLD->isPredecessorOf(RLD) ||
16902           RLD->isPredecessorOf(LLD))
16903         return false;
16904       Addr = DAG.getSelect(SDLoc(TheSelect),
16905                            LLD->getBasePtr().getValueType(),
16906                            TheSelect->getOperand(0), LLD->getBasePtr(),
16907                            RLD->getBasePtr());
16908     } else {  // Otherwise SELECT_CC
16909       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16910       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16911 
16912       if ((LLD->hasAnyUseOfValue(1) &&
16913            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16914           (RLD->hasAnyUseOfValue(1) &&
16915            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16916         return false;
16917 
16918       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16919                          LLD->getBasePtr().getValueType(),
16920                          TheSelect->getOperand(0),
16921                          TheSelect->getOperand(1),
16922                          LLD->getBasePtr(), RLD->getBasePtr(),
16923                          TheSelect->getOperand(4));
16924     }
16925 
16926     SDValue Load;
16927     // It is safe to replace the two loads if they have different alignments,
16928     // but the new load must be the minimum (most restrictive) alignment of the
16929     // inputs.
16930     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16931     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16932     if (!RLD->isInvariant())
16933       MMOFlags &= ~MachineMemOperand::MOInvariant;
16934     if (!RLD->isDereferenceable())
16935       MMOFlags &= ~MachineMemOperand::MODereferenceable;
16936     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16937       // FIXME: Discards pointer and AA info.
16938       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16939                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16940                          MMOFlags);
16941     } else {
16942       // FIXME: Discards pointer and AA info.
16943       Load = DAG.getExtLoad(
16944           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16945                                                   : LLD->getExtensionType(),
16946           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16947           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16948     }
16949 
16950     // Users of the select now use the result of the load.
16951     CombineTo(TheSelect, Load);
16952 
16953     // Users of the old loads now use the new load's chain.  We know the
16954     // old-load value is dead now.
16955     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16956     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16957     return true;
16958   }
16959 
16960   return false;
16961 }
16962 
16963 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16964 /// bitwise 'and'.
16965 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16966                                             SDValue N1, SDValue N2, SDValue N3,
16967                                             ISD::CondCode CC) {
16968   // If this is a select where the false operand is zero and the compare is a
16969   // check of the sign bit, see if we can perform the "gzip trick":
16970   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16971   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16972   EVT XType = N0.getValueType();
16973   EVT AType = N2.getValueType();
16974   if (!isNullConstant(N3) || !XType.bitsGE(AType))
16975     return SDValue();
16976 
16977   // If the comparison is testing for a positive value, we have to invert
16978   // the sign bit mask, so only do that transform if the target has a bitwise
16979   // 'and not' instruction (the invert is free).
16980   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16981     // (X > -1) ? A : 0
16982     // (X >  0) ? X : 0 <-- This is canonical signed max.
16983     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16984       return SDValue();
16985   } else if (CC == ISD::SETLT) {
16986     // (X <  0) ? A : 0
16987     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
16988     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16989       return SDValue();
16990   } else {
16991     return SDValue();
16992   }
16993 
16994   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16995   // constant.
16996   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16997   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16998   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16999     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
17000     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
17001     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
17002     AddToWorklist(Shift.getNode());
17003 
17004     if (XType.bitsGT(AType)) {
17005       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17006       AddToWorklist(Shift.getNode());
17007     }
17008 
17009     if (CC == ISD::SETGT)
17010       Shift = DAG.getNOT(DL, Shift, AType);
17011 
17012     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17013   }
17014 
17015   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
17016   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
17017   AddToWorklist(Shift.getNode());
17018 
17019   if (XType.bitsGT(AType)) {
17020     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17021     AddToWorklist(Shift.getNode());
17022   }
17023 
17024   if (CC == ISD::SETGT)
17025     Shift = DAG.getNOT(DL, Shift, AType);
17026 
17027   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17028 }
17029 
17030 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
17031 /// where 'cond' is the comparison specified by CC.
17032 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
17033                                       SDValue N2, SDValue N3, ISD::CondCode CC,
17034                                       bool NotExtCompare) {
17035   // (x ? y : y) -> y.
17036   if (N2 == N3) return N2;
17037 
17038   EVT VT = N2.getValueType();
17039   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
17040   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
17041 
17042   // Determine if the condition we're dealing with is constant
17043   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
17044                               N0, N1, CC, DL, false);
17045   if (SCC.getNode()) AddToWorklist(SCC.getNode());
17046 
17047   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
17048     // fold select_cc true, x, y -> x
17049     // fold select_cc false, x, y -> y
17050     return !SCCC->isNullValue() ? N2 : N3;
17051   }
17052 
17053   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
17054   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
17055   // in it.  This is a win when the constant is not otherwise available because
17056   // it replaces two constant pool loads with one.  We only do this if the FP
17057   // type is known to be legal, because if it isn't, then we are before legalize
17058   // types an we want the other legalization to happen first (e.g. to avoid
17059   // messing with soft float) and if the ConstantFP is not legal, because if
17060   // it is legal, we may not need to store the FP constant in a constant pool.
17061   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
17062     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
17063       if (TLI.isTypeLegal(N2.getValueType()) &&
17064           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
17065                TargetLowering::Legal &&
17066            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
17067            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
17068           // If both constants have multiple uses, then we won't need to do an
17069           // extra load, they are likely around in registers for other users.
17070           (TV->hasOneUse() || FV->hasOneUse())) {
17071         Constant *Elts[] = {
17072           const_cast<ConstantFP*>(FV->getConstantFPValue()),
17073           const_cast<ConstantFP*>(TV->getConstantFPValue())
17074         };
17075         Type *FPTy = Elts[0]->getType();
17076         const DataLayout &TD = DAG.getDataLayout();
17077 
17078         // Create a ConstantArray of the two constants.
17079         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
17080         SDValue CPIdx =
17081             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
17082                                 TD.getPrefTypeAlignment(FPTy));
17083         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
17084 
17085         // Get the offsets to the 0 and 1 element of the array so that we can
17086         // select between them.
17087         SDValue Zero = DAG.getIntPtrConstant(0, DL);
17088         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
17089         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
17090 
17091         SDValue Cond = DAG.getSetCC(DL,
17092                                     getSetCCResultType(N0.getValueType()),
17093                                     N0, N1, CC);
17094         AddToWorklist(Cond.getNode());
17095         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
17096                                           Cond, One, Zero);
17097         AddToWorklist(CstOffset.getNode());
17098         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
17099                             CstOffset);
17100         AddToWorklist(CPIdx.getNode());
17101         return DAG.getLoad(
17102             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
17103             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17104             Alignment);
17105       }
17106     }
17107 
17108   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
17109     return V;
17110 
17111   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
17112   // where y is has a single bit set.
17113   // A plaintext description would be, we can turn the SELECT_CC into an AND
17114   // when the condition can be materialized as an all-ones register.  Any
17115   // single bit-test can be materialized as an all-ones register with
17116   // shift-left and shift-right-arith.
17117   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
17118       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
17119     SDValue AndLHS = N0->getOperand(0);
17120     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17121     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
17122       // Shift the tested bit over the sign bit.
17123       const APInt &AndMask = ConstAndRHS->getAPIntValue();
17124       SDValue ShlAmt =
17125         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
17126                         getShiftAmountTy(AndLHS.getValueType()));
17127       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
17128 
17129       // Now arithmetic right shift it all the way over, so the result is either
17130       // all-ones, or zero.
17131       SDValue ShrAmt =
17132         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
17133                         getShiftAmountTy(Shl.getValueType()));
17134       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
17135 
17136       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17137     }
17138   }
17139 
17140   // fold select C, 16, 0 -> shl C, 4
17141   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17142       TLI.getBooleanContents(N0.getValueType()) ==
17143           TargetLowering::ZeroOrOneBooleanContent) {
17144 
17145     // If the caller doesn't want us to simplify this into a zext of a compare,
17146     // don't do it.
17147     if (NotExtCompare && N2C->isOne())
17148       return SDValue();
17149 
17150     // Get a SetCC of the condition
17151     // NOTE: Don't create a SETCC if it's not legal on this target.
17152     if (!LegalOperations ||
17153         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17154       SDValue Temp, SCC;
17155       // cast from setcc result type to select result type
17156       if (LegalTypes) {
17157         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17158                             N0, N1, CC);
17159         if (N2.getValueType().bitsLT(SCC.getValueType()))
17160           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17161                                         N2.getValueType());
17162         else
17163           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17164                              N2.getValueType(), SCC);
17165       } else {
17166         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17167         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17168                            N2.getValueType(), SCC);
17169       }
17170 
17171       AddToWorklist(SCC.getNode());
17172       AddToWorklist(Temp.getNode());
17173 
17174       if (N2C->isOne())
17175         return Temp;
17176 
17177       // shl setcc result by log2 n2c
17178       return DAG.getNode(
17179           ISD::SHL, DL, N2.getValueType(), Temp,
17180           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17181                           getShiftAmountTy(Temp.getValueType())));
17182     }
17183   }
17184 
17185   // Check to see if this is an integer abs.
17186   // select_cc setg[te] X,  0,  X, -X ->
17187   // select_cc setgt    X, -1,  X, -X ->
17188   // select_cc setl[te] X,  0, -X,  X ->
17189   // select_cc setlt    X,  1, -X,  X ->
17190   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17191   if (N1C) {
17192     ConstantSDNode *SubC = nullptr;
17193     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17194          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17195         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17196       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17197     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17198               (N1C->isOne() && CC == ISD::SETLT)) &&
17199              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17200       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17201 
17202     EVT XType = N0.getValueType();
17203     if (SubC && SubC->isNullValue() && XType.isInteger()) {
17204       SDLoc DL(N0);
17205       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17206                                   N0,
17207                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
17208                                          getShiftAmountTy(N0.getValueType())));
17209       SDValue Add = DAG.getNode(ISD::ADD, DL,
17210                                 XType, N0, Shift);
17211       AddToWorklist(Shift.getNode());
17212       AddToWorklist(Add.getNode());
17213       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17214     }
17215   }
17216 
17217   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17218   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17219   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17220   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17221   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17222   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17223   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17224   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17225   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17226     SDValue ValueOnZero = N2;
17227     SDValue Count = N3;
17228     // If the condition is NE instead of E, swap the operands.
17229     if (CC == ISD::SETNE)
17230       std::swap(ValueOnZero, Count);
17231     // Check if the value on zero is a constant equal to the bits in the type.
17232     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17233       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17234         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17235         // legal, combine to just cttz.
17236         if ((Count.getOpcode() == ISD::CTTZ ||
17237              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17238             N0 == Count.getOperand(0) &&
17239             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17240           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17241         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17242         // legal, combine to just ctlz.
17243         if ((Count.getOpcode() == ISD::CTLZ ||
17244              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17245             N0 == Count.getOperand(0) &&
17246             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17247           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17248       }
17249     }
17250   }
17251 
17252   return SDValue();
17253 }
17254 
17255 /// This is a stub for TargetLowering::SimplifySetCC.
17256 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17257                                    ISD::CondCode Cond, const SDLoc &DL,
17258                                    bool foldBooleans) {
17259   TargetLowering::DAGCombinerInfo
17260     DagCombineInfo(DAG, Level, false, this);
17261   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17262 }
17263 
17264 /// Given an ISD::SDIV node expressing a divide by constant, return
17265 /// a DAG expression to select that will generate the same value by multiplying
17266 /// by a magic number.
17267 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17268 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17269   // when optimising for minimum size, we don't want to expand a div to a mul
17270   // and a shift.
17271   if (DAG.getMachineFunction().getFunction().optForMinSize())
17272     return SDValue();
17273 
17274   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17275   if (!C)
17276     return SDValue();
17277 
17278   // Avoid division by zero.
17279   if (C->isNullValue())
17280     return SDValue();
17281 
17282   std::vector<SDNode *> Built;
17283   SDValue S =
17284       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17285 
17286   for (SDNode *N : Built)
17287     AddToWorklist(N);
17288   return S;
17289 }
17290 
17291 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17292 /// DAG expression that will generate the same value by right shifting.
17293 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17294   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17295   if (!C)
17296     return SDValue();
17297 
17298   // Avoid division by zero.
17299   if (C->isNullValue())
17300     return SDValue();
17301 
17302   std::vector<SDNode *> Built;
17303   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17304 
17305   for (SDNode *N : Built)
17306     AddToWorklist(N);
17307   return S;
17308 }
17309 
17310 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17311 /// expression that will generate the same value by multiplying by a magic
17312 /// number.
17313 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17314 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17315   // when optimising for minimum size, we don't want to expand a div to a mul
17316   // and a shift.
17317   if (DAG.getMachineFunction().getFunction().optForMinSize())
17318     return SDValue();
17319 
17320   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17321   if (!C)
17322     return SDValue();
17323 
17324   // Avoid division by zero.
17325   if (C->isNullValue())
17326     return SDValue();
17327 
17328   std::vector<SDNode *> Built;
17329   SDValue S =
17330       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17331 
17332   for (SDNode *N : Built)
17333     AddToWorklist(N);
17334   return S;
17335 }
17336 
17337 /// Determines the LogBase2 value for a non-null input value using the
17338 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17339 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17340   EVT VT = V.getValueType();
17341   unsigned EltBits = VT.getScalarSizeInBits();
17342   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17343   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17344   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17345   return LogBase2;
17346 }
17347 
17348 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17349 /// For the reciprocal, we need to find the zero of the function:
17350 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
17351 ///     =>
17352 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17353 ///     does not require additional intermediate precision]
17354 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17355   if (Level >= AfterLegalizeDAG)
17356     return SDValue();
17357 
17358   // TODO: Handle half and/or extended types?
17359   EVT VT = Op.getValueType();
17360   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17361     return SDValue();
17362 
17363   // If estimates are explicitly disabled for this function, we're done.
17364   MachineFunction &MF = DAG.getMachineFunction();
17365   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17366   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17367     return SDValue();
17368 
17369   // Estimates may be explicitly enabled for this type with a custom number of
17370   // refinement steps.
17371   int Iterations = TLI.getDivRefinementSteps(VT, MF);
17372   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17373     AddToWorklist(Est.getNode());
17374 
17375     if (Iterations) {
17376       EVT VT = Op.getValueType();
17377       SDLoc DL(Op);
17378       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17379 
17380       // Newton iterations: Est = Est + Est (1 - Arg * Est)
17381       for (int i = 0; i < Iterations; ++i) {
17382         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17383         AddToWorklist(NewEst.getNode());
17384 
17385         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17386         AddToWorklist(NewEst.getNode());
17387 
17388         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17389         AddToWorklist(NewEst.getNode());
17390 
17391         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17392         AddToWorklist(Est.getNode());
17393       }
17394     }
17395     return Est;
17396   }
17397 
17398   return SDValue();
17399 }
17400 
17401 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17402 /// For the reciprocal sqrt, we need to find the zero of the function:
17403 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17404 ///     =>
17405 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17406 /// As a result, we precompute A/2 prior to the iteration loop.
17407 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17408                                          unsigned Iterations,
17409                                          SDNodeFlags Flags, bool Reciprocal) {
17410   EVT VT = Arg.getValueType();
17411   SDLoc DL(Arg);
17412   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17413 
17414   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17415   // this entire sequence requires only one FP constant.
17416   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17417   AddToWorklist(HalfArg.getNode());
17418 
17419   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17420   AddToWorklist(HalfArg.getNode());
17421 
17422   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17423   for (unsigned i = 0; i < Iterations; ++i) {
17424     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17425     AddToWorklist(NewEst.getNode());
17426 
17427     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17428     AddToWorklist(NewEst.getNode());
17429 
17430     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17431     AddToWorklist(NewEst.getNode());
17432 
17433     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17434     AddToWorklist(Est.getNode());
17435   }
17436 
17437   // If non-reciprocal square root is requested, multiply the result by Arg.
17438   if (!Reciprocal) {
17439     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17440     AddToWorklist(Est.getNode());
17441   }
17442 
17443   return Est;
17444 }
17445 
17446 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17447 /// For the reciprocal sqrt, we need to find the zero of the function:
17448 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17449 ///     =>
17450 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17451 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17452                                          unsigned Iterations,
17453                                          SDNodeFlags Flags, bool Reciprocal) {
17454   EVT VT = Arg.getValueType();
17455   SDLoc DL(Arg);
17456   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17457   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17458 
17459   // This routine must enter the loop below to work correctly
17460   // when (Reciprocal == false).
17461   assert(Iterations > 0);
17462 
17463   // Newton iterations for reciprocal square root:
17464   // E = (E * -0.5) * ((A * E) * E + -3.0)
17465   for (unsigned i = 0; i < Iterations; ++i) {
17466     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17467     AddToWorklist(AE.getNode());
17468 
17469     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17470     AddToWorklist(AEE.getNode());
17471 
17472     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17473     AddToWorklist(RHS.getNode());
17474 
17475     // When calculating a square root at the last iteration build:
17476     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17477     // (notice a common subexpression)
17478     SDValue LHS;
17479     if (Reciprocal || (i + 1) < Iterations) {
17480       // RSQRT: LHS = (E * -0.5)
17481       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17482     } else {
17483       // SQRT: LHS = (A * E) * -0.5
17484       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17485     }
17486     AddToWorklist(LHS.getNode());
17487 
17488     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17489     AddToWorklist(Est.getNode());
17490   }
17491 
17492   return Est;
17493 }
17494 
17495 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17496 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17497 /// Op can be zero.
17498 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17499                                            bool Reciprocal) {
17500   if (Level >= AfterLegalizeDAG)
17501     return SDValue();
17502 
17503   // TODO: Handle half and/or extended types?
17504   EVT VT = Op.getValueType();
17505   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17506     return SDValue();
17507 
17508   // If estimates are explicitly disabled for this function, we're done.
17509   MachineFunction &MF = DAG.getMachineFunction();
17510   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17511   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17512     return SDValue();
17513 
17514   // Estimates may be explicitly enabled for this type with a custom number of
17515   // refinement steps.
17516   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17517 
17518   bool UseOneConstNR = false;
17519   if (SDValue Est =
17520       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17521                           Reciprocal)) {
17522     AddToWorklist(Est.getNode());
17523 
17524     if (Iterations) {
17525       Est = UseOneConstNR
17526             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17527             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17528 
17529       if (!Reciprocal) {
17530         // The estimate is now completely wrong if the input was exactly 0.0 or
17531         // possibly a denormal. Force the answer to 0.0 for those cases.
17532         EVT VT = Op.getValueType();
17533         SDLoc DL(Op);
17534         EVT CCVT = getSetCCResultType(VT);
17535         ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
17536         const Function &F = DAG.getMachineFunction().getFunction();
17537         Attribute Denorms = F.getFnAttribute("denormal-fp-math");
17538         if (Denorms.getValueAsString().equals("ieee")) {
17539           // fabs(X) < SmallestNormal ? 0.0 : Est
17540           const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
17541           APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
17542           SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
17543           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17544           SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
17545           SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
17546           Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
17547           AddToWorklist(Fabs.getNode());
17548           AddToWorklist(IsDenorm.getNode());
17549           AddToWorklist(Est.getNode());
17550         } else {
17551           // X == 0.0 ? 0.0 : Est
17552           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17553           SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17554           Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
17555           AddToWorklist(IsZero.getNode());
17556           AddToWorklist(Est.getNode());
17557         }
17558       }
17559     }
17560     return Est;
17561   }
17562 
17563   return SDValue();
17564 }
17565 
17566 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17567   return buildSqrtEstimateImpl(Op, Flags, true);
17568 }
17569 
17570 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17571   return buildSqrtEstimateImpl(Op, Flags, false);
17572 }
17573 
17574 /// Return true if there is any possibility that the two addresses overlap.
17575 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17576   // If they are the same then they must be aliases.
17577   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17578 
17579   // If they are both volatile then they cannot be reordered.
17580   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17581 
17582   // If one operation reads from invariant memory, and the other may store, they
17583   // cannot alias. These should really be checking the equivalent of mayWrite,
17584   // but it only matters for memory nodes other than load /store.
17585   if (Op0->isInvariant() && Op1->writeMem())
17586     return false;
17587 
17588   if (Op1->isInvariant() && Op0->writeMem())
17589     return false;
17590 
17591   unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17592   unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17593 
17594   // Check for BaseIndexOffset matching.
17595   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG);
17596   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG);
17597   int64_t PtrDiff;
17598   if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) {
17599     if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17600       return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17601 
17602     // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17603     // able to calculate their relative offset if at least one arises
17604     // from an alloca. However, these allocas cannot overlap and we
17605     // can infer there is no alias.
17606     if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17607       if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17608         MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17609         // If the base are the same frame index but the we couldn't find a
17610         // constant offset, (indices are different) be conservative.
17611         if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17612                        !MFI.isFixedObjectIndex(B->getIndex())))
17613           return false;
17614       }
17615 
17616     bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
17617     bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
17618     bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
17619     bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
17620     bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
17621     bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
17622 
17623     // If of mismatched base types or checkable indices we can check
17624     // they do not alias.
17625     if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
17626          (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
17627         (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1))
17628       return false;
17629   }
17630 
17631   // If we know required SrcValue1 and SrcValue2 have relatively large
17632   // alignment compared to the size and offset of the access, we may be able
17633   // to prove they do not alias. This check is conservative for now to catch
17634   // cases created by splitting vector types.
17635   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17636   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17637   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17638   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17639   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17640       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17641     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17642     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17643 
17644     // There is no overlap between these relatively aligned accesses of
17645     // similar size. Return no alias.
17646     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17647         (OffAlign1 + NumBytes1) <= OffAlign0)
17648       return false;
17649   }
17650 
17651   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17652                    ? CombinerGlobalAA
17653                    : DAG.getSubtarget().useAA();
17654 #ifndef NDEBUG
17655   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17656       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17657     UseAA = false;
17658 #endif
17659 
17660   if (UseAA && AA &&
17661       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17662     // Use alias analysis information.
17663     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17664     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17665     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17666     AliasResult AAResult =
17667         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17668                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17669                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17670                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17671     if (AAResult == NoAlias)
17672       return false;
17673   }
17674 
17675   // Otherwise we have to assume they alias.
17676   return true;
17677 }
17678 
17679 /// Walk up chain skipping non-aliasing memory nodes,
17680 /// looking for aliasing nodes and adding them to the Aliases vector.
17681 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17682                                    SmallVectorImpl<SDValue> &Aliases) {
17683   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17684   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17685 
17686   // Get alias information for node.
17687   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17688 
17689   // Starting off.
17690   Chains.push_back(OriginalChain);
17691   unsigned Depth = 0;
17692 
17693   // Look at each chain and determine if it is an alias.  If so, add it to the
17694   // aliases list.  If not, then continue up the chain looking for the next
17695   // candidate.
17696   while (!Chains.empty()) {
17697     SDValue Chain = Chains.pop_back_val();
17698 
17699     // For TokenFactor nodes, look at each operand and only continue up the
17700     // chain until we reach the depth limit.
17701     //
17702     // FIXME: The depth check could be made to return the last non-aliasing
17703     // chain we found before we hit a tokenfactor rather than the original
17704     // chain.
17705     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17706       Aliases.clear();
17707       Aliases.push_back(OriginalChain);
17708       return;
17709     }
17710 
17711     // Don't bother if we've been before.
17712     if (!Visited.insert(Chain.getNode()).second)
17713       continue;
17714 
17715     switch (Chain.getOpcode()) {
17716     case ISD::EntryToken:
17717       // Entry token is ideal chain operand, but handled in FindBetterChain.
17718       break;
17719 
17720     case ISD::LOAD:
17721     case ISD::STORE: {
17722       // Get alias information for Chain.
17723       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17724           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17725 
17726       // If chain is alias then stop here.
17727       if (!(IsLoad && IsOpLoad) &&
17728           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17729         Aliases.push_back(Chain);
17730       } else {
17731         // Look further up the chain.
17732         Chains.push_back(Chain.getOperand(0));
17733         ++Depth;
17734       }
17735       break;
17736     }
17737 
17738     case ISD::TokenFactor:
17739       // We have to check each of the operands of the token factor for "small"
17740       // token factors, so we queue them up.  Adding the operands to the queue
17741       // (stack) in reverse order maintains the original order and increases the
17742       // likelihood that getNode will find a matching token factor (CSE.)
17743       if (Chain.getNumOperands() > 16) {
17744         Aliases.push_back(Chain);
17745         break;
17746       }
17747       for (unsigned n = Chain.getNumOperands(); n;)
17748         Chains.push_back(Chain.getOperand(--n));
17749       ++Depth;
17750       break;
17751 
17752     case ISD::CopyFromReg:
17753       // Forward past CopyFromReg.
17754       Chains.push_back(Chain.getOperand(0));
17755       ++Depth;
17756       break;
17757 
17758     default:
17759       // For all other instructions we will just have to take what we can get.
17760       Aliases.push_back(Chain);
17761       break;
17762     }
17763   }
17764 }
17765 
17766 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17767 /// (aliasing node.)
17768 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17769   if (OptLevel == CodeGenOpt::None)
17770     return OldChain;
17771 
17772   // Ops for replacing token factor.
17773   SmallVector<SDValue, 8> Aliases;
17774 
17775   // Accumulate all the aliases to this node.
17776   GatherAllAliases(N, OldChain, Aliases);
17777 
17778   // If no operands then chain to entry token.
17779   if (Aliases.size() == 0)
17780     return DAG.getEntryNode();
17781 
17782   // If a single operand then chain to it.  We don't need to revisit it.
17783   if (Aliases.size() == 1)
17784     return Aliases[0];
17785 
17786   // Construct a custom tailored token factor.
17787   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17788 }
17789 
17790 // This function tries to collect a bunch of potentially interesting
17791 // nodes to improve the chains of, all at once. This might seem
17792 // redundant, as this function gets called when visiting every store
17793 // node, so why not let the work be done on each store as it's visited?
17794 //
17795 // I believe this is mainly important because MergeConsecutiveStores
17796 // is unable to deal with merging stores of different sizes, so unless
17797 // we improve the chains of all the potential candidates up-front
17798 // before running MergeConsecutiveStores, it might only see some of
17799 // the nodes that will eventually be candidates, and then not be able
17800 // to go from a partially-merged state to the desired final
17801 // fully-merged state.
17802 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17803   if (OptLevel == CodeGenOpt::None)
17804     return false;
17805 
17806   // This holds the base pointer, index, and the offset in bytes from the base
17807   // pointer.
17808   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
17809 
17810   // We must have a base and an offset.
17811   if (!BasePtr.getBase().getNode())
17812     return false;
17813 
17814   // Do not handle stores to undef base pointers.
17815   if (BasePtr.getBase().isUndef())
17816     return false;
17817 
17818   SmallVector<StoreSDNode *, 8> ChainedStores;
17819   ChainedStores.push_back(St);
17820 
17821   // Walk up the chain and look for nodes with offsets from the same
17822   // base pointer. Stop when reaching an instruction with a different kind
17823   // or instruction which has a different base pointer.
17824   StoreSDNode *Index = St;
17825   while (Index) {
17826     // If the chain has more than one use, then we can't reorder the mem ops.
17827     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17828       break;
17829 
17830     if (Index->isVolatile() || Index->isIndexed())
17831       break;
17832 
17833     // Find the base pointer and offset for this memory node.
17834     BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG);
17835 
17836     // Check that the base pointer is the same as the original one.
17837     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17838       break;
17839 
17840     // Walk up the chain to find the next store node, ignoring any
17841     // intermediate loads. Any other kind of node will halt the loop.
17842     SDNode *NextInChain = Index->getChain().getNode();
17843     while (true) {
17844       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17845         // We found a store node. Use it for the next iteration.
17846         if (STn->isVolatile() || STn->isIndexed()) {
17847           Index = nullptr;
17848           break;
17849         }
17850         ChainedStores.push_back(STn);
17851         Index = STn;
17852         break;
17853       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17854         NextInChain = Ldn->getChain().getNode();
17855         continue;
17856       } else {
17857         Index = nullptr;
17858         break;
17859       }
17860     } // end while
17861   }
17862 
17863   // At this point, ChainedStores lists all of the Store nodes
17864   // reachable by iterating up through chain nodes matching the above
17865   // conditions.  For each such store identified, try to find an
17866   // earlier chain to attach the store to which won't violate the
17867   // required ordering.
17868   bool MadeChangeToSt = false;
17869   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17870 
17871   for (StoreSDNode *ChainedStore : ChainedStores) {
17872     SDValue Chain = ChainedStore->getChain();
17873     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17874 
17875     if (Chain != BetterChain) {
17876       if (ChainedStore == St)
17877         MadeChangeToSt = true;
17878       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17879     }
17880   }
17881 
17882   // Do all replacements after finding the replacements to make to avoid making
17883   // the chains more complicated by introducing new TokenFactors.
17884   for (auto Replacement : BetterChains)
17885     replaceStoreChain(Replacement.first, Replacement.second);
17886 
17887   return MadeChangeToSt;
17888 }
17889 
17890 /// This is the entry point for the file.
17891 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17892                            CodeGenOpt::Level OptLevel) {
17893   /// This is the main entry point to this class.
17894   DAGCombiner(*this, AA, OptLevel).Run(Level);
17895 }
17896