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     /// 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     /// 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     /// 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     /// 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     /// Call the node-specific routine that knows how to fold each
272     /// particular type of node. If that doesn't do anything, try the
273     /// target-specific DAG combines.
274     SDValue combine(SDNode *N);
275 
276     // Visitation implementation - Implement dag node combining for different
277     // node types.  The semantics are as follows:
278     // Return Value:
279     //   SDValue.getNode() == 0 - No change was made
280     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
281     //   otherwise              - N should be replaced by the returned Operand.
282     //
283     SDValue visitTokenFactor(SDNode *N);
284     SDValue visitMERGE_VALUES(SDNode *N);
285     SDValue visitADD(SDNode *N);
286     SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
287     SDValue visitSUB(SDNode *N);
288     SDValue visitADDC(SDNode *N);
289     SDValue visitUADDO(SDNode *N);
290     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
291     SDValue visitSUBC(SDNode *N);
292     SDValue visitUSUBO(SDNode *N);
293     SDValue visitADDE(SDNode *N);
294     SDValue visitADDCARRY(SDNode *N);
295     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
296     SDValue visitSUBE(SDNode *N);
297     SDValue visitSUBCARRY(SDNode *N);
298     SDValue visitMUL(SDNode *N);
299     SDValue useDivRem(SDNode *N);
300     SDValue visitSDIV(SDNode *N);
301     SDValue visitUDIV(SDNode *N);
302     SDValue visitREM(SDNode *N);
303     SDValue visitMULHU(SDNode *N);
304     SDValue visitMULHS(SDNode *N);
305     SDValue visitSMUL_LOHI(SDNode *N);
306     SDValue visitUMUL_LOHI(SDNode *N);
307     SDValue visitSMULO(SDNode *N);
308     SDValue visitUMULO(SDNode *N);
309     SDValue visitIMINMAX(SDNode *N);
310     SDValue visitAND(SDNode *N);
311     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
312     SDValue visitOR(SDNode *N);
313     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
314     SDValue visitXOR(SDNode *N);
315     SDValue SimplifyVBinOp(SDNode *N);
316     SDValue visitSHL(SDNode *N);
317     SDValue visitSRA(SDNode *N);
318     SDValue visitSRL(SDNode *N);
319     SDValue visitRotate(SDNode *N);
320     SDValue visitABS(SDNode *N);
321     SDValue visitBSWAP(SDNode *N);
322     SDValue visitBITREVERSE(SDNode *N);
323     SDValue visitCTLZ(SDNode *N);
324     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
325     SDValue visitCTTZ(SDNode *N);
326     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
327     SDValue visitCTPOP(SDNode *N);
328     SDValue visitSELECT(SDNode *N);
329     SDValue visitVSELECT(SDNode *N);
330     SDValue visitSELECT_CC(SDNode *N);
331     SDValue visitSETCC(SDNode *N);
332     SDValue visitSETCCE(SDNode *N);
333     SDValue visitSETCCCARRY(SDNode *N);
334     SDValue visitSIGN_EXTEND(SDNode *N);
335     SDValue visitZERO_EXTEND(SDNode *N);
336     SDValue visitANY_EXTEND(SDNode *N);
337     SDValue visitAssertExt(SDNode *N);
338     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
339     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
340     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
341     SDValue visitTRUNCATE(SDNode *N);
342     SDValue visitBITCAST(SDNode *N);
343     SDValue visitBUILD_PAIR(SDNode *N);
344     SDValue visitFADD(SDNode *N);
345     SDValue visitFSUB(SDNode *N);
346     SDValue visitFMUL(SDNode *N);
347     SDValue visitFMA(SDNode *N);
348     SDValue visitFDIV(SDNode *N);
349     SDValue visitFREM(SDNode *N);
350     SDValue visitFSQRT(SDNode *N);
351     SDValue visitFCOPYSIGN(SDNode *N);
352     SDValue visitSINT_TO_FP(SDNode *N);
353     SDValue visitUINT_TO_FP(SDNode *N);
354     SDValue visitFP_TO_SINT(SDNode *N);
355     SDValue visitFP_TO_UINT(SDNode *N);
356     SDValue visitFP_ROUND(SDNode *N);
357     SDValue visitFP_ROUND_INREG(SDNode *N);
358     SDValue visitFP_EXTEND(SDNode *N);
359     SDValue visitFNEG(SDNode *N);
360     SDValue visitFABS(SDNode *N);
361     SDValue visitFCEIL(SDNode *N);
362     SDValue visitFTRUNC(SDNode *N);
363     SDValue visitFFLOOR(SDNode *N);
364     SDValue visitFMINNUM(SDNode *N);
365     SDValue visitFMAXNUM(SDNode *N);
366     SDValue visitBRCOND(SDNode *N);
367     SDValue visitBR_CC(SDNode *N);
368     SDValue visitLOAD(SDNode *N);
369 
370     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
371     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
372 
373     SDValue visitSTORE(SDNode *N);
374     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
375     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
376     SDValue visitBUILD_VECTOR(SDNode *N);
377     SDValue visitCONCAT_VECTORS(SDNode *N);
378     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
379     SDValue visitVECTOR_SHUFFLE(SDNode *N);
380     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
381     SDValue visitINSERT_SUBVECTOR(SDNode *N);
382     SDValue visitMLOAD(SDNode *N);
383     SDValue visitMSTORE(SDNode *N);
384     SDValue visitMGATHER(SDNode *N);
385     SDValue visitMSCATTER(SDNode *N);
386     SDValue visitFP_TO_FP16(SDNode *N);
387     SDValue visitFP16_TO_FP(SDNode *N);
388 
389     SDValue visitFADDForFMACombine(SDNode *N);
390     SDValue visitFSUBForFMACombine(SDNode *N);
391     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
392 
393     SDValue XformToShuffleWithZero(SDNode *N);
394     SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
395                            SDValue RHS);
396 
397     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
398 
399     SDValue foldSelectOfConstants(SDNode *N);
400     SDValue foldVSelectOfConstants(SDNode *N);
401     SDValue foldBinOpIntoSelect(SDNode *BO);
402     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
403     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
404     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
405     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
406                              SDValue N2, SDValue N3, ISD::CondCode CC,
407                              bool NotExtCompare = false);
408     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
409                                    SDValue N2, SDValue N3, ISD::CondCode CC);
410     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
411                               const SDLoc &DL);
412     SDValue unfoldMaskedMerge(SDNode *N);
413     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
414                           const SDLoc &DL, bool foldBooleans);
415     SDValue rebuildSetCC(SDValue N);
416 
417     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
418                            SDValue &CC) const;
419     bool isOneUseSetCC(SDValue N) const;
420 
421     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
422                                          unsigned HiOp);
423     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
424     SDValue CombineExtLoad(SDNode *N);
425     SDValue CombineZExtLogicopShiftLoad(SDNode *N);
426     SDValue combineRepeatedFPDivisors(SDNode *N);
427     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
428     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
429     SDValue BuildSDIV(SDNode *N);
430     SDValue BuildSDIVPow2(SDNode *N);
431     SDValue BuildUDIV(SDNode *N);
432     SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
433     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
434     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
435     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
436     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
437     SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
438                                 SDNodeFlags Flags, bool Reciprocal);
439     SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
440                                 SDNodeFlags Flags, bool Reciprocal);
441     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
442                                bool DemandHighBits = true);
443     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
444     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
445                               SDValue InnerPos, SDValue InnerNeg,
446                               unsigned PosOpcode, unsigned NegOpcode,
447                               const SDLoc &DL);
448     SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
449     SDValue MatchLoadCombine(SDNode *N);
450     SDValue ReduceLoadWidth(SDNode *N);
451     SDValue ReduceLoadOpStoreWidth(SDNode *N);
452     SDValue splitMergedValStore(StoreSDNode *ST);
453     SDValue TransformFPLoadStorePair(SDNode *N);
454     SDValue convertBuildVecZextToZext(SDNode *N);
455     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
456     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
457     SDValue reduceBuildVecToShuffle(SDNode *N);
458     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
459                                   ArrayRef<int> VectorMask, SDValue VecIn1,
460                                   SDValue VecIn2, unsigned LeftIdx);
461     SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
462 
463     /// Walk up chain skipping non-aliasing memory nodes,
464     /// looking for aliasing nodes and adding them to the Aliases vector.
465     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
466                           SmallVectorImpl<SDValue> &Aliases);
467 
468     /// Return true if there is any possibility that the two addresses overlap.
469     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
470 
471     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
472     /// chain (aliasing node.)
473     SDValue FindBetterChain(SDNode *N, SDValue Chain);
474 
475     /// Try to replace a store and any possibly adjacent stores on
476     /// consecutive chains with better chains. Return true only if St is
477     /// replaced.
478     ///
479     /// Notice that other chains may still be replaced even if the function
480     /// returns false.
481     bool findBetterNeighborChains(StoreSDNode *St);
482 
483     /// Match "(X shl/srl V1) & V2" where V2 may not be present.
484     bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
485 
486     /// Holds a pointer to an LSBaseSDNode as well as information on where it
487     /// is located in a sequence of memory operations connected by a chain.
488     struct MemOpLink {
489       // Ptr to the mem node.
490       LSBaseSDNode *MemNode;
491 
492       // Offset from the base ptr.
493       int64_t OffsetFromBase;
494 
495       MemOpLink(LSBaseSDNode *N, int64_t Offset)
496           : MemNode(N), OffsetFromBase(Offset) {}
497     };
498 
499     /// This is a helper function for visitMUL to check the profitability
500     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
501     /// MulNode is the original multiply, AddNode is (add x, c1),
502     /// and ConstNode is c2.
503     bool isMulAddWithConstProfitable(SDNode *MulNode,
504                                      SDValue &AddNode,
505                                      SDValue &ConstNode);
506 
507     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
508     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
509     /// the type of the loaded value to be extended.
510     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
511                           EVT LoadResultTy, EVT &ExtVT);
512 
513     /// Helper function to calculate whether the given Load can have its
514     /// width reduced to ExtVT.
515     bool isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
516                            EVT &ExtVT, unsigned ShAmt = 0);
517 
518     /// Used by BackwardsPropagateMask to find suitable loads.
519     bool SearchForAndLoads(SDNode *N, SmallPtrSetImpl<LoadSDNode*> &Loads,
520                            SmallPtrSetImpl<SDNode*> &NodeWithConsts,
521                            ConstantSDNode *Mask, SDNode *&UncombinedNode);
522     /// Attempt to propagate a given AND node back to load leaves so that they
523     /// can be combined into narrow loads.
524     bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG);
525 
526     /// Helper function for MergeConsecutiveStores which merges the
527     /// component store chains.
528     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
529                                 unsigned NumStores);
530 
531     /// This is a helper function for MergeConsecutiveStores. When the
532     /// source elements of the consecutive stores are all constants or
533     /// all extracted vector elements, try to merge them into one
534     /// larger store introducing bitcasts if necessary.  \return True
535     /// if a merged store was created.
536     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
537                                          EVT MemVT, unsigned NumStores,
538                                          bool IsConstantSrc, bool UseVector,
539                                          bool UseTrunc);
540 
541     /// This is a helper function for MergeConsecutiveStores. Stores
542     /// that potentially may be merged with St are placed in
543     /// StoreNodes. RootNode is a chain predecessor to all store
544     /// candidates.
545     void getStoreMergeCandidates(StoreSDNode *St,
546                                  SmallVectorImpl<MemOpLink> &StoreNodes,
547                                  SDNode *&Root);
548 
549     /// Helper function for MergeConsecutiveStores. Checks if
550     /// candidate stores have indirect dependency through their
551     /// operands. RootNode is the predecessor to all stores calculated
552     /// by getStoreMergeCandidates and is used to prune the dependency check.
553     /// \return True if safe to merge.
554     bool checkMergeStoreCandidatesForDependencies(
555         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
556         SDNode *RootNode);
557 
558     /// Merge consecutive store operations into a wide store.
559     /// This optimization uses wide integers or vectors when possible.
560     /// \return number of stores that were merged into a merged store (the
561     /// affected nodes are stored as a prefix in \p StoreNodes).
562     bool MergeConsecutiveStores(StoreSDNode *N);
563 
564     /// Try to transform a truncation where C is a constant:
565     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
566     ///
567     /// \p N needs to be a truncation and its first operand an AND. Other
568     /// requirements are checked by the function (e.g. that trunc is
569     /// single-use) and if missed an empty SDValue is returned.
570     SDValue distributeTruncateThroughAnd(SDNode *N);
571 
572   public:
573     /// Runs the dag combiner on all nodes in the work list
574     void Run(CombineLevel AtLevel);
575 
576     SelectionDAG &getDAG() const { return DAG; }
577 
578     /// Returns a type large enough to hold any valid shift amount - before type
579     /// legalization these can be huge.
580     EVT getShiftAmountTy(EVT LHSTy) {
581       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
582       return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
583     }
584 
585     /// This method returns true if we are running before type legalization or
586     /// if the specified VT is legal.
587     bool isTypeLegal(const EVT &VT) {
588       if (!LegalTypes) return true;
589       return TLI.isTypeLegal(VT);
590     }
591 
592     /// Convenience wrapper around TargetLowering::getSetCCResultType
593     EVT getSetCCResultType(EVT VT) const {
594       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
595     }
596 
597     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
598                          SDValue OrigLoad, SDValue ExtLoad,
599                          ISD::NodeType ExtType);
600   };
601 
602 /// This class is a DAGUpdateListener that removes any deleted
603 /// nodes from the worklist.
604 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
605   DAGCombiner &DC;
606 
607 public:
608   explicit WorklistRemover(DAGCombiner &dc)
609     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
610 
611   void NodeDeleted(SDNode *N, SDNode *E) override {
612     DC.removeFromWorklist(N);
613   }
614 };
615 
616 } // end anonymous namespace
617 
618 //===----------------------------------------------------------------------===//
619 //  TargetLowering::DAGCombinerInfo implementation
620 //===----------------------------------------------------------------------===//
621 
622 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
623   ((DAGCombiner*)DC)->AddToWorklist(N);
624 }
625 
626 SDValue TargetLowering::DAGCombinerInfo::
627 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
628   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
629 }
630 
631 SDValue TargetLowering::DAGCombinerInfo::
632 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
633   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
634 }
635 
636 SDValue TargetLowering::DAGCombinerInfo::
637 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
638   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
639 }
640 
641 void TargetLowering::DAGCombinerInfo::
642 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
643   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
644 }
645 
646 //===----------------------------------------------------------------------===//
647 // Helper Functions
648 //===----------------------------------------------------------------------===//
649 
650 void DAGCombiner::deleteAndRecombine(SDNode *N) {
651   removeFromWorklist(N);
652 
653   // If the operands of this node are only used by the node, they will now be
654   // dead. Make sure to re-visit them and recursively delete dead nodes.
655   for (const SDValue &Op : N->ops())
656     // For an operand generating multiple values, one of the values may
657     // become dead allowing further simplification (e.g. split index
658     // arithmetic from an indexed load).
659     if (Op->hasOneUse() || Op->getNumValues() > 1)
660       AddToWorklist(Op.getNode());
661 
662   DAG.DeleteNode(N);
663 }
664 
665 /// Return 1 if we can compute the negated form of the specified expression for
666 /// the same cost as the expression itself, or 2 if we can compute the negated
667 /// form more cheaply than the expression itself.
668 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
669                                const TargetLowering &TLI,
670                                const TargetOptions *Options,
671                                unsigned Depth = 0) {
672   // fneg is removable even if it has multiple uses.
673   if (Op.getOpcode() == ISD::FNEG) return 2;
674 
675   // Don't allow anything with multiple uses unless we know it is free.
676   EVT VT = Op.getValueType();
677   if (!Op.hasOneUse())
678     if (!(Op.getOpcode() == ISD::FP_EXTEND &&
679           TLI.isFPExtFree(VT, Op.getOperand(0).getValueType())))
680       return 0;
681 
682   // Don't recurse exponentially.
683   if (Depth > 6) return 0;
684 
685   switch (Op.getOpcode()) {
686   default: return false;
687   case ISD::ConstantFP: {
688     if (!LegalOperations)
689       return 1;
690 
691     // Don't invert constant FP values after legalization unless the target says
692     // the negated constant is legal.
693     return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
694       TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
695   }
696   case ISD::FADD:
697     // FIXME: determine better conditions for this xform.
698     if (!Options->UnsafeFPMath) return 0;
699 
700     // After operation legalization, it might not be legal to create new FSUBs.
701     if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
702       return 0;
703 
704     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
705     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
706                                     Options, Depth + 1))
707       return V;
708     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
709     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
710                               Depth + 1);
711   case ISD::FSUB:
712     // We can't turn -(A-B) into B-A when we honor signed zeros.
713     if (!Options->NoSignedZerosFPMath &&
714         !Op.getNode()->getFlags().hasNoSignedZeros())
715       return 0;
716 
717     // fold (fneg (fsub A, B)) -> (fsub B, A)
718     return 1;
719 
720   case ISD::FMUL:
721   case ISD::FDIV:
722     if (Options->HonorSignDependentRoundingFPMath()) return 0;
723 
724     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
725     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
726                                     Options, Depth + 1))
727       return V;
728 
729     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
730                               Depth + 1);
731 
732   case ISD::FP_EXTEND:
733   case ISD::FP_ROUND:
734   case ISD::FSIN:
735     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
736                               Depth + 1);
737   }
738 }
739 
740 /// If isNegatibleForFree returns true, return the newly negated expression.
741 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
742                                     bool LegalOperations, unsigned Depth = 0) {
743   const TargetOptions &Options = DAG.getTarget().Options;
744   // fneg is removable even if it has multiple uses.
745   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
746 
747   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
748 
749   const SDNodeFlags Flags = Op.getNode()->getFlags();
750 
751   switch (Op.getOpcode()) {
752   default: llvm_unreachable("Unknown code");
753   case ISD::ConstantFP: {
754     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
755     V.changeSign();
756     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
757   }
758   case ISD::FADD:
759     // FIXME: determine better conditions for this xform.
760     assert(Options.UnsafeFPMath);
761 
762     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
763     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
764                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
765       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
766                          GetNegatedExpression(Op.getOperand(0), DAG,
767                                               LegalOperations, Depth+1),
768                          Op.getOperand(1), Flags);
769     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
770     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
771                        GetNegatedExpression(Op.getOperand(1), DAG,
772                                             LegalOperations, Depth+1),
773                        Op.getOperand(0), Flags);
774   case ISD::FSUB:
775     // fold (fneg (fsub 0, B)) -> B
776     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
777       if (N0CFP->isZero())
778         return Op.getOperand(1);
779 
780     // fold (fneg (fsub A, B)) -> (fsub B, A)
781     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
782                        Op.getOperand(1), Op.getOperand(0), Flags);
783 
784   case ISD::FMUL:
785   case ISD::FDIV:
786     assert(!Options.HonorSignDependentRoundingFPMath());
787 
788     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
789     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
790                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
791       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
792                          GetNegatedExpression(Op.getOperand(0), DAG,
793                                               LegalOperations, Depth+1),
794                          Op.getOperand(1), Flags);
795 
796     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
797     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
798                        Op.getOperand(0),
799                        GetNegatedExpression(Op.getOperand(1), DAG,
800                                             LegalOperations, Depth+1), Flags);
801 
802   case ISD::FP_EXTEND:
803   case ISD::FSIN:
804     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
805                        GetNegatedExpression(Op.getOperand(0), DAG,
806                                             LegalOperations, Depth+1));
807   case ISD::FP_ROUND:
808       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
809                          GetNegatedExpression(Op.getOperand(0), DAG,
810                                               LegalOperations, Depth+1),
811                          Op.getOperand(1));
812   }
813 }
814 
815 // APInts must be the same size for most operations, this helper
816 // function zero extends the shorter of the pair so that they match.
817 // We provide an Offset so that we can create bitwidths that won't overflow.
818 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
819   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
820   LHS = LHS.zextOrSelf(Bits);
821   RHS = RHS.zextOrSelf(Bits);
822 }
823 
824 // Return true if this node is a setcc, or is a select_cc
825 // that selects between the target values used for true and false, making it
826 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
827 // the appropriate nodes based on the type of node we are checking. This
828 // simplifies life a bit for the callers.
829 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
830                                     SDValue &CC) const {
831   if (N.getOpcode() == ISD::SETCC) {
832     LHS = N.getOperand(0);
833     RHS = N.getOperand(1);
834     CC  = N.getOperand(2);
835     return true;
836   }
837 
838   if (N.getOpcode() != ISD::SELECT_CC ||
839       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
840       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
841     return false;
842 
843   if (TLI.getBooleanContents(N.getValueType()) ==
844       TargetLowering::UndefinedBooleanContent)
845     return false;
846 
847   LHS = N.getOperand(0);
848   RHS = N.getOperand(1);
849   CC  = N.getOperand(4);
850   return true;
851 }
852 
853 /// Return true if this is a SetCC-equivalent operation with only one use.
854 /// If this is true, it allows the users to invert the operation for free when
855 /// it is profitable to do so.
856 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
857   SDValue N0, N1, N2;
858   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
859     return true;
860   return false;
861 }
862 
863 static SDValue peekThroughBitcast(SDValue V) {
864   while (V.getOpcode() == ISD::BITCAST)
865     V = V.getOperand(0);
866   return V;
867 }
868 
869 // Returns the SDNode if it is a constant float BuildVector
870 // or constant float.
871 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
872   if (isa<ConstantFPSDNode>(N))
873     return N.getNode();
874   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
875     return N.getNode();
876   return nullptr;
877 }
878 
879 // Determines if it is a constant integer or a build vector of constant
880 // integers (and undefs).
881 // Do not permit build vector implicit truncation.
882 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
883   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
884     return !(Const->isOpaque() && NoOpaques);
885   if (N.getOpcode() != ISD::BUILD_VECTOR)
886     return false;
887   unsigned BitWidth = N.getScalarValueSizeInBits();
888   for (const SDValue &Op : N->op_values()) {
889     if (Op.isUndef())
890       continue;
891     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
892     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
893         (Const->isOpaque() && NoOpaques))
894       return false;
895   }
896   return true;
897 }
898 
899 // Determines if it is a constant null integer or a splatted vector of a
900 // constant null integer (with no undefs).
901 // Build vector implicit truncation is not an issue for null values.
902 static bool isNullConstantOrNullSplatConstant(SDValue N) {
903   // TODO: may want to use peekThroughBitcast() here.
904   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
905     return Splat->isNullValue();
906   return false;
907 }
908 
909 // Determines if it is a constant integer of one or a splatted vector of a
910 // constant integer of one (with no undefs).
911 // Do not permit build vector implicit truncation.
912 static bool isOneConstantOrOneSplatConstant(SDValue N) {
913   // TODO: may want to use peekThroughBitcast() here.
914   unsigned BitWidth = N.getScalarValueSizeInBits();
915   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
916     return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
917   return false;
918 }
919 
920 // Determines if it is a constant integer of all ones or a splatted vector of a
921 // constant integer of all ones (with no undefs).
922 // Do not permit build vector implicit truncation.
923 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
924   N = peekThroughBitcast(N);
925   unsigned BitWidth = N.getScalarValueSizeInBits();
926   if (ConstantSDNode *Splat = isConstOrConstSplat(N))
927     return Splat->isAllOnesValue() &&
928            Splat->getAPIntValue().getBitWidth() == BitWidth;
929   return false;
930 }
931 
932 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
933 // undef's.
934 static bool isAnyConstantBuildVector(const SDNode *N) {
935   return ISD::isBuildVectorOfConstantSDNodes(N) ||
936          ISD::isBuildVectorOfConstantFPSDNodes(N);
937 }
938 
939 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
940                                     SDValue N1) {
941   EVT VT = N0.getValueType();
942   if (N0.getOpcode() == Opc) {
943     if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
944       if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
945         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
946         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
947           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
948         return SDValue();
949       }
950       if (N0.hasOneUse()) {
951         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
952         // use
953         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
954         if (!OpNode.getNode())
955           return SDValue();
956         AddToWorklist(OpNode.getNode());
957         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
958       }
959     }
960   }
961 
962   if (N1.getOpcode() == Opc) {
963     if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
964       if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
965         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
966         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
967           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
968         return SDValue();
969       }
970       if (N1.hasOneUse()) {
971         // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
972         // use
973         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
974         if (!OpNode.getNode())
975           return SDValue();
976         AddToWorklist(OpNode.getNode());
977         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
978       }
979     }
980   }
981 
982   return SDValue();
983 }
984 
985 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
986                                bool AddTo) {
987   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
988   ++NodesCombined;
989   LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
990              To[0].getNode()->dump(&DAG);
991              dbgs() << " and " << NumTo - 1 << " other values\n");
992   for (unsigned i = 0, e = NumTo; i != e; ++i)
993     assert((!To[i].getNode() ||
994             N->getValueType(i) == To[i].getValueType()) &&
995            "Cannot combine value to value of different type!");
996 
997   WorklistRemover DeadNodes(*this);
998   DAG.ReplaceAllUsesWith(N, To);
999   if (AddTo) {
1000     // Push the new nodes and any users onto the worklist
1001     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1002       if (To[i].getNode()) {
1003         AddToWorklist(To[i].getNode());
1004         AddUsersToWorklist(To[i].getNode());
1005       }
1006     }
1007   }
1008 
1009   // Finally, if the node is now dead, remove it from the graph.  The node
1010   // may not be dead if the replacement process recursively simplified to
1011   // something else needing this node.
1012   if (N->use_empty())
1013     deleteAndRecombine(N);
1014   return SDValue(N, 0);
1015 }
1016 
1017 void DAGCombiner::
1018 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1019   // Replace all uses.  If any nodes become isomorphic to other nodes and
1020   // are deleted, make sure to remove them from our worklist.
1021   WorklistRemover DeadNodes(*this);
1022   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1023 
1024   // Push the new node and any (possibly new) users onto the worklist.
1025   AddToWorklist(TLO.New.getNode());
1026   AddUsersToWorklist(TLO.New.getNode());
1027 
1028   // Finally, if the node is now dead, remove it from the graph.  The node
1029   // may not be dead if the replacement process recursively simplified to
1030   // something else needing this node.
1031   if (TLO.Old.getNode()->use_empty())
1032     deleteAndRecombine(TLO.Old.getNode());
1033 }
1034 
1035 /// Check the specified integer node value to see if it can be simplified or if
1036 /// things it uses can be simplified by bit propagation. If so, return true.
1037 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
1038   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1039   KnownBits Known;
1040   if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
1041     return false;
1042 
1043   // Revisit the node.
1044   AddToWorklist(Op.getNode());
1045 
1046   // Replace the old value with the new one.
1047   ++NodesCombined;
1048   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1049              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1050              dbgs() << '\n');
1051 
1052   CommitTargetLoweringOpt(TLO);
1053   return true;
1054 }
1055 
1056 /// Check the specified vector node value to see if it can be simplified or
1057 /// if things it uses can be simplified as it only uses some of the elements.
1058 /// If so, return true.
1059 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1060                                              const APInt &Demanded) {
1061   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1062   APInt KnownUndef, KnownZero;
1063   if (!TLI.SimplifyDemandedVectorElts(Op, Demanded, KnownUndef, KnownZero, TLO))
1064     return false;
1065 
1066   // Revisit the node.
1067   AddToWorklist(Op.getNode());
1068 
1069   // Replace the old value with the new one.
1070   ++NodesCombined;
1071   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1072              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1073              dbgs() << '\n');
1074 
1075   CommitTargetLoweringOpt(TLO);
1076   return true;
1077 }
1078 
1079 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1080   SDLoc DL(Load);
1081   EVT VT = Load->getValueType(0);
1082   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1083 
1084   LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1085              Trunc.getNode()->dump(&DAG); dbgs() << '\n');
1086   WorklistRemover DeadNodes(*this);
1087   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1088   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1089   deleteAndRecombine(Load);
1090   AddToWorklist(Trunc.getNode());
1091 }
1092 
1093 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1094   Replace = false;
1095   SDLoc DL(Op);
1096   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1097     LoadSDNode *LD = cast<LoadSDNode>(Op);
1098     EVT MemVT = LD->getMemoryVT();
1099     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1100                                                       : LD->getExtensionType();
1101     Replace = true;
1102     return DAG.getExtLoad(ExtType, DL, PVT,
1103                           LD->getChain(), LD->getBasePtr(),
1104                           MemVT, LD->getMemOperand());
1105   }
1106 
1107   unsigned Opc = Op.getOpcode();
1108   switch (Opc) {
1109   default: break;
1110   case ISD::AssertSext:
1111     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1112       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1113     break;
1114   case ISD::AssertZext:
1115     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1116       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1117     break;
1118   case ISD::Constant: {
1119     unsigned ExtOpc =
1120       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1121     return DAG.getNode(ExtOpc, DL, PVT, Op);
1122   }
1123   }
1124 
1125   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1126     return SDValue();
1127   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1128 }
1129 
1130 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1131   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1132     return SDValue();
1133   EVT OldVT = Op.getValueType();
1134   SDLoc DL(Op);
1135   bool Replace = false;
1136   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1137   if (!NewOp.getNode())
1138     return SDValue();
1139   AddToWorklist(NewOp.getNode());
1140 
1141   if (Replace)
1142     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1143   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1144                      DAG.getValueType(OldVT));
1145 }
1146 
1147 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1148   EVT OldVT = Op.getValueType();
1149   SDLoc DL(Op);
1150   bool Replace = false;
1151   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1152   if (!NewOp.getNode())
1153     return SDValue();
1154   AddToWorklist(NewOp.getNode());
1155 
1156   if (Replace)
1157     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1158   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1159 }
1160 
1161 /// Promote the specified integer binary operation if the target indicates it is
1162 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1163 /// i32 since i16 instructions are longer.
1164 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1165   if (!LegalOperations)
1166     return SDValue();
1167 
1168   EVT VT = Op.getValueType();
1169   if (VT.isVector() || !VT.isInteger())
1170     return SDValue();
1171 
1172   // If operation type is 'undesirable', e.g. i16 on x86, consider
1173   // promoting it.
1174   unsigned Opc = Op.getOpcode();
1175   if (TLI.isTypeDesirableForOp(Opc, VT))
1176     return SDValue();
1177 
1178   EVT PVT = VT;
1179   // Consult target whether it is a good idea to promote this operation and
1180   // what's the right type to promote it to.
1181   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1182     assert(PVT != VT && "Don't know what type to promote to!");
1183 
1184     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1185 
1186     bool Replace0 = false;
1187     SDValue N0 = Op.getOperand(0);
1188     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1189 
1190     bool Replace1 = false;
1191     SDValue N1 = Op.getOperand(1);
1192     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1193     SDLoc DL(Op);
1194 
1195     SDValue RV =
1196         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1197 
1198     // We are always replacing N0/N1's use in N and only need
1199     // additional replacements if there are additional uses.
1200     Replace0 &= !N0->hasOneUse();
1201     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1202 
1203     // Combine Op here so it is preserved past replacements.
1204     CombineTo(Op.getNode(), RV);
1205 
1206     // If operands have a use ordering, make sure we deal with
1207     // predecessor first.
1208     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1209       std::swap(N0, N1);
1210       std::swap(NN0, NN1);
1211     }
1212 
1213     if (Replace0) {
1214       AddToWorklist(NN0.getNode());
1215       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1216     }
1217     if (Replace1) {
1218       AddToWorklist(NN1.getNode());
1219       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1220     }
1221     return Op;
1222   }
1223   return SDValue();
1224 }
1225 
1226 /// Promote the specified integer shift operation if the target indicates it is
1227 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1228 /// i32 since i16 instructions are longer.
1229 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1230   if (!LegalOperations)
1231     return SDValue();
1232 
1233   EVT VT = Op.getValueType();
1234   if (VT.isVector() || !VT.isInteger())
1235     return SDValue();
1236 
1237   // If operation type is 'undesirable', e.g. i16 on x86, consider
1238   // promoting it.
1239   unsigned Opc = Op.getOpcode();
1240   if (TLI.isTypeDesirableForOp(Opc, VT))
1241     return SDValue();
1242 
1243   EVT PVT = VT;
1244   // Consult target whether it is a good idea to promote this operation and
1245   // what's the right type to promote it to.
1246   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1247     assert(PVT != VT && "Don't know what type to promote to!");
1248 
1249     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1250 
1251     bool Replace = false;
1252     SDValue N0 = Op.getOperand(0);
1253     SDValue N1 = Op.getOperand(1);
1254     if (Opc == ISD::SRA)
1255       N0 = SExtPromoteOperand(N0, PVT);
1256     else if (Opc == ISD::SRL)
1257       N0 = ZExtPromoteOperand(N0, PVT);
1258     else
1259       N0 = PromoteOperand(N0, PVT, Replace);
1260 
1261     if (!N0.getNode())
1262       return SDValue();
1263 
1264     SDLoc DL(Op);
1265     SDValue RV =
1266         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1267 
1268     AddToWorklist(N0.getNode());
1269     if (Replace)
1270       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1271 
1272     // Deal with Op being deleted.
1273     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1274       return RV;
1275   }
1276   return SDValue();
1277 }
1278 
1279 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1280   if (!LegalOperations)
1281     return SDValue();
1282 
1283   EVT VT = Op.getValueType();
1284   if (VT.isVector() || !VT.isInteger())
1285     return SDValue();
1286 
1287   // If operation type is 'undesirable', e.g. i16 on x86, consider
1288   // promoting it.
1289   unsigned Opc = Op.getOpcode();
1290   if (TLI.isTypeDesirableForOp(Opc, VT))
1291     return SDValue();
1292 
1293   EVT PVT = VT;
1294   // Consult target whether it is a good idea to promote this operation and
1295   // what's the right type to promote it to.
1296   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1297     assert(PVT != VT && "Don't know what type to promote to!");
1298     // fold (aext (aext x)) -> (aext x)
1299     // fold (aext (zext x)) -> (zext x)
1300     // fold (aext (sext x)) -> (sext x)
1301     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1302     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1303   }
1304   return SDValue();
1305 }
1306 
1307 bool DAGCombiner::PromoteLoad(SDValue Op) {
1308   if (!LegalOperations)
1309     return false;
1310 
1311   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1312     return false;
1313 
1314   EVT VT = Op.getValueType();
1315   if (VT.isVector() || !VT.isInteger())
1316     return false;
1317 
1318   // If operation type is 'undesirable', e.g. i16 on x86, consider
1319   // promoting it.
1320   unsigned Opc = Op.getOpcode();
1321   if (TLI.isTypeDesirableForOp(Opc, VT))
1322     return false;
1323 
1324   EVT PVT = VT;
1325   // Consult target whether it is a good idea to promote this operation and
1326   // what's the right type to promote it to.
1327   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1328     assert(PVT != VT && "Don't know what type to promote to!");
1329 
1330     SDLoc DL(Op);
1331     SDNode *N = Op.getNode();
1332     LoadSDNode *LD = cast<LoadSDNode>(N);
1333     EVT MemVT = LD->getMemoryVT();
1334     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1335                                                       : LD->getExtensionType();
1336     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1337                                    LD->getChain(), LD->getBasePtr(),
1338                                    MemVT, LD->getMemOperand());
1339     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1340 
1341     LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1342                Result.getNode()->dump(&DAG); 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 /// 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     LLVM_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     LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
1466 
1467     if (N->getNumValues() == RV.getNode()->getNumValues())
1468       DAG.ReplaceAllUsesWith(N, RV.getNode());
1469     else {
1470       assert(N->getValueType(0) == RV.getValueType() &&
1471              N->getNumValues() == 1 && "Type mismatch");
1472       DAG.ReplaceAllUsesWith(N, &RV);
1473     }
1474 
1475     // Push the new node and any users onto the worklist
1476     AddToWorklist(RV.getNode());
1477     AddUsersToWorklist(RV.getNode());
1478 
1479     // Finally, if the node is now dead, remove it from the graph.  The node
1480     // may not be dead if the replacement process recursively simplified to
1481     // something else needing this node. This will also take care of adding any
1482     // operands which have lost a user to the worklist.
1483     recursivelyDeleteUnusedNodes(N);
1484   }
1485 
1486   // If the root changed (e.g. it was a dead load, update the root).
1487   DAG.setRoot(Dummy.getValue());
1488   DAG.RemoveDeadNodes();
1489 }
1490 
1491 SDValue DAGCombiner::visit(SDNode *N) {
1492   switch (N->getOpcode()) {
1493   default: break;
1494   case ISD::TokenFactor:        return visitTokenFactor(N);
1495   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1496   case ISD::ADD:                return visitADD(N);
1497   case ISD::SUB:                return visitSUB(N);
1498   case ISD::ADDC:               return visitADDC(N);
1499   case ISD::UADDO:              return visitUADDO(N);
1500   case ISD::SUBC:               return visitSUBC(N);
1501   case ISD::USUBO:              return visitUSUBO(N);
1502   case ISD::ADDE:               return visitADDE(N);
1503   case ISD::ADDCARRY:           return visitADDCARRY(N);
1504   case ISD::SUBE:               return visitSUBE(N);
1505   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1506   case ISD::MUL:                return visitMUL(N);
1507   case ISD::SDIV:               return visitSDIV(N);
1508   case ISD::UDIV:               return visitUDIV(N);
1509   case ISD::SREM:
1510   case ISD::UREM:               return visitREM(N);
1511   case ISD::MULHU:              return visitMULHU(N);
1512   case ISD::MULHS:              return visitMULHS(N);
1513   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1514   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1515   case ISD::SMULO:              return visitSMULO(N);
1516   case ISD::UMULO:              return visitUMULO(N);
1517   case ISD::SMIN:
1518   case ISD::SMAX:
1519   case ISD::UMIN:
1520   case ISD::UMAX:               return visitIMINMAX(N);
1521   case ISD::AND:                return visitAND(N);
1522   case ISD::OR:                 return visitOR(N);
1523   case ISD::XOR:                return visitXOR(N);
1524   case ISD::SHL:                return visitSHL(N);
1525   case ISD::SRA:                return visitSRA(N);
1526   case ISD::SRL:                return visitSRL(N);
1527   case ISD::ROTR:
1528   case ISD::ROTL:               return visitRotate(N);
1529   case ISD::ABS:                return visitABS(N);
1530   case ISD::BSWAP:              return visitBSWAP(N);
1531   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1532   case ISD::CTLZ:               return visitCTLZ(N);
1533   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1534   case ISD::CTTZ:               return visitCTTZ(N);
1535   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1536   case ISD::CTPOP:              return visitCTPOP(N);
1537   case ISD::SELECT:             return visitSELECT(N);
1538   case ISD::VSELECT:            return visitVSELECT(N);
1539   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1540   case ISD::SETCC:              return visitSETCC(N);
1541   case ISD::SETCCE:             return visitSETCCE(N);
1542   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1543   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1544   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1545   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1546   case ISD::AssertSext:
1547   case ISD::AssertZext:         return visitAssertExt(N);
1548   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1549   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1550   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1551   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1552   case ISD::BITCAST:            return visitBITCAST(N);
1553   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1554   case ISD::FADD:               return visitFADD(N);
1555   case ISD::FSUB:               return visitFSUB(N);
1556   case ISD::FMUL:               return visitFMUL(N);
1557   case ISD::FMA:                return visitFMA(N);
1558   case ISD::FDIV:               return visitFDIV(N);
1559   case ISD::FREM:               return visitFREM(N);
1560   case ISD::FSQRT:              return visitFSQRT(N);
1561   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1562   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1563   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1564   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1565   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1566   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1567   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1568   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1569   case ISD::FNEG:               return visitFNEG(N);
1570   case ISD::FABS:               return visitFABS(N);
1571   case ISD::FFLOOR:             return visitFFLOOR(N);
1572   case ISD::FMINNUM:            return visitFMINNUM(N);
1573   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1574   case ISD::FCEIL:              return visitFCEIL(N);
1575   case ISD::FTRUNC:             return visitFTRUNC(N);
1576   case ISD::BRCOND:             return visitBRCOND(N);
1577   case ISD::BR_CC:              return visitBR_CC(N);
1578   case ISD::LOAD:               return visitLOAD(N);
1579   case ISD::STORE:              return visitSTORE(N);
1580   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1581   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1582   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1583   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1584   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1585   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1586   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1587   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1588   case ISD::MGATHER:            return visitMGATHER(N);
1589   case ISD::MLOAD:              return visitMLOAD(N);
1590   case ISD::MSCATTER:           return visitMSCATTER(N);
1591   case ISD::MSTORE:             return visitMSTORE(N);
1592   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1593   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1594   }
1595   return SDValue();
1596 }
1597 
1598 SDValue DAGCombiner::combine(SDNode *N) {
1599   SDValue RV = visit(N);
1600 
1601   // If nothing happened, try a target-specific DAG combine.
1602   if (!RV.getNode()) {
1603     assert(N->getOpcode() != ISD::DELETED_NODE &&
1604            "Node was deleted but visit returned NULL!");
1605 
1606     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1607         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1608 
1609       // Expose the DAG combiner to the target combiner impls.
1610       TargetLowering::DAGCombinerInfo
1611         DagCombineInfo(DAG, Level, false, this);
1612 
1613       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1614     }
1615   }
1616 
1617   // If nothing happened still, try promoting the operation.
1618   if (!RV.getNode()) {
1619     switch (N->getOpcode()) {
1620     default: break;
1621     case ISD::ADD:
1622     case ISD::SUB:
1623     case ISD::MUL:
1624     case ISD::AND:
1625     case ISD::OR:
1626     case ISD::XOR:
1627       RV = PromoteIntBinOp(SDValue(N, 0));
1628       break;
1629     case ISD::SHL:
1630     case ISD::SRA:
1631     case ISD::SRL:
1632       RV = PromoteIntShiftOp(SDValue(N, 0));
1633       break;
1634     case ISD::SIGN_EXTEND:
1635     case ISD::ZERO_EXTEND:
1636     case ISD::ANY_EXTEND:
1637       RV = PromoteExtend(SDValue(N, 0));
1638       break;
1639     case ISD::LOAD:
1640       if (PromoteLoad(SDValue(N, 0)))
1641         RV = SDValue(N, 0);
1642       break;
1643     }
1644   }
1645 
1646   // If N is a commutative binary node, try eliminate it if the commuted
1647   // version is already present in the DAG.
1648   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1649       N->getNumValues() == 1) {
1650     SDValue N0 = N->getOperand(0);
1651     SDValue N1 = N->getOperand(1);
1652 
1653     // Constant operands are canonicalized to RHS.
1654     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1655       SDValue Ops[] = {N1, N0};
1656       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1657                                             N->getFlags());
1658       if (CSENode)
1659         return SDValue(CSENode, 0);
1660     }
1661   }
1662 
1663   return RV;
1664 }
1665 
1666 /// Given a node, return its input chain if it has one, otherwise return a null
1667 /// sd operand.
1668 static SDValue getInputChainForNode(SDNode *N) {
1669   if (unsigned NumOps = N->getNumOperands()) {
1670     if (N->getOperand(0).getValueType() == MVT::Other)
1671       return N->getOperand(0);
1672     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1673       return N->getOperand(NumOps-1);
1674     for (unsigned i = 1; i < NumOps-1; ++i)
1675       if (N->getOperand(i).getValueType() == MVT::Other)
1676         return N->getOperand(i);
1677   }
1678   return SDValue();
1679 }
1680 
1681 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1682   // If N has two operands, where one has an input chain equal to the other,
1683   // the 'other' chain is redundant.
1684   if (N->getNumOperands() == 2) {
1685     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1686       return N->getOperand(0);
1687     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1688       return N->getOperand(1);
1689   }
1690 
1691   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1692   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1693   SmallPtrSet<SDNode*, 16> SeenOps;
1694   bool Changed = false;             // If we should replace this token factor.
1695 
1696   // Start out with this token factor.
1697   TFs.push_back(N);
1698 
1699   // Iterate through token factors.  The TFs grows when new token factors are
1700   // encountered.
1701   for (unsigned i = 0; i < TFs.size(); ++i) {
1702     SDNode *TF = TFs[i];
1703 
1704     // Check each of the operands.
1705     for (const SDValue &Op : TF->op_values()) {
1706       switch (Op.getOpcode()) {
1707       case ISD::EntryToken:
1708         // Entry tokens don't need to be added to the list. They are
1709         // redundant.
1710         Changed = true;
1711         break;
1712 
1713       case ISD::TokenFactor:
1714         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1715           // Queue up for processing.
1716           TFs.push_back(Op.getNode());
1717           // Clean up in case the token factor is removed.
1718           AddToWorklist(Op.getNode());
1719           Changed = true;
1720           break;
1721         }
1722         LLVM_FALLTHROUGH;
1723 
1724       default:
1725         // Only add if it isn't already in the list.
1726         if (SeenOps.insert(Op.getNode()).second)
1727           Ops.push_back(Op);
1728         else
1729           Changed = true;
1730         break;
1731       }
1732     }
1733   }
1734 
1735   // Remove Nodes that are chained to another node in the list. Do so
1736   // by walking up chains breath-first stopping when we've seen
1737   // another operand. In general we must climb to the EntryNode, but we can exit
1738   // early if we find all remaining work is associated with just one operand as
1739   // no further pruning is possible.
1740 
1741   // List of nodes to search through and original Ops from which they originate.
1742   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1743   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1744   SmallPtrSet<SDNode *, 16> SeenChains;
1745   bool DidPruneOps = false;
1746 
1747   unsigned NumLeftToConsider = 0;
1748   for (const SDValue &Op : Ops) {
1749     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1750     OpWorkCount.push_back(1);
1751   }
1752 
1753   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1754     // If this is an Op, we can remove the op from the list. Remark any
1755     // search associated with it as from the current OpNumber.
1756     if (SeenOps.count(Op) != 0) {
1757       Changed = true;
1758       DidPruneOps = true;
1759       unsigned OrigOpNumber = 0;
1760       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1761         OrigOpNumber++;
1762       assert((OrigOpNumber != Ops.size()) &&
1763              "expected to find TokenFactor Operand");
1764       // Re-mark worklist from OrigOpNumber to OpNumber
1765       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1766         if (Worklist[i].second == OrigOpNumber) {
1767           Worklist[i].second = OpNumber;
1768         }
1769       }
1770       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1771       OpWorkCount[OrigOpNumber] = 0;
1772       NumLeftToConsider--;
1773     }
1774     // Add if it's a new chain
1775     if (SeenChains.insert(Op).second) {
1776       OpWorkCount[OpNumber]++;
1777       Worklist.push_back(std::make_pair(Op, OpNumber));
1778     }
1779   };
1780 
1781   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1782     // We need at least be consider at least 2 Ops to prune.
1783     if (NumLeftToConsider <= 1)
1784       break;
1785     auto CurNode = Worklist[i].first;
1786     auto CurOpNumber = Worklist[i].second;
1787     assert((OpWorkCount[CurOpNumber] > 0) &&
1788            "Node should not appear in worklist");
1789     switch (CurNode->getOpcode()) {
1790     case ISD::EntryToken:
1791       // Hitting EntryToken is the only way for the search to terminate without
1792       // hitting
1793       // another operand's search. Prevent us from marking this operand
1794       // considered.
1795       NumLeftToConsider++;
1796       break;
1797     case ISD::TokenFactor:
1798       for (const SDValue &Op : CurNode->op_values())
1799         AddToWorklist(i, Op.getNode(), CurOpNumber);
1800       break;
1801     case ISD::CopyFromReg:
1802     case ISD::CopyToReg:
1803       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1804       break;
1805     default:
1806       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1807         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1808       break;
1809     }
1810     OpWorkCount[CurOpNumber]--;
1811     if (OpWorkCount[CurOpNumber] == 0)
1812       NumLeftToConsider--;
1813   }
1814 
1815   // If we've changed things around then replace token factor.
1816   if (Changed) {
1817     SDValue Result;
1818     if (Ops.empty()) {
1819       // The entry token is the only possible outcome.
1820       Result = DAG.getEntryNode();
1821     } else {
1822       if (DidPruneOps) {
1823         SmallVector<SDValue, 8> PrunedOps;
1824         //
1825         for (const SDValue &Op : Ops) {
1826           if (SeenChains.count(Op.getNode()) == 0)
1827             PrunedOps.push_back(Op);
1828         }
1829         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1830       } else {
1831         Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1832       }
1833     }
1834     return Result;
1835   }
1836   return SDValue();
1837 }
1838 
1839 /// MERGE_VALUES can always be eliminated.
1840 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1841   WorklistRemover DeadNodes(*this);
1842   // Replacing results may cause a different MERGE_VALUES to suddenly
1843   // be CSE'd with N, and carry its uses with it. Iterate until no
1844   // uses remain, to ensure that the node can be safely deleted.
1845   // First add the users of this node to the work list so that they
1846   // can be tried again once they have new operands.
1847   AddUsersToWorklist(N);
1848   do {
1849     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1850       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1851   } while (!N->use_empty());
1852   deleteAndRecombine(N);
1853   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1854 }
1855 
1856 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1857 /// ConstantSDNode pointer else nullptr.
1858 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1859   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1860   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1861 }
1862 
1863 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1864   auto BinOpcode = BO->getOpcode();
1865   assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1866           BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1867           BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1868           BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1869           BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1870           BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1871           BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1872           BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1873           BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1874          "Unexpected binary operator");
1875 
1876   // Bail out if any constants are opaque because we can't constant fold those.
1877   SDValue C1 = BO->getOperand(1);
1878   if (!isConstantOrConstantVector(C1, true) &&
1879       !isConstantFPBuildVectorOrConstantFP(C1))
1880     return SDValue();
1881 
1882   // Don't do this unless the old select is going away. We want to eliminate the
1883   // binary operator, not replace a binop with a select.
1884   // TODO: Handle ISD::SELECT_CC.
1885   SDValue Sel = BO->getOperand(0);
1886   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1887     return SDValue();
1888 
1889   SDValue CT = Sel.getOperand(1);
1890   if (!isConstantOrConstantVector(CT, true) &&
1891       !isConstantFPBuildVectorOrConstantFP(CT))
1892     return SDValue();
1893 
1894   SDValue CF = Sel.getOperand(2);
1895   if (!isConstantOrConstantVector(CF, true) &&
1896       !isConstantFPBuildVectorOrConstantFP(CF))
1897     return SDValue();
1898 
1899   // We have a select-of-constants followed by a binary operator with a
1900   // constant. Eliminate the binop by pulling the constant math into the select.
1901   // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1902   EVT VT = Sel.getValueType();
1903   SDLoc DL(Sel);
1904   SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1905   if (!NewCT.isUndef() &&
1906       !isConstantOrConstantVector(NewCT, true) &&
1907       !isConstantFPBuildVectorOrConstantFP(NewCT))
1908     return SDValue();
1909 
1910   SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1911   if (!NewCF.isUndef() &&
1912       !isConstantOrConstantVector(NewCF, true) &&
1913       !isConstantFPBuildVectorOrConstantFP(NewCF))
1914     return SDValue();
1915 
1916   return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1917 }
1918 
1919 SDValue DAGCombiner::visitADD(SDNode *N) {
1920   SDValue N0 = N->getOperand(0);
1921   SDValue N1 = N->getOperand(1);
1922   EVT VT = N0.getValueType();
1923   SDLoc DL(N);
1924 
1925   // fold vector ops
1926   if (VT.isVector()) {
1927     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1928       return FoldedVOp;
1929 
1930     // fold (add x, 0) -> x, vector edition
1931     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1932       return N0;
1933     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1934       return N1;
1935   }
1936 
1937   // fold (add x, undef) -> undef
1938   if (N0.isUndef())
1939     return N0;
1940 
1941   if (N1.isUndef())
1942     return N1;
1943 
1944   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1945     // canonicalize constant to RHS
1946     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1947       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1948     // fold (add c1, c2) -> c1+c2
1949     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1950                                       N1.getNode());
1951   }
1952 
1953   // fold (add x, 0) -> x
1954   if (isNullConstant(N1))
1955     return N0;
1956 
1957   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1958     // fold ((c1-A)+c2) -> (c1+c2)-A
1959     if (N0.getOpcode() == ISD::SUB &&
1960         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1961       // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1962       return DAG.getNode(ISD::SUB, DL, VT,
1963                          DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1964                          N0.getOperand(1));
1965     }
1966 
1967     // add (sext i1 X), 1 -> zext (not i1 X)
1968     // We don't transform this pattern:
1969     //   add (zext i1 X), -1 -> sext (not i1 X)
1970     // because most (?) targets generate better code for the zext form.
1971     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1972         isOneConstantOrOneSplatConstant(N1)) {
1973       SDValue X = N0.getOperand(0);
1974       if ((!LegalOperations ||
1975            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1976             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1977           X.getScalarValueSizeInBits() == 1) {
1978         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1979         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1980       }
1981     }
1982 
1983     // Undo the add -> or combine to merge constant offsets from a frame index.
1984     if (N0.getOpcode() == ISD::OR &&
1985         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
1986         isa<ConstantSDNode>(N0.getOperand(1)) &&
1987         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
1988       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
1989       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
1990     }
1991   }
1992 
1993   if (SDValue NewSel = foldBinOpIntoSelect(N))
1994     return NewSel;
1995 
1996   // reassociate add
1997   if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1998     return RADD;
1999 
2000   // fold ((0-A) + B) -> B-A
2001   if (N0.getOpcode() == ISD::SUB &&
2002       isNullConstantOrNullSplatConstant(N0.getOperand(0)))
2003     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2004 
2005   // fold (A + (0-B)) -> A-B
2006   if (N1.getOpcode() == ISD::SUB &&
2007       isNullConstantOrNullSplatConstant(N1.getOperand(0)))
2008     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2009 
2010   // fold (A+(B-A)) -> B
2011   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2012     return N1.getOperand(0);
2013 
2014   // fold ((B-A)+A) -> B
2015   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2016     return N0.getOperand(0);
2017 
2018   // fold (A+(B-(A+C))) to (B-C)
2019   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2020       N0 == N1.getOperand(1).getOperand(0))
2021     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2022                        N1.getOperand(1).getOperand(1));
2023 
2024   // fold (A+(B-(C+A))) to (B-C)
2025   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2026       N0 == N1.getOperand(1).getOperand(1))
2027     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2028                        N1.getOperand(1).getOperand(0));
2029 
2030   // fold (A+((B-A)+or-C)) to (B+or-C)
2031   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2032       N1.getOperand(0).getOpcode() == ISD::SUB &&
2033       N0 == N1.getOperand(0).getOperand(1))
2034     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2035                        N1.getOperand(1));
2036 
2037   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2038   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2039     SDValue N00 = N0.getOperand(0);
2040     SDValue N01 = N0.getOperand(1);
2041     SDValue N10 = N1.getOperand(0);
2042     SDValue N11 = N1.getOperand(1);
2043 
2044     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2045       return DAG.getNode(ISD::SUB, DL, VT,
2046                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2047                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2048   }
2049 
2050   if (SimplifyDemandedBits(SDValue(N, 0)))
2051     return SDValue(N, 0);
2052 
2053   // fold (a+b) -> (a|b) iff a and b share no bits.
2054   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2055       DAG.haveNoCommonBitsSet(N0, N1))
2056     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2057 
2058   if (SDValue Combined = visitADDLike(N0, N1, N))
2059     return Combined;
2060 
2061   if (SDValue Combined = visitADDLike(N1, N0, N))
2062     return Combined;
2063 
2064   return SDValue();
2065 }
2066 
2067 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2068   bool Masked = false;
2069 
2070   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2071   while (true) {
2072     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2073       V = V.getOperand(0);
2074       continue;
2075     }
2076 
2077     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2078       Masked = true;
2079       V = V.getOperand(0);
2080       continue;
2081     }
2082 
2083     break;
2084   }
2085 
2086   // If this is not a carry, return.
2087   if (V.getResNo() != 1)
2088     return SDValue();
2089 
2090   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2091       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2092     return SDValue();
2093 
2094   // If the result is masked, then no matter what kind of bool it is we can
2095   // return. If it isn't, then we need to make sure the bool type is either 0 or
2096   // 1 and not other values.
2097   if (Masked ||
2098       TLI.getBooleanContents(V.getValueType()) ==
2099           TargetLoweringBase::ZeroOrOneBooleanContent)
2100     return V;
2101 
2102   return SDValue();
2103 }
2104 
2105 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2106   EVT VT = N0.getValueType();
2107   SDLoc DL(LocReference);
2108 
2109   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2110   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2111       isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2112     return DAG.getNode(ISD::SUB, DL, VT, N0,
2113                        DAG.getNode(ISD::SHL, DL, VT,
2114                                    N1.getOperand(0).getOperand(1),
2115                                    N1.getOperand(1)));
2116 
2117   if (N1.getOpcode() == ISD::AND) {
2118     SDValue AndOp0 = N1.getOperand(0);
2119     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2120     unsigned DestBits = VT.getScalarSizeInBits();
2121 
2122     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2123     // and similar xforms where the inner op is either ~0 or 0.
2124     if (NumSignBits == DestBits &&
2125         isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2126       return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2127   }
2128 
2129   // add (sext i1), X -> sub X, (zext i1)
2130   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2131       N0.getOperand(0).getValueType() == MVT::i1 &&
2132       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2133     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2134     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2135   }
2136 
2137   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2138   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2139     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2140     if (TN->getVT() == MVT::i1) {
2141       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2142                                  DAG.getConstant(1, DL, VT));
2143       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2144     }
2145   }
2146 
2147   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2148   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2149       N1.getResNo() == 0)
2150     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2151                        N0, N1.getOperand(0), N1.getOperand(2));
2152 
2153   // (add X, Carry) -> (addcarry X, 0, Carry)
2154   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2155     if (SDValue Carry = getAsCarry(TLI, N1))
2156       return DAG.getNode(ISD::ADDCARRY, DL,
2157                          DAG.getVTList(VT, Carry.getValueType()), N0,
2158                          DAG.getConstant(0, DL, VT), Carry);
2159 
2160   return SDValue();
2161 }
2162 
2163 SDValue DAGCombiner::visitADDC(SDNode *N) {
2164   SDValue N0 = N->getOperand(0);
2165   SDValue N1 = N->getOperand(1);
2166   EVT VT = N0.getValueType();
2167   SDLoc DL(N);
2168 
2169   // If the flag result is dead, turn this into an ADD.
2170   if (!N->hasAnyUseOfValue(1))
2171     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2172                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2173 
2174   // canonicalize constant to RHS.
2175   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2176   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2177   if (N0C && !N1C)
2178     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2179 
2180   // fold (addc x, 0) -> x + no carry out
2181   if (isNullConstant(N1))
2182     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2183                                         DL, MVT::Glue));
2184 
2185   // If it cannot overflow, transform into an add.
2186   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2187     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2188                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2189 
2190   return SDValue();
2191 }
2192 
2193 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2194   SDValue N0 = N->getOperand(0);
2195   SDValue N1 = N->getOperand(1);
2196   EVT VT = N0.getValueType();
2197   if (VT.isVector())
2198     return SDValue();
2199 
2200   EVT CarryVT = N->getValueType(1);
2201   SDLoc DL(N);
2202 
2203   // If the flag result is dead, turn this into an ADD.
2204   if (!N->hasAnyUseOfValue(1))
2205     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2206                      DAG.getUNDEF(CarryVT));
2207 
2208   // canonicalize constant to RHS.
2209   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2210   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2211   if (N0C && !N1C)
2212     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2213 
2214   // fold (uaddo x, 0) -> x + no carry out
2215   if (isNullConstant(N1))
2216     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2217 
2218   // If it cannot overflow, transform into an add.
2219   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2220     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2221                      DAG.getConstant(0, DL, CarryVT));
2222 
2223   if (SDValue Combined = visitUADDOLike(N0, N1, N))
2224     return Combined;
2225 
2226   if (SDValue Combined = visitUADDOLike(N1, N0, N))
2227     return Combined;
2228 
2229   return SDValue();
2230 }
2231 
2232 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2233   auto VT = N0.getValueType();
2234 
2235   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2236   // If Y + 1 cannot overflow.
2237   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2238     SDValue Y = N1.getOperand(0);
2239     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2240     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2241       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2242                          N1.getOperand(2));
2243   }
2244 
2245   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2246   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2247     if (SDValue Carry = getAsCarry(TLI, N1))
2248       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2249                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2250 
2251   return SDValue();
2252 }
2253 
2254 SDValue DAGCombiner::visitADDE(SDNode *N) {
2255   SDValue N0 = N->getOperand(0);
2256   SDValue N1 = N->getOperand(1);
2257   SDValue CarryIn = N->getOperand(2);
2258 
2259   // canonicalize constant to RHS
2260   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2261   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2262   if (N0C && !N1C)
2263     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2264                        N1, N0, CarryIn);
2265 
2266   // fold (adde x, y, false) -> (addc x, y)
2267   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2268     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2269 
2270   return SDValue();
2271 }
2272 
2273 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2274   SDValue N0 = N->getOperand(0);
2275   SDValue N1 = N->getOperand(1);
2276   SDValue CarryIn = N->getOperand(2);
2277   SDLoc DL(N);
2278 
2279   // canonicalize constant to RHS
2280   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2282   if (N0C && !N1C)
2283     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2284 
2285   // fold (addcarry x, y, false) -> (uaddo x, y)
2286   if (isNullConstant(CarryIn))
2287     return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2288 
2289   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2290   if (isNullConstant(N0) && isNullConstant(N1)) {
2291     EVT VT = N0.getValueType();
2292     EVT CarryVT = CarryIn.getValueType();
2293     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2294     AddToWorklist(CarryExt.getNode());
2295     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2296                                     DAG.getConstant(1, DL, VT)),
2297                      DAG.getConstant(0, DL, CarryVT));
2298   }
2299 
2300   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2301     return Combined;
2302 
2303   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2304     return Combined;
2305 
2306   return SDValue();
2307 }
2308 
2309 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2310                                        SDNode *N) {
2311   // Iff the flag result is dead:
2312   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2313   if ((N0.getOpcode() == ISD::ADD ||
2314        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2315       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2316     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2317                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2318 
2319   /**
2320    * When one of the addcarry argument is itself a carry, we may be facing
2321    * a diamond carry propagation. In which case we try to transform the DAG
2322    * to ensure linear carry propagation if that is possible.
2323    *
2324    * We are trying to get:
2325    *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2326    */
2327   if (auto Y = getAsCarry(TLI, N1)) {
2328     /**
2329      *            (uaddo A, B)
2330      *             /       \
2331      *          Carry      Sum
2332      *            |          \
2333      *            | (addcarry *, 0, Z)
2334      *            |       /
2335      *             \   Carry
2336      *              |   /
2337      * (addcarry X, *, *)
2338      */
2339     if (Y.getOpcode() == ISD::UADDO &&
2340         CarryIn.getResNo() == 1 &&
2341         CarryIn.getOpcode() == ISD::ADDCARRY &&
2342         isNullConstant(CarryIn.getOperand(1)) &&
2343         CarryIn.getOperand(0) == Y.getValue(0)) {
2344       auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2345                               Y.getOperand(0), Y.getOperand(1),
2346                               CarryIn.getOperand(2));
2347       AddToWorklist(NewY.getNode());
2348       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2349                          DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2350                          NewY.getValue(1));
2351     }
2352   }
2353 
2354   return SDValue();
2355 }
2356 
2357 // Since it may not be valid to emit a fold to zero for vector initializers
2358 // check if we can before folding.
2359 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2360                              SelectionDAG &DAG, bool LegalOperations,
2361                              bool LegalTypes) {
2362   if (!VT.isVector())
2363     return DAG.getConstant(0, DL, VT);
2364   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2365     return DAG.getConstant(0, DL, VT);
2366   return SDValue();
2367 }
2368 
2369 SDValue DAGCombiner::visitSUB(SDNode *N) {
2370   SDValue N0 = N->getOperand(0);
2371   SDValue N1 = N->getOperand(1);
2372   EVT VT = N0.getValueType();
2373   SDLoc DL(N);
2374 
2375   // fold vector ops
2376   if (VT.isVector()) {
2377     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2378       return FoldedVOp;
2379 
2380     // fold (sub x, 0) -> x, vector edition
2381     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2382       return N0;
2383   }
2384 
2385   // fold (sub x, x) -> 0
2386   // FIXME: Refactor this and xor and other similar operations together.
2387   if (N0 == N1)
2388     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2389   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2390       DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2391     // fold (sub c1, c2) -> c1-c2
2392     return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2393                                       N1.getNode());
2394   }
2395 
2396   if (SDValue NewSel = foldBinOpIntoSelect(N))
2397     return NewSel;
2398 
2399   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2400 
2401   // fold (sub x, c) -> (add x, -c)
2402   if (N1C) {
2403     return DAG.getNode(ISD::ADD, DL, VT, N0,
2404                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2405   }
2406 
2407   if (isNullConstantOrNullSplatConstant(N0)) {
2408     unsigned BitWidth = VT.getScalarSizeInBits();
2409     // Right-shifting everything out but the sign bit followed by negation is
2410     // the same as flipping arithmetic/logical shift type without the negation:
2411     // -(X >>u 31) -> (X >>s 31)
2412     // -(X >>s 31) -> (X >>u 31)
2413     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2414       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2415       if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2416         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2417         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2418           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2419       }
2420     }
2421 
2422     // 0 - X --> 0 if the sub is NUW.
2423     if (N->getFlags().hasNoUnsignedWrap())
2424       return N0;
2425 
2426     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2427       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2428       // N1 must be 0 because negating the minimum signed value is undefined.
2429       if (N->getFlags().hasNoSignedWrap())
2430         return N0;
2431 
2432       // 0 - X --> X if X is 0 or the minimum signed value.
2433       return N1;
2434     }
2435   }
2436 
2437   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2438   if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2439     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2440 
2441   // fold A-(A-B) -> B
2442   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2443     return N1.getOperand(1);
2444 
2445   // fold (A+B)-A -> B
2446   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2447     return N0.getOperand(1);
2448 
2449   // fold (A+B)-B -> A
2450   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2451     return N0.getOperand(0);
2452 
2453   // fold C2-(A+C1) -> (C2-C1)-A
2454   if (N1.getOpcode() == ISD::ADD) {
2455     SDValue N11 = N1.getOperand(1);
2456     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2457         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2458       SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2459       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2460     }
2461   }
2462 
2463   // fold ((A+(B+or-C))-B) -> A+or-C
2464   if (N0.getOpcode() == ISD::ADD &&
2465       (N0.getOperand(1).getOpcode() == ISD::SUB ||
2466        N0.getOperand(1).getOpcode() == ISD::ADD) &&
2467       N0.getOperand(1).getOperand(0) == N1)
2468     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2469                        N0.getOperand(1).getOperand(1));
2470 
2471   // fold ((A+(C+B))-B) -> A+C
2472   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2473       N0.getOperand(1).getOperand(1) == N1)
2474     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2475                        N0.getOperand(1).getOperand(0));
2476 
2477   // fold ((A-(B-C))-C) -> A-B
2478   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2479       N0.getOperand(1).getOperand(1) == N1)
2480     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2481                        N0.getOperand(1).getOperand(0));
2482 
2483   // If either operand of a sub is undef, the result is undef
2484   if (N0.isUndef())
2485     return N0;
2486   if (N1.isUndef())
2487     return N1;
2488 
2489   // If the relocation model supports it, consider symbol offsets.
2490   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2491     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2492       // fold (sub Sym, c) -> Sym-c
2493       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2494         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2495                                     GA->getOffset() -
2496                                         (uint64_t)N1C->getSExtValue());
2497       // fold (sub Sym+c1, Sym+c2) -> c1-c2
2498       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2499         if (GA->getGlobal() == GB->getGlobal())
2500           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2501                                  DL, VT);
2502     }
2503 
2504   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2505   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2506     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2507     if (TN->getVT() == MVT::i1) {
2508       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2509                                  DAG.getConstant(1, DL, VT));
2510       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2511     }
2512   }
2513 
2514   return SDValue();
2515 }
2516 
2517 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2518   SDValue N0 = N->getOperand(0);
2519   SDValue N1 = N->getOperand(1);
2520   EVT VT = N0.getValueType();
2521   SDLoc DL(N);
2522 
2523   // If the flag result is dead, turn this into an SUB.
2524   if (!N->hasAnyUseOfValue(1))
2525     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2526                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2527 
2528   // fold (subc x, x) -> 0 + no borrow
2529   if (N0 == N1)
2530     return CombineTo(N, DAG.getConstant(0, DL, VT),
2531                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2532 
2533   // fold (subc x, 0) -> x + no borrow
2534   if (isNullConstant(N1))
2535     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2536 
2537   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2538   if (isAllOnesConstant(N0))
2539     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2540                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2541 
2542   return SDValue();
2543 }
2544 
2545 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2546   SDValue N0 = N->getOperand(0);
2547   SDValue N1 = N->getOperand(1);
2548   EVT VT = N0.getValueType();
2549   if (VT.isVector())
2550     return SDValue();
2551 
2552   EVT CarryVT = N->getValueType(1);
2553   SDLoc DL(N);
2554 
2555   // If the flag result is dead, turn this into an SUB.
2556   if (!N->hasAnyUseOfValue(1))
2557     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2558                      DAG.getUNDEF(CarryVT));
2559 
2560   // fold (usubo x, x) -> 0 + no borrow
2561   if (N0 == N1)
2562     return CombineTo(N, DAG.getConstant(0, DL, VT),
2563                      DAG.getConstant(0, DL, CarryVT));
2564 
2565   // fold (usubo x, 0) -> x + no borrow
2566   if (isNullConstant(N1))
2567     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2568 
2569   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2570   if (isAllOnesConstant(N0))
2571     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2572                      DAG.getConstant(0, DL, CarryVT));
2573 
2574   return SDValue();
2575 }
2576 
2577 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2578   SDValue N0 = N->getOperand(0);
2579   SDValue N1 = N->getOperand(1);
2580   SDValue CarryIn = N->getOperand(2);
2581 
2582   // fold (sube x, y, false) -> (subc x, y)
2583   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2584     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2585 
2586   return SDValue();
2587 }
2588 
2589 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2590   SDValue N0 = N->getOperand(0);
2591   SDValue N1 = N->getOperand(1);
2592   SDValue CarryIn = N->getOperand(2);
2593 
2594   // fold (subcarry x, y, false) -> (usubo x, y)
2595   if (isNullConstant(CarryIn))
2596     return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2597 
2598   return SDValue();
2599 }
2600 
2601 SDValue DAGCombiner::visitMUL(SDNode *N) {
2602   SDValue N0 = N->getOperand(0);
2603   SDValue N1 = N->getOperand(1);
2604   EVT VT = N0.getValueType();
2605 
2606   // fold (mul x, undef) -> 0
2607   if (N0.isUndef() || N1.isUndef())
2608     return DAG.getConstant(0, SDLoc(N), VT);
2609 
2610   bool N0IsConst = false;
2611   bool N1IsConst = false;
2612   bool N1IsOpaqueConst = false;
2613   bool N0IsOpaqueConst = false;
2614   APInt ConstValue0, ConstValue1;
2615   // fold vector ops
2616   if (VT.isVector()) {
2617     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2618       return FoldedVOp;
2619 
2620     N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2621     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2622     assert((!N0IsConst ||
2623             ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) &&
2624            "Splat APInt should be element width");
2625     assert((!N1IsConst ||
2626             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
2627            "Splat APInt should be element width");
2628   } else {
2629     N0IsConst = isa<ConstantSDNode>(N0);
2630     if (N0IsConst) {
2631       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2632       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2633     }
2634     N1IsConst = isa<ConstantSDNode>(N1);
2635     if (N1IsConst) {
2636       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2637       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2638     }
2639   }
2640 
2641   // fold (mul c1, c2) -> c1*c2
2642   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2643     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2644                                       N0.getNode(), N1.getNode());
2645 
2646   // canonicalize constant to RHS (vector doesn't have to splat)
2647   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2648      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2649     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2650   // fold (mul x, 0) -> 0
2651   if (N1IsConst && ConstValue1.isNullValue())
2652     return N1;
2653   // fold (mul x, 1) -> x
2654   if (N1IsConst && ConstValue1.isOneValue())
2655     return N0;
2656 
2657   if (SDValue NewSel = foldBinOpIntoSelect(N))
2658     return NewSel;
2659 
2660   // fold (mul x, -1) -> 0-x
2661   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2662     SDLoc DL(N);
2663     return DAG.getNode(ISD::SUB, DL, VT,
2664                        DAG.getConstant(0, DL, VT), N0);
2665   }
2666   // fold (mul x, (1 << c)) -> x << c
2667   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2668       DAG.isKnownToBeAPowerOfTwo(N1) &&
2669       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
2670     SDLoc DL(N);
2671     SDValue LogBase2 = BuildLogBase2(N1, DL);
2672     AddToWorklist(LogBase2.getNode());
2673 
2674     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2675     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2676     AddToWorklist(Trunc.getNode());
2677     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
2678   }
2679   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2680   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
2681     unsigned Log2Val = (-ConstValue1).logBase2();
2682     SDLoc DL(N);
2683     // FIXME: If the input is something that is easily negated (e.g. a
2684     // single-use add), we should put the negate there.
2685     return DAG.getNode(ISD::SUB, DL, VT,
2686                        DAG.getConstant(0, DL, VT),
2687                        DAG.getNode(ISD::SHL, DL, VT, N0,
2688                             DAG.getConstant(Log2Val, DL,
2689                                       getShiftAmountTy(N0.getValueType()))));
2690   }
2691 
2692   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2693   if (N0.getOpcode() == ISD::SHL &&
2694       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2695       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2696     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2697     if (isConstantOrConstantVector(C3))
2698       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2699   }
2700 
2701   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2702   // use.
2703   {
2704     SDValue Sh(nullptr, 0), Y(nullptr, 0);
2705 
2706     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2707     if (N0.getOpcode() == ISD::SHL &&
2708         isConstantOrConstantVector(N0.getOperand(1)) &&
2709         N0.getNode()->hasOneUse()) {
2710       Sh = N0; Y = N1;
2711     } else if (N1.getOpcode() == ISD::SHL &&
2712                isConstantOrConstantVector(N1.getOperand(1)) &&
2713                N1.getNode()->hasOneUse()) {
2714       Sh = N1; Y = N0;
2715     }
2716 
2717     if (Sh.getNode()) {
2718       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2719       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2720     }
2721   }
2722 
2723   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2724   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2725       N0.getOpcode() == ISD::ADD &&
2726       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2727       isMulAddWithConstProfitable(N, N0, N1))
2728       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2729                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2730                                      N0.getOperand(0), N1),
2731                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2732                                      N0.getOperand(1), N1));
2733 
2734   // reassociate mul
2735   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2736     return RMUL;
2737 
2738   return SDValue();
2739 }
2740 
2741 /// Return true if divmod libcall is available.
2742 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2743                                      const TargetLowering &TLI) {
2744   RTLIB::Libcall LC;
2745   EVT NodeType = Node->getValueType(0);
2746   if (!NodeType.isSimple())
2747     return false;
2748   switch (NodeType.getSimpleVT().SimpleTy) {
2749   default: return false; // No libcall for vector types.
2750   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2751   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2752   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2753   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2754   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2755   }
2756 
2757   return TLI.getLibcallName(LC) != nullptr;
2758 }
2759 
2760 /// Issue divrem if both quotient and remainder are needed.
2761 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2762   if (Node->use_empty())
2763     return SDValue(); // This is a dead node, leave it alone.
2764 
2765   unsigned Opcode = Node->getOpcode();
2766   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2767   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2768 
2769   // DivMod lib calls can still work on non-legal types if using lib-calls.
2770   EVT VT = Node->getValueType(0);
2771   if (VT.isVector() || !VT.isInteger())
2772     return SDValue();
2773 
2774   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2775     return SDValue();
2776 
2777   // If DIVREM is going to get expanded into a libcall,
2778   // but there is no libcall available, then don't combine.
2779   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2780       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2781     return SDValue();
2782 
2783   // If div is legal, it's better to do the normal expansion
2784   unsigned OtherOpcode = 0;
2785   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2786     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2787     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2788       return SDValue();
2789   } else {
2790     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2791     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2792       return SDValue();
2793   }
2794 
2795   SDValue Op0 = Node->getOperand(0);
2796   SDValue Op1 = Node->getOperand(1);
2797   SDValue combined;
2798   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2799          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2800     SDNode *User = *UI;
2801     if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
2802         User->use_empty())
2803       continue;
2804     // Convert the other matching node(s), too;
2805     // otherwise, the DIVREM may get target-legalized into something
2806     // target-specific that we won't be able to recognize.
2807     unsigned UserOpc = User->getOpcode();
2808     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2809         User->getOperand(0) == Op0 &&
2810         User->getOperand(1) == Op1) {
2811       if (!combined) {
2812         if (UserOpc == OtherOpcode) {
2813           SDVTList VTs = DAG.getVTList(VT, VT);
2814           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2815         } else if (UserOpc == DivRemOpc) {
2816           combined = SDValue(User, 0);
2817         } else {
2818           assert(UserOpc == Opcode);
2819           continue;
2820         }
2821       }
2822       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2823         CombineTo(User, combined);
2824       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2825         CombineTo(User, combined.getValue(1));
2826     }
2827   }
2828   return combined;
2829 }
2830 
2831 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2832   SDValue N0 = N->getOperand(0);
2833   SDValue N1 = N->getOperand(1);
2834   EVT VT = N->getValueType(0);
2835   SDLoc DL(N);
2836 
2837   if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2838     return DAG.getUNDEF(VT);
2839 
2840   // undef / X -> 0
2841   // undef % X -> 0
2842   if (N0.isUndef())
2843     return DAG.getConstant(0, DL, VT);
2844 
2845   return SDValue();
2846 }
2847 
2848 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2849   SDValue N0 = N->getOperand(0);
2850   SDValue N1 = N->getOperand(1);
2851   EVT VT = N->getValueType(0);
2852 
2853   // fold vector ops
2854   if (VT.isVector())
2855     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2856       return FoldedVOp;
2857 
2858   SDLoc DL(N);
2859 
2860   // fold (sdiv c1, c2) -> c1/c2
2861   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2862   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2863   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2864     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2865   // fold (sdiv X, 1) -> X
2866   if (N1C && N1C->isOne())
2867     return N0;
2868   // fold (sdiv X, -1) -> 0-X
2869   if (N1C && N1C->isAllOnesValue())
2870     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2871 
2872   if (SDValue V = simplifyDivRem(N, DAG))
2873     return V;
2874 
2875   if (SDValue NewSel = foldBinOpIntoSelect(N))
2876     return NewSel;
2877 
2878   // If we know the sign bits of both operands are zero, strength reduce to a
2879   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2880   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2881     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2882 
2883   // Helper for determining whether a value is a power-2 constant scalar or a
2884   // vector of such elements.
2885   SmallBitVector KnownNegatives(
2886       (N1C || !VT.isVector()) ? 1 : VT.getVectorNumElements(), false);
2887   unsigned EltIndex = 0;
2888   auto IsPowerOfTwo = [&KnownNegatives, &EltIndex](ConstantSDNode *C) {
2889     unsigned Idx = EltIndex++;
2890     if (C->isNullValue() || C->isOpaque())
2891       return false;
2892     // The instruction sequence to be generated contains shifting C by (op size
2893     // in bits - # of trailing zeros in C), which results in an undef value when
2894     // C == 1. (e.g. if the op size in bits is 32, it will be (sra x , 32) if C
2895     // == 1)
2896     if (C->getAPIntValue().isOneValue())
2897       return false;
2898 
2899     if (C->getAPIntValue().isPowerOf2())
2900       return true;
2901     if ((-C->getAPIntValue()).isPowerOf2()) {
2902       KnownNegatives.set(Idx);
2903       return true;
2904     }
2905     return false;
2906   };
2907 
2908   // fold (sdiv X, pow2) -> simple ops after legalize
2909   // FIXME: We check for the exact bit here because the generic lowering gives
2910   // better results in that case. The target-specific lowering should learn how
2911   // to handle exact sdivs efficiently.
2912   if (!N->getFlags().hasExact() &&
2913       ISD::matchUnaryPredicate(N1C ? SDValue(N1C, 0) : N1, IsPowerOfTwo)) {
2914     // Target-specific implementation of sdiv x, pow2.
2915     if (SDValue Res = BuildSDIVPow2(N))
2916       return Res;
2917 
2918     // Create constants that are functions of the shift amount value.
2919     EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
2920     SDValue Bits = DAG.getConstant(VT.getScalarSizeInBits(), DL, ShiftAmtTy);
2921     SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
2922     C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
2923     SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
2924     if (!isConstantOrConstantVector(Inexact))
2925       return SDValue();
2926     // Splat the sign bit into the register
2927     SDValue Sign = DAG.getNode(
2928         ISD::SRA, DL, VT, N0,
2929         DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, ShiftAmtTy));
2930     AddToWorklist(Sign.getNode());
2931 
2932     // Add (N0 < 0) ? abs2 - 1 : 0;
2933     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
2934     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
2935     AddToWorklist(Srl.getNode());
2936     AddToWorklist(Add.getNode()); // Divide by pow2
2937     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
2938 
2939     // If dividing by a positive value, we're done. Otherwise, the result must
2940     // be negated.
2941     if (KnownNegatives.none())
2942       return Sra;
2943 
2944     AddToWorklist(Sra.getNode());
2945     SDValue Sub =
2946         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Sra);
2947     // If all shift amount elements are negative, we're done.
2948     if (KnownNegatives.all())
2949       return Sub;
2950 
2951     // Shift amount has both positive and negative elements.
2952     assert(VT.isVector() && !N0C &&
2953            "Expecting a non-splat vector shift amount");
2954 
2955     SmallVector<SDValue, 64> VSelectMask;
2956     for (int i = 0, e = VT.getVectorNumElements(); i < e; ++i)
2957       VSelectMask.push_back(
2958           DAG.getConstant(KnownNegatives[i] ? -1 : 0, DL, MVT::i1));
2959 
2960     SDValue Mask =
2961         DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i1,
2962                                             VT.getVectorElementCount()),
2963                            DL, VSelectMask);
2964     return DAG.getNode(ISD::VSELECT, DL, VT, Mask, Sub, Sra);
2965   }
2966 
2967   // If integer divide is expensive and we satisfy the requirements, emit an
2968   // alternate sequence.  Targets may check function attributes for size/speed
2969   // trade-offs.
2970   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
2971   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2972     if (SDValue Op = BuildSDIV(N))
2973       return Op;
2974 
2975   // sdiv, srem -> sdivrem
2976   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2977   // true.  Otherwise, we break the simplification logic in visitREM().
2978   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2979     if (SDValue DivRem = useDivRem(N))
2980         return DivRem;
2981 
2982   return SDValue();
2983 }
2984 
2985 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2986   SDValue N0 = N->getOperand(0);
2987   SDValue N1 = N->getOperand(1);
2988   EVT VT = N->getValueType(0);
2989 
2990   // fold vector ops
2991   if (VT.isVector())
2992     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2993       return FoldedVOp;
2994 
2995   SDLoc DL(N);
2996 
2997   // fold (udiv c1, c2) -> c1/c2
2998   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2999   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3000   if (N0C && N1C)
3001     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
3002                                                     N0C, N1C))
3003       return Folded;
3004 
3005   if (SDValue V = simplifyDivRem(N, DAG))
3006     return V;
3007 
3008   if (SDValue NewSel = foldBinOpIntoSelect(N))
3009     return NewSel;
3010 
3011   // fold (udiv x, (1 << c)) -> x >>u c
3012   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3013       DAG.isKnownToBeAPowerOfTwo(N1)) {
3014     SDValue LogBase2 = BuildLogBase2(N1, DL);
3015     AddToWorklist(LogBase2.getNode());
3016 
3017     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3018     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3019     AddToWorklist(Trunc.getNode());
3020     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3021   }
3022 
3023   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3024   if (N1.getOpcode() == ISD::SHL) {
3025     SDValue N10 = N1.getOperand(0);
3026     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3027         DAG.isKnownToBeAPowerOfTwo(N10)) {
3028       SDValue LogBase2 = BuildLogBase2(N10, DL);
3029       AddToWorklist(LogBase2.getNode());
3030 
3031       EVT ADDVT = N1.getOperand(1).getValueType();
3032       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3033       AddToWorklist(Trunc.getNode());
3034       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3035       AddToWorklist(Add.getNode());
3036       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3037     }
3038   }
3039 
3040   // fold (udiv x, c) -> alternate
3041   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3042   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
3043     if (SDValue Op = BuildUDIV(N))
3044       return Op;
3045 
3046   // sdiv, srem -> sdivrem
3047   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3048   // true.  Otherwise, we break the simplification logic in visitREM().
3049   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3050     if (SDValue DivRem = useDivRem(N))
3051         return DivRem;
3052 
3053   return SDValue();
3054 }
3055 
3056 // handles ISD::SREM and ISD::UREM
3057 SDValue DAGCombiner::visitREM(SDNode *N) {
3058   unsigned Opcode = N->getOpcode();
3059   SDValue N0 = N->getOperand(0);
3060   SDValue N1 = N->getOperand(1);
3061   EVT VT = N->getValueType(0);
3062   bool isSigned = (Opcode == ISD::SREM);
3063   SDLoc DL(N);
3064 
3065   // fold (rem c1, c2) -> c1%c2
3066   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3067   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3068   if (N0C && N1C)
3069     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
3070       return Folded;
3071 
3072   if (SDValue V = simplifyDivRem(N, DAG))
3073     return V;
3074 
3075   if (SDValue NewSel = foldBinOpIntoSelect(N))
3076     return NewSel;
3077 
3078   if (isSigned) {
3079     // If we know the sign bits of both operands are zero, strength reduce to a
3080     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
3081     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3082       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
3083   } else {
3084     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
3085     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
3086       // fold (urem x, pow2) -> (and x, pow2-1)
3087       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3088       AddToWorklist(Add.getNode());
3089       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3090     }
3091     if (N1.getOpcode() == ISD::SHL &&
3092         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
3093       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
3094       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
3095       AddToWorklist(Add.getNode());
3096       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
3097     }
3098   }
3099 
3100   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3101 
3102   // If X/C can be simplified by the division-by-constant logic, lower
3103   // X%C to the equivalent of X-X/C*C.
3104   // To avoid mangling nodes, this simplification requires that the combine()
3105   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
3106   // against this by skipping the simplification if isIntDivCheap().  When
3107   // div is not cheap, combine will not return a DIVREM.  Regardless,
3108   // checking cheapness here makes sense since the simplification results in
3109   // fatter code.
3110   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
3111     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3112     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
3113     AddToWorklist(Div.getNode());
3114     SDValue OptimizedDiv = combine(Div.getNode());
3115     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode() &&
3116         OptimizedDiv.getOpcode() != ISD::UDIVREM &&
3117         OptimizedDiv.getOpcode() != ISD::SDIVREM) {
3118       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
3119       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3120       AddToWorklist(Mul.getNode());
3121       return Sub;
3122     }
3123   }
3124 
3125   // sdiv, srem -> sdivrem
3126   if (SDValue DivRem = useDivRem(N))
3127     return DivRem.getValue(1);
3128 
3129   return SDValue();
3130 }
3131 
3132 SDValue DAGCombiner::visitMULHS(SDNode *N) {
3133   SDValue N0 = N->getOperand(0);
3134   SDValue N1 = N->getOperand(1);
3135   EVT VT = N->getValueType(0);
3136   SDLoc DL(N);
3137 
3138   if (VT.isVector()) {
3139     // fold (mulhs x, 0) -> 0
3140     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3141       return N1;
3142     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3143       return N0;
3144   }
3145 
3146   // fold (mulhs x, 0) -> 0
3147   if (isNullConstant(N1))
3148     return N1;
3149   // fold (mulhs x, 1) -> (sra x, size(x)-1)
3150   if (isOneConstant(N1))
3151     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3152                        DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3153                                        getShiftAmountTy(N0.getValueType())));
3154 
3155   // fold (mulhs x, undef) -> 0
3156   if (N0.isUndef() || N1.isUndef())
3157     return DAG.getConstant(0, DL, VT);
3158 
3159   // If the type twice as wide is legal, transform the mulhs to a wider multiply
3160   // plus a shift.
3161   if (VT.isSimple() && !VT.isVector()) {
3162     MVT Simple = VT.getSimpleVT();
3163     unsigned SimpleSize = Simple.getSizeInBits();
3164     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3165     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3166       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3167       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3168       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3169       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3170             DAG.getConstant(SimpleSize, DL,
3171                             getShiftAmountTy(N1.getValueType())));
3172       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3173     }
3174   }
3175 
3176   return SDValue();
3177 }
3178 
3179 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3180   SDValue N0 = N->getOperand(0);
3181   SDValue N1 = N->getOperand(1);
3182   EVT VT = N->getValueType(0);
3183   SDLoc DL(N);
3184 
3185   if (VT.isVector()) {
3186     // fold (mulhu x, 0) -> 0
3187     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3188       return N1;
3189     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3190       return N0;
3191   }
3192 
3193   // fold (mulhu x, 0) -> 0
3194   if (isNullConstant(N1))
3195     return N1;
3196   // fold (mulhu x, 1) -> 0
3197   if (isOneConstant(N1))
3198     return DAG.getConstant(0, DL, N0.getValueType());
3199   // fold (mulhu x, undef) -> 0
3200   if (N0.isUndef() || N1.isUndef())
3201     return DAG.getConstant(0, DL, VT);
3202 
3203   // If the type twice as wide is legal, transform the mulhu to a wider multiply
3204   // plus a shift.
3205   if (VT.isSimple() && !VT.isVector()) {
3206     MVT Simple = VT.getSimpleVT();
3207     unsigned SimpleSize = Simple.getSizeInBits();
3208     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3209     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3210       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3211       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3212       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3213       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3214             DAG.getConstant(SimpleSize, DL,
3215                             getShiftAmountTy(N1.getValueType())));
3216       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3217     }
3218   }
3219 
3220   return SDValue();
3221 }
3222 
3223 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3224 /// give the opcodes for the two computations that are being performed. Return
3225 /// true if a simplification was made.
3226 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3227                                                 unsigned HiOp) {
3228   // If the high half is not needed, just compute the low half.
3229   bool HiExists = N->hasAnyUseOfValue(1);
3230   if (!HiExists &&
3231       (!LegalOperations ||
3232        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3233     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3234     return CombineTo(N, Res, Res);
3235   }
3236 
3237   // If the low half is not needed, just compute the high half.
3238   bool LoExists = N->hasAnyUseOfValue(0);
3239   if (!LoExists &&
3240       (!LegalOperations ||
3241        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3242     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3243     return CombineTo(N, Res, Res);
3244   }
3245 
3246   // If both halves are used, return as it is.
3247   if (LoExists && HiExists)
3248     return SDValue();
3249 
3250   // If the two computed results can be simplified separately, separate them.
3251   if (LoExists) {
3252     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3253     AddToWorklist(Lo.getNode());
3254     SDValue LoOpt = combine(Lo.getNode());
3255     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3256         (!LegalOperations ||
3257          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3258       return CombineTo(N, LoOpt, LoOpt);
3259   }
3260 
3261   if (HiExists) {
3262     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3263     AddToWorklist(Hi.getNode());
3264     SDValue HiOpt = combine(Hi.getNode());
3265     if (HiOpt.getNode() && HiOpt != Hi &&
3266         (!LegalOperations ||
3267          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3268       return CombineTo(N, HiOpt, HiOpt);
3269   }
3270 
3271   return SDValue();
3272 }
3273 
3274 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3275   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3276     return Res;
3277 
3278   EVT VT = N->getValueType(0);
3279   SDLoc DL(N);
3280 
3281   // If the type is twice as wide is legal, transform the mulhu to a wider
3282   // multiply plus a shift.
3283   if (VT.isSimple() && !VT.isVector()) {
3284     MVT Simple = VT.getSimpleVT();
3285     unsigned SimpleSize = Simple.getSizeInBits();
3286     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3287     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3288       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3289       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3290       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3291       // Compute the high part as N1.
3292       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3293             DAG.getConstant(SimpleSize, DL,
3294                             getShiftAmountTy(Lo.getValueType())));
3295       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3296       // Compute the low part as N0.
3297       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3298       return CombineTo(N, Lo, Hi);
3299     }
3300   }
3301 
3302   return SDValue();
3303 }
3304 
3305 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3306   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3307     return Res;
3308 
3309   EVT VT = N->getValueType(0);
3310   SDLoc DL(N);
3311 
3312   // If the type is twice as wide is legal, transform the mulhu to a wider
3313   // multiply plus a shift.
3314   if (VT.isSimple() && !VT.isVector()) {
3315     MVT Simple = VT.getSimpleVT();
3316     unsigned SimpleSize = Simple.getSizeInBits();
3317     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3318     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3319       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3320       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3321       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3322       // Compute the high part as N1.
3323       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3324             DAG.getConstant(SimpleSize, DL,
3325                             getShiftAmountTy(Lo.getValueType())));
3326       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3327       // Compute the low part as N0.
3328       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3329       return CombineTo(N, Lo, Hi);
3330     }
3331   }
3332 
3333   return SDValue();
3334 }
3335 
3336 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3337   // (smulo x, 2) -> (saddo x, x)
3338   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3339     if (C2->getAPIntValue() == 2)
3340       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3341                          N->getOperand(0), N->getOperand(0));
3342 
3343   return SDValue();
3344 }
3345 
3346 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3347   // (umulo x, 2) -> (uaddo x, x)
3348   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3349     if (C2->getAPIntValue() == 2)
3350       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3351                          N->getOperand(0), N->getOperand(0));
3352 
3353   return SDValue();
3354 }
3355 
3356 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3357   SDValue N0 = N->getOperand(0);
3358   SDValue N1 = N->getOperand(1);
3359   EVT VT = N0.getValueType();
3360 
3361   // fold vector ops
3362   if (VT.isVector())
3363     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3364       return FoldedVOp;
3365 
3366   // fold operation with constant operands.
3367   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3368   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3369   if (N0C && N1C)
3370     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3371 
3372   // canonicalize constant to RHS
3373   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3374      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3375     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3376 
3377   // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
3378   // Only do this if the current op isn't legal and the flipped is.
3379   unsigned Opcode = N->getOpcode();
3380   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3381   if (!TLI.isOperationLegal(Opcode, VT) &&
3382       (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
3383       (N1.isUndef() || DAG.SignBitIsZero(N1))) {
3384     unsigned AltOpcode;
3385     switch (Opcode) {
3386     case ISD::SMIN: AltOpcode = ISD::UMIN; break;
3387     case ISD::SMAX: AltOpcode = ISD::UMAX; break;
3388     case ISD::UMIN: AltOpcode = ISD::SMIN; break;
3389     case ISD::UMAX: AltOpcode = ISD::SMAX; break;
3390     default: llvm_unreachable("Unknown MINMAX opcode");
3391     }
3392     if (TLI.isOperationLegal(AltOpcode, VT))
3393       return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
3394   }
3395 
3396   return SDValue();
3397 }
3398 
3399 /// If this is a binary operator with two operands of the same opcode, try to
3400 /// simplify it.
3401 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3402   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3403   EVT VT = N0.getValueType();
3404   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3405 
3406   // Bail early if none of these transforms apply.
3407   if (N0.getNumOperands() == 0) return SDValue();
3408 
3409   // For each of OP in AND/OR/XOR:
3410   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3411   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3412   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3413   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3414   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3415   //
3416   // do not sink logical op inside of a vector extend, since it may combine
3417   // into a vsetcc.
3418   EVT Op0VT = N0.getOperand(0).getValueType();
3419   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3420        N0.getOpcode() == ISD::SIGN_EXTEND ||
3421        N0.getOpcode() == ISD::BSWAP ||
3422        // Avoid infinite looping with PromoteIntBinOp.
3423        (N0.getOpcode() == ISD::ANY_EXTEND &&
3424         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3425        (N0.getOpcode() == ISD::TRUNCATE &&
3426         (!TLI.isZExtFree(VT, Op0VT) ||
3427          !TLI.isTruncateFree(Op0VT, VT)) &&
3428         TLI.isTypeLegal(Op0VT))) &&
3429       !VT.isVector() &&
3430       Op0VT == N1.getOperand(0).getValueType() &&
3431       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3432     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3433                                  N0.getOperand(0).getValueType(),
3434                                  N0.getOperand(0), N1.getOperand(0));
3435     AddToWorklist(ORNode.getNode());
3436     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3437   }
3438 
3439   // For each of OP in SHL/SRL/SRA/AND...
3440   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3441   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
3442   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3443   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3444        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3445       N0.getOperand(1) == N1.getOperand(1)) {
3446     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3447                                  N0.getOperand(0).getValueType(),
3448                                  N0.getOperand(0), N1.getOperand(0));
3449     AddToWorklist(ORNode.getNode());
3450     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3451                        ORNode, N0.getOperand(1));
3452   }
3453 
3454   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3455   // Only perform this optimization up until type legalization, before
3456   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3457   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3458   // we don't want to undo this promotion.
3459   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3460   // on scalars.
3461   if ((N0.getOpcode() == ISD::BITCAST ||
3462        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3463        Level <= AfterLegalizeTypes) {
3464     SDValue In0 = N0.getOperand(0);
3465     SDValue In1 = N1.getOperand(0);
3466     EVT In0Ty = In0.getValueType();
3467     EVT In1Ty = In1.getValueType();
3468     SDLoc DL(N);
3469     // If both incoming values are integers, and the original types are the
3470     // same.
3471     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3472       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3473       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3474       AddToWorklist(Op.getNode());
3475       return BC;
3476     }
3477   }
3478 
3479   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3480   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3481   // If both shuffles use the same mask, and both shuffle within a single
3482   // vector, then it is worthwhile to move the swizzle after the operation.
3483   // The type-legalizer generates this pattern when loading illegal
3484   // vector types from memory. In many cases this allows additional shuffle
3485   // optimizations.
3486   // There are other cases where moving the shuffle after the xor/and/or
3487   // is profitable even if shuffles don't perform a swizzle.
3488   // If both shuffles use the same mask, and both shuffles have the same first
3489   // or second operand, then it might still be profitable to move the shuffle
3490   // after the xor/and/or operation.
3491   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3492     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3493     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3494 
3495     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3496            "Inputs to shuffles are not the same type");
3497 
3498     // Check that both shuffles use the same mask. The masks are known to be of
3499     // the same length because the result vector type is the same.
3500     // Check also that shuffles have only one use to avoid introducing extra
3501     // instructions.
3502     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3503         SVN0->getMask().equals(SVN1->getMask())) {
3504       SDValue ShOp = N0->getOperand(1);
3505 
3506       // Don't try to fold this node if it requires introducing a
3507       // build vector of all zeros that might be illegal at this stage.
3508       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3509         if (!LegalTypes)
3510           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3511         else
3512           ShOp = SDValue();
3513       }
3514 
3515       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3516       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
3517       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3518       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3519         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3520                                       N0->getOperand(0), N1->getOperand(0));
3521         AddToWorklist(NewNode.getNode());
3522         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3523                                     SVN0->getMask());
3524       }
3525 
3526       // Don't try to fold this node if it requires introducing a
3527       // build vector of all zeros that might be illegal at this stage.
3528       ShOp = N0->getOperand(0);
3529       if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3530         if (!LegalTypes)
3531           ShOp = DAG.getConstant(0, SDLoc(N), VT);
3532         else
3533           ShOp = SDValue();
3534       }
3535 
3536       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3537       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
3538       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3539       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3540         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3541                                       N0->getOperand(1), N1->getOperand(1));
3542         AddToWorklist(NewNode.getNode());
3543         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3544                                     SVN0->getMask());
3545       }
3546     }
3547   }
3548 
3549   return SDValue();
3550 }
3551 
3552 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3553 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3554                                        const SDLoc &DL) {
3555   SDValue LL, LR, RL, RR, N0CC, N1CC;
3556   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3557       !isSetCCEquivalent(N1, RL, RR, N1CC))
3558     return SDValue();
3559 
3560   assert(N0.getValueType() == N1.getValueType() &&
3561          "Unexpected operand types for bitwise logic op");
3562   assert(LL.getValueType() == LR.getValueType() &&
3563          RL.getValueType() == RR.getValueType() &&
3564          "Unexpected operand types for setcc");
3565 
3566   // If we're here post-legalization or the logic op type is not i1, the logic
3567   // op type must match a setcc result type. Also, all folds require new
3568   // operations on the left and right operands, so those types must match.
3569   EVT VT = N0.getValueType();
3570   EVT OpVT = LL.getValueType();
3571   if (LegalOperations || VT.getScalarType() != MVT::i1)
3572     if (VT != getSetCCResultType(OpVT))
3573       return SDValue();
3574   if (OpVT != RL.getValueType())
3575     return SDValue();
3576 
3577   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3578   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3579   bool IsInteger = OpVT.isInteger();
3580   if (LR == RR && CC0 == CC1 && IsInteger) {
3581     bool IsZero = isNullConstantOrNullSplatConstant(LR);
3582     bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3583 
3584     // All bits clear?
3585     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3586     // All sign bits clear?
3587     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3588     // Any bits set?
3589     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3590     // Any sign bits set?
3591     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3592 
3593     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
3594     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3595     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
3596     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
3597     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3598       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3599       AddToWorklist(Or.getNode());
3600       return DAG.getSetCC(DL, VT, Or, LR, CC1);
3601     }
3602 
3603     // All bits set?
3604     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3605     // All sign bits set?
3606     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3607     // Any bits clear?
3608     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3609     // Any sign bits clear?
3610     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3611 
3612     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3613     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
3614     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3615     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
3616     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3617       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3618       AddToWorklist(And.getNode());
3619       return DAG.getSetCC(DL, VT, And, LR, CC1);
3620     }
3621   }
3622 
3623   // TODO: What is the 'or' equivalent of this fold?
3624   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3625   if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
3626       IsInteger && CC0 == ISD::SETNE &&
3627       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3628        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3629     SDValue One = DAG.getConstant(1, DL, OpVT);
3630     SDValue Two = DAG.getConstant(2, DL, OpVT);
3631     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3632     AddToWorklist(Add.getNode());
3633     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3634   }
3635 
3636   // Try more general transforms if the predicates match and the only user of
3637   // the compares is the 'and' or 'or'.
3638   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3639       N0.hasOneUse() && N1.hasOneUse()) {
3640     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3641     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3642     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3643       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3644       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3645       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3646       SDValue Zero = DAG.getConstant(0, DL, OpVT);
3647       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3648     }
3649   }
3650 
3651   // Canonicalize equivalent operands to LL == RL.
3652   if (LL == RR && LR == RL) {
3653     CC1 = ISD::getSetCCSwappedOperands(CC1);
3654     std::swap(RL, RR);
3655   }
3656 
3657   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3658   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3659   if (LL == RL && LR == RR) {
3660     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3661                                 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3662     if (NewCC != ISD::SETCC_INVALID &&
3663         (!LegalOperations ||
3664          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3665           TLI.isOperationLegal(ISD::SETCC, OpVT))))
3666       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3667   }
3668 
3669   return SDValue();
3670 }
3671 
3672 /// This contains all DAGCombine rules which reduce two values combined by
3673 /// an And operation to a single value. This makes them reusable in the context
3674 /// of visitSELECT(). Rules involving constants are not included as
3675 /// visitSELECT() already handles those cases.
3676 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3677   EVT VT = N1.getValueType();
3678   SDLoc DL(N);
3679 
3680   // fold (and x, undef) -> 0
3681   if (N0.isUndef() || N1.isUndef())
3682     return DAG.getConstant(0, DL, VT);
3683 
3684   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3685     return V;
3686 
3687   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3688       VT.getSizeInBits() <= 64) {
3689     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3690       if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3691         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3692         // immediate for an add, but it is legal if its top c2 bits are set,
3693         // transform the ADD so the immediate doesn't need to be materialized
3694         // in a register.
3695         APInt ADDC = ADDI->getAPIntValue();
3696         APInt SRLC = SRLI->getAPIntValue();
3697         if (ADDC.getMinSignedBits() <= 64 &&
3698             SRLC.ult(VT.getSizeInBits()) &&
3699             !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3700           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3701                                              SRLC.getZExtValue());
3702           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3703             ADDC |= Mask;
3704             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3705               SDLoc DL0(N0);
3706               SDValue NewAdd =
3707                 DAG.getNode(ISD::ADD, DL0, VT,
3708                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3709               CombineTo(N0.getNode(), NewAdd);
3710               // Return N so it doesn't get rechecked!
3711               return SDValue(N, 0);
3712             }
3713           }
3714         }
3715       }
3716     }
3717   }
3718 
3719   // Reduce bit extract of low half of an integer to the narrower type.
3720   // (and (srl i64:x, K), KMask) ->
3721   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3722   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3723     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3724       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3725         unsigned Size = VT.getSizeInBits();
3726         const APInt &AndMask = CAnd->getAPIntValue();
3727         unsigned ShiftBits = CShift->getZExtValue();
3728 
3729         // Bail out, this node will probably disappear anyway.
3730         if (ShiftBits == 0)
3731           return SDValue();
3732 
3733         unsigned MaskBits = AndMask.countTrailingOnes();
3734         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3735 
3736         if (AndMask.isMask() &&
3737             // Required bits must not span the two halves of the integer and
3738             // must fit in the half size type.
3739             (ShiftBits + MaskBits <= Size / 2) &&
3740             TLI.isNarrowingProfitable(VT, HalfVT) &&
3741             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3742             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3743             TLI.isTruncateFree(VT, HalfVT) &&
3744             TLI.isZExtFree(HalfVT, VT)) {
3745           // The isNarrowingProfitable is to avoid regressions on PPC and
3746           // AArch64 which match a few 64-bit bit insert / bit extract patterns
3747           // on downstream users of this. Those patterns could probably be
3748           // extended to handle extensions mixed in.
3749 
3750           SDValue SL(N0);
3751           assert(MaskBits <= Size);
3752 
3753           // Extracting the highest bit of the low half.
3754           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3755           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3756                                       N0.getOperand(0));
3757 
3758           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3759           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3760           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3761           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3762           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3763         }
3764       }
3765     }
3766   }
3767 
3768   return SDValue();
3769 }
3770 
3771 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3772                                    EVT LoadResultTy, EVT &ExtVT) {
3773   if (!AndC->getAPIntValue().isMask())
3774     return false;
3775 
3776   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
3777 
3778   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3779   EVT LoadedVT = LoadN->getMemoryVT();
3780 
3781   if (ExtVT == LoadedVT &&
3782       (!LegalOperations ||
3783        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3784     // ZEXTLOAD will match without needing to change the size of the value being
3785     // loaded.
3786     return true;
3787   }
3788 
3789   // Do not change the width of a volatile load.
3790   if (LoadN->isVolatile())
3791     return false;
3792 
3793   // Do not generate loads of non-round integer types since these can
3794   // be expensive (and would be wrong if the type is not byte sized).
3795   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3796     return false;
3797 
3798   if (LegalOperations &&
3799       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3800     return false;
3801 
3802   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3803     return false;
3804 
3805   return true;
3806 }
3807 
3808 bool DAGCombiner::isLegalNarrowLoad(LoadSDNode *LoadN, ISD::LoadExtType ExtType,
3809                                     EVT &ExtVT, unsigned ShAmt) {
3810   // Don't transform one with multiple uses, this would require adding a new
3811   // load.
3812   if (!SDValue(LoadN, 0).hasOneUse())
3813     return false;
3814 
3815   if (LegalOperations &&
3816       !TLI.isLoadExtLegal(ExtType, LoadN->getValueType(0), ExtVT))
3817     return false;
3818 
3819   // Do not generate loads of non-round integer types since these can
3820   // be expensive (and would be wrong if the type is not byte sized).
3821   if (!ExtVT.isRound())
3822     return false;
3823 
3824   // Don't change the width of a volatile load.
3825   if (LoadN->isVolatile())
3826     return false;
3827 
3828   // Verify that we are actually reducing a load width here.
3829   if (LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits())
3830     return false;
3831 
3832   // For the transform to be legal, the load must produce only two values
3833   // (the value loaded and the chain).  Don't transform a pre-increment
3834   // load, for example, which produces an extra value.  Otherwise the
3835   // transformation is not equivalent, and the downstream logic to replace
3836   // uses gets things wrong.
3837   if (LoadN->getNumValues() > 2)
3838     return false;
3839 
3840  // Only allow byte offsets.
3841   if (ShAmt % 8)
3842     return false;
3843 
3844   // Ensure that this isn't going to produce an unsupported unaligned access.
3845   if (ShAmt && !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
3846                                        ExtVT, LoadN->getAddressSpace(),
3847                                        ShAmt / 8))
3848     return false;
3849 
3850 
3851   // If the load that we're shrinking is an extload and we're not just
3852   // discarding the extension we can't simply shrink the load. Bail.
3853   // TODO: It would be possible to merge the extensions in some cases.
3854   if (LoadN->getExtensionType() != ISD::NON_EXTLOAD &&
3855       LoadN->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
3856     return false;
3857 
3858   if (!TLI.shouldReduceLoadWidth(LoadN, ExtType, ExtVT))
3859     return false;
3860 
3861   // It's not possible to generate a constant of extended or untyped type.
3862   EVT PtrType = LoadN->getOperand(1).getValueType();
3863   if (PtrType == MVT::Untyped || PtrType.isExtended())
3864     return false;
3865 
3866   return true;
3867 }
3868 
3869 bool DAGCombiner::SearchForAndLoads(SDNode *N,
3870                                     SmallPtrSetImpl<LoadSDNode*> &Loads,
3871                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
3872                                     ConstantSDNode *Mask,
3873                                     SDNode *&NodeToMask) {
3874   // Recursively search for the operands, looking for loads which can be
3875   // narrowed.
3876   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) {
3877     SDValue Op = N->getOperand(i);
3878 
3879     if (Op.getValueType().isVector())
3880       return false;
3881 
3882     // Some constants may need fixing up later if they are too large.
3883     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3884       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
3885           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
3886         NodesWithConsts.insert(N);
3887       continue;
3888     }
3889 
3890     if (!Op.hasOneUse())
3891       return false;
3892 
3893     switch(Op.getOpcode()) {
3894     case ISD::LOAD: {
3895       auto *Load = cast<LoadSDNode>(Op);
3896       EVT ExtVT;
3897       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
3898           isLegalNarrowLoad(Load, ISD::ZEXTLOAD, ExtVT)) {
3899 
3900         // ZEXTLOAD is already small enough.
3901         if (Load->getExtensionType() == ISD::ZEXTLOAD &&
3902             ExtVT.bitsGE(Load->getMemoryVT()))
3903           continue;
3904 
3905         // Use LE to convert equal sized loads to zext.
3906         if (ExtVT.bitsLE(Load->getMemoryVT()))
3907           Loads.insert(Load);
3908 
3909         continue;
3910       }
3911       return false;
3912     }
3913     case ISD::ZERO_EXTEND:
3914     case ISD::AssertZext: {
3915       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
3916       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3917       EVT VT = Op.getOpcode() == ISD::AssertZext ?
3918         cast<VTSDNode>(Op.getOperand(1))->getVT() :
3919         Op.getOperand(0).getValueType();
3920 
3921       // We can accept extending nodes if the mask is wider or an equal
3922       // width to the original type.
3923       if (ExtVT.bitsGE(VT))
3924         continue;
3925       break;
3926     }
3927     case ISD::OR:
3928     case ISD::XOR:
3929     case ISD::AND:
3930       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
3931                              NodeToMask))
3932         return false;
3933       continue;
3934     }
3935 
3936     // Allow one node which will masked along with any loads found.
3937     if (NodeToMask)
3938       return false;
3939     NodeToMask = Op.getNode();
3940   }
3941   return true;
3942 }
3943 
3944 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) {
3945   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
3946   if (!Mask)
3947     return false;
3948 
3949   if (!Mask->getAPIntValue().isMask())
3950     return false;
3951 
3952   // No need to do anything if the and directly uses a load.
3953   if (isa<LoadSDNode>(N->getOperand(0)))
3954     return false;
3955 
3956   SmallPtrSet<LoadSDNode*, 8> Loads;
3957   SmallPtrSet<SDNode*, 2> NodesWithConsts;
3958   SDNode *FixupNode = nullptr;
3959   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
3960     if (Loads.size() == 0)
3961       return false;
3962 
3963     LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
3964     SDValue MaskOp = N->getOperand(1);
3965 
3966     // If it exists, fixup the single node we allow in the tree that needs
3967     // masking.
3968     if (FixupNode) {
3969       LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
3970       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
3971                                 FixupNode->getValueType(0),
3972                                 SDValue(FixupNode, 0), MaskOp);
3973       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
3974       DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0),
3975                              MaskOp);
3976     }
3977 
3978     // Narrow any constants that need it.
3979     for (auto *LogicN : NodesWithConsts) {
3980       SDValue Op0 = LogicN->getOperand(0);
3981       SDValue Op1 = LogicN->getOperand(1);
3982 
3983       if (isa<ConstantSDNode>(Op0))
3984           std::swap(Op0, Op1);
3985 
3986       SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
3987                                 Op1, MaskOp);
3988 
3989       DAG.UpdateNodeOperands(LogicN, Op0, And);
3990     }
3991 
3992     // Create narrow loads.
3993     for (auto *Load : Loads) {
3994       LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
3995       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
3996                                 SDValue(Load, 0), MaskOp);
3997       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
3998       DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp);
3999       SDValue NewLoad = ReduceLoadWidth(And.getNode());
4000       assert(NewLoad &&
4001              "Shouldn't be masking the load if it can't be narrowed");
4002       CombineTo(Load, NewLoad, NewLoad.getValue(1));
4003     }
4004     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
4005     return true;
4006   }
4007   return false;
4008 }
4009 
4010 SDValue DAGCombiner::visitAND(SDNode *N) {
4011   SDValue N0 = N->getOperand(0);
4012   SDValue N1 = N->getOperand(1);
4013   EVT VT = N1.getValueType();
4014 
4015   // x & x --> x
4016   if (N0 == N1)
4017     return N0;
4018 
4019   // fold vector ops
4020   if (VT.isVector()) {
4021     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4022       return FoldedVOp;
4023 
4024     // fold (and x, 0) -> 0, vector edition
4025     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4026       // do not return N0, because undef node may exist in N0
4027       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
4028                              SDLoc(N), N0.getValueType());
4029     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4030       // do not return N1, because undef node may exist in N1
4031       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
4032                              SDLoc(N), N1.getValueType());
4033 
4034     // fold (and x, -1) -> x, vector edition
4035     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4036       return N1;
4037     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4038       return N0;
4039   }
4040 
4041   // fold (and c1, c2) -> c1&c2
4042   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4043   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4044   if (N0C && N1C && !N1C->isOpaque())
4045     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
4046   // canonicalize constant to RHS
4047   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4048      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4049     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
4050   // fold (and x, -1) -> x
4051   if (isAllOnesConstant(N1))
4052     return N0;
4053   // if (and x, c) is known to be zero, return 0
4054   unsigned BitWidth = VT.getScalarSizeInBits();
4055   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4056                                    APInt::getAllOnesValue(BitWidth)))
4057     return DAG.getConstant(0, SDLoc(N), VT);
4058 
4059   if (SDValue NewSel = foldBinOpIntoSelect(N))
4060     return NewSel;
4061 
4062   // reassociate and
4063   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
4064     return RAND;
4065 
4066   // Try to convert a constant mask AND into a shuffle clear mask.
4067   if (VT.isVector())
4068     if (SDValue Shuffle = XformToShuffleWithZero(N))
4069       return Shuffle;
4070 
4071   // fold (and (or x, C), D) -> D if (C & D) == D
4072   auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4073     return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
4074   };
4075   if (N0.getOpcode() == ISD::OR &&
4076       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
4077     return N1;
4078   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
4079   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4080     SDValue N0Op0 = N0.getOperand(0);
4081     APInt Mask = ~N1C->getAPIntValue();
4082     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
4083     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
4084       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
4085                                  N0.getValueType(), N0Op0);
4086 
4087       // Replace uses of the AND with uses of the Zero extend node.
4088       CombineTo(N, Zext);
4089 
4090       // We actually want to replace all uses of the any_extend with the
4091       // zero_extend, to avoid duplicating things.  This will later cause this
4092       // AND to be folded.
4093       CombineTo(N0.getNode(), Zext);
4094       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4095     }
4096   }
4097   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
4098   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
4099   // already be zero by virtue of the width of the base type of the load.
4100   //
4101   // the 'X' node here can either be nothing or an extract_vector_elt to catch
4102   // more cases.
4103   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4104        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
4105        N0.getOperand(0).getOpcode() == ISD::LOAD &&
4106        N0.getOperand(0).getResNo() == 0) ||
4107       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
4108     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
4109                                          N0 : N0.getOperand(0) );
4110 
4111     // Get the constant (if applicable) the zero'th operand is being ANDed with.
4112     // This can be a pure constant or a vector splat, in which case we treat the
4113     // vector as a scalar and use the splat value.
4114     APInt Constant = APInt::getNullValue(1);
4115     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
4116       Constant = C->getAPIntValue();
4117     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
4118       APInt SplatValue, SplatUndef;
4119       unsigned SplatBitSize;
4120       bool HasAnyUndefs;
4121       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
4122                                              SplatBitSize, HasAnyUndefs);
4123       if (IsSplat) {
4124         // Undef bits can contribute to a possible optimisation if set, so
4125         // set them.
4126         SplatValue |= SplatUndef;
4127 
4128         // The splat value may be something like "0x00FFFFFF", which means 0 for
4129         // the first vector value and FF for the rest, repeating. We need a mask
4130         // that will apply equally to all members of the vector, so AND all the
4131         // lanes of the constant together.
4132         EVT VT = Vector->getValueType(0);
4133         unsigned BitWidth = VT.getScalarSizeInBits();
4134 
4135         // If the splat value has been compressed to a bitlength lower
4136         // than the size of the vector lane, we need to re-expand it to
4137         // the lane size.
4138         if (BitWidth > SplatBitSize)
4139           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
4140                SplatBitSize < BitWidth;
4141                SplatBitSize = SplatBitSize * 2)
4142             SplatValue |= SplatValue.shl(SplatBitSize);
4143 
4144         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
4145         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
4146         if (SplatBitSize % BitWidth == 0) {
4147           Constant = APInt::getAllOnesValue(BitWidth);
4148           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
4149             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
4150         }
4151       }
4152     }
4153 
4154     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
4155     // actually legal and isn't going to get expanded, else this is a false
4156     // optimisation.
4157     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
4158                                                     Load->getValueType(0),
4159                                                     Load->getMemoryVT());
4160 
4161     // Resize the constant to the same size as the original memory access before
4162     // extension. If it is still the AllOnesValue then this AND is completely
4163     // unneeded.
4164     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
4165 
4166     bool B;
4167     switch (Load->getExtensionType()) {
4168     default: B = false; break;
4169     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
4170     case ISD::ZEXTLOAD:
4171     case ISD::NON_EXTLOAD: B = true; break;
4172     }
4173 
4174     if (B && Constant.isAllOnesValue()) {
4175       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
4176       // preserve semantics once we get rid of the AND.
4177       SDValue NewLoad(Load, 0);
4178 
4179       // Fold the AND away. NewLoad may get replaced immediately.
4180       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
4181 
4182       if (Load->getExtensionType() == ISD::EXTLOAD) {
4183         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
4184                               Load->getValueType(0), SDLoc(Load),
4185                               Load->getChain(), Load->getBasePtr(),
4186                               Load->getOffset(), Load->getMemoryVT(),
4187                               Load->getMemOperand());
4188         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
4189         if (Load->getNumValues() == 3) {
4190           // PRE/POST_INC loads have 3 values.
4191           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
4192                            NewLoad.getValue(2) };
4193           CombineTo(Load, To, 3, true);
4194         } else {
4195           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
4196         }
4197       }
4198 
4199       return SDValue(N, 0); // Return N so it doesn't get rechecked!
4200     }
4201   }
4202 
4203   // fold (and (load x), 255) -> (zextload x, i8)
4204   // fold (and (extload x, i16), 255) -> (zextload x, i8)
4205   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
4206   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
4207                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
4208                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
4209     if (SDValue Res = ReduceLoadWidth(N)) {
4210       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
4211         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
4212 
4213       AddToWorklist(N);
4214       CombineTo(LN0, Res, Res.getValue(1));
4215       return SDValue(N, 0);
4216     }
4217   }
4218 
4219   if (Level >= AfterLegalizeTypes) {
4220     // Attempt to propagate the AND back up to the leaves which, if they're
4221     // loads, can be combined to narrow loads and the AND node can be removed.
4222     // Perform after legalization so that extend nodes will already be
4223     // combined into the loads.
4224     if (BackwardsPropagateMask(N, DAG)) {
4225       return SDValue(N, 0);
4226     }
4227   }
4228 
4229   if (SDValue Combined = visitANDLike(N0, N1, N))
4230     return Combined;
4231 
4232   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
4233   if (N0.getOpcode() == N1.getOpcode())
4234     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4235       return Tmp;
4236 
4237   // Masking the negated extension of a boolean is just the zero-extended
4238   // boolean:
4239   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
4240   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
4241   //
4242   // Note: the SimplifyDemandedBits fold below can make an information-losing
4243   // transform, and then we have no way to find this better fold.
4244   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
4245     if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
4246       SDValue SubRHS = N0.getOperand(1);
4247       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
4248           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4249         return SubRHS;
4250       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
4251           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
4252         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
4253     }
4254   }
4255 
4256   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
4257   // fold (and (sra)) -> (and (srl)) when possible.
4258   if (SimplifyDemandedBits(SDValue(N, 0)))
4259     return SDValue(N, 0);
4260 
4261   // fold (zext_inreg (extload x)) -> (zextload x)
4262   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
4263     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4264     EVT MemVT = LN0->getMemoryVT();
4265     // If we zero all the possible extended bits, then we can turn this into
4266     // a zextload if we are running before legalize or the operation is legal.
4267     unsigned BitWidth = N1.getScalarValueSizeInBits();
4268     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4269                            BitWidth - MemVT.getScalarSizeInBits())) &&
4270         ((!LegalOperations && !LN0->isVolatile()) ||
4271          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4272       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4273                                        LN0->getChain(), LN0->getBasePtr(),
4274                                        MemVT, LN0->getMemOperand());
4275       AddToWorklist(N);
4276       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4277       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4278     }
4279   }
4280   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
4281   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4282       N0.hasOneUse()) {
4283     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4284     EVT MemVT = LN0->getMemoryVT();
4285     // If we zero all the possible extended bits, then we can turn this into
4286     // a zextload if we are running before legalize or the operation is legal.
4287     unsigned BitWidth = N1.getScalarValueSizeInBits();
4288     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
4289                            BitWidth - MemVT.getScalarSizeInBits())) &&
4290         ((!LegalOperations && !LN0->isVolatile()) ||
4291          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
4292       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
4293                                        LN0->getChain(), LN0->getBasePtr(),
4294                                        MemVT, LN0->getMemOperand());
4295       AddToWorklist(N);
4296       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4297       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4298     }
4299   }
4300   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
4301   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
4302     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
4303                                            N0.getOperand(1), false))
4304       return BSwap;
4305   }
4306 
4307   return SDValue();
4308 }
4309 
4310 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
4311 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
4312                                         bool DemandHighBits) {
4313   if (!LegalOperations)
4314     return SDValue();
4315 
4316   EVT VT = N->getValueType(0);
4317   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
4318     return SDValue();
4319   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4320     return SDValue();
4321 
4322   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
4323   bool LookPassAnd0 = false;
4324   bool LookPassAnd1 = false;
4325   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
4326       std::swap(N0, N1);
4327   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
4328       std::swap(N0, N1);
4329   if (N0.getOpcode() == ISD::AND) {
4330     if (!N0.getNode()->hasOneUse())
4331       return SDValue();
4332     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4333     // Also handle 0xffff since the LHS is guaranteed to have zeros there.
4334     // This is needed for X86.
4335     if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
4336                   N01C->getZExtValue() != 0xFFFF))
4337       return SDValue();
4338     N0 = N0.getOperand(0);
4339     LookPassAnd0 = true;
4340   }
4341 
4342   if (N1.getOpcode() == ISD::AND) {
4343     if (!N1.getNode()->hasOneUse())
4344       return SDValue();
4345     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4346     if (!N11C || N11C->getZExtValue() != 0xFF)
4347       return SDValue();
4348     N1 = N1.getOperand(0);
4349     LookPassAnd1 = true;
4350   }
4351 
4352   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
4353     std::swap(N0, N1);
4354   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4355     return SDValue();
4356   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4357     return SDValue();
4358 
4359   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4360   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4361   if (!N01C || !N11C)
4362     return SDValue();
4363   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4364     return SDValue();
4365 
4366   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4367   SDValue N00 = N0->getOperand(0);
4368   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4369     if (!N00.getNode()->hasOneUse())
4370       return SDValue();
4371     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4372     if (!N001C || N001C->getZExtValue() != 0xFF)
4373       return SDValue();
4374     N00 = N00.getOperand(0);
4375     LookPassAnd0 = true;
4376   }
4377 
4378   SDValue N10 = N1->getOperand(0);
4379   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4380     if (!N10.getNode()->hasOneUse())
4381       return SDValue();
4382     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4383     // Also allow 0xFFFF since the bits will be shifted out. This is needed
4384     // for X86.
4385     if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
4386                    N101C->getZExtValue() != 0xFFFF))
4387       return SDValue();
4388     N10 = N10.getOperand(0);
4389     LookPassAnd1 = true;
4390   }
4391 
4392   if (N00 != N10)
4393     return SDValue();
4394 
4395   // Make sure everything beyond the low halfword gets set to zero since the SRL
4396   // 16 will clear the top bits.
4397   unsigned OpSizeInBits = VT.getSizeInBits();
4398   if (DemandHighBits && OpSizeInBits > 16) {
4399     // If the left-shift isn't masked out then the only way this is a bswap is
4400     // if all bits beyond the low 8 are 0. In that case the entire pattern
4401     // reduces to a left shift anyway: leave it for other parts of the combiner.
4402     if (!LookPassAnd0)
4403       return SDValue();
4404 
4405     // However, if the right shift isn't masked out then it might be because
4406     // it's not needed. See if we can spot that too.
4407     if (!LookPassAnd1 &&
4408         !DAG.MaskedValueIsZero(
4409             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4410       return SDValue();
4411   }
4412 
4413   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4414   if (OpSizeInBits > 16) {
4415     SDLoc DL(N);
4416     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4417                       DAG.getConstant(OpSizeInBits - 16, DL,
4418                                       getShiftAmountTy(VT)));
4419   }
4420   return Res;
4421 }
4422 
4423 /// Return true if the specified node is an element that makes up a 32-bit
4424 /// packed halfword byteswap.
4425 /// ((x & 0x000000ff) << 8) |
4426 /// ((x & 0x0000ff00) >> 8) |
4427 /// ((x & 0x00ff0000) << 8) |
4428 /// ((x & 0xff000000) >> 8)
4429 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4430   if (!N.getNode()->hasOneUse())
4431     return false;
4432 
4433   unsigned Opc = N.getOpcode();
4434   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4435     return false;
4436 
4437   SDValue N0 = N.getOperand(0);
4438   unsigned Opc0 = N0.getOpcode();
4439   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4440     return false;
4441 
4442   ConstantSDNode *N1C = nullptr;
4443   // SHL or SRL: look upstream for AND mask operand
4444   if (Opc == ISD::AND)
4445     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4446   else if (Opc0 == ISD::AND)
4447     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4448   if (!N1C)
4449     return false;
4450 
4451   unsigned MaskByteOffset;
4452   switch (N1C->getZExtValue()) {
4453   default:
4454     return false;
4455   case 0xFF:       MaskByteOffset = 0; break;
4456   case 0xFF00:     MaskByteOffset = 1; break;
4457   case 0xFFFF:
4458     // In case demanded bits didn't clear the bits that will be shifted out.
4459     // This is needed for X86.
4460     if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
4461       MaskByteOffset = 1;
4462       break;
4463     }
4464     return false;
4465   case 0xFF0000:   MaskByteOffset = 2; break;
4466   case 0xFF000000: MaskByteOffset = 3; break;
4467   }
4468 
4469   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4470   if (Opc == ISD::AND) {
4471     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4472       // (x >> 8) & 0xff
4473       // (x >> 8) & 0xff0000
4474       if (Opc0 != ISD::SRL)
4475         return false;
4476       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4477       if (!C || C->getZExtValue() != 8)
4478         return false;
4479     } else {
4480       // (x << 8) & 0xff00
4481       // (x << 8) & 0xff000000
4482       if (Opc0 != ISD::SHL)
4483         return false;
4484       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4485       if (!C || C->getZExtValue() != 8)
4486         return false;
4487     }
4488   } else if (Opc == ISD::SHL) {
4489     // (x & 0xff) << 8
4490     // (x & 0xff0000) << 8
4491     if (MaskByteOffset != 0 && MaskByteOffset != 2)
4492       return false;
4493     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4494     if (!C || C->getZExtValue() != 8)
4495       return false;
4496   } else { // Opc == ISD::SRL
4497     // (x & 0xff00) >> 8
4498     // (x & 0xff000000) >> 8
4499     if (MaskByteOffset != 1 && MaskByteOffset != 3)
4500       return false;
4501     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4502     if (!C || C->getZExtValue() != 8)
4503       return false;
4504   }
4505 
4506   if (Parts[MaskByteOffset])
4507     return false;
4508 
4509   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4510   return true;
4511 }
4512 
4513 /// Match a 32-bit packed halfword bswap. That is
4514 /// ((x & 0x000000ff) << 8) |
4515 /// ((x & 0x0000ff00) >> 8) |
4516 /// ((x & 0x00ff0000) << 8) |
4517 /// ((x & 0xff000000) >> 8)
4518 /// => (rotl (bswap x), 16)
4519 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4520   if (!LegalOperations)
4521     return SDValue();
4522 
4523   EVT VT = N->getValueType(0);
4524   if (VT != MVT::i32)
4525     return SDValue();
4526   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4527     return SDValue();
4528 
4529   // Look for either
4530   // (or (or (and), (and)), (or (and), (and)))
4531   // (or (or (or (and), (and)), (and)), (and))
4532   if (N0.getOpcode() != ISD::OR)
4533     return SDValue();
4534   SDValue N00 = N0.getOperand(0);
4535   SDValue N01 = N0.getOperand(1);
4536   SDNode *Parts[4] = {};
4537 
4538   if (N1.getOpcode() == ISD::OR &&
4539       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4540     // (or (or (and), (and)), (or (and), (and)))
4541     if (!isBSwapHWordElement(N00, Parts))
4542       return SDValue();
4543 
4544     if (!isBSwapHWordElement(N01, Parts))
4545       return SDValue();
4546     SDValue N10 = N1.getOperand(0);
4547     if (!isBSwapHWordElement(N10, Parts))
4548       return SDValue();
4549     SDValue N11 = N1.getOperand(1);
4550     if (!isBSwapHWordElement(N11, Parts))
4551       return SDValue();
4552   } else {
4553     // (or (or (or (and), (and)), (and)), (and))
4554     if (!isBSwapHWordElement(N1, Parts))
4555       return SDValue();
4556     if (!isBSwapHWordElement(N01, Parts))
4557       return SDValue();
4558     if (N00.getOpcode() != ISD::OR)
4559       return SDValue();
4560     SDValue N000 = N00.getOperand(0);
4561     if (!isBSwapHWordElement(N000, Parts))
4562       return SDValue();
4563     SDValue N001 = N00.getOperand(1);
4564     if (!isBSwapHWordElement(N001, Parts))
4565       return SDValue();
4566   }
4567 
4568   // Make sure the parts are all coming from the same node.
4569   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4570     return SDValue();
4571 
4572   SDLoc DL(N);
4573   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4574                               SDValue(Parts[0], 0));
4575 
4576   // Result of the bswap should be rotated by 16. If it's not legal, then
4577   // do  (x << 16) | (x >> 16).
4578   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4579   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4580     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4581   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4582     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4583   return DAG.getNode(ISD::OR, DL, VT,
4584                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4585                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4586 }
4587 
4588 /// This contains all DAGCombine rules which reduce two values combined by
4589 /// an Or operation to a single value \see visitANDLike().
4590 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4591   EVT VT = N1.getValueType();
4592   SDLoc DL(N);
4593 
4594   // fold (or x, undef) -> -1
4595   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4596     return DAG.getAllOnesConstant(DL, VT);
4597 
4598   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4599     return V;
4600 
4601   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
4602   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4603       // Don't increase # computations.
4604       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4605     // We can only do this xform if we know that bits from X that are set in C2
4606     // but not in C1 are already zero.  Likewise for Y.
4607     if (const ConstantSDNode *N0O1C =
4608         getAsNonOpaqueConstant(N0.getOperand(1))) {
4609       if (const ConstantSDNode *N1O1C =
4610           getAsNonOpaqueConstant(N1.getOperand(1))) {
4611         // We can only do this xform if we know that bits from X that are set in
4612         // C2 but not in C1 are already zero.  Likewise for Y.
4613         const APInt &LHSMask = N0O1C->getAPIntValue();
4614         const APInt &RHSMask = N1O1C->getAPIntValue();
4615 
4616         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4617             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4618           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4619                                   N0.getOperand(0), N1.getOperand(0));
4620           return DAG.getNode(ISD::AND, DL, VT, X,
4621                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
4622         }
4623       }
4624     }
4625   }
4626 
4627   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4628   if (N0.getOpcode() == ISD::AND &&
4629       N1.getOpcode() == ISD::AND &&
4630       N0.getOperand(0) == N1.getOperand(0) &&
4631       // Don't increase # computations.
4632       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4633     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4634                             N0.getOperand(1), N1.getOperand(1));
4635     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4636   }
4637 
4638   return SDValue();
4639 }
4640 
4641 SDValue DAGCombiner::visitOR(SDNode *N) {
4642   SDValue N0 = N->getOperand(0);
4643   SDValue N1 = N->getOperand(1);
4644   EVT VT = N1.getValueType();
4645 
4646   // x | x --> x
4647   if (N0 == N1)
4648     return N0;
4649 
4650   // fold vector ops
4651   if (VT.isVector()) {
4652     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4653       return FoldedVOp;
4654 
4655     // fold (or x, 0) -> x, vector edition
4656     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4657       return N1;
4658     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4659       return N0;
4660 
4661     // fold (or x, -1) -> -1, vector edition
4662     if (ISD::isBuildVectorAllOnes(N0.getNode()))
4663       // do not return N0, because undef node may exist in N0
4664       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4665     if (ISD::isBuildVectorAllOnes(N1.getNode()))
4666       // do not return N1, because undef node may exist in N1
4667       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4668 
4669     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4670     // Do this only if the resulting shuffle is legal.
4671     if (isa<ShuffleVectorSDNode>(N0) &&
4672         isa<ShuffleVectorSDNode>(N1) &&
4673         // Avoid folding a node with illegal type.
4674         TLI.isTypeLegal(VT)) {
4675       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4676       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4677       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4678       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4679       // Ensure both shuffles have a zero input.
4680       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4681         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4682         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4683         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4684         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4685         bool CanFold = true;
4686         int NumElts = VT.getVectorNumElements();
4687         SmallVector<int, 4> Mask(NumElts);
4688 
4689         for (int i = 0; i != NumElts; ++i) {
4690           int M0 = SV0->getMaskElt(i);
4691           int M1 = SV1->getMaskElt(i);
4692 
4693           // Determine if either index is pointing to a zero vector.
4694           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4695           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4696 
4697           // If one element is zero and the otherside is undef, keep undef.
4698           // This also handles the case that both are undef.
4699           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4700             Mask[i] = -1;
4701             continue;
4702           }
4703 
4704           // Make sure only one of the elements is zero.
4705           if (M0Zero == M1Zero) {
4706             CanFold = false;
4707             break;
4708           }
4709 
4710           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4711 
4712           // We have a zero and non-zero element. If the non-zero came from
4713           // SV0 make the index a LHS index. If it came from SV1, make it
4714           // a RHS index. We need to mod by NumElts because we don't care
4715           // which operand it came from in the original shuffles.
4716           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4717         }
4718 
4719         if (CanFold) {
4720           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4721           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4722 
4723           bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4724           if (!LegalMask) {
4725             std::swap(NewLHS, NewRHS);
4726             ShuffleVectorSDNode::commuteMask(Mask);
4727             LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4728           }
4729 
4730           if (LegalMask)
4731             return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4732         }
4733       }
4734     }
4735   }
4736 
4737   // fold (or c1, c2) -> c1|c2
4738   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4739   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4740   if (N0C && N1C && !N1C->isOpaque())
4741     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4742   // canonicalize constant to RHS
4743   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4744      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4745     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4746   // fold (or x, 0) -> x
4747   if (isNullConstant(N1))
4748     return N0;
4749   // fold (or x, -1) -> -1
4750   if (isAllOnesConstant(N1))
4751     return N1;
4752 
4753   if (SDValue NewSel = foldBinOpIntoSelect(N))
4754     return NewSel;
4755 
4756   // fold (or x, c) -> c iff (x & ~c) == 0
4757   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4758     return N1;
4759 
4760   if (SDValue Combined = visitORLike(N0, N1, N))
4761     return Combined;
4762 
4763   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4764   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4765     return BSwap;
4766   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4767     return BSwap;
4768 
4769   // reassociate or
4770   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4771     return ROR;
4772 
4773   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4774   // iff (c1 & c2) != 0.
4775   auto MatchIntersect = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
4776     return LHS->getAPIntValue().intersects(RHS->getAPIntValue());
4777   };
4778   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4779       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect)) {
4780     if (SDValue COR = DAG.FoldConstantArithmetic(
4781             ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) {
4782       SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
4783       AddToWorklist(IOR.getNode());
4784       return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
4785     }
4786   }
4787 
4788   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
4789   if (N0.getOpcode() == N1.getOpcode())
4790     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4791       return Tmp;
4792 
4793   // See if this is some rotate idiom.
4794   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4795     return SDValue(Rot, 0);
4796 
4797   if (SDValue Load = MatchLoadCombine(N))
4798     return Load;
4799 
4800   // Simplify the operands using demanded-bits information.
4801   if (SimplifyDemandedBits(SDValue(N, 0)))
4802     return SDValue(N, 0);
4803 
4804   return SDValue();
4805 }
4806 
4807 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4808 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4809   if (Op.getOpcode() == ISD::AND) {
4810     if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4811       Mask = Op.getOperand(1);
4812       Op = Op.getOperand(0);
4813     } else {
4814       return false;
4815     }
4816   }
4817 
4818   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4819     Shift = Op;
4820     return true;
4821   }
4822 
4823   return false;
4824 }
4825 
4826 // Return true if we can prove that, whenever Neg and Pos are both in the
4827 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
4828 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4829 //
4830 //     (or (shift1 X, Neg), (shift2 X, Pos))
4831 //
4832 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4833 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
4834 // to consider shift amounts with defined behavior.
4835 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
4836                            SelectionDAG &DAG) {
4837   // If EltSize is a power of 2 then:
4838   //
4839   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4840   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4841   //
4842   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4843   // for the stronger condition:
4844   //
4845   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
4846   //
4847   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4848   // we can just replace Neg with Neg' for the rest of the function.
4849   //
4850   // In other cases we check for the even stronger condition:
4851   //
4852   //     Neg == EltSize - Pos                                    [B]
4853   //
4854   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
4855   // behavior if Pos == 0 (and consequently Neg == EltSize).
4856   //
4857   // We could actually use [A] whenever EltSize is a power of 2, but the
4858   // only extra cases that it would match are those uninteresting ones
4859   // where Neg and Pos are never in range at the same time.  E.g. for
4860   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4861   // as well as (sub 32, Pos), but:
4862   //
4863   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4864   //
4865   // always invokes undefined behavior for 32-bit X.
4866   //
4867   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4868   unsigned MaskLoBits = 0;
4869   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4870     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4871       KnownBits Known;
4872       DAG.computeKnownBits(Neg.getOperand(0), Known);
4873       unsigned Bits = Log2_64(EltSize);
4874       if (NegC->getAPIntValue().getActiveBits() <= Bits &&
4875           ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) {
4876         Neg = Neg.getOperand(0);
4877         MaskLoBits = Bits;
4878       }
4879     }
4880   }
4881 
4882   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4883   if (Neg.getOpcode() != ISD::SUB)
4884     return false;
4885   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4886   if (!NegC)
4887     return false;
4888   SDValue NegOp1 = Neg.getOperand(1);
4889 
4890   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4891   // Pos'.  The truncation is redundant for the purpose of the equality.
4892   if (MaskLoBits && Pos.getOpcode() == ISD::AND) {
4893     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) {
4894       KnownBits Known;
4895       DAG.computeKnownBits(Pos.getOperand(0), Known);
4896       if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
4897           ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >=
4898            MaskLoBits))
4899         Pos = Pos.getOperand(0);
4900     }
4901   }
4902 
4903   // The condition we need is now:
4904   //
4905   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4906   //
4907   // If NegOp1 == Pos then we need:
4908   //
4909   //              EltSize & Mask == NegC & Mask
4910   //
4911   // (because "x & Mask" is a truncation and distributes through subtraction).
4912   APInt Width;
4913   if (Pos == NegOp1)
4914     Width = NegC->getAPIntValue();
4915 
4916   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4917   // Then the condition we want to prove becomes:
4918   //
4919   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4920   //
4921   // which, again because "x & Mask" is a truncation, becomes:
4922   //
4923   //                NegC & Mask == (EltSize - PosC) & Mask
4924   //             EltSize & Mask == (NegC + PosC) & Mask
4925   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4926     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4927       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4928     else
4929       return false;
4930   } else
4931     return false;
4932 
4933   // Now we just need to check that EltSize & Mask == Width & Mask.
4934   if (MaskLoBits)
4935     // EltSize & Mask is 0 since Mask is EltSize - 1.
4936     return Width.getLoBits(MaskLoBits) == 0;
4937   return Width == EltSize;
4938 }
4939 
4940 // A subroutine of MatchRotate used once we have found an OR of two opposite
4941 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
4942 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4943 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
4944 // Neg with outer conversions stripped away.
4945 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4946                                        SDValue Neg, SDValue InnerPos,
4947                                        SDValue InnerNeg, unsigned PosOpcode,
4948                                        unsigned NegOpcode, const SDLoc &DL) {
4949   // fold (or (shl x, (*ext y)),
4950   //          (srl x, (*ext (sub 32, y)))) ->
4951   //   (rotl x, y) or (rotr x, (sub 32, y))
4952   //
4953   // fold (or (shl x, (*ext (sub 32, y))),
4954   //          (srl x, (*ext y))) ->
4955   //   (rotr x, y) or (rotl x, (sub 32, y))
4956   EVT VT = Shifted.getValueType();
4957   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) {
4958     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4959     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4960                        HasPos ? Pos : Neg).getNode();
4961   }
4962 
4963   return nullptr;
4964 }
4965 
4966 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
4967 // idioms for rotate, and if the target supports rotation instructions, generate
4968 // a rot[lr].
4969 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4970   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
4971   EVT VT = LHS.getValueType();
4972   if (!TLI.isTypeLegal(VT)) return nullptr;
4973 
4974   // The target must have at least one rotate flavor.
4975   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4976   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4977   if (!HasROTL && !HasROTR) return nullptr;
4978 
4979   // Check for truncated rotate.
4980   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
4981       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
4982     assert(LHS.getValueType() == RHS.getValueType());
4983     if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
4984       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(),
4985                          SDValue(Rot, 0)).getNode();
4986     }
4987   }
4988 
4989   // Match "(X shl/srl V1) & V2" where V2 may not be present.
4990   SDValue LHSShift;   // The shift.
4991   SDValue LHSMask;    // AND value if any.
4992   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4993     return nullptr; // Not part of a rotate.
4994 
4995   SDValue RHSShift;   // The shift.
4996   SDValue RHSMask;    // AND value if any.
4997   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4998     return nullptr; // Not part of a rotate.
4999 
5000   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
5001     return nullptr;   // Not shifting the same value.
5002 
5003   if (LHSShift.getOpcode() == RHSShift.getOpcode())
5004     return nullptr;   // Shifts must disagree.
5005 
5006   // Canonicalize shl to left side in a shl/srl pair.
5007   if (RHSShift.getOpcode() == ISD::SHL) {
5008     std::swap(LHS, RHS);
5009     std::swap(LHSShift, RHSShift);
5010     std::swap(LHSMask, RHSMask);
5011   }
5012 
5013   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5014   SDValue LHSShiftArg = LHSShift.getOperand(0);
5015   SDValue LHSShiftAmt = LHSShift.getOperand(1);
5016   SDValue RHSShiftArg = RHSShift.getOperand(0);
5017   SDValue RHSShiftAmt = RHSShift.getOperand(1);
5018 
5019   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
5020   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
5021   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
5022                                         ConstantSDNode *RHS) {
5023     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
5024   };
5025   if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
5026     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
5027                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
5028 
5029     // If there is an AND of either shifted operand, apply it to the result.
5030     if (LHSMask.getNode() || RHSMask.getNode()) {
5031       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
5032       SDValue Mask = AllOnes;
5033 
5034       if (LHSMask.getNode()) {
5035         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
5036         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5037                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
5038       }
5039       if (RHSMask.getNode()) {
5040         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
5041         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
5042                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
5043       }
5044 
5045       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
5046     }
5047 
5048     return Rot.getNode();
5049   }
5050 
5051   // If there is a mask here, and we have a variable shift, we can't be sure
5052   // that we're masking out the right stuff.
5053   if (LHSMask.getNode() || RHSMask.getNode())
5054     return nullptr;
5055 
5056   // If the shift amount is sign/zext/any-extended just peel it off.
5057   SDValue LExtOp0 = LHSShiftAmt;
5058   SDValue RExtOp0 = RHSShiftAmt;
5059   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5060        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5061        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5062        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
5063       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
5064        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
5065        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
5066        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
5067     LExtOp0 = LHSShiftAmt.getOperand(0);
5068     RExtOp0 = RHSShiftAmt.getOperand(0);
5069   }
5070 
5071   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
5072                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
5073   if (TryL)
5074     return TryL;
5075 
5076   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
5077                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
5078   if (TryR)
5079     return TryR;
5080 
5081   return nullptr;
5082 }
5083 
5084 namespace {
5085 
5086 /// Represents known origin of an individual byte in load combine pattern. The
5087 /// value of the byte is either constant zero or comes from memory.
5088 struct ByteProvider {
5089   // For constant zero providers Load is set to nullptr. For memory providers
5090   // Load represents the node which loads the byte from memory.
5091   // ByteOffset is the offset of the byte in the value produced by the load.
5092   LoadSDNode *Load = nullptr;
5093   unsigned ByteOffset = 0;
5094 
5095   ByteProvider() = default;
5096 
5097   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
5098     return ByteProvider(Load, ByteOffset);
5099   }
5100 
5101   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
5102 
5103   bool isConstantZero() const { return !Load; }
5104   bool isMemory() const { return Load; }
5105 
5106   bool operator==(const ByteProvider &Other) const {
5107     return Other.Load == Load && Other.ByteOffset == ByteOffset;
5108   }
5109 
5110 private:
5111   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
5112       : Load(Load), ByteOffset(ByteOffset) {}
5113 };
5114 
5115 } // end anonymous namespace
5116 
5117 /// Recursively traverses the expression calculating the origin of the requested
5118 /// byte of the given value. Returns None if the provider can't be calculated.
5119 ///
5120 /// For all the values except the root of the expression verifies that the value
5121 /// has exactly one use and if it's not true return None. This way if the origin
5122 /// of the byte is returned it's guaranteed that the values which contribute to
5123 /// the byte are not used outside of this expression.
5124 ///
5125 /// Because the parts of the expression are not allowed to have more than one
5126 /// use this function iterates over trees, not DAGs. So it never visits the same
5127 /// node more than once.
5128 static const Optional<ByteProvider>
5129 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
5130                       bool Root = false) {
5131   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
5132   if (Depth == 10)
5133     return None;
5134 
5135   if (!Root && !Op.hasOneUse())
5136     return None;
5137 
5138   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
5139   unsigned BitWidth = Op.getValueSizeInBits();
5140   if (BitWidth % 8 != 0)
5141     return None;
5142   unsigned ByteWidth = BitWidth / 8;
5143   assert(Index < ByteWidth && "invalid index requested");
5144   (void) ByteWidth;
5145 
5146   switch (Op.getOpcode()) {
5147   case ISD::OR: {
5148     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
5149     if (!LHS)
5150       return None;
5151     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
5152     if (!RHS)
5153       return None;
5154 
5155     if (LHS->isConstantZero())
5156       return RHS;
5157     if (RHS->isConstantZero())
5158       return LHS;
5159     return None;
5160   }
5161   case ISD::SHL: {
5162     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
5163     if (!ShiftOp)
5164       return None;
5165 
5166     uint64_t BitShift = ShiftOp->getZExtValue();
5167     if (BitShift % 8 != 0)
5168       return None;
5169     uint64_t ByteShift = BitShift / 8;
5170 
5171     return Index < ByteShift
5172                ? ByteProvider::getConstantZero()
5173                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
5174                                        Depth + 1);
5175   }
5176   case ISD::ANY_EXTEND:
5177   case ISD::SIGN_EXTEND:
5178   case ISD::ZERO_EXTEND: {
5179     SDValue NarrowOp = Op->getOperand(0);
5180     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
5181     if (NarrowBitWidth % 8 != 0)
5182       return None;
5183     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5184 
5185     if (Index >= NarrowByteWidth)
5186       return Op.getOpcode() == ISD::ZERO_EXTEND
5187                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5188                  : None;
5189     return calculateByteProvider(NarrowOp, Index, Depth + 1);
5190   }
5191   case ISD::BSWAP:
5192     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
5193                                  Depth + 1);
5194   case ISD::LOAD: {
5195     auto L = cast<LoadSDNode>(Op.getNode());
5196     if (L->isVolatile() || L->isIndexed())
5197       return None;
5198 
5199     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
5200     if (NarrowBitWidth % 8 != 0)
5201       return None;
5202     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
5203 
5204     if (Index >= NarrowByteWidth)
5205       return L->getExtensionType() == ISD::ZEXTLOAD
5206                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
5207                  : None;
5208     return ByteProvider::getMemory(L, Index);
5209   }
5210   }
5211 
5212   return None;
5213 }
5214 
5215 /// Match a pattern where a wide type scalar value is loaded by several narrow
5216 /// loads and combined by shifts and ors. Fold it into a single load or a load
5217 /// and a BSWAP if the targets supports it.
5218 ///
5219 /// Assuming little endian target:
5220 ///  i8 *a = ...
5221 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
5222 /// =>
5223 ///  i32 val = *((i32)a)
5224 ///
5225 ///  i8 *a = ...
5226 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
5227 /// =>
5228 ///  i32 val = BSWAP(*((i32)a))
5229 ///
5230 /// TODO: This rule matches complex patterns with OR node roots and doesn't
5231 /// interact well with the worklist mechanism. When a part of the pattern is
5232 /// updated (e.g. one of the loads) its direct users are put into the worklist,
5233 /// but the root node of the pattern which triggers the load combine is not
5234 /// necessarily a direct user of the changed node. For example, once the address
5235 /// of t28 load is reassociated load combine won't be triggered:
5236 ///             t25: i32 = add t4, Constant:i32<2>
5237 ///           t26: i64 = sign_extend t25
5238 ///        t27: i64 = add t2, t26
5239 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
5240 ///     t29: i32 = zero_extend t28
5241 ///   t32: i32 = shl t29, Constant:i8<8>
5242 /// t33: i32 = or t23, t32
5243 /// As a possible fix visitLoad can check if the load can be a part of a load
5244 /// combine pattern and add corresponding OR roots to the worklist.
5245 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
5246   assert(N->getOpcode() == ISD::OR &&
5247          "Can only match load combining against OR nodes");
5248 
5249   // Handles simple types only
5250   EVT VT = N->getValueType(0);
5251   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
5252     return SDValue();
5253   unsigned ByteWidth = VT.getSizeInBits() / 8;
5254 
5255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5256   // Before legalize we can introduce too wide illegal loads which will be later
5257   // split into legal sized loads. This enables us to combine i64 load by i8
5258   // patterns to a couple of i32 loads on 32 bit targets.
5259   if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
5260     return SDValue();
5261 
5262   std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
5263     unsigned BW, unsigned i) { return i; };
5264   std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
5265     unsigned BW, unsigned i) { return BW - i - 1; };
5266 
5267   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
5268   auto MemoryByteOffset = [&] (ByteProvider P) {
5269     assert(P.isMemory() && "Must be a memory byte provider");
5270     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
5271     assert(LoadBitWidth % 8 == 0 &&
5272            "can only analyze providers for individual bytes not bit");
5273     unsigned LoadByteWidth = LoadBitWidth / 8;
5274     return IsBigEndianTarget
5275             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
5276             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
5277   };
5278 
5279   Optional<BaseIndexOffset> Base;
5280   SDValue Chain;
5281 
5282   SmallSet<LoadSDNode *, 8> Loads;
5283   Optional<ByteProvider> FirstByteProvider;
5284   int64_t FirstOffset = INT64_MAX;
5285 
5286   // Check if all the bytes of the OR we are looking at are loaded from the same
5287   // base address. Collect bytes offsets from Base address in ByteOffsets.
5288   SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
5289   for (unsigned i = 0; i < ByteWidth; i++) {
5290     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
5291     if (!P || !P->isMemory()) // All the bytes must be loaded from memory
5292       return SDValue();
5293 
5294     LoadSDNode *L = P->Load;
5295     assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
5296            "Must be enforced by calculateByteProvider");
5297     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
5298 
5299     // All loads must share the same chain
5300     SDValue LChain = L->getChain();
5301     if (!Chain)
5302       Chain = LChain;
5303     else if (Chain != LChain)
5304       return SDValue();
5305 
5306     // Loads must share the same base address
5307     BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
5308     int64_t ByteOffsetFromBase = 0;
5309     if (!Base)
5310       Base = Ptr;
5311     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
5312       return SDValue();
5313 
5314     // Calculate the offset of the current byte from the base address
5315     ByteOffsetFromBase += MemoryByteOffset(*P);
5316     ByteOffsets[i] = ByteOffsetFromBase;
5317 
5318     // Remember the first byte load
5319     if (ByteOffsetFromBase < FirstOffset) {
5320       FirstByteProvider = P;
5321       FirstOffset = ByteOffsetFromBase;
5322     }
5323 
5324     Loads.insert(L);
5325   }
5326   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
5327          "memory, so there must be at least one load which produces the value");
5328   assert(Base && "Base address of the accessed memory location must be set");
5329   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
5330 
5331   // Check if the bytes of the OR we are looking at match with either big or
5332   // little endian value load
5333   bool BigEndian = true, LittleEndian = true;
5334   for (unsigned i = 0; i < ByteWidth; i++) {
5335     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
5336     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
5337     BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
5338     if (!BigEndian && !LittleEndian)
5339       return SDValue();
5340   }
5341   assert((BigEndian != LittleEndian) && "should be either or");
5342   assert(FirstByteProvider && "must be set");
5343 
5344   // Ensure that the first byte is loaded from zero offset of the first load.
5345   // So the combined value can be loaded from the first load address.
5346   if (MemoryByteOffset(*FirstByteProvider) != 0)
5347     return SDValue();
5348   LoadSDNode *FirstLoad = FirstByteProvider->Load;
5349 
5350   // The node we are looking at matches with the pattern, check if we can
5351   // replace it with a single load and bswap if needed.
5352 
5353   // If the load needs byte swap check if the target supports it
5354   bool NeedsBswap = IsBigEndianTarget != BigEndian;
5355 
5356   // Before legalize we can introduce illegal bswaps which will be later
5357   // converted to an explicit bswap sequence. This way we end up with a single
5358   // load and byte shuffling instead of several loads and byte shuffling.
5359   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
5360     return SDValue();
5361 
5362   // Check that a load of the wide type is both allowed and fast on the target
5363   bool Fast = false;
5364   bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
5365                                         VT, FirstLoad->getAddressSpace(),
5366                                         FirstLoad->getAlignment(), &Fast);
5367   if (!Allowed || !Fast)
5368     return SDValue();
5369 
5370   SDValue NewLoad =
5371       DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
5372                   FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
5373 
5374   // Transfer chain users from old loads to the new load.
5375   for (LoadSDNode *L : Loads)
5376     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
5377 
5378   return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5379 }
5380 
5381 // If the target has andn, bsl, or a similar bit-select instruction,
5382 // we want to unfold masked merge, with canonical pattern of:
5383 //   |        A  |  |B|
5384 //   ((x ^ y) & m) ^ y
5385 //    |  D  |
5386 // Into:
5387 //   (x & m) | (y & ~m)
5388 // If y is a constant, and the 'andn' does not work with immediates,
5389 // we unfold into a different pattern:
5390 //   ~(~x & m) & (m | y)
5391 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
5392 //       the very least that breaks andnpd / andnps patterns, and because those
5393 //       patterns are simplified in IR and shouldn't be created in the DAG
5394 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
5395   assert(N->getOpcode() == ISD::XOR);
5396 
5397   // Don't touch 'not' (i.e. where y = -1).
5398   if (isAllOnesConstantOrAllOnesSplatConstant(N->getOperand(1)))
5399     return SDValue();
5400 
5401   EVT VT = N->getValueType(0);
5402 
5403   // There are 3 commutable operators in the pattern,
5404   // so we have to deal with 8 possible variants of the basic pattern.
5405   SDValue X, Y, M;
5406   auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
5407     if (And.getOpcode() != ISD::AND || !And.hasOneUse())
5408       return false;
5409     SDValue Xor = And.getOperand(XorIdx);
5410     if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
5411       return false;
5412     SDValue Xor0 = Xor.getOperand(0);
5413     SDValue Xor1 = Xor.getOperand(1);
5414     // Don't touch 'not' (i.e. where y = -1).
5415     if (isAllOnesConstantOrAllOnesSplatConstant(Xor1))
5416       return false;
5417     if (Other == Xor0)
5418       std::swap(Xor0, Xor1);
5419     if (Other != Xor1)
5420       return false;
5421     X = Xor0;
5422     Y = Xor1;
5423     M = And.getOperand(XorIdx ? 0 : 1);
5424     return true;
5425   };
5426 
5427   SDValue N0 = N->getOperand(0);
5428   SDValue N1 = N->getOperand(1);
5429   if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
5430       !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
5431     return SDValue();
5432 
5433   // Don't do anything if the mask is constant. This should not be reachable.
5434   // InstCombine should have already unfolded this pattern, and DAGCombiner
5435   // probably shouldn't produce it, too.
5436   if (isa<ConstantSDNode>(M.getNode()))
5437     return SDValue();
5438 
5439   // We can transform if the target has AndNot
5440   if (!TLI.hasAndNot(M))
5441     return SDValue();
5442 
5443   SDLoc DL(N);
5444 
5445   // If Y is a constant, check that 'andn' works with immediates.
5446   if (!TLI.hasAndNot(Y)) {
5447     assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
5448     // If not, we need to do a bit more work to make sure andn is still used.
5449     SDValue NotX = DAG.getNOT(DL, X, VT);
5450     SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
5451     SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
5452     SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
5453     return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
5454   }
5455 
5456   SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
5457   SDValue NotM = DAG.getNOT(DL, M, VT);
5458   SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
5459 
5460   return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
5461 }
5462 
5463 SDValue DAGCombiner::visitXOR(SDNode *N) {
5464   SDValue N0 = N->getOperand(0);
5465   SDValue N1 = N->getOperand(1);
5466   EVT VT = N0.getValueType();
5467 
5468   // fold vector ops
5469   if (VT.isVector()) {
5470     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5471       return FoldedVOp;
5472 
5473     // fold (xor x, 0) -> x, vector edition
5474     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5475       return N1;
5476     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5477       return N0;
5478   }
5479 
5480   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5481   if (N0.isUndef() && N1.isUndef())
5482     return DAG.getConstant(0, SDLoc(N), VT);
5483   // fold (xor x, undef) -> undef
5484   if (N0.isUndef())
5485     return N0;
5486   if (N1.isUndef())
5487     return N1;
5488   // fold (xor c1, c2) -> c1^c2
5489   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5490   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5491   if (N0C && N1C)
5492     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5493   // canonicalize constant to RHS
5494   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5495      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5496     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5497   // fold (xor x, 0) -> x
5498   if (isNullConstant(N1))
5499     return N0;
5500 
5501   if (SDValue NewSel = foldBinOpIntoSelect(N))
5502     return NewSel;
5503 
5504   // reassociate xor
5505   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5506     return RXOR;
5507 
5508   // fold !(x cc y) -> (x !cc y)
5509   SDValue LHS, RHS, CC;
5510   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5511     bool isInt = LHS.getValueType().isInteger();
5512     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5513                                                isInt);
5514 
5515     if (!LegalOperations ||
5516         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5517       switch (N0.getOpcode()) {
5518       default:
5519         llvm_unreachable("Unhandled SetCC Equivalent!");
5520       case ISD::SETCC:
5521         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5522       case ISD::SELECT_CC:
5523         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5524                                N0.getOperand(3), NotCC);
5525       }
5526     }
5527   }
5528 
5529   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5530   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5531       N0.getNode()->hasOneUse() &&
5532       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5533     SDValue V = N0.getOperand(0);
5534     SDLoc DL(N0);
5535     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5536                     DAG.getConstant(1, DL, V.getValueType()));
5537     AddToWorklist(V.getNode());
5538     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5539   }
5540 
5541   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5542   if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
5543       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5544     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5545     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5546       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5547       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5548       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5549       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5550       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5551     }
5552   }
5553   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5554   if (isAllOnesConstant(N1) && N0.hasOneUse() &&
5555       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5556     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5557     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5558       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5559       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5560       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5561       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5562       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5563     }
5564   }
5565   // fold (xor (and x, y), y) -> (and (not x), y)
5566   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5567       N0->getOperand(1) == N1) {
5568     SDValue X = N0->getOperand(0);
5569     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5570     AddToWorklist(NotX.getNode());
5571     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5572   }
5573 
5574   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5575   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5576   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5577       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5578       TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5579     if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5580       if (C->getAPIntValue() == (OpSizeInBits - 1))
5581         return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5582   }
5583 
5584   // fold (xor x, x) -> 0
5585   if (N0 == N1)
5586     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5587 
5588   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5589   // Here is a concrete example of this equivalence:
5590   // i16   x ==  14
5591   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
5592   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5593   //
5594   // =>
5595   //
5596   // i16     ~1      == 0b1111111111111110
5597   // i16 rol(~1, 14) == 0b1011111111111111
5598   //
5599   // Some additional tips to help conceptualize this transform:
5600   // - Try to see the operation as placing a single zero in a value of all ones.
5601   // - There exists no value for x which would allow the result to contain zero.
5602   // - Values of x larger than the bitwidth are undefined and do not require a
5603   //   consistent result.
5604   // - Pushing the zero left requires shifting one bits in from the right.
5605   // A rotate left of ~1 is a nice way of achieving the desired result.
5606   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5607       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5608     SDLoc DL(N);
5609     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5610                        N0.getOperand(1));
5611   }
5612 
5613   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
5614   if (N0.getOpcode() == N1.getOpcode())
5615     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5616       return Tmp;
5617 
5618   // Unfold  ((x ^ y) & m) ^ y  into  (x & m) | (y & ~m)  if profitable
5619   if (SDValue MM = unfoldMaskedMerge(N))
5620     return MM;
5621 
5622   // Simplify the expression using non-local knowledge.
5623   if (SimplifyDemandedBits(SDValue(N, 0)))
5624     return SDValue(N, 0);
5625 
5626   return SDValue();
5627 }
5628 
5629 /// Handle transforms common to the three shifts, when the shift amount is a
5630 /// constant.
5631 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5632   SDNode *LHS = N->getOperand(0).getNode();
5633   if (!LHS->hasOneUse()) return SDValue();
5634 
5635   // We want to pull some binops through shifts, so that we have (and (shift))
5636   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
5637   // thing happens with address calculations, so it's important to canonicalize
5638   // it.
5639   bool HighBitSet = false;  // Can we transform this if the high bit is set?
5640 
5641   switch (LHS->getOpcode()) {
5642   default: return SDValue();
5643   case ISD::OR:
5644   case ISD::XOR:
5645     HighBitSet = false; // We can only transform sra if the high bit is clear.
5646     break;
5647   case ISD::AND:
5648     HighBitSet = true;  // We can only transform sra if the high bit is set.
5649     break;
5650   case ISD::ADD:
5651     if (N->getOpcode() != ISD::SHL)
5652       return SDValue(); // only shl(add) not sr[al](add).
5653     HighBitSet = false; // We can only transform sra if the high bit is clear.
5654     break;
5655   }
5656 
5657   // We require the RHS of the binop to be a constant and not opaque as well.
5658   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5659   if (!BinOpCst) return SDValue();
5660 
5661   // FIXME: disable this unless the input to the binop is a shift by a constant
5662   // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5663   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5664   bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5665                  BinOpLHSVal->getOpcode() == ISD::SRA ||
5666                  BinOpLHSVal->getOpcode() == ISD::SRL;
5667   bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5668                         BinOpLHSVal->getOpcode() == ISD::SELECT;
5669 
5670   if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5671       !isCopyOrSelect)
5672     return SDValue();
5673 
5674   if (isCopyOrSelect && N->hasOneUse())
5675     return SDValue();
5676 
5677   EVT VT = N->getValueType(0);
5678 
5679   // If this is a signed shift right, and the high bit is modified by the
5680   // logical operation, do not perform the transformation. The highBitSet
5681   // boolean indicates the value of the high bit of the constant which would
5682   // cause it to be modified for this operation.
5683   if (N->getOpcode() == ISD::SRA) {
5684     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5685     if (BinOpRHSSignSet != HighBitSet)
5686       return SDValue();
5687   }
5688 
5689   if (!TLI.isDesirableToCommuteWithShift(LHS))
5690     return SDValue();
5691 
5692   // Fold the constants, shifting the binop RHS by the shift amount.
5693   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5694                                N->getValueType(0),
5695                                LHS->getOperand(1), N->getOperand(1));
5696   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5697 
5698   // Create the new shift.
5699   SDValue NewShift = DAG.getNode(N->getOpcode(),
5700                                  SDLoc(LHS->getOperand(0)),
5701                                  VT, LHS->getOperand(0), N->getOperand(1));
5702 
5703   // Create the new binop.
5704   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5705 }
5706 
5707 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5708   assert(N->getOpcode() == ISD::TRUNCATE);
5709   assert(N->getOperand(0).getOpcode() == ISD::AND);
5710 
5711   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5712   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5713     SDValue N01 = N->getOperand(0).getOperand(1);
5714     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5715       SDLoc DL(N);
5716       EVT TruncVT = N->getValueType(0);
5717       SDValue N00 = N->getOperand(0).getOperand(0);
5718       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5719       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5720       AddToWorklist(Trunc00.getNode());
5721       AddToWorklist(Trunc01.getNode());
5722       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5723     }
5724   }
5725 
5726   return SDValue();
5727 }
5728 
5729 SDValue DAGCombiner::visitRotate(SDNode *N) {
5730   SDLoc dl(N);
5731   SDValue N0 = N->getOperand(0);
5732   SDValue N1 = N->getOperand(1);
5733   EVT VT = N->getValueType(0);
5734   unsigned Bitsize = VT.getScalarSizeInBits();
5735 
5736   // fold (rot x, 0) -> x
5737   if (isNullConstantOrNullSplatConstant(N1))
5738     return N0;
5739 
5740   // fold (rot x, c) -> (rot x, c % BitSize)
5741   if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5742     if (Cst->getAPIntValue().uge(Bitsize)) {
5743       uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5744       return DAG.getNode(N->getOpcode(), dl, VT, N0,
5745                          DAG.getConstant(RotAmt, dl, N1.getValueType()));
5746     }
5747   }
5748 
5749   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5750   if (N1.getOpcode() == ISD::TRUNCATE &&
5751       N1.getOperand(0).getOpcode() == ISD::AND) {
5752     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5753       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5754   }
5755 
5756   unsigned NextOp = N0.getOpcode();
5757   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5758   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5759     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5760     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5761     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5762       EVT ShiftVT = C1->getValueType(0);
5763       bool SameSide = (N->getOpcode() == NextOp);
5764       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5765       if (SDValue CombinedShift =
5766               DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5767         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5768         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5769             ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5770             BitsizeC.getNode());
5771         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5772                            CombinedShiftNorm);
5773       }
5774     }
5775   }
5776   return SDValue();
5777 }
5778 
5779 SDValue DAGCombiner::visitSHL(SDNode *N) {
5780   SDValue N0 = N->getOperand(0);
5781   SDValue N1 = N->getOperand(1);
5782   EVT VT = N0.getValueType();
5783   unsigned OpSizeInBits = VT.getScalarSizeInBits();
5784 
5785   // fold vector ops
5786   if (VT.isVector()) {
5787     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5788       return FoldedVOp;
5789 
5790     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5791     // If setcc produces all-one true value then:
5792     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5793     if (N1CV && N1CV->isConstant()) {
5794       if (N0.getOpcode() == ISD::AND) {
5795         SDValue N00 = N0->getOperand(0);
5796         SDValue N01 = N0->getOperand(1);
5797         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5798 
5799         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5800             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5801                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5802           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5803                                                      N01CV, N1CV))
5804             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5805         }
5806       }
5807     }
5808   }
5809 
5810   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5811 
5812   // fold (shl c1, c2) -> c1<<c2
5813   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5814   if (N0C && N1C && !N1C->isOpaque())
5815     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5816   // fold (shl 0, x) -> 0
5817   if (isNullConstantOrNullSplatConstant(N0))
5818     return N0;
5819   // fold (shl x, c >= size(x)) -> undef
5820   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
5821   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
5822     return Val->getAPIntValue().uge(OpSizeInBits);
5823   };
5824   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
5825     return DAG.getUNDEF(VT);
5826   // fold (shl x, 0) -> x
5827   if (N1C && N1C->isNullValue())
5828     return N0;
5829   // fold (shl undef, x) -> 0
5830   if (N0.isUndef())
5831     return DAG.getConstant(0, SDLoc(N), VT);
5832 
5833   if (SDValue NewSel = foldBinOpIntoSelect(N))
5834     return NewSel;
5835 
5836   // if (shl x, c) is known to be zero, return 0
5837   if (DAG.MaskedValueIsZero(SDValue(N, 0),
5838                             APInt::getAllOnesValue(OpSizeInBits)))
5839     return DAG.getConstant(0, SDLoc(N), VT);
5840   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5841   if (N1.getOpcode() == ISD::TRUNCATE &&
5842       N1.getOperand(0).getOpcode() == ISD::AND) {
5843     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5844       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5845   }
5846 
5847   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5848     return SDValue(N, 0);
5849 
5850   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5851   if (N0.getOpcode() == ISD::SHL) {
5852     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
5853                                           ConstantSDNode *RHS) {
5854       APInt c1 = LHS->getAPIntValue();
5855       APInt c2 = RHS->getAPIntValue();
5856       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5857       return (c1 + c2).uge(OpSizeInBits);
5858     };
5859     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
5860       return DAG.getConstant(0, SDLoc(N), VT);
5861 
5862     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
5863                                        ConstantSDNode *RHS) {
5864       APInt c1 = LHS->getAPIntValue();
5865       APInt c2 = RHS->getAPIntValue();
5866       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5867       return (c1 + c2).ult(OpSizeInBits);
5868     };
5869     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
5870       SDLoc DL(N);
5871       EVT ShiftVT = N1.getValueType();
5872       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
5873       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
5874     }
5875   }
5876 
5877   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5878   // For this to be valid, the second form must not preserve any of the bits
5879   // that are shifted out by the inner shift in the first form.  This means
5880   // the outer shift size must be >= the number of bits added by the ext.
5881   // As a corollary, we don't care what kind of ext it is.
5882   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5883               N0.getOpcode() == ISD::ANY_EXTEND ||
5884               N0.getOpcode() == ISD::SIGN_EXTEND) &&
5885       N0.getOperand(0).getOpcode() == ISD::SHL) {
5886     SDValue N0Op0 = N0.getOperand(0);
5887     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5888       APInt c1 = N0Op0C1->getAPIntValue();
5889       APInt c2 = N1C->getAPIntValue();
5890       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5891 
5892       EVT InnerShiftVT = N0Op0.getValueType();
5893       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5894       if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5895         SDLoc DL(N0);
5896         APInt Sum = c1 + c2;
5897         if (Sum.uge(OpSizeInBits))
5898           return DAG.getConstant(0, DL, VT);
5899 
5900         return DAG.getNode(
5901             ISD::SHL, DL, VT,
5902             DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5903             DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5904       }
5905     }
5906   }
5907 
5908   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5909   // Only fold this if the inner zext has no other uses to avoid increasing
5910   // the total number of instructions.
5911   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5912       N0.getOperand(0).getOpcode() == ISD::SRL) {
5913     SDValue N0Op0 = N0.getOperand(0);
5914     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5915       if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5916         uint64_t c1 = N0Op0C1->getZExtValue();
5917         uint64_t c2 = N1C->getZExtValue();
5918         if (c1 == c2) {
5919           SDValue NewOp0 = N0.getOperand(0);
5920           EVT CountVT = NewOp0.getOperand(1).getValueType();
5921           SDLoc DL(N);
5922           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5923                                        NewOp0,
5924                                        DAG.getConstant(c2, DL, CountVT));
5925           AddToWorklist(NewSHL.getNode());
5926           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5927         }
5928       }
5929     }
5930   }
5931 
5932   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
5933   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
5934   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5935       N0->getFlags().hasExact()) {
5936     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5937       uint64_t C1 = N0C1->getZExtValue();
5938       uint64_t C2 = N1C->getZExtValue();
5939       SDLoc DL(N);
5940       if (C1 <= C2)
5941         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5942                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5943       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5944                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5945     }
5946   }
5947 
5948   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5949   //                               (and (srl x, (sub c1, c2), MASK)
5950   // Only fold this if the inner shift has no other uses -- if it does, folding
5951   // this will increase the total number of instructions.
5952   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5953     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5954       uint64_t c1 = N0C1->getZExtValue();
5955       if (c1 < OpSizeInBits) {
5956         uint64_t c2 = N1C->getZExtValue();
5957         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5958         SDValue Shift;
5959         if (c2 > c1) {
5960           Mask <<= c2 - c1;
5961           SDLoc DL(N);
5962           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5963                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5964         } else {
5965           Mask.lshrInPlace(c1 - c2);
5966           SDLoc DL(N);
5967           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5968                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5969         }
5970         SDLoc DL(N0);
5971         return DAG.getNode(ISD::AND, DL, VT, Shift,
5972                            DAG.getConstant(Mask, DL, VT));
5973       }
5974     }
5975   }
5976 
5977   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5978   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5979       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5980     SDLoc DL(N);
5981     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5982     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5983     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5984   }
5985 
5986   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5987   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
5988   // Variant of version done on multiply, except mul by a power of 2 is turned
5989   // into a shift.
5990   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
5991       N0.getNode()->hasOneUse() &&
5992       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5993       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5994     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5995     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5996     AddToWorklist(Shl0.getNode());
5997     AddToWorklist(Shl1.getNode());
5998     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
5999   }
6000 
6001   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
6002   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
6003       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
6004       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
6005     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
6006     if (isConstantOrConstantVector(Shl))
6007       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
6008   }
6009 
6010   if (N1C && !N1C->isOpaque())
6011     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
6012       return NewSHL;
6013 
6014   return SDValue();
6015 }
6016 
6017 SDValue DAGCombiner::visitSRA(SDNode *N) {
6018   SDValue N0 = N->getOperand(0);
6019   SDValue N1 = N->getOperand(1);
6020   EVT VT = N0.getValueType();
6021   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6022 
6023   // Arithmetic shifting an all-sign-bit value is a no-op.
6024   // fold (sra 0, x) -> 0
6025   // fold (sra -1, x) -> -1
6026   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
6027     return N0;
6028 
6029   // fold vector ops
6030   if (VT.isVector())
6031     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6032       return FoldedVOp;
6033 
6034   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6035 
6036   // fold (sra c1, c2) -> (sra c1, c2)
6037   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6038   if (N0C && N1C && !N1C->isOpaque())
6039     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
6040   // fold (sra x, c >= size(x)) -> undef
6041   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6042   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6043     return Val->getAPIntValue().uge(OpSizeInBits);
6044   };
6045   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6046     return DAG.getUNDEF(VT);
6047   // fold (sra x, 0) -> x
6048   if (N1C && N1C->isNullValue())
6049     return N0;
6050 
6051   if (SDValue NewSel = foldBinOpIntoSelect(N))
6052     return NewSel;
6053 
6054   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
6055   // sext_inreg.
6056   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
6057     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
6058     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
6059     if (VT.isVector())
6060       ExtVT = EVT::getVectorVT(*DAG.getContext(),
6061                                ExtVT, VT.getVectorNumElements());
6062     if ((!LegalOperations ||
6063          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
6064       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6065                          N0.getOperand(0), DAG.getValueType(ExtVT));
6066   }
6067 
6068   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
6069   if (N0.getOpcode() == ISD::SRA) {
6070     SDLoc DL(N);
6071     EVT ShiftVT = N1.getValueType();
6072 
6073     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6074                                           ConstantSDNode *RHS) {
6075       APInt c1 = LHS->getAPIntValue();
6076       APInt c2 = RHS->getAPIntValue();
6077       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6078       return (c1 + c2).uge(OpSizeInBits);
6079     };
6080     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6081       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
6082                          DAG.getConstant(OpSizeInBits - 1, DL, ShiftVT));
6083 
6084     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6085                                        ConstantSDNode *RHS) {
6086       APInt c1 = LHS->getAPIntValue();
6087       APInt c2 = RHS->getAPIntValue();
6088       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6089       return (c1 + c2).ult(OpSizeInBits);
6090     };
6091     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6092       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6093       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), Sum);
6094     }
6095   }
6096 
6097   // fold (sra (shl X, m), (sub result_size, n))
6098   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
6099   // result_size - n != m.
6100   // If truncate is free for the target sext(shl) is likely to result in better
6101   // code.
6102   if (N0.getOpcode() == ISD::SHL && N1C) {
6103     // Get the two constanst of the shifts, CN0 = m, CN = n.
6104     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
6105     if (N01C) {
6106       LLVMContext &Ctx = *DAG.getContext();
6107       // Determine what the truncate's result bitsize and type would be.
6108       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
6109 
6110       if (VT.isVector())
6111         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
6112 
6113       // Determine the residual right-shift amount.
6114       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
6115 
6116       // If the shift is not a no-op (in which case this should be just a sign
6117       // extend already), the truncated to type is legal, sign_extend is legal
6118       // on that type, and the truncate to that type is both legal and free,
6119       // perform the transform.
6120       if ((ShiftAmt > 0) &&
6121           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
6122           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
6123           TLI.isTruncateFree(VT, TruncVT)) {
6124         SDLoc DL(N);
6125         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
6126             getShiftAmountTy(N0.getOperand(0).getValueType()));
6127         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
6128                                     N0.getOperand(0), Amt);
6129         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
6130                                     Shift);
6131         return DAG.getNode(ISD::SIGN_EXTEND, DL,
6132                            N->getValueType(0), Trunc);
6133       }
6134     }
6135   }
6136 
6137   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
6138   if (N1.getOpcode() == ISD::TRUNCATE &&
6139       N1.getOperand(0).getOpcode() == ISD::AND) {
6140     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6141       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
6142   }
6143 
6144   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
6145   //      if c1 is equal to the number of bits the trunc removes
6146   if (N0.getOpcode() == ISD::TRUNCATE &&
6147       (N0.getOperand(0).getOpcode() == ISD::SRL ||
6148        N0.getOperand(0).getOpcode() == ISD::SRA) &&
6149       N0.getOperand(0).hasOneUse() &&
6150       N0.getOperand(0).getOperand(1).hasOneUse() &&
6151       N1C) {
6152     SDValue N0Op0 = N0.getOperand(0);
6153     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
6154       unsigned LargeShiftVal = LargeShift->getZExtValue();
6155       EVT LargeVT = N0Op0.getValueType();
6156 
6157       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
6158         SDLoc DL(N);
6159         SDValue Amt =
6160           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
6161                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
6162         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
6163                                   N0Op0.getOperand(0), Amt);
6164         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
6165       }
6166     }
6167   }
6168 
6169   // Simplify, based on bits shifted out of the LHS.
6170   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6171     return SDValue(N, 0);
6172 
6173   // If the sign bit is known to be zero, switch this to a SRL.
6174   if (DAG.SignBitIsZero(N0))
6175     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
6176 
6177   if (N1C && !N1C->isOpaque())
6178     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
6179       return NewSRA;
6180 
6181   return SDValue();
6182 }
6183 
6184 SDValue DAGCombiner::visitSRL(SDNode *N) {
6185   SDValue N0 = N->getOperand(0);
6186   SDValue N1 = N->getOperand(1);
6187   EVT VT = N0.getValueType();
6188   unsigned OpSizeInBits = VT.getScalarSizeInBits();
6189 
6190   // fold vector ops
6191   if (VT.isVector())
6192     if (SDValue FoldedVOp = SimplifyVBinOp(N))
6193       return FoldedVOp;
6194 
6195   ConstantSDNode *N1C = isConstOrConstSplat(N1);
6196 
6197   // fold (srl c1, c2) -> c1 >>u c2
6198   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
6199   if (N0C && N1C && !N1C->isOpaque())
6200     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
6201   // fold (srl 0, x) -> 0
6202   if (isNullConstantOrNullSplatConstant(N0))
6203     return N0;
6204   // fold (srl x, c >= size(x)) -> undef
6205   // NOTE: ALL vector elements must be too big to avoid partial UNDEFs.
6206   auto MatchShiftTooBig = [OpSizeInBits](ConstantSDNode *Val) {
6207     return Val->getAPIntValue().uge(OpSizeInBits);
6208   };
6209   if (ISD::matchUnaryPredicate(N1, MatchShiftTooBig))
6210     return DAG.getUNDEF(VT);
6211   // fold (srl x, 0) -> x
6212   if (N1C && N1C->isNullValue())
6213     return N0;
6214 
6215   if (SDValue NewSel = foldBinOpIntoSelect(N))
6216     return NewSel;
6217 
6218   // if (srl x, c) is known to be zero, return 0
6219   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
6220                                    APInt::getAllOnesValue(OpSizeInBits)))
6221     return DAG.getConstant(0, SDLoc(N), VT);
6222 
6223   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
6224   if (N0.getOpcode() == ISD::SRL) {
6225     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
6226                                           ConstantSDNode *RHS) {
6227       APInt c1 = LHS->getAPIntValue();
6228       APInt c2 = RHS->getAPIntValue();
6229       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6230       return (c1 + c2).uge(OpSizeInBits);
6231     };
6232     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
6233       return DAG.getConstant(0, SDLoc(N), VT);
6234 
6235     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
6236                                        ConstantSDNode *RHS) {
6237       APInt c1 = LHS->getAPIntValue();
6238       APInt c2 = RHS->getAPIntValue();
6239       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
6240       return (c1 + c2).ult(OpSizeInBits);
6241     };
6242     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
6243       SDLoc DL(N);
6244       EVT ShiftVT = N1.getValueType();
6245       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
6246       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
6247     }
6248   }
6249 
6250   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
6251   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
6252       N0.getOperand(0).getOpcode() == ISD::SRL) {
6253     if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
6254       uint64_t c1 = N001C->getZExtValue();
6255       uint64_t c2 = N1C->getZExtValue();
6256       EVT InnerShiftVT = N0.getOperand(0).getValueType();
6257       EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
6258       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
6259       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
6260       if (c1 + OpSizeInBits == InnerShiftSize) {
6261         SDLoc DL(N0);
6262         if (c1 + c2 >= InnerShiftSize)
6263           return DAG.getConstant(0, DL, VT);
6264         return DAG.getNode(ISD::TRUNCATE, DL, VT,
6265                            DAG.getNode(ISD::SRL, DL, InnerShiftVT,
6266                                        N0.getOperand(0).getOperand(0),
6267                                        DAG.getConstant(c1 + c2, DL,
6268                                                        ShiftCountVT)));
6269       }
6270     }
6271   }
6272 
6273   // fold (srl (shl x, c), c) -> (and x, cst2)
6274   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
6275       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
6276     SDLoc DL(N);
6277     SDValue Mask =
6278         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
6279     AddToWorklist(Mask.getNode());
6280     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
6281   }
6282 
6283   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
6284   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
6285     // Shifting in all undef bits?
6286     EVT SmallVT = N0.getOperand(0).getValueType();
6287     unsigned BitSize = SmallVT.getScalarSizeInBits();
6288     if (N1C->getZExtValue() >= BitSize)
6289       return DAG.getUNDEF(VT);
6290 
6291     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
6292       uint64_t ShiftAmt = N1C->getZExtValue();
6293       SDLoc DL0(N0);
6294       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
6295                                        N0.getOperand(0),
6296                           DAG.getConstant(ShiftAmt, DL0,
6297                                           getShiftAmountTy(SmallVT)));
6298       AddToWorklist(SmallShift.getNode());
6299       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
6300       SDLoc DL(N);
6301       return DAG.getNode(ISD::AND, DL, VT,
6302                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
6303                          DAG.getConstant(Mask, DL, VT));
6304     }
6305   }
6306 
6307   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
6308   // bit, which is unmodified by sra.
6309   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
6310     if (N0.getOpcode() == ISD::SRA)
6311       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
6312   }
6313 
6314   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
6315   if (N1C && N0.getOpcode() == ISD::CTLZ &&
6316       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
6317     KnownBits Known;
6318     DAG.computeKnownBits(N0.getOperand(0), Known);
6319 
6320     // If any of the input bits are KnownOne, then the input couldn't be all
6321     // zeros, thus the result of the srl will always be zero.
6322     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
6323 
6324     // If all of the bits input the to ctlz node are known to be zero, then
6325     // the result of the ctlz is "32" and the result of the shift is one.
6326     APInt UnknownBits = ~Known.Zero;
6327     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
6328 
6329     // Otherwise, check to see if there is exactly one bit input to the ctlz.
6330     if (UnknownBits.isPowerOf2()) {
6331       // Okay, we know that only that the single bit specified by UnknownBits
6332       // could be set on input to the CTLZ node. If this bit is set, the SRL
6333       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
6334       // to an SRL/XOR pair, which is likely to simplify more.
6335       unsigned ShAmt = UnknownBits.countTrailingZeros();
6336       SDValue Op = N0.getOperand(0);
6337 
6338       if (ShAmt) {
6339         SDLoc DL(N0);
6340         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
6341                   DAG.getConstant(ShAmt, DL,
6342                                   getShiftAmountTy(Op.getValueType())));
6343         AddToWorklist(Op.getNode());
6344       }
6345 
6346       SDLoc DL(N);
6347       return DAG.getNode(ISD::XOR, DL, VT,
6348                          Op, DAG.getConstant(1, DL, VT));
6349     }
6350   }
6351 
6352   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
6353   if (N1.getOpcode() == ISD::TRUNCATE &&
6354       N1.getOperand(0).getOpcode() == ISD::AND) {
6355     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
6356       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
6357   }
6358 
6359   // fold operands of srl based on knowledge that the low bits are not
6360   // demanded.
6361   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
6362     return SDValue(N, 0);
6363 
6364   if (N1C && !N1C->isOpaque())
6365     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
6366       return NewSRL;
6367 
6368   // Attempt to convert a srl of a load into a narrower zero-extending load.
6369   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6370     return NarrowLoad;
6371 
6372   // Here is a common situation. We want to optimize:
6373   //
6374   //   %a = ...
6375   //   %b = and i32 %a, 2
6376   //   %c = srl i32 %b, 1
6377   //   brcond i32 %c ...
6378   //
6379   // into
6380   //
6381   //   %a = ...
6382   //   %b = and %a, 2
6383   //   %c = setcc eq %b, 0
6384   //   brcond %c ...
6385   //
6386   // However when after the source operand of SRL is optimized into AND, the SRL
6387   // itself may not be optimized further. Look for it and add the BRCOND into
6388   // the worklist.
6389   if (N->hasOneUse()) {
6390     SDNode *Use = *N->use_begin();
6391     if (Use->getOpcode() == ISD::BRCOND)
6392       AddToWorklist(Use);
6393     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
6394       // Also look pass the truncate.
6395       Use = *Use->use_begin();
6396       if (Use->getOpcode() == ISD::BRCOND)
6397         AddToWorklist(Use);
6398     }
6399   }
6400 
6401   return SDValue();
6402 }
6403 
6404 SDValue DAGCombiner::visitABS(SDNode *N) {
6405   SDValue N0 = N->getOperand(0);
6406   EVT VT = N->getValueType(0);
6407 
6408   // fold (abs c1) -> c2
6409   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6410     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
6411   // fold (abs (abs x)) -> (abs x)
6412   if (N0.getOpcode() == ISD::ABS)
6413     return N0;
6414   // fold (abs x) -> x iff not-negative
6415   if (DAG.SignBitIsZero(N0))
6416     return N0;
6417   return SDValue();
6418 }
6419 
6420 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
6421   SDValue N0 = N->getOperand(0);
6422   EVT VT = N->getValueType(0);
6423 
6424   // fold (bswap c1) -> c2
6425   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6426     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
6427   // fold (bswap (bswap x)) -> x
6428   if (N0.getOpcode() == ISD::BSWAP)
6429     return N0->getOperand(0);
6430   return SDValue();
6431 }
6432 
6433 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
6434   SDValue N0 = N->getOperand(0);
6435   EVT VT = N->getValueType(0);
6436 
6437   // fold (bitreverse c1) -> c2
6438   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6439     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
6440   // fold (bitreverse (bitreverse x)) -> x
6441   if (N0.getOpcode() == ISD::BITREVERSE)
6442     return N0.getOperand(0);
6443   return SDValue();
6444 }
6445 
6446 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
6447   SDValue N0 = N->getOperand(0);
6448   EVT VT = N->getValueType(0);
6449 
6450   // fold (ctlz c1) -> c2
6451   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6452     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
6453 
6454   // If the value is known never to be zero, switch to the undef version.
6455   if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
6456     if (DAG.isKnownNeverZero(N0))
6457       return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6458   }
6459 
6460   return SDValue();
6461 }
6462 
6463 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
6464   SDValue N0 = N->getOperand(0);
6465   EVT VT = N->getValueType(0);
6466 
6467   // fold (ctlz_zero_undef c1) -> c2
6468   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6469     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6470   return SDValue();
6471 }
6472 
6473 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
6474   SDValue N0 = N->getOperand(0);
6475   EVT VT = N->getValueType(0);
6476 
6477   // fold (cttz c1) -> c2
6478   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6479     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
6480 
6481   // If the value is known never to be zero, switch to the undef version.
6482   if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
6483     if (DAG.isKnownNeverZero(N0))
6484       return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6485   }
6486 
6487   return SDValue();
6488 }
6489 
6490 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
6491   SDValue N0 = N->getOperand(0);
6492   EVT VT = N->getValueType(0);
6493 
6494   // fold (cttz_zero_undef c1) -> c2
6495   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6496     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
6497   return SDValue();
6498 }
6499 
6500 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
6501   SDValue N0 = N->getOperand(0);
6502   EVT VT = N->getValueType(0);
6503 
6504   // fold (ctpop c1) -> c2
6505   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
6506     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6507   return SDValue();
6508 }
6509 
6510 /// Generate Min/Max node
6511 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6512                                    SDValue RHS, SDValue True, SDValue False,
6513                                    ISD::CondCode CC, const TargetLowering &TLI,
6514                                    SelectionDAG &DAG) {
6515   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6516     return SDValue();
6517 
6518   switch (CC) {
6519   case ISD::SETOLT:
6520   case ISD::SETOLE:
6521   case ISD::SETLT:
6522   case ISD::SETLE:
6523   case ISD::SETULT:
6524   case ISD::SETULE: {
6525     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6526     if (TLI.isOperationLegal(Opcode, VT))
6527       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6528     return SDValue();
6529   }
6530   case ISD::SETOGT:
6531   case ISD::SETOGE:
6532   case ISD::SETGT:
6533   case ISD::SETGE:
6534   case ISD::SETUGT:
6535   case ISD::SETUGE: {
6536     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6537     if (TLI.isOperationLegal(Opcode, VT))
6538       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6539     return SDValue();
6540   }
6541   default:
6542     return SDValue();
6543   }
6544 }
6545 
6546 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6547   SDValue Cond = N->getOperand(0);
6548   SDValue N1 = N->getOperand(1);
6549   SDValue N2 = N->getOperand(2);
6550   EVT VT = N->getValueType(0);
6551   EVT CondVT = Cond.getValueType();
6552   SDLoc DL(N);
6553 
6554   if (!VT.isInteger())
6555     return SDValue();
6556 
6557   auto *C1 = dyn_cast<ConstantSDNode>(N1);
6558   auto *C2 = dyn_cast<ConstantSDNode>(N2);
6559   if (!C1 || !C2)
6560     return SDValue();
6561 
6562   // Only do this before legalization to avoid conflicting with target-specific
6563   // transforms in the other direction (create a select from a zext/sext). There
6564   // is also a target-independent combine here in DAGCombiner in the other
6565   // direction for (select Cond, -1, 0) when the condition is not i1.
6566   if (CondVT == MVT::i1 && !LegalOperations) {
6567     if (C1->isNullValue() && C2->isOne()) {
6568       // select Cond, 0, 1 --> zext (!Cond)
6569       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6570       if (VT != MVT::i1)
6571         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6572       return NotCond;
6573     }
6574     if (C1->isNullValue() && C2->isAllOnesValue()) {
6575       // select Cond, 0, -1 --> sext (!Cond)
6576       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6577       if (VT != MVT::i1)
6578         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6579       return NotCond;
6580     }
6581     if (C1->isOne() && C2->isNullValue()) {
6582       // select Cond, 1, 0 --> zext (Cond)
6583       if (VT != MVT::i1)
6584         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6585       return Cond;
6586     }
6587     if (C1->isAllOnesValue() && C2->isNullValue()) {
6588       // select Cond, -1, 0 --> sext (Cond)
6589       if (VT != MVT::i1)
6590         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6591       return Cond;
6592     }
6593 
6594     // For any constants that differ by 1, we can transform the select into an
6595     // extend and add. Use a target hook because some targets may prefer to
6596     // transform in the other direction.
6597     if (TLI.convertSelectOfConstantsToMath(VT)) {
6598       if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6599         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6600         if (VT != MVT::i1)
6601           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6602         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6603       }
6604       if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6605         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6606         if (VT != MVT::i1)
6607           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6608         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6609       }
6610     }
6611 
6612     return SDValue();
6613   }
6614 
6615   // fold (select Cond, 0, 1) -> (xor Cond, 1)
6616   // We can't do this reliably if integer based booleans have different contents
6617   // to floating point based booleans. This is because we can't tell whether we
6618   // have an integer-based boolean or a floating-point-based boolean unless we
6619   // can find the SETCC that produced it and inspect its operands. This is
6620   // fairly easy if C is the SETCC node, but it can potentially be
6621   // undiscoverable (or not reasonably discoverable). For example, it could be
6622   // in another basic block or it could require searching a complicated
6623   // expression.
6624   if (CondVT.isInteger() &&
6625       TLI.getBooleanContents(false, true) ==
6626           TargetLowering::ZeroOrOneBooleanContent &&
6627       TLI.getBooleanContents(false, false) ==
6628           TargetLowering::ZeroOrOneBooleanContent &&
6629       C1->isNullValue() && C2->isOne()) {
6630     SDValue NotCond =
6631         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6632     if (VT.bitsEq(CondVT))
6633       return NotCond;
6634     return DAG.getZExtOrTrunc(NotCond, DL, VT);
6635   }
6636 
6637   return SDValue();
6638 }
6639 
6640 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6641   SDValue N0 = N->getOperand(0);
6642   SDValue N1 = N->getOperand(1);
6643   SDValue N2 = N->getOperand(2);
6644   EVT VT = N->getValueType(0);
6645   EVT VT0 = N0.getValueType();
6646   SDLoc DL(N);
6647 
6648   // fold (select C, X, X) -> X
6649   if (N1 == N2)
6650     return N1;
6651 
6652   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6653     // fold (select true, X, Y) -> X
6654     // fold (select false, X, Y) -> Y
6655     return !N0C->isNullValue() ? N1 : N2;
6656   }
6657 
6658   // fold (select X, X, Y) -> (or X, Y)
6659   // fold (select X, 1, Y) -> (or C, Y)
6660   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6661     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6662 
6663   if (SDValue V = foldSelectOfConstants(N))
6664     return V;
6665 
6666   // fold (select C, 0, X) -> (and (not C), X)
6667   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6668     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6669     AddToWorklist(NOTNode.getNode());
6670     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6671   }
6672   // fold (select C, X, 1) -> (or (not C), X)
6673   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6674     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6675     AddToWorklist(NOTNode.getNode());
6676     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6677   }
6678   // fold (select X, Y, X) -> (and X, Y)
6679   // fold (select X, Y, 0) -> (and X, Y)
6680   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6681     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6682 
6683   // If we can fold this based on the true/false value, do so.
6684   if (SimplifySelectOps(N, N1, N2))
6685     return SDValue(N, 0); // Don't revisit N.
6686 
6687   if (VT0 == MVT::i1) {
6688     // The code in this block deals with the following 2 equivalences:
6689     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6690     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6691     // The target can specify its preferred form with the
6692     // shouldNormalizeToSelectSequence() callback. However we always transform
6693     // to the right anyway if we find the inner select exists in the DAG anyway
6694     // and we always transform to the left side if we know that we can further
6695     // optimize the combination of the conditions.
6696     bool normalizeToSequence =
6697         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6698     // select (and Cond0, Cond1), X, Y
6699     //   -> select Cond0, (select Cond1, X, Y), Y
6700     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6701       SDValue Cond0 = N0->getOperand(0);
6702       SDValue Cond1 = N0->getOperand(1);
6703       SDValue InnerSelect =
6704           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6705       if (normalizeToSequence || !InnerSelect.use_empty())
6706         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6707                            InnerSelect, N2);
6708     }
6709     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6710     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6711       SDValue Cond0 = N0->getOperand(0);
6712       SDValue Cond1 = N0->getOperand(1);
6713       SDValue InnerSelect =
6714           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6715       if (normalizeToSequence || !InnerSelect.use_empty())
6716         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6717                            InnerSelect);
6718     }
6719 
6720     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6721     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6722       SDValue N1_0 = N1->getOperand(0);
6723       SDValue N1_1 = N1->getOperand(1);
6724       SDValue N1_2 = N1->getOperand(2);
6725       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6726         // Create the actual and node if we can generate good code for it.
6727         if (!normalizeToSequence) {
6728           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6729           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6730         }
6731         // Otherwise see if we can optimize the "and" to a better pattern.
6732         if (SDValue Combined = visitANDLike(N0, N1_0, N))
6733           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6734                              N2);
6735       }
6736     }
6737     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6738     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6739       SDValue N2_0 = N2->getOperand(0);
6740       SDValue N2_1 = N2->getOperand(1);
6741       SDValue N2_2 = N2->getOperand(2);
6742       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6743         // Create the actual or node if we can generate good code for it.
6744         if (!normalizeToSequence) {
6745           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6746           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6747         }
6748         // Otherwise see if we can optimize to a better pattern.
6749         if (SDValue Combined = visitORLike(N0, N2_0, N))
6750           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6751                              N2_2);
6752       }
6753     }
6754   }
6755 
6756   // select (xor Cond, 1), X, Y -> select Cond, Y, X
6757   if (VT0 == MVT::i1) {
6758     if (N0->getOpcode() == ISD::XOR) {
6759       if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6760         SDValue Cond0 = N0->getOperand(0);
6761         if (C->isOne())
6762           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6763       }
6764     }
6765   }
6766 
6767   // fold selects based on a setcc into other things, such as min/max/abs
6768   if (N0.getOpcode() == ISD::SETCC) {
6769     // select x, y (fcmp lt x, y) -> fminnum x, y
6770     // select x, y (fcmp gt x, y) -> fmaxnum x, y
6771     //
6772     // This is OK if we don't care about what happens if either operand is a
6773     // NaN.
6774     //
6775 
6776     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6777     // no signed zeros as well as no nans.
6778     const TargetOptions &Options = DAG.getTarget().Options;
6779     if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6780         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6781       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6782 
6783       if (SDValue FMinMax = combineMinNumMaxNum(
6784               DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6785         return FMinMax;
6786     }
6787 
6788     if ((!LegalOperations &&
6789          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6790         TLI.isOperationLegal(ISD::SELECT_CC, VT))
6791       return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6792                          N0.getOperand(1), N1, N2, N0.getOperand(2));
6793     return SimplifySelect(DL, N0, N1, N2);
6794   }
6795 
6796   return SDValue();
6797 }
6798 
6799 static
6800 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6801   SDLoc DL(N);
6802   EVT LoVT, HiVT;
6803   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6804 
6805   // Split the inputs.
6806   SDValue Lo, Hi, LL, LH, RL, RH;
6807   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6808   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6809 
6810   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6811   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6812 
6813   return std::make_pair(Lo, Hi);
6814 }
6815 
6816 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6817 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6818 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6819   SDLoc DL(N);
6820   SDValue Cond = N->getOperand(0);
6821   SDValue LHS = N->getOperand(1);
6822   SDValue RHS = N->getOperand(2);
6823   EVT VT = N->getValueType(0);
6824   int NumElems = VT.getVectorNumElements();
6825   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6826          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6827          Cond.getOpcode() == ISD::BUILD_VECTOR);
6828 
6829   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6830   // binary ones here.
6831   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6832     return SDValue();
6833 
6834   // We're sure we have an even number of elements due to the
6835   // concat_vectors we have as arguments to vselect.
6836   // Skip BV elements until we find one that's not an UNDEF
6837   // After we find an UNDEF element, keep looping until we get to half the
6838   // length of the BV and see if all the non-undef nodes are the same.
6839   ConstantSDNode *BottomHalf = nullptr;
6840   for (int i = 0; i < NumElems / 2; ++i) {
6841     if (Cond->getOperand(i)->isUndef())
6842       continue;
6843 
6844     if (BottomHalf == nullptr)
6845       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6846     else if (Cond->getOperand(i).getNode() != BottomHalf)
6847       return SDValue();
6848   }
6849 
6850   // Do the same for the second half of the BuildVector
6851   ConstantSDNode *TopHalf = nullptr;
6852   for (int i = NumElems / 2; i < NumElems; ++i) {
6853     if (Cond->getOperand(i)->isUndef())
6854       continue;
6855 
6856     if (TopHalf == nullptr)
6857       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6858     else if (Cond->getOperand(i).getNode() != TopHalf)
6859       return SDValue();
6860   }
6861 
6862   assert(TopHalf && BottomHalf &&
6863          "One half of the selector was all UNDEFs and the other was all the "
6864          "same value. This should have been addressed before this function.");
6865   return DAG.getNode(
6866       ISD::CONCAT_VECTORS, DL, VT,
6867       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6868       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6869 }
6870 
6871 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6872   if (Level >= AfterLegalizeTypes)
6873     return SDValue();
6874 
6875   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6876   SDValue Mask = MSC->getMask();
6877   SDValue Data  = MSC->getValue();
6878   SDLoc DL(N);
6879 
6880   // If the MSCATTER data type requires splitting and the mask is provided by a
6881   // SETCC, then split both nodes and its operands before legalization. This
6882   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6883   // and enables future optimizations (e.g. min/max pattern matching on X86).
6884   if (Mask.getOpcode() != ISD::SETCC)
6885     return SDValue();
6886 
6887   // Check if any splitting is required.
6888   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6889       TargetLowering::TypeSplitVector)
6890     return SDValue();
6891   SDValue MaskLo, MaskHi, Lo, Hi;
6892   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6893 
6894   EVT LoVT, HiVT;
6895   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6896 
6897   SDValue Chain = MSC->getChain();
6898 
6899   EVT MemoryVT = MSC->getMemoryVT();
6900   unsigned Alignment = MSC->getOriginalAlignment();
6901 
6902   EVT LoMemVT, HiMemVT;
6903   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6904 
6905   SDValue DataLo, DataHi;
6906   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6907 
6908   SDValue Scale = MSC->getScale();
6909   SDValue BasePtr = MSC->getBasePtr();
6910   SDValue IndexLo, IndexHi;
6911   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6912 
6913   MachineMemOperand *MMO = DAG.getMachineFunction().
6914     getMachineMemOperand(MSC->getPointerInfo(),
6915                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6916                           Alignment, MSC->getAAInfo(), MSC->getRanges());
6917 
6918   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale };
6919   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6920                             DL, OpsLo, MMO);
6921 
6922   SDValue OpsHi[] = { Chain, DataHi, MaskHi, BasePtr, IndexHi, Scale };
6923   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6924                             DL, OpsHi, MMO);
6925 
6926   AddToWorklist(Lo.getNode());
6927   AddToWorklist(Hi.getNode());
6928 
6929   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6930 }
6931 
6932 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6933   if (Level >= AfterLegalizeTypes)
6934     return SDValue();
6935 
6936   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6937   SDValue Mask = MST->getMask();
6938   SDValue Data  = MST->getValue();
6939   EVT VT = Data.getValueType();
6940   SDLoc DL(N);
6941 
6942   // If the MSTORE data type requires splitting and the mask is provided by a
6943   // SETCC, then split both nodes and its operands before legalization. This
6944   // prevents the type legalizer from unrolling SETCC into scalar comparisons
6945   // and enables future optimizations (e.g. min/max pattern matching on X86).
6946   if (Mask.getOpcode() == ISD::SETCC) {
6947     // Check if any splitting is required.
6948     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6949         TargetLowering::TypeSplitVector)
6950       return SDValue();
6951 
6952     SDValue MaskLo, MaskHi, Lo, Hi;
6953     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6954 
6955     SDValue Chain = MST->getChain();
6956     SDValue Ptr   = MST->getBasePtr();
6957 
6958     EVT MemoryVT = MST->getMemoryVT();
6959     unsigned Alignment = MST->getOriginalAlignment();
6960 
6961     // if Alignment is equal to the vector size,
6962     // take the half of it for the second part
6963     unsigned SecondHalfAlignment =
6964       (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6965 
6966     EVT LoMemVT, HiMemVT;
6967     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6968 
6969     SDValue DataLo, DataHi;
6970     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6971 
6972     MachineMemOperand *MMO = DAG.getMachineFunction().
6973       getMachineMemOperand(MST->getPointerInfo(),
6974                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
6975                            Alignment, MST->getAAInfo(), MST->getRanges());
6976 
6977     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6978                             MST->isTruncatingStore(),
6979                             MST->isCompressingStore());
6980 
6981     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6982                                      MST->isCompressingStore());
6983     unsigned HiOffset = LoMemVT.getStoreSize();
6984 
6985     MMO = DAG.getMachineFunction().getMachineMemOperand(
6986         MST->getPointerInfo().getWithOffset(HiOffset),
6987         MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment,
6988         MST->getAAInfo(), MST->getRanges());
6989 
6990     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6991                             MST->isTruncatingStore(),
6992                             MST->isCompressingStore());
6993 
6994     AddToWorklist(Lo.getNode());
6995     AddToWorklist(Hi.getNode());
6996 
6997     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6998   }
6999   return SDValue();
7000 }
7001 
7002 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
7003   if (Level >= AfterLegalizeTypes)
7004     return SDValue();
7005 
7006   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
7007   SDValue Mask = MGT->getMask();
7008   SDLoc DL(N);
7009 
7010   // If the MGATHER result requires splitting and the mask is provided by a
7011   // SETCC, then split both nodes and its operands before legalization. This
7012   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7013   // and enables future optimizations (e.g. min/max pattern matching on X86).
7014 
7015   if (Mask.getOpcode() != ISD::SETCC)
7016     return SDValue();
7017 
7018   EVT VT = N->getValueType(0);
7019 
7020   // Check if any splitting is required.
7021   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
7022       TargetLowering::TypeSplitVector)
7023     return SDValue();
7024 
7025   SDValue MaskLo, MaskHi, Lo, Hi;
7026   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7027 
7028   SDValue Src0 = MGT->getValue();
7029   SDValue Src0Lo, Src0Hi;
7030   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
7031 
7032   EVT LoVT, HiVT;
7033   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
7034 
7035   SDValue Chain = MGT->getChain();
7036   EVT MemoryVT = MGT->getMemoryVT();
7037   unsigned Alignment = MGT->getOriginalAlignment();
7038 
7039   EVT LoMemVT, HiMemVT;
7040   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7041 
7042   SDValue Scale = MGT->getScale();
7043   SDValue BasePtr = MGT->getBasePtr();
7044   SDValue Index = MGT->getIndex();
7045   SDValue IndexLo, IndexHi;
7046   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
7047 
7048   MachineMemOperand *MMO = DAG.getMachineFunction().
7049     getMachineMemOperand(MGT->getPointerInfo(),
7050                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
7051                           Alignment, MGT->getAAInfo(), MGT->getRanges());
7052 
7053   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo, Scale };
7054   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
7055                            MMO);
7056 
7057   SDValue OpsHi[] = { Chain, Src0Hi, MaskHi, BasePtr, IndexHi, Scale };
7058   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
7059                            MMO);
7060 
7061   AddToWorklist(Lo.getNode());
7062   AddToWorklist(Hi.getNode());
7063 
7064   // Build a factor node to remember that this load is independent of the
7065   // other one.
7066   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7067                       Hi.getValue(1));
7068 
7069   // Legalized the chain result - switch anything that used the old chain to
7070   // use the new one.
7071   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
7072 
7073   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7074 
7075   SDValue RetOps[] = { GatherRes, Chain };
7076   return DAG.getMergeValues(RetOps, DL);
7077 }
7078 
7079 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
7080   if (Level >= AfterLegalizeTypes)
7081     return SDValue();
7082 
7083   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
7084   SDValue Mask = MLD->getMask();
7085   SDLoc DL(N);
7086 
7087   // If the MLOAD result requires splitting and the mask is provided by a
7088   // SETCC, then split both nodes and its operands before legalization. This
7089   // prevents the type legalizer from unrolling SETCC into scalar comparisons
7090   // and enables future optimizations (e.g. min/max pattern matching on X86).
7091   if (Mask.getOpcode() == ISD::SETCC) {
7092     EVT VT = N->getValueType(0);
7093 
7094     // Check if any splitting is required.
7095     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
7096         TargetLowering::TypeSplitVector)
7097       return SDValue();
7098 
7099     SDValue MaskLo, MaskHi, Lo, Hi;
7100     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
7101 
7102     SDValue Src0 = MLD->getSrc0();
7103     SDValue Src0Lo, Src0Hi;
7104     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
7105 
7106     EVT LoVT, HiVT;
7107     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
7108 
7109     SDValue Chain = MLD->getChain();
7110     SDValue Ptr   = MLD->getBasePtr();
7111     EVT MemoryVT = MLD->getMemoryVT();
7112     unsigned Alignment = MLD->getOriginalAlignment();
7113 
7114     // if Alignment is equal to the vector size,
7115     // take the half of it for the second part
7116     unsigned SecondHalfAlignment =
7117       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
7118          Alignment/2 : Alignment;
7119 
7120     EVT LoMemVT, HiMemVT;
7121     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
7122 
7123     MachineMemOperand *MMO = DAG.getMachineFunction().
7124     getMachineMemOperand(MLD->getPointerInfo(),
7125                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
7126                          Alignment, MLD->getAAInfo(), MLD->getRanges());
7127 
7128     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
7129                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7130 
7131     Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
7132                                      MLD->isExpandingLoad());
7133     unsigned HiOffset = LoMemVT.getStoreSize();
7134 
7135     MMO = DAG.getMachineFunction().getMachineMemOperand(
7136         MLD->getPointerInfo().getWithOffset(HiOffset),
7137         MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment,
7138         MLD->getAAInfo(), MLD->getRanges());
7139 
7140     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
7141                            ISD::NON_EXTLOAD, MLD->isExpandingLoad());
7142 
7143     AddToWorklist(Lo.getNode());
7144     AddToWorklist(Hi.getNode());
7145 
7146     // Build a factor node to remember that this load is independent of the
7147     // other one.
7148     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
7149                         Hi.getValue(1));
7150 
7151     // Legalized the chain result - switch anything that used the old chain to
7152     // use the new one.
7153     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
7154 
7155     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
7156 
7157     SDValue RetOps[] = { LoadRes, Chain };
7158     return DAG.getMergeValues(RetOps, DL);
7159   }
7160   return SDValue();
7161 }
7162 
7163 /// A vector select of 2 constant vectors can be simplified to math/logic to
7164 /// avoid a variable select instruction and possibly avoid constant loads.
7165 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
7166   SDValue Cond = N->getOperand(0);
7167   SDValue N1 = N->getOperand(1);
7168   SDValue N2 = N->getOperand(2);
7169   EVT VT = N->getValueType(0);
7170   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
7171       !TLI.convertSelectOfConstantsToMath(VT) ||
7172       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
7173       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
7174     return SDValue();
7175 
7176   // Check if we can use the condition value to increment/decrement a single
7177   // constant value. This simplifies a select to an add and removes a constant
7178   // load/materialization from the general case.
7179   bool AllAddOne = true;
7180   bool AllSubOne = true;
7181   unsigned Elts = VT.getVectorNumElements();
7182   for (unsigned i = 0; i != Elts; ++i) {
7183     SDValue N1Elt = N1.getOperand(i);
7184     SDValue N2Elt = N2.getOperand(i);
7185     if (N1Elt.isUndef() || N2Elt.isUndef())
7186       continue;
7187 
7188     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
7189     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
7190     if (C1 != C2 + 1)
7191       AllAddOne = false;
7192     if (C1 != C2 - 1)
7193       AllSubOne = false;
7194   }
7195 
7196   // Further simplifications for the extra-special cases where the constants are
7197   // all 0 or all -1 should be implemented as folds of these patterns.
7198   SDLoc DL(N);
7199   if (AllAddOne || AllSubOne) {
7200     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
7201     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
7202     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
7203     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
7204     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
7205   }
7206 
7207   // The general case for select-of-constants:
7208   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
7209   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
7210   // leave that to a machine-specific pass.
7211   return SDValue();
7212 }
7213 
7214 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
7215   SDValue N0 = N->getOperand(0);
7216   SDValue N1 = N->getOperand(1);
7217   SDValue N2 = N->getOperand(2);
7218   SDLoc DL(N);
7219 
7220   // fold (vselect C, X, X) -> X
7221   if (N1 == N2)
7222     return N1;
7223 
7224   // Canonicalize integer abs.
7225   // vselect (setg[te] X,  0),  X, -X ->
7226   // vselect (setgt    X, -1),  X, -X ->
7227   // vselect (setl[te] X,  0), -X,  X ->
7228   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7229   if (N0.getOpcode() == ISD::SETCC) {
7230     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
7231     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7232     bool isAbs = false;
7233     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
7234 
7235     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7236          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
7237         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
7238       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
7239     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
7240              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
7241       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
7242 
7243     if (isAbs) {
7244       EVT VT = LHS.getValueType();
7245       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
7246         return DAG.getNode(ISD::ABS, DL, VT, LHS);
7247 
7248       SDValue Shift = DAG.getNode(
7249           ISD::SRA, DL, VT, LHS,
7250           DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
7251       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
7252       AddToWorklist(Shift.getNode());
7253       AddToWorklist(Add.getNode());
7254       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
7255     }
7256   }
7257 
7258   if (SimplifySelectOps(N, N1, N2))
7259     return SDValue(N, 0);  // Don't revisit N.
7260 
7261   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
7262   if (ISD::isBuildVectorAllOnes(N0.getNode()))
7263     return N1;
7264   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
7265   if (ISD::isBuildVectorAllZeros(N0.getNode()))
7266     return N2;
7267 
7268   // The ConvertSelectToConcatVector function is assuming both the above
7269   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
7270   // and addressed.
7271   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
7272       N2.getOpcode() == ISD::CONCAT_VECTORS &&
7273       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
7274     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
7275       return CV;
7276   }
7277 
7278   if (SDValue V = foldVSelectOfConstants(N))
7279     return V;
7280 
7281   return SDValue();
7282 }
7283 
7284 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
7285   SDValue N0 = N->getOperand(0);
7286   SDValue N1 = N->getOperand(1);
7287   SDValue N2 = N->getOperand(2);
7288   SDValue N3 = N->getOperand(3);
7289   SDValue N4 = N->getOperand(4);
7290   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
7291 
7292   // fold select_cc lhs, rhs, x, x, cc -> x
7293   if (N2 == N3)
7294     return N2;
7295 
7296   // Determine if the condition we're dealing with is constant
7297   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
7298                                   CC, SDLoc(N), false)) {
7299     AddToWorklist(SCC.getNode());
7300 
7301     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
7302       if (!SCCC->isNullValue())
7303         return N2;    // cond always true -> true val
7304       else
7305         return N3;    // cond always false -> false val
7306     } else if (SCC->isUndef()) {
7307       // When the condition is UNDEF, just return the first operand. This is
7308       // coherent the DAG creation, no setcc node is created in this case
7309       return N2;
7310     } else if (SCC.getOpcode() == ISD::SETCC) {
7311       // Fold to a simpler select_cc
7312       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
7313                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
7314                          SCC.getOperand(2));
7315     }
7316   }
7317 
7318   // If we can fold this based on the true/false value, do so.
7319   if (SimplifySelectOps(N, N2, N3))
7320     return SDValue(N, 0);  // Don't revisit N.
7321 
7322   // fold select_cc into other things, such as min/max/abs
7323   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
7324 }
7325 
7326 SDValue DAGCombiner::visitSETCC(SDNode *N) {
7327   // setcc is very commonly used as an argument to brcond. This pattern
7328   // also lend itself to numerous combines and, as a result, it is desired
7329   // we keep the argument to a brcond as a setcc as much as possible.
7330   bool PreferSetCC =
7331       N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
7332 
7333   SDValue Combined = SimplifySetCC(
7334       N->getValueType(0), N->getOperand(0), N->getOperand(1),
7335       cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC);
7336 
7337   if (!Combined)
7338     return SDValue();
7339 
7340   // If we prefer to have a setcc, and we don't, we'll try our best to
7341   // recreate one using rebuildSetCC.
7342   if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
7343     SDValue NewSetCC = rebuildSetCC(Combined);
7344 
7345     // We don't have anything interesting to combine to.
7346     if (NewSetCC.getNode() == N)
7347       return SDValue();
7348 
7349     if (NewSetCC)
7350       return NewSetCC;
7351   }
7352 
7353   return Combined;
7354 }
7355 
7356 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
7357   SDValue LHS = N->getOperand(0);
7358   SDValue RHS = N->getOperand(1);
7359   SDValue Carry = N->getOperand(2);
7360   SDValue Cond = N->getOperand(3);
7361 
7362   // If Carry is false, fold to a regular SETCC.
7363   if (Carry.getOpcode() == ISD::CARRY_FALSE)
7364     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7365 
7366   return SDValue();
7367 }
7368 
7369 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
7370   SDValue LHS = N->getOperand(0);
7371   SDValue RHS = N->getOperand(1);
7372   SDValue Carry = N->getOperand(2);
7373   SDValue Cond = N->getOperand(3);
7374 
7375   // If Carry is false, fold to a regular SETCC.
7376   if (isNullConstant(Carry))
7377     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
7378 
7379   return SDValue();
7380 }
7381 
7382 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
7383 /// a build_vector of constants.
7384 /// This function is called by the DAGCombiner when visiting sext/zext/aext
7385 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
7386 /// Vector extends are not folded if operations are legal; this is to
7387 /// avoid introducing illegal build_vector dag nodes.
7388 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
7389                                          SelectionDAG &DAG, bool LegalTypes,
7390                                          bool LegalOperations) {
7391   unsigned Opcode = N->getOpcode();
7392   SDValue N0 = N->getOperand(0);
7393   EVT VT = N->getValueType(0);
7394 
7395   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
7396          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7397          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
7398          && "Expected EXTEND dag node in input!");
7399 
7400   // fold (sext c1) -> c1
7401   // fold (zext c1) -> c1
7402   // fold (aext c1) -> c1
7403   if (isa<ConstantSDNode>(N0))
7404     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
7405 
7406   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
7407   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
7408   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
7409   EVT SVT = VT.getScalarType();
7410   if (!(VT.isVector() &&
7411       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
7412       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
7413     return nullptr;
7414 
7415   // We can fold this node into a build_vector.
7416   unsigned VTBits = SVT.getSizeInBits();
7417   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
7418   SmallVector<SDValue, 8> Elts;
7419   unsigned NumElts = VT.getVectorNumElements();
7420   SDLoc DL(N);
7421 
7422   for (unsigned i=0; i != NumElts; ++i) {
7423     SDValue Op = N0->getOperand(i);
7424     if (Op->isUndef()) {
7425       Elts.push_back(DAG.getUNDEF(SVT));
7426       continue;
7427     }
7428 
7429     SDLoc DL(Op);
7430     // Get the constant value and if needed trunc it to the size of the type.
7431     // Nodes like build_vector might have constants wider than the scalar type.
7432     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
7433     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
7434       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
7435     else
7436       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
7437   }
7438 
7439   return DAG.getBuildVector(VT, DL, Elts).getNode();
7440 }
7441 
7442 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
7443 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
7444 // transformation. Returns true if extension are possible and the above
7445 // mentioned transformation is profitable.
7446 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
7447                                     unsigned ExtOpc,
7448                                     SmallVectorImpl<SDNode *> &ExtendNodes,
7449                                     const TargetLowering &TLI) {
7450   bool HasCopyToRegUses = false;
7451   bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
7452   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
7453                             UE = N0.getNode()->use_end();
7454        UI != UE; ++UI) {
7455     SDNode *User = *UI;
7456     if (User == N)
7457       continue;
7458     if (UI.getUse().getResNo() != N0.getResNo())
7459       continue;
7460     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
7461     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
7462       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
7463       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
7464         // Sign bits will be lost after a zext.
7465         return false;
7466       bool Add = false;
7467       for (unsigned i = 0; i != 2; ++i) {
7468         SDValue UseOp = User->getOperand(i);
7469         if (UseOp == N0)
7470           continue;
7471         if (!isa<ConstantSDNode>(UseOp))
7472           return false;
7473         Add = true;
7474       }
7475       if (Add)
7476         ExtendNodes.push_back(User);
7477       continue;
7478     }
7479     // If truncates aren't free and there are users we can't
7480     // extend, it isn't worthwhile.
7481     if (!isTruncFree)
7482       return false;
7483     // Remember if this value is live-out.
7484     if (User->getOpcode() == ISD::CopyToReg)
7485       HasCopyToRegUses = true;
7486   }
7487 
7488   if (HasCopyToRegUses) {
7489     bool BothLiveOut = false;
7490     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7491          UI != UE; ++UI) {
7492       SDUse &Use = UI.getUse();
7493       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
7494         BothLiveOut = true;
7495         break;
7496       }
7497     }
7498     if (BothLiveOut)
7499       // Both unextended and extended values are live out. There had better be
7500       // a good reason for the transformation.
7501       return ExtendNodes.size();
7502   }
7503   return true;
7504 }
7505 
7506 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
7507                                   SDValue OrigLoad, SDValue ExtLoad,
7508                                   ISD::NodeType ExtType) {
7509   // Extend SetCC uses if necessary.
7510   SDLoc DL(ExtLoad);
7511   for (SDNode *SetCC : SetCCs) {
7512     SmallVector<SDValue, 4> Ops;
7513 
7514     for (unsigned j = 0; j != 2; ++j) {
7515       SDValue SOp = SetCC->getOperand(j);
7516       if (SOp == OrigLoad)
7517         Ops.push_back(ExtLoad);
7518       else
7519         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
7520     }
7521 
7522     Ops.push_back(SetCC->getOperand(2));
7523     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7524   }
7525 }
7526 
7527 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
7528 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
7529   SDValue N0 = N->getOperand(0);
7530   EVT DstVT = N->getValueType(0);
7531   EVT SrcVT = N0.getValueType();
7532 
7533   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
7534           N->getOpcode() == ISD::ZERO_EXTEND) &&
7535          "Unexpected node type (not an extend)!");
7536 
7537   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
7538   // For example, on a target with legal v4i32, but illegal v8i32, turn:
7539   //   (v8i32 (sext (v8i16 (load x))))
7540   // into:
7541   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
7542   //                          (v4i32 (sextload (x + 16)))))
7543   // Where uses of the original load, i.e.:
7544   //   (v8i16 (load x))
7545   // are replaced with:
7546   //   (v8i16 (truncate
7547   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
7548   //                            (v4i32 (sextload (x + 16)))))))
7549   //
7550   // This combine is only applicable to illegal, but splittable, vectors.
7551   // All legal types, and illegal non-vector types, are handled elsewhere.
7552   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
7553   //
7554   if (N0->getOpcode() != ISD::LOAD)
7555     return SDValue();
7556 
7557   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7558 
7559   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
7560       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
7561       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
7562     return SDValue();
7563 
7564   SmallVector<SDNode *, 4> SetCCs;
7565   if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
7566     return SDValue();
7567 
7568   ISD::LoadExtType ExtType =
7569       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
7570 
7571   // Try to split the vector types to get down to legal types.
7572   EVT SplitSrcVT = SrcVT;
7573   EVT SplitDstVT = DstVT;
7574   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
7575          SplitSrcVT.getVectorNumElements() > 1) {
7576     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
7577     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
7578   }
7579 
7580   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7581     return SDValue();
7582 
7583   SDLoc DL(N);
7584   const unsigned NumSplits =
7585       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7586   const unsigned Stride = SplitSrcVT.getStoreSize();
7587   SmallVector<SDValue, 4> Loads;
7588   SmallVector<SDValue, 4> Chains;
7589 
7590   SDValue BasePtr = LN0->getBasePtr();
7591   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7592     const unsigned Offset = Idx * Stride;
7593     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7594 
7595     SDValue SplitLoad = DAG.getExtLoad(
7596         ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
7597         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7598         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7599 
7600     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7601                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7602 
7603     Loads.push_back(SplitLoad.getValue(0));
7604     Chains.push_back(SplitLoad.getValue(1));
7605   }
7606 
7607   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7608   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7609 
7610   // Simplify TF.
7611   AddToWorklist(NewChain.getNode());
7612 
7613   CombineTo(N, NewValue);
7614 
7615   // Replace uses of the original load (before extension)
7616   // with a truncate of the concatenated sextloaded vectors.
7617   SDValue Trunc =
7618       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7619   ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
7620   CombineTo(N0.getNode(), Trunc, NewChain);
7621   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7622 }
7623 
7624 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
7625 //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
7626 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
7627   assert(N->getOpcode() == ISD::ZERO_EXTEND);
7628   EVT VT = N->getValueType(0);
7629 
7630   // and/or/xor
7631   SDValue N0 = N->getOperand(0);
7632   if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7633         N0.getOpcode() == ISD::XOR) ||
7634       N0.getOperand(1).getOpcode() != ISD::Constant ||
7635       (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
7636     return SDValue();
7637 
7638   // shl/shr
7639   SDValue N1 = N0->getOperand(0);
7640   if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
7641       N1.getOperand(1).getOpcode() != ISD::Constant ||
7642       (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
7643     return SDValue();
7644 
7645   // load
7646   if (!isa<LoadSDNode>(N1.getOperand(0)))
7647     return SDValue();
7648   LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
7649   EVT MemVT = Load->getMemoryVT();
7650   if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
7651       Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
7652     return SDValue();
7653 
7654 
7655   // If the shift op is SHL, the logic op must be AND, otherwise the result
7656   // will be wrong.
7657   if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
7658     return SDValue();
7659 
7660   if (!N0.hasOneUse() || !N1.hasOneUse())
7661     return SDValue();
7662 
7663   SmallVector<SDNode*, 4> SetCCs;
7664   if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
7665                                ISD::ZERO_EXTEND, SetCCs, TLI))
7666     return SDValue();
7667 
7668   // Actually do the transformation.
7669   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
7670                                    Load->getChain(), Load->getBasePtr(),
7671                                    Load->getMemoryVT(), Load->getMemOperand());
7672 
7673   SDLoc DL1(N1);
7674   SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
7675                               N1.getOperand(1));
7676 
7677   APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7678   Mask = Mask.zext(VT.getSizeInBits());
7679   SDLoc DL0(N0);
7680   SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
7681                             DAG.getConstant(Mask, DL0, VT));
7682 
7683   ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
7684   CombineTo(N, And);
7685   if (SDValue(Load, 0).hasOneUse()) {
7686     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
7687   } else {
7688     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
7689                                 Load->getValueType(0), ExtLoad);
7690     CombineTo(Load, Trunc, ExtLoad.getValue(1));
7691   }
7692   return SDValue(N,0); // Return N so it doesn't get rechecked!
7693 }
7694 
7695 /// If we're narrowing or widening the result of a vector select and the final
7696 /// size is the same size as a setcc (compare) feeding the select, then try to
7697 /// apply the cast operation to the select's operands because matching vector
7698 /// sizes for a select condition and other operands should be more efficient.
7699 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7700   unsigned CastOpcode = Cast->getOpcode();
7701   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7702           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7703           CastOpcode == ISD::FP_ROUND) &&
7704          "Unexpected opcode for vector select narrowing/widening");
7705 
7706   // We only do this transform before legal ops because the pattern may be
7707   // obfuscated by target-specific operations after legalization. Do not create
7708   // an illegal select op, however, because that may be difficult to lower.
7709   EVT VT = Cast->getValueType(0);
7710   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7711     return SDValue();
7712 
7713   SDValue VSel = Cast->getOperand(0);
7714   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7715       VSel.getOperand(0).getOpcode() != ISD::SETCC)
7716     return SDValue();
7717 
7718   // Does the setcc have the same vector size as the casted select?
7719   SDValue SetCC = VSel.getOperand(0);
7720   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7721   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7722     return SDValue();
7723 
7724   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7725   SDValue A = VSel.getOperand(1);
7726   SDValue B = VSel.getOperand(2);
7727   SDValue CastA, CastB;
7728   SDLoc DL(Cast);
7729   if (CastOpcode == ISD::FP_ROUND) {
7730     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7731     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7732     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7733   } else {
7734     CastA = DAG.getNode(CastOpcode, DL, VT, A);
7735     CastB = DAG.getNode(CastOpcode, DL, VT, B);
7736   }
7737   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7738 }
7739 
7740 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
7741 // fold ([s|z]ext (     extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
7742 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
7743                                      const TargetLowering &TLI, EVT VT,
7744                                      bool LegalOperations, SDNode *N,
7745                                      SDValue N0, ISD::LoadExtType ExtLoadType) {
7746   SDNode *N0Node = N0.getNode();
7747   bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
7748                                                    : ISD::isZEXTLoad(N0Node);
7749   if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
7750       !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
7751     return {};
7752 
7753   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7754   EVT MemVT = LN0->getMemoryVT();
7755   if ((LegalOperations || LN0->isVolatile()) &&
7756       !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
7757     return {};
7758 
7759   SDValue ExtLoad =
7760       DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
7761                      LN0->getBasePtr(), MemVT, LN0->getMemOperand());
7762   Combiner.CombineTo(N, ExtLoad);
7763   DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7764   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7765 }
7766 
7767 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
7768 // Only generate vector extloads when 1) they're legal, and 2) they are
7769 // deemed desirable by the target.
7770 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
7771                                   const TargetLowering &TLI, EVT VT,
7772                                   bool LegalOperations, SDNode *N, SDValue N0,
7773                                   ISD::LoadExtType ExtLoadType,
7774                                   ISD::NodeType ExtOpc) {
7775   if (!ISD::isNON_EXTLoad(N0.getNode()) ||
7776       !ISD::isUNINDEXEDLoad(N0.getNode()) ||
7777       ((LegalOperations || VT.isVector() ||
7778         cast<LoadSDNode>(N0)->isVolatile()) &&
7779        !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
7780     return {};
7781 
7782   bool DoXform = true;
7783   SmallVector<SDNode *, 4> SetCCs;
7784   if (!N0.hasOneUse())
7785     DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
7786   if (VT.isVector())
7787     DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7788   if (!DoXform)
7789     return {};
7790 
7791   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7792   SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
7793                                    LN0->getBasePtr(), N0.getValueType(),
7794                                    LN0->getMemOperand());
7795   Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
7796   // If the load value is used only by N, replace it via CombineTo N.
7797   bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7798   Combiner.CombineTo(N, ExtLoad);
7799   if (NoReplaceTrunc) {
7800     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7801   } else {
7802     SDValue Trunc =
7803         DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
7804     Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7805   }
7806   return SDValue(N, 0); // Return N so it doesn't get rechecked!
7807 }
7808 
7809 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7810   SDValue N0 = N->getOperand(0);
7811   EVT VT = N->getValueType(0);
7812   SDLoc DL(N);
7813 
7814   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7815                                               LegalOperations))
7816     return SDValue(Res, 0);
7817 
7818   // fold (sext (sext x)) -> (sext x)
7819   // fold (sext (aext x)) -> (sext x)
7820   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7821     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7822 
7823   if (N0.getOpcode() == ISD::TRUNCATE) {
7824     // fold (sext (truncate (load x))) -> (sext (smaller load x))
7825     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7826     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7827       SDNode *oye = N0.getOperand(0).getNode();
7828       if (NarrowLoad.getNode() != N0.getNode()) {
7829         CombineTo(N0.getNode(), NarrowLoad);
7830         // CombineTo deleted the truncate, if needed, but not what's under it.
7831         AddToWorklist(oye);
7832       }
7833       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7834     }
7835 
7836     // See if the value being truncated is already sign extended.  If so, just
7837     // eliminate the trunc/sext pair.
7838     SDValue Op = N0.getOperand(0);
7839     unsigned OpBits   = Op.getScalarValueSizeInBits();
7840     unsigned MidBits  = N0.getScalarValueSizeInBits();
7841     unsigned DestBits = VT.getScalarSizeInBits();
7842     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7843 
7844     if (OpBits == DestBits) {
7845       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7846       // bits, it is already ready.
7847       if (NumSignBits > DestBits-MidBits)
7848         return Op;
7849     } else if (OpBits < DestBits) {
7850       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7851       // bits, just sext from i32.
7852       if (NumSignBits > OpBits-MidBits)
7853         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7854     } else {
7855       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7856       // bits, just truncate to i32.
7857       if (NumSignBits > OpBits-MidBits)
7858         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7859     }
7860 
7861     // fold (sext (truncate x)) -> (sextinreg x).
7862     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7863                                                  N0.getValueType())) {
7864       if (OpBits < DestBits)
7865         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7866       else if (OpBits > DestBits)
7867         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7868       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7869                          DAG.getValueType(N0.getValueType()));
7870     }
7871   }
7872 
7873   // Try to simplify (sext (load x)).
7874   if (SDValue foldedExt =
7875           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
7876                              ISD::SEXTLOAD, ISD::SIGN_EXTEND))
7877     return foldedExt;
7878 
7879   // fold (sext (load x)) to multiple smaller sextloads.
7880   // Only on illegal but splittable vectors.
7881   if (SDValue ExtLoad = CombineExtLoad(N))
7882     return ExtLoad;
7883 
7884   // Try to simplify (sext (sextload x)).
7885   if (SDValue foldedExt = tryToFoldExtOfExtload(
7886           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
7887     return foldedExt;
7888 
7889   // fold (sext (and/or/xor (load x), cst)) ->
7890   //      (and/or/xor (sextload x), (sext cst))
7891   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7892        N0.getOpcode() == ISD::XOR) &&
7893       isa<LoadSDNode>(N0.getOperand(0)) &&
7894       N0.getOperand(1).getOpcode() == ISD::Constant &&
7895       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7896     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
7897     EVT MemVT = LN00->getMemoryVT();
7898     if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
7899       LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
7900       SmallVector<SDNode*, 4> SetCCs;
7901       bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
7902                                              ISD::SIGN_EXTEND, SetCCs, TLI);
7903       if (DoXform) {
7904         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
7905                                          LN00->getChain(), LN00->getBasePtr(),
7906                                          LN00->getMemoryVT(),
7907                                          LN00->getMemOperand());
7908         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7909         Mask = Mask.sext(VT.getSizeInBits());
7910         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7911                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
7912         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
7913         bool NoReplaceTruncAnd = !N0.hasOneUse();
7914         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
7915         CombineTo(N, And);
7916         // If N0 has multiple uses, change other uses as well.
7917         if (NoReplaceTruncAnd) {
7918           SDValue TruncAnd =
7919               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
7920           CombineTo(N0.getNode(), TruncAnd);
7921         }
7922         if (NoReplaceTrunc) {
7923           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
7924         } else {
7925           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
7926                                       LN00->getValueType(0), ExtLoad);
7927           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
7928         }
7929         return SDValue(N,0); // Return N so it doesn't get rechecked!
7930       }
7931     }
7932   }
7933 
7934   if (N0.getOpcode() == ISD::SETCC) {
7935     SDValue N00 = N0.getOperand(0);
7936     SDValue N01 = N0.getOperand(1);
7937     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7938     EVT N00VT = N0.getOperand(0).getValueType();
7939 
7940     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7941     // Only do this before legalize for now.
7942     if (VT.isVector() && !LegalOperations &&
7943         TLI.getBooleanContents(N00VT) ==
7944             TargetLowering::ZeroOrNegativeOneBooleanContent) {
7945       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7946       // of the same size as the compared operands. Only optimize sext(setcc())
7947       // if this is the case.
7948       EVT SVT = getSetCCResultType(N00VT);
7949 
7950       // We know that the # elements of the results is the same as the
7951       // # elements of the compare (and the # elements of the compare result
7952       // for that matter).  Check to see that they are the same size.  If so,
7953       // we know that the element size of the sext'd result matches the
7954       // element size of the compare operands.
7955       if (VT.getSizeInBits() == SVT.getSizeInBits())
7956         return DAG.getSetCC(DL, VT, N00, N01, CC);
7957 
7958       // If the desired elements are smaller or larger than the source
7959       // elements, we can use a matching integer vector type and then
7960       // truncate/sign extend.
7961       EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7962       if (SVT == MatchingVecType) {
7963         SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7964         return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7965       }
7966     }
7967 
7968     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7969     // Here, T can be 1 or -1, depending on the type of the setcc and
7970     // getBooleanContents().
7971     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7972 
7973     // To determine the "true" side of the select, we need to know the high bit
7974     // of the value returned by the setcc if it evaluates to true.
7975     // If the type of the setcc is i1, then the true case of the select is just
7976     // sext(i1 1), that is, -1.
7977     // If the type of the setcc is larger (say, i8) then the value of the high
7978     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7979     // of the appropriate width.
7980     SDValue ExtTrueVal = (SetCCWidth == 1)
7981                              ? DAG.getAllOnesConstant(DL, VT)
7982                              : DAG.getBoolConstant(true, DL, VT, N00VT);
7983     SDValue Zero = DAG.getConstant(0, DL, VT);
7984     if (SDValue SCC =
7985             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7986       return SCC;
7987 
7988     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
7989       EVT SetCCVT = getSetCCResultType(N00VT);
7990       // Don't do this transform for i1 because there's a select transform
7991       // that would reverse it.
7992       // TODO: We should not do this transform at all without a target hook
7993       // because a sext is likely cheaper than a select?
7994       if (SetCCVT.getScalarSizeInBits() != 1 &&
7995           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7996         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7997         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7998       }
7999     }
8000   }
8001 
8002   // fold (sext x) -> (zext x) if the sign bit is known zero.
8003   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
8004       DAG.SignBitIsZero(N0))
8005     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
8006 
8007   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8008     return NewVSel;
8009 
8010   return SDValue();
8011 }
8012 
8013 // isTruncateOf - If N is a truncate of some other value, return true, record
8014 // the value being truncated in Op and which of Op's bits are zero/one in Known.
8015 // This function computes KnownBits to avoid a duplicated call to
8016 // computeKnownBits in the caller.
8017 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
8018                          KnownBits &Known) {
8019   if (N->getOpcode() == ISD::TRUNCATE) {
8020     Op = N->getOperand(0);
8021     DAG.computeKnownBits(Op, Known);
8022     return true;
8023   }
8024 
8025   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
8026       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
8027     return false;
8028 
8029   SDValue Op0 = N->getOperand(0);
8030   SDValue Op1 = N->getOperand(1);
8031   assert(Op0.getValueType() == Op1.getValueType());
8032 
8033   if (isNullConstant(Op0))
8034     Op = Op1;
8035   else if (isNullConstant(Op1))
8036     Op = Op0;
8037   else
8038     return false;
8039 
8040   DAG.computeKnownBits(Op, Known);
8041 
8042   if (!(Known.Zero | 1).isAllOnesValue())
8043     return false;
8044 
8045   return true;
8046 }
8047 
8048 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
8049   SDValue N0 = N->getOperand(0);
8050   EVT VT = N->getValueType(0);
8051 
8052   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8053                                               LegalOperations))
8054     return SDValue(Res, 0);
8055 
8056   // fold (zext (zext x)) -> (zext x)
8057   // fold (zext (aext x)) -> (zext x)
8058   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
8059     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
8060                        N0.getOperand(0));
8061 
8062   // fold (zext (truncate x)) -> (zext x) or
8063   //      (zext (truncate x)) -> (truncate x)
8064   // This is valid when the truncated bits of x are already zero.
8065   // FIXME: We should extend this to work for vectors too.
8066   SDValue Op;
8067   KnownBits Known;
8068   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
8069     APInt TruncatedBits =
8070       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
8071       APInt(Op.getValueSizeInBits(), 0) :
8072       APInt::getBitsSet(Op.getValueSizeInBits(),
8073                         N0.getValueSizeInBits(),
8074                         std::min(Op.getValueSizeInBits(),
8075                                  VT.getSizeInBits()));
8076     if (TruncatedBits.isSubsetOf(Known.Zero))
8077       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
8078   }
8079 
8080   // fold (zext (truncate x)) -> (and x, mask)
8081   if (N0.getOpcode() == ISD::TRUNCATE) {
8082     // fold (zext (truncate (load x))) -> (zext (smaller load x))
8083     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
8084     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8085       SDNode *oye = N0.getOperand(0).getNode();
8086       if (NarrowLoad.getNode() != N0.getNode()) {
8087         CombineTo(N0.getNode(), NarrowLoad);
8088         // CombineTo deleted the truncate, if needed, but not what's under it.
8089         AddToWorklist(oye);
8090       }
8091       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8092     }
8093 
8094     EVT SrcVT = N0.getOperand(0).getValueType();
8095     EVT MinVT = N0.getValueType();
8096 
8097     // Try to mask before the extension to avoid having to generate a larger mask,
8098     // possibly over several sub-vectors.
8099     if (SrcVT.bitsLT(VT) && VT.isVector()) {
8100       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
8101                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
8102         SDValue Op = N0.getOperand(0);
8103         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
8104         AddToWorklist(Op.getNode());
8105         SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
8106         // Transfer the debug info; the new node is equivalent to N0.
8107         DAG.transferDbgValues(N0, ZExtOrTrunc);
8108         return ZExtOrTrunc;
8109       }
8110     }
8111 
8112     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
8113       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8114       AddToWorklist(Op.getNode());
8115       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
8116       // We may safely transfer the debug info describing the truncate node over
8117       // to the equivalent and operation.
8118       DAG.transferDbgValues(N0, And);
8119       return And;
8120     }
8121   }
8122 
8123   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
8124   // if either of the casts is not free.
8125   if (N0.getOpcode() == ISD::AND &&
8126       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8127       N0.getOperand(1).getOpcode() == ISD::Constant &&
8128       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8129                            N0.getValueType()) ||
8130        !TLI.isZExtFree(N0.getValueType(), VT))) {
8131     SDValue X = N0.getOperand(0).getOperand(0);
8132     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
8133     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8134     Mask = Mask.zext(VT.getSizeInBits());
8135     SDLoc DL(N);
8136     return DAG.getNode(ISD::AND, DL, VT,
8137                        X, DAG.getConstant(Mask, DL, VT));
8138   }
8139 
8140   // Try to simplify (zext (load x)).
8141   if (SDValue foldedExt =
8142           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
8143                              ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
8144     return foldedExt;
8145 
8146   // fold (zext (load x)) to multiple smaller zextloads.
8147   // Only on illegal but splittable vectors.
8148   if (SDValue ExtLoad = CombineExtLoad(N))
8149     return ExtLoad;
8150 
8151   // fold (zext (and/or/xor (load x), cst)) ->
8152   //      (and/or/xor (zextload x), (zext cst))
8153   // Unless (and (load x) cst) will match as a zextload already and has
8154   // additional users.
8155   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
8156        N0.getOpcode() == ISD::XOR) &&
8157       isa<LoadSDNode>(N0.getOperand(0)) &&
8158       N0.getOperand(1).getOpcode() == ISD::Constant &&
8159       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
8160     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
8161     EVT MemVT = LN00->getMemoryVT();
8162     if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
8163         LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
8164       bool DoXform = true;
8165       SmallVector<SDNode*, 4> SetCCs;
8166       if (!N0.hasOneUse()) {
8167         if (N0.getOpcode() == ISD::AND) {
8168           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
8169           EVT LoadResultTy = AndC->getValueType(0);
8170           EVT ExtVT;
8171           if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
8172             DoXform = false;
8173         }
8174       }
8175       if (DoXform)
8176         DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
8177                                           ISD::ZERO_EXTEND, SetCCs, TLI);
8178       if (DoXform) {
8179         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
8180                                          LN00->getChain(), LN00->getBasePtr(),
8181                                          LN00->getMemoryVT(),
8182                                          LN00->getMemOperand());
8183         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8184         Mask = Mask.zext(VT.getSizeInBits());
8185         SDLoc DL(N);
8186         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
8187                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
8188         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
8189         bool NoReplaceTruncAnd = !N0.hasOneUse();
8190         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
8191         CombineTo(N, And);
8192         // If N0 has multiple uses, change other uses as well.
8193         if (NoReplaceTruncAnd) {
8194           SDValue TruncAnd =
8195               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
8196           CombineTo(N0.getNode(), TruncAnd);
8197         }
8198         if (NoReplaceTrunc) {
8199           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
8200         } else {
8201           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
8202                                       LN00->getValueType(0), ExtLoad);
8203           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
8204         }
8205         return SDValue(N,0); // Return N so it doesn't get rechecked!
8206       }
8207     }
8208   }
8209 
8210   // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
8211   //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
8212   if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
8213     return ZExtLoad;
8214 
8215   // Try to simplify (zext (zextload x)).
8216   if (SDValue foldedExt = tryToFoldExtOfExtload(
8217           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
8218     return foldedExt;
8219 
8220   if (N0.getOpcode() == ISD::SETCC) {
8221     // Only do this before legalize for now.
8222     if (!LegalOperations && VT.isVector() &&
8223         N0.getValueType().getVectorElementType() == MVT::i1) {
8224       EVT N00VT = N0.getOperand(0).getValueType();
8225       if (getSetCCResultType(N00VT) == N0.getValueType())
8226         return SDValue();
8227 
8228       // We know that the # elements of the results is the same as the #
8229       // elements of the compare (and the # elements of the compare result for
8230       // that matter). Check to see that they are the same size. If so, we know
8231       // that the element size of the sext'd result matches the element size of
8232       // the compare operands.
8233       SDLoc DL(N);
8234       SDValue VecOnes = DAG.getConstant(1, DL, VT);
8235       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
8236         // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
8237         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
8238                                      N0.getOperand(1), N0.getOperand(2));
8239         return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
8240       }
8241 
8242       // If the desired elements are smaller or larger than the source
8243       // elements we can use a matching integer vector type and then
8244       // truncate/sign extend.
8245       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8246       SDValue VsetCC =
8247           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
8248                       N0.getOperand(1), N0.getOperand(2));
8249       return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
8250                          VecOnes);
8251     }
8252 
8253     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8254     SDLoc DL(N);
8255     if (SDValue SCC = SimplifySelectCC(
8256             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8257             DAG.getConstant(0, DL, VT),
8258             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8259       return SCC;
8260   }
8261 
8262   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
8263   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
8264       isa<ConstantSDNode>(N0.getOperand(1)) &&
8265       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
8266       N0.hasOneUse()) {
8267     SDValue ShAmt = N0.getOperand(1);
8268     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8269     if (N0.getOpcode() == ISD::SHL) {
8270       SDValue InnerZExt = N0.getOperand(0);
8271       // If the original shl may be shifting out bits, do not perform this
8272       // transformation.
8273       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
8274         InnerZExt.getOperand(0).getValueSizeInBits();
8275       if (ShAmtVal > KnownZeroBits)
8276         return SDValue();
8277     }
8278 
8279     SDLoc DL(N);
8280 
8281     // Ensure that the shift amount is wide enough for the shifted value.
8282     if (VT.getSizeInBits() >= 256)
8283       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
8284 
8285     return DAG.getNode(N0.getOpcode(), DL, VT,
8286                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
8287                        ShAmt);
8288   }
8289 
8290   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8291     return NewVSel;
8292 
8293   return SDValue();
8294 }
8295 
8296 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
8297   SDValue N0 = N->getOperand(0);
8298   EVT VT = N->getValueType(0);
8299 
8300   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8301                                               LegalOperations))
8302     return SDValue(Res, 0);
8303 
8304   // fold (aext (aext x)) -> (aext x)
8305   // fold (aext (zext x)) -> (zext x)
8306   // fold (aext (sext x)) -> (sext x)
8307   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
8308       N0.getOpcode() == ISD::ZERO_EXTEND ||
8309       N0.getOpcode() == ISD::SIGN_EXTEND)
8310     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8311 
8312   // fold (aext (truncate (load x))) -> (aext (smaller load x))
8313   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
8314   if (N0.getOpcode() == ISD::TRUNCATE) {
8315     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
8316       SDNode *oye = N0.getOperand(0).getNode();
8317       if (NarrowLoad.getNode() != N0.getNode()) {
8318         CombineTo(N0.getNode(), NarrowLoad);
8319         // CombineTo deleted the truncate, if needed, but not what's under it.
8320         AddToWorklist(oye);
8321       }
8322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8323     }
8324   }
8325 
8326   // fold (aext (truncate x))
8327   if (N0.getOpcode() == ISD::TRUNCATE)
8328     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
8329 
8330   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
8331   // if the trunc is not free.
8332   if (N0.getOpcode() == ISD::AND &&
8333       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
8334       N0.getOperand(1).getOpcode() == ISD::Constant &&
8335       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
8336                           N0.getValueType())) {
8337     SDLoc DL(N);
8338     SDValue X = N0.getOperand(0).getOperand(0);
8339     X = DAG.getAnyExtOrTrunc(X, DL, VT);
8340     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
8341     Mask = Mask.zext(VT.getSizeInBits());
8342     return DAG.getNode(ISD::AND, DL, VT,
8343                        X, DAG.getConstant(Mask, DL, VT));
8344   }
8345 
8346   // fold (aext (load x)) -> (aext (truncate (extload x)))
8347   // None of the supported targets knows how to perform load and any_ext
8348   // on vectors in one instruction.  We only perform this transformation on
8349   // scalars.
8350   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
8351       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8352       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8353     bool DoXform = true;
8354     SmallVector<SDNode*, 4> SetCCs;
8355     if (!N0.hasOneUse())
8356       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs,
8357                                         TLI);
8358     if (DoXform) {
8359       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8360       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8361                                        LN0->getChain(),
8362                                        LN0->getBasePtr(), N0.getValueType(),
8363                                        LN0->getMemOperand());
8364       ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
8365       // If the load value is used only by N, replace it via CombineTo N.
8366       bool NoReplaceTrunc = N0.hasOneUse();
8367       CombineTo(N, ExtLoad);
8368       if (NoReplaceTrunc) {
8369         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8370       } else {
8371         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
8372                                     N0.getValueType(), ExtLoad);
8373         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
8374       }
8375       return SDValue(N, 0); // Return N so it doesn't get rechecked!
8376     }
8377   }
8378 
8379   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
8380   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
8381   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
8382   if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
8383       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
8384     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8385     ISD::LoadExtType ExtType = LN0->getExtensionType();
8386     EVT MemVT = LN0->getMemoryVT();
8387     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
8388       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
8389                                        VT, LN0->getChain(), LN0->getBasePtr(),
8390                                        MemVT, LN0->getMemOperand());
8391       CombineTo(N, ExtLoad);
8392       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
8393       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8394     }
8395   }
8396 
8397   if (N0.getOpcode() == ISD::SETCC) {
8398     // For vectors:
8399     // aext(setcc) -> vsetcc
8400     // aext(setcc) -> truncate(vsetcc)
8401     // aext(setcc) -> aext(vsetcc)
8402     // Only do this before legalize for now.
8403     if (VT.isVector() && !LegalOperations) {
8404       EVT N00VT = N0.getOperand(0).getValueType();
8405       if (getSetCCResultType(N00VT) == N0.getValueType())
8406         return SDValue();
8407 
8408       // We know that the # elements of the results is the same as the
8409       // # elements of the compare (and the # elements of the compare result
8410       // for that matter).  Check to see that they are the same size.  If so,
8411       // we know that the element size of the sext'd result matches the
8412       // element size of the compare operands.
8413       if (VT.getSizeInBits() == N00VT.getSizeInBits())
8414         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
8415                              N0.getOperand(1),
8416                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
8417       // If the desired elements are smaller or larger than the source
8418       // elements we can use a matching integer vector type and then
8419       // truncate/any extend
8420       else {
8421         EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
8422         SDValue VsetCC =
8423           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
8424                         N0.getOperand(1),
8425                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
8426         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
8427       }
8428     }
8429 
8430     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
8431     SDLoc DL(N);
8432     if (SDValue SCC = SimplifySelectCC(
8433             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
8434             DAG.getConstant(0, DL, VT),
8435             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
8436       return SCC;
8437   }
8438 
8439   return SDValue();
8440 }
8441 
8442 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
8443   unsigned Opcode = N->getOpcode();
8444   SDValue N0 = N->getOperand(0);
8445   SDValue N1 = N->getOperand(1);
8446   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
8447 
8448   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
8449   if (N0.getOpcode() == Opcode &&
8450       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
8451     return N0;
8452 
8453   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
8454       N0.getOperand(0).getOpcode() == Opcode) {
8455     // We have an assert, truncate, assert sandwich. Make one stronger assert
8456     // by asserting on the smallest asserted type to the larger source type.
8457     // This eliminates the later assert:
8458     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
8459     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
8460     SDValue BigA = N0.getOperand(0);
8461     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
8462     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
8463            "Asserting zero/sign-extended bits to a type larger than the "
8464            "truncated destination does not provide information");
8465 
8466     SDLoc DL(N);
8467     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
8468     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
8469     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
8470                                     BigA.getOperand(0), MinAssertVTVal);
8471     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
8472   }
8473 
8474   return SDValue();
8475 }
8476 
8477 /// If the result of a wider load is shifted to right of N  bits and then
8478 /// truncated to a narrower type and where N is a multiple of number of bits of
8479 /// the narrower type, transform it to a narrower load from address + N / num of
8480 /// bits of new type. Also narrow the load if the result is masked with an AND
8481 /// to effectively produce a smaller type. If the result is to be extended, also
8482 /// fold the extension to form a extending load.
8483 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
8484   unsigned Opc = N->getOpcode();
8485 
8486   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
8487   SDValue N0 = N->getOperand(0);
8488   EVT VT = N->getValueType(0);
8489   EVT ExtVT = VT;
8490 
8491   // This transformation isn't valid for vector loads.
8492   if (VT.isVector())
8493     return SDValue();
8494 
8495   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
8496   // extended to VT.
8497   if (Opc == ISD::SIGN_EXTEND_INREG) {
8498     ExtType = ISD::SEXTLOAD;
8499     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8500   } else if (Opc == ISD::SRL) {
8501     // Another special-case: SRL is basically zero-extending a narrower value,
8502     // or it maybe shifting a higher subword, half or byte into the lowest
8503     // bits.
8504     ExtType = ISD::ZEXTLOAD;
8505     N0 = SDValue(N, 0);
8506 
8507     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
8508     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8509     if (!N01 || !LN0)
8510       return SDValue();
8511 
8512     uint64_t ShiftAmt = N01->getZExtValue();
8513     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
8514     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
8515       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
8516     else
8517       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
8518                                 VT.getSizeInBits() - ShiftAmt);
8519   } else if (Opc == ISD::AND) {
8520     // An AND with a constant mask is the same as a truncate + zero-extend.
8521     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
8522     if (!AndC || !AndC->getAPIntValue().isMask())
8523       return SDValue();
8524 
8525     unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
8526     ExtType = ISD::ZEXTLOAD;
8527     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
8528   }
8529 
8530   unsigned ShAmt = 0;
8531   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
8532     SDValue SRL = N0;
8533     if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) {
8534       ShAmt = ConstShift->getZExtValue();
8535       unsigned EVTBits = ExtVT.getSizeInBits();
8536       // Is the shift amount a multiple of size of VT?
8537       if ((ShAmt & (EVTBits-1)) == 0) {
8538         N0 = N0.getOperand(0);
8539         // Is the load width a multiple of size of VT?
8540         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
8541           return SDValue();
8542       }
8543 
8544       // At this point, we must have a load or else we can't do the transform.
8545       if (!isa<LoadSDNode>(N0)) return SDValue();
8546 
8547       auto *LN0 = cast<LoadSDNode>(N0);
8548 
8549       // Because a SRL must be assumed to *need* to zero-extend the high bits
8550       // (as opposed to anyext the high bits), we can't combine the zextload
8551       // lowering of SRL and an sextload.
8552       if (LN0->getExtensionType() == ISD::SEXTLOAD)
8553         return SDValue();
8554 
8555       // If the shift amount is larger than the input type then we're not
8556       // accessing any of the loaded bytes.  If the load was a zextload/extload
8557       // then the result of the shift+trunc is zero/undef (handled elsewhere).
8558       if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
8559         return SDValue();
8560 
8561       // If the SRL is only used by a masking AND, we may be able to adjust
8562       // the ExtVT to make the AND redundant.
8563       SDNode *Mask = *(SRL->use_begin());
8564       if (Mask->getOpcode() == ISD::AND &&
8565           isa<ConstantSDNode>(Mask->getOperand(1))) {
8566         const APInt &ShiftMask =
8567           cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue();
8568         if (ShiftMask.isMask()) {
8569           EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
8570                                            ShiftMask.countTrailingOnes());
8571           // Recompute the type.
8572           if (TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT))
8573             ExtVT = MaskedVT;
8574         }
8575       }
8576     }
8577   }
8578 
8579   // If the load is shifted left (and the result isn't shifted back right),
8580   // we can fold the truncate through the shift.
8581   unsigned ShLeftAmt = 0;
8582   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8583       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
8584     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
8585       ShLeftAmt = N01->getZExtValue();
8586       N0 = N0.getOperand(0);
8587     }
8588   }
8589 
8590   // If we haven't found a load, we can't narrow it.
8591   if (!isa<LoadSDNode>(N0))
8592     return SDValue();
8593 
8594   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8595   if (!isLegalNarrowLoad(LN0, ExtType, ExtVT, ShAmt))
8596     return SDValue();
8597 
8598   // For big endian targets, we need to adjust the offset to the pointer to
8599   // load the correct bytes.
8600   if (DAG.getDataLayout().isBigEndian()) {
8601     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
8602     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
8603     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
8604   }
8605 
8606   EVT PtrType = N0.getOperand(1).getValueType();
8607   uint64_t PtrOff = ShAmt / 8;
8608   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
8609   SDLoc DL(LN0);
8610   // The original load itself didn't wrap, so an offset within it doesn't.
8611   SDNodeFlags Flags;
8612   Flags.setNoUnsignedWrap(true);
8613   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
8614                                PtrType, LN0->getBasePtr(),
8615                                DAG.getConstant(PtrOff, DL, PtrType),
8616                                Flags);
8617   AddToWorklist(NewPtr.getNode());
8618 
8619   SDValue Load;
8620   if (ExtType == ISD::NON_EXTLOAD)
8621     Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8622                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8623                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8624   else
8625     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8626                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8627                           NewAlign, LN0->getMemOperand()->getFlags(),
8628                           LN0->getAAInfo());
8629 
8630   // Replace the old load's chain with the new load's chain.
8631   WorklistRemover DeadNodes(*this);
8632   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8633 
8634   // Shift the result left, if we've swallowed a left shift.
8635   SDValue Result = Load;
8636   if (ShLeftAmt != 0) {
8637     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8638     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8639       ShImmTy = VT;
8640     // If the shift amount is as large as the result size (but, presumably,
8641     // no larger than the source) then the useful bits of the result are
8642     // zero; we can't simply return the shortened shift, because the result
8643     // of that operation is undefined.
8644     SDLoc DL(N0);
8645     if (ShLeftAmt >= VT.getSizeInBits())
8646       Result = DAG.getConstant(0, DL, VT);
8647     else
8648       Result = DAG.getNode(ISD::SHL, DL, VT,
8649                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8650   }
8651 
8652   // Return the new loaded value.
8653   return Result;
8654 }
8655 
8656 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8657   SDValue N0 = N->getOperand(0);
8658   SDValue N1 = N->getOperand(1);
8659   EVT VT = N->getValueType(0);
8660   EVT EVT = cast<VTSDNode>(N1)->getVT();
8661   unsigned VTBits = VT.getScalarSizeInBits();
8662   unsigned EVTBits = EVT.getScalarSizeInBits();
8663 
8664   if (N0.isUndef())
8665     return DAG.getUNDEF(VT);
8666 
8667   // fold (sext_in_reg c1) -> c1
8668   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8669     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8670 
8671   // If the input is already sign extended, just drop the extension.
8672   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8673     return N0;
8674 
8675   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8676   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8677       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8678     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8679                        N0.getOperand(0), N1);
8680 
8681   // fold (sext_in_reg (sext x)) -> (sext x)
8682   // fold (sext_in_reg (aext x)) -> (sext x)
8683   // if x is small enough.
8684   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8685     SDValue N00 = N0.getOperand(0);
8686     if (N00.getScalarValueSizeInBits() <= EVTBits &&
8687         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8688       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8689   }
8690 
8691   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
8692   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8693        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8694        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8695       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8696     if (!LegalOperations ||
8697         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8698       return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8699   }
8700 
8701   // fold (sext_in_reg (zext x)) -> (sext x)
8702   // iff we are extending the source sign bit.
8703   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8704     SDValue N00 = N0.getOperand(0);
8705     if (N00.getScalarValueSizeInBits() == EVTBits &&
8706         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8707       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8708   }
8709 
8710   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8711   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8712     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8713 
8714   // fold operands of sext_in_reg based on knowledge that the top bits are not
8715   // demanded.
8716   if (SimplifyDemandedBits(SDValue(N, 0)))
8717     return SDValue(N, 0);
8718 
8719   // fold (sext_in_reg (load x)) -> (smaller sextload x)
8720   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8721   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8722     return NarrowLoad;
8723 
8724   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8725   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8726   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8727   if (N0.getOpcode() == ISD::SRL) {
8728     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8729       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8730         // We can turn this into an SRA iff the input to the SRL is already sign
8731         // extended enough.
8732         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8733         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8734           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8735                              N0.getOperand(0), N0.getOperand(1));
8736       }
8737   }
8738 
8739   // fold (sext_inreg (extload x)) -> (sextload x)
8740   // If sextload is not supported by target, we can only do the combine when
8741   // load has one use. Doing otherwise can block folding the extload with other
8742   // extends that the target does support.
8743   if (ISD::isEXTLoad(N0.getNode()) &&
8744       ISD::isUNINDEXEDLoad(N0.getNode()) &&
8745       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8746       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() &&
8747         N0.hasOneUse()) ||
8748        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8749     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8750     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8751                                      LN0->getChain(),
8752                                      LN0->getBasePtr(), EVT,
8753                                      LN0->getMemOperand());
8754     CombineTo(N, ExtLoad);
8755     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8756     AddToWorklist(ExtLoad.getNode());
8757     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8758   }
8759   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8760   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8761       N0.hasOneUse() &&
8762       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8763       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8764        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8765     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8766     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8767                                      LN0->getChain(),
8768                                      LN0->getBasePtr(), EVT,
8769                                      LN0->getMemOperand());
8770     CombineTo(N, ExtLoad);
8771     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8772     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8773   }
8774 
8775   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8776   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8777     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8778                                            N0.getOperand(1), false))
8779       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8780                          BSwap, N1);
8781   }
8782 
8783   return SDValue();
8784 }
8785 
8786 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8787   SDValue N0 = N->getOperand(0);
8788   EVT VT = N->getValueType(0);
8789 
8790   if (N0.isUndef())
8791     return DAG.getUNDEF(VT);
8792 
8793   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8794                                               LegalOperations))
8795     return SDValue(Res, 0);
8796 
8797   return SDValue();
8798 }
8799 
8800 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8801   SDValue N0 = N->getOperand(0);
8802   EVT VT = N->getValueType(0);
8803 
8804   if (N0.isUndef())
8805     return DAG.getUNDEF(VT);
8806 
8807   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8808                                               LegalOperations))
8809     return SDValue(Res, 0);
8810 
8811   return SDValue();
8812 }
8813 
8814 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8815   SDValue N0 = N->getOperand(0);
8816   EVT VT = N->getValueType(0);
8817   bool isLE = DAG.getDataLayout().isLittleEndian();
8818 
8819   // noop truncate
8820   if (N0.getValueType() == N->getValueType(0))
8821     return N0;
8822 
8823   // fold (truncate (truncate x)) -> (truncate x)
8824   if (N0.getOpcode() == ISD::TRUNCATE)
8825     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8826 
8827   // fold (truncate c1) -> c1
8828   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
8829     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8830     if (C.getNode() != N)
8831       return C;
8832   }
8833 
8834   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8835   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8836       N0.getOpcode() == ISD::SIGN_EXTEND ||
8837       N0.getOpcode() == ISD::ANY_EXTEND) {
8838     // if the source is smaller than the dest, we still need an extend.
8839     if (N0.getOperand(0).getValueType().bitsLT(VT))
8840       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8841     // if the source is larger than the dest, than we just need the truncate.
8842     if (N0.getOperand(0).getValueType().bitsGT(VT))
8843       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8844     // if the source and dest are the same type, we can drop both the extend
8845     // and the truncate.
8846     return N0.getOperand(0);
8847   }
8848 
8849   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8850   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8851     return SDValue();
8852 
8853   // Fold extract-and-trunc into a narrow extract. For example:
8854   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8855   //   i32 y = TRUNCATE(i64 x)
8856   //        -- becomes --
8857   //   v16i8 b = BITCAST (v2i64 val)
8858   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8859   //
8860   // Note: We only run this optimization after type legalization (which often
8861   // creates this pattern) and before operation legalization after which
8862   // we need to be more careful about the vector instructions that we generate.
8863   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8864       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8865     EVT VecTy = N0.getOperand(0).getValueType();
8866     EVT ExTy = N0.getValueType();
8867     EVT TrTy = N->getValueType(0);
8868 
8869     unsigned NumElem = VecTy.getVectorNumElements();
8870     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8871 
8872     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8873     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8874 
8875     SDValue EltNo = N0->getOperand(1);
8876     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8877       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8878       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8879       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8880 
8881       SDLoc DL(N);
8882       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8883                          DAG.getBitcast(NVT, N0.getOperand(0)),
8884                          DAG.getConstant(Index, DL, IndexTy));
8885     }
8886   }
8887 
8888   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8889   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8890     EVT SrcVT = N0.getValueType();
8891     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8892         TLI.isTruncateFree(SrcVT, VT)) {
8893       SDLoc SL(N0);
8894       SDValue Cond = N0.getOperand(0);
8895       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8896       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8897       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8898     }
8899   }
8900 
8901   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8902   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8903       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8904       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8905     SDValue Amt = N0.getOperand(1);
8906     KnownBits Known;
8907     DAG.computeKnownBits(Amt, Known);
8908     unsigned Size = VT.getScalarSizeInBits();
8909     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8910       SDLoc SL(N);
8911       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8912 
8913       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8914       if (AmtVT != Amt.getValueType()) {
8915         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8916         AddToWorklist(Amt.getNode());
8917       }
8918       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8919     }
8920   }
8921 
8922   // Fold a series of buildvector, bitcast, and truncate if possible.
8923   // For example fold
8924   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8925   //   (2xi32 (buildvector x, y)).
8926   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8927       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8928       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8929       N0.getOperand(0).hasOneUse()) {
8930     SDValue BuildVect = N0.getOperand(0);
8931     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8932     EVT TruncVecEltTy = VT.getVectorElementType();
8933 
8934     // Check that the element types match.
8935     if (BuildVectEltTy == TruncVecEltTy) {
8936       // Now we only need to compute the offset of the truncated elements.
8937       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
8938       unsigned TruncVecNumElts = VT.getVectorNumElements();
8939       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8940 
8941       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8942              "Invalid number of elements");
8943 
8944       SmallVector<SDValue, 8> Opnds;
8945       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8946         Opnds.push_back(BuildVect.getOperand(i));
8947 
8948       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8949     }
8950   }
8951 
8952   // See if we can simplify the input to this truncate through knowledge that
8953   // only the low bits are being used.
8954   // For example "trunc (or (shl x, 8), y)" // -> trunc y
8955   // Currently we only perform this optimization on scalars because vectors
8956   // may have different active low bits.
8957   if (!VT.isVector()) {
8958     APInt Mask =
8959         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
8960     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
8961       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8962   }
8963 
8964   // fold (truncate (load x)) -> (smaller load x)
8965   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8966   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8967     if (SDValue Reduced = ReduceLoadWidth(N))
8968       return Reduced;
8969 
8970     // Handle the case where the load remains an extending load even
8971     // after truncation.
8972     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8973       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8974       if (!LN0->isVolatile() &&
8975           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8976         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8977                                          VT, LN0->getChain(), LN0->getBasePtr(),
8978                                          LN0->getMemoryVT(),
8979                                          LN0->getMemOperand());
8980         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8981         return NewLoad;
8982       }
8983     }
8984   }
8985 
8986   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8987   // where ... are all 'undef'.
8988   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8989     SmallVector<EVT, 8> VTs;
8990     SDValue V;
8991     unsigned Idx = 0;
8992     unsigned NumDefs = 0;
8993 
8994     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8995       SDValue X = N0.getOperand(i);
8996       if (!X.isUndef()) {
8997         V = X;
8998         Idx = i;
8999         NumDefs++;
9000       }
9001       // Stop if more than one members are non-undef.
9002       if (NumDefs > 1)
9003         break;
9004       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
9005                                      VT.getVectorElementType(),
9006                                      X.getValueType().getVectorNumElements()));
9007     }
9008 
9009     if (NumDefs == 0)
9010       return DAG.getUNDEF(VT);
9011 
9012     if (NumDefs == 1) {
9013       assert(V.getNode() && "The single defined operand is empty!");
9014       SmallVector<SDValue, 8> Opnds;
9015       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
9016         if (i != Idx) {
9017           Opnds.push_back(DAG.getUNDEF(VTs[i]));
9018           continue;
9019         }
9020         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
9021         AddToWorklist(NV.getNode());
9022         Opnds.push_back(NV);
9023       }
9024       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
9025     }
9026   }
9027 
9028   // Fold truncate of a bitcast of a vector to an extract of the low vector
9029   // element.
9030   //
9031   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
9032   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
9033     SDValue VecSrc = N0.getOperand(0);
9034     EVT SrcVT = VecSrc.getValueType();
9035     if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
9036         (!LegalOperations ||
9037          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
9038       SDLoc SL(N);
9039 
9040       EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
9041       unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1;
9042       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
9043                          VecSrc, DAG.getConstant(Idx, SL, IdxVT));
9044     }
9045   }
9046 
9047   // Simplify the operands using demanded-bits information.
9048   if (!VT.isVector() &&
9049       SimplifyDemandedBits(SDValue(N, 0)))
9050     return SDValue(N, 0);
9051 
9052   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
9053   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
9054   // When the adde's carry is not used.
9055   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
9056       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
9057       (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
9058     SDLoc SL(N);
9059     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
9060     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
9061     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
9062     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
9063   }
9064 
9065   // fold (truncate (extract_subvector(ext x))) ->
9066   //      (extract_subvector x)
9067   // TODO: This can be generalized to cover cases where the truncate and extract
9068   // do not fully cancel each other out.
9069   if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9070     SDValue N00 = N0.getOperand(0);
9071     if (N00.getOpcode() == ISD::SIGN_EXTEND ||
9072         N00.getOpcode() == ISD::ZERO_EXTEND ||
9073         N00.getOpcode() == ISD::ANY_EXTEND) {
9074       if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
9075           VT.getVectorElementType())
9076         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
9077                            N00.getOperand(0), N0.getOperand(1));
9078     }
9079   }
9080 
9081   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
9082     return NewVSel;
9083 
9084   return SDValue();
9085 }
9086 
9087 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
9088   SDValue Elt = N->getOperand(i);
9089   if (Elt.getOpcode() != ISD::MERGE_VALUES)
9090     return Elt.getNode();
9091   return Elt.getOperand(Elt.getResNo()).getNode();
9092 }
9093 
9094 /// build_pair (load, load) -> load
9095 /// if load locations are consecutive.
9096 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
9097   assert(N->getOpcode() == ISD::BUILD_PAIR);
9098 
9099   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
9100   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
9101 
9102   // A BUILD_PAIR is always having the least significant part in elt 0 and the
9103   // most significant part in elt 1. So when combining into one large load, we
9104   // need to consider the endianness.
9105   if (DAG.getDataLayout().isBigEndian())
9106     std::swap(LD1, LD2);
9107 
9108   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
9109       LD1->getAddressSpace() != LD2->getAddressSpace())
9110     return SDValue();
9111   EVT LD1VT = LD1->getValueType(0);
9112   unsigned LD1Bytes = LD1VT.getStoreSize();
9113   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
9114       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
9115     unsigned Align = LD1->getAlignment();
9116     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
9117         VT.getTypeForEVT(*DAG.getContext()));
9118 
9119     if (NewAlign <= Align &&
9120         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
9121       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
9122                          LD1->getPointerInfo(), Align);
9123   }
9124 
9125   return SDValue();
9126 }
9127 
9128 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
9129   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
9130   // and Lo parts; on big-endian machines it doesn't.
9131   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
9132 }
9133 
9134 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
9135                                     const TargetLowering &TLI) {
9136   // If this is not a bitcast to an FP type or if the target doesn't have
9137   // IEEE754-compliant FP logic, we're done.
9138   EVT VT = N->getValueType(0);
9139   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
9140     return SDValue();
9141 
9142   // TODO: Use splat values for the constant-checking below and remove this
9143   // restriction.
9144   SDValue N0 = N->getOperand(0);
9145   EVT SourceVT = N0.getValueType();
9146   if (SourceVT.isVector())
9147     return SDValue();
9148 
9149   unsigned FPOpcode;
9150   APInt SignMask;
9151   switch (N0.getOpcode()) {
9152   case ISD::AND:
9153     FPOpcode = ISD::FABS;
9154     SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
9155     break;
9156   case ISD::XOR:
9157     FPOpcode = ISD::FNEG;
9158     SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
9159     break;
9160   // TODO: ISD::OR --> ISD::FNABS?
9161   default:
9162     return SDValue();
9163   }
9164 
9165   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
9166   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
9167   SDValue LogicOp0 = N0.getOperand(0);
9168   ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9169   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
9170       LogicOp0.getOpcode() == ISD::BITCAST &&
9171       LogicOp0->getOperand(0).getValueType() == VT)
9172     return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
9173 
9174   return SDValue();
9175 }
9176 
9177 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
9178   SDValue N0 = N->getOperand(0);
9179   EVT VT = N->getValueType(0);
9180 
9181   if (N0.isUndef())
9182     return DAG.getUNDEF(VT);
9183 
9184   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
9185   // Only do this before legalize, since afterward the target may be depending
9186   // on the bitconvert.
9187   // First check to see if this is all constant.
9188   if (!LegalTypes &&
9189       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
9190       VT.isVector()) {
9191     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
9192 
9193     EVT DestEltVT = N->getValueType(0).getVectorElementType();
9194     assert(!DestEltVT.isVector() &&
9195            "Element type of vector ValueType must not be vector!");
9196     if (isSimple)
9197       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
9198   }
9199 
9200   // If the input is a constant, let getNode fold it.
9201   // We always need to check that this is just a fp -> int or int -> conversion
9202   // otherwise we will get back N which will confuse the caller into thinking
9203   // we used CombineTo. This can block target combines from running. If we can't
9204   // allowed legal operations, we need to ensure the resulting operation will be
9205   // legal.
9206   // TODO: Maybe we should check that the return value isn't N explicitly?
9207   if ((isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
9208        (!LegalOperations || TLI.isOperationLegal(ISD::ConstantFP, VT))) ||
9209       (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
9210        (!LegalOperations || TLI.isOperationLegal(ISD::Constant, VT))))
9211     return DAG.getBitcast(VT, N0);
9212 
9213   // (conv (conv x, t1), t2) -> (conv x, t2)
9214   if (N0.getOpcode() == ISD::BITCAST)
9215     return DAG.getBitcast(VT, N0.getOperand(0));
9216 
9217   // fold (conv (load x)) -> (load (conv*)x)
9218   // If the resultant load doesn't need a higher alignment than the original!
9219   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9220       // Do not change the width of a volatile load.
9221       !cast<LoadSDNode>(N0)->isVolatile() &&
9222       // Do not remove the cast if the types differ in endian layout.
9223       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
9224           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
9225       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
9226       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
9227     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9228     unsigned OrigAlign = LN0->getAlignment();
9229 
9230     bool Fast = false;
9231     if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
9232                                LN0->getAddressSpace(), OrigAlign, &Fast) &&
9233         Fast) {
9234       SDValue Load =
9235           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9236                       LN0->getPointerInfo(), OrigAlign,
9237                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
9238       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
9239       return Load;
9240     }
9241   }
9242 
9243   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
9244     return V;
9245 
9246   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
9247   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
9248   //
9249   // For ppc_fp128:
9250   // fold (bitcast (fneg x)) ->
9251   //     flipbit = signbit
9252   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9253   //
9254   // fold (bitcast (fabs x)) ->
9255   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
9256   //     (xor (bitcast x) (build_pair flipbit, flipbit))
9257   // This often reduces constant pool loads.
9258   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
9259        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
9260       N0.getNode()->hasOneUse() && VT.isInteger() &&
9261       !VT.isVector() && !N0.getValueType().isVector()) {
9262     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
9263     AddToWorklist(NewConv.getNode());
9264 
9265     SDLoc DL(N);
9266     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9267       assert(VT.getSizeInBits() == 128);
9268       SDValue SignBit = DAG.getConstant(
9269           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
9270       SDValue FlipBit;
9271       if (N0.getOpcode() == ISD::FNEG) {
9272         FlipBit = SignBit;
9273         AddToWorklist(FlipBit.getNode());
9274       } else {
9275         assert(N0.getOpcode() == ISD::FABS);
9276         SDValue Hi =
9277             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
9278                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9279                                               SDLoc(NewConv)));
9280         AddToWorklist(Hi.getNode());
9281         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
9282         AddToWorklist(FlipBit.getNode());
9283       }
9284       SDValue FlipBits =
9285           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9286       AddToWorklist(FlipBits.getNode());
9287       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
9288     }
9289     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9290     if (N0.getOpcode() == ISD::FNEG)
9291       return DAG.getNode(ISD::XOR, DL, VT,
9292                          NewConv, DAG.getConstant(SignBit, DL, VT));
9293     assert(N0.getOpcode() == ISD::FABS);
9294     return DAG.getNode(ISD::AND, DL, VT,
9295                        NewConv, DAG.getConstant(~SignBit, DL, VT));
9296   }
9297 
9298   // fold (bitconvert (fcopysign cst, x)) ->
9299   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
9300   // Note that we don't handle (copysign x, cst) because this can always be
9301   // folded to an fneg or fabs.
9302   //
9303   // For ppc_fp128:
9304   // fold (bitcast (fcopysign cst, x)) ->
9305   //     flipbit = (and (extract_element
9306   //                     (xor (bitcast cst), (bitcast x)), 0),
9307   //                    signbit)
9308   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
9309   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
9310       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
9311       VT.isInteger() && !VT.isVector()) {
9312     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
9313     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
9314     if (isTypeLegal(IntXVT)) {
9315       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
9316       AddToWorklist(X.getNode());
9317 
9318       // If X has a different width than the result/lhs, sext it or truncate it.
9319       unsigned VTWidth = VT.getSizeInBits();
9320       if (OrigXWidth < VTWidth) {
9321         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
9322         AddToWorklist(X.getNode());
9323       } else if (OrigXWidth > VTWidth) {
9324         // To get the sign bit in the right place, we have to shift it right
9325         // before truncating.
9326         SDLoc DL(X);
9327         X = DAG.getNode(ISD::SRL, DL,
9328                         X.getValueType(), X,
9329                         DAG.getConstant(OrigXWidth-VTWidth, DL,
9330                                         X.getValueType()));
9331         AddToWorklist(X.getNode());
9332         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
9333         AddToWorklist(X.getNode());
9334       }
9335 
9336       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
9337         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
9338         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9339         AddToWorklist(Cst.getNode());
9340         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
9341         AddToWorklist(X.getNode());
9342         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
9343         AddToWorklist(XorResult.getNode());
9344         SDValue XorResult64 = DAG.getNode(
9345             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
9346             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
9347                                   SDLoc(XorResult)));
9348         AddToWorklist(XorResult64.getNode());
9349         SDValue FlipBit =
9350             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
9351                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
9352         AddToWorklist(FlipBit.getNode());
9353         SDValue FlipBits =
9354             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
9355         AddToWorklist(FlipBits.getNode());
9356         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
9357       }
9358       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
9359       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
9360                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
9361       AddToWorklist(X.getNode());
9362 
9363       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
9364       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
9365                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
9366       AddToWorklist(Cst.getNode());
9367 
9368       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
9369     }
9370   }
9371 
9372   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
9373   if (N0.getOpcode() == ISD::BUILD_PAIR)
9374     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
9375       return CombineLD;
9376 
9377   // Remove double bitcasts from shuffles - this is often a legacy of
9378   // XformToShuffleWithZero being used to combine bitmaskings (of
9379   // float vectors bitcast to integer vectors) into shuffles.
9380   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
9381   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
9382       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
9383       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
9384       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
9385     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
9386 
9387     // If operands are a bitcast, peek through if it casts the original VT.
9388     // If operands are a constant, just bitcast back to original VT.
9389     auto PeekThroughBitcast = [&](SDValue Op) {
9390       if (Op.getOpcode() == ISD::BITCAST &&
9391           Op.getOperand(0).getValueType() == VT)
9392         return SDValue(Op.getOperand(0));
9393       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
9394           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
9395         return DAG.getBitcast(VT, Op);
9396       return SDValue();
9397     };
9398 
9399     // FIXME: If either input vector is bitcast, try to convert the shuffle to
9400     // the result type of this bitcast. This would eliminate at least one
9401     // bitcast. See the transform in InstCombine.
9402     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
9403     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
9404     if (!(SV0 && SV1))
9405       return SDValue();
9406 
9407     int MaskScale =
9408         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
9409     SmallVector<int, 8> NewMask;
9410     for (int M : SVN->getMask())
9411       for (int i = 0; i != MaskScale; ++i)
9412         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
9413 
9414     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9415     if (!LegalMask) {
9416       std::swap(SV0, SV1);
9417       ShuffleVectorSDNode::commuteMask(NewMask);
9418       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
9419     }
9420 
9421     if (LegalMask)
9422       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
9423   }
9424 
9425   return SDValue();
9426 }
9427 
9428 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
9429   EVT VT = N->getValueType(0);
9430   return CombineConsecutiveLoads(N, VT);
9431 }
9432 
9433 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
9434 /// operands. DstEltVT indicates the destination element value type.
9435 SDValue DAGCombiner::
9436 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
9437   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
9438 
9439   // If this is already the right type, we're done.
9440   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
9441 
9442   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
9443   unsigned DstBitSize = DstEltVT.getSizeInBits();
9444 
9445   // If this is a conversion of N elements of one type to N elements of another
9446   // type, convert each element.  This handles FP<->INT cases.
9447   if (SrcBitSize == DstBitSize) {
9448     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9449                               BV->getValueType(0).getVectorNumElements());
9450 
9451     // Due to the FP element handling below calling this routine recursively,
9452     // we can end up with a scalar-to-vector node here.
9453     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
9454       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
9455                          DAG.getBitcast(DstEltVT, BV->getOperand(0)));
9456 
9457     SmallVector<SDValue, 8> Ops;
9458     for (SDValue Op : BV->op_values()) {
9459       // If the vector element type is not legal, the BUILD_VECTOR operands
9460       // are promoted and implicitly truncated.  Make that explicit here.
9461       if (Op.getValueType() != SrcEltVT)
9462         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
9463       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
9464       AddToWorklist(Ops.back().getNode());
9465     }
9466     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
9467   }
9468 
9469   // Otherwise, we're growing or shrinking the elements.  To avoid having to
9470   // handle annoying details of growing/shrinking FP values, we convert them to
9471   // int first.
9472   if (SrcEltVT.isFloatingPoint()) {
9473     // Convert the input float vector to a int vector where the elements are the
9474     // same sizes.
9475     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
9476     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
9477     SrcEltVT = IntVT;
9478   }
9479 
9480   // Now we know the input is an integer vector.  If the output is a FP type,
9481   // convert to integer first, then to FP of the right size.
9482   if (DstEltVT.isFloatingPoint()) {
9483     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
9484     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
9485 
9486     // Next, convert to FP elements of the same size.
9487     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
9488   }
9489 
9490   SDLoc DL(BV);
9491 
9492   // Okay, we know the src/dst types are both integers of differing types.
9493   // Handling growing first.
9494   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
9495   if (SrcBitSize < DstBitSize) {
9496     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
9497 
9498     SmallVector<SDValue, 8> Ops;
9499     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
9500          i += NumInputsPerOutput) {
9501       bool isLE = DAG.getDataLayout().isLittleEndian();
9502       APInt NewBits = APInt(DstBitSize, 0);
9503       bool EltIsUndef = true;
9504       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
9505         // Shift the previously computed bits over.
9506         NewBits <<= SrcBitSize;
9507         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
9508         if (Op.isUndef()) continue;
9509         EltIsUndef = false;
9510 
9511         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
9512                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
9513       }
9514 
9515       if (EltIsUndef)
9516         Ops.push_back(DAG.getUNDEF(DstEltVT));
9517       else
9518         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
9519     }
9520 
9521     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
9522     return DAG.getBuildVector(VT, DL, Ops);
9523   }
9524 
9525   // Finally, this must be the case where we are shrinking elements: each input
9526   // turns into multiple outputs.
9527   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
9528   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
9529                             NumOutputsPerInput*BV->getNumOperands());
9530   SmallVector<SDValue, 8> Ops;
9531 
9532   for (const SDValue &Op : BV->op_values()) {
9533     if (Op.isUndef()) {
9534       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
9535       continue;
9536     }
9537 
9538     APInt OpVal = cast<ConstantSDNode>(Op)->
9539                   getAPIntValue().zextOrTrunc(SrcBitSize);
9540 
9541     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
9542       APInt ThisVal = OpVal.trunc(DstBitSize);
9543       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
9544       OpVal.lshrInPlace(DstBitSize);
9545     }
9546 
9547     // For big endian targets, swap the order of the pieces of each element.
9548     if (DAG.getDataLayout().isBigEndian())
9549       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
9550   }
9551 
9552   return DAG.getBuildVector(VT, DL, Ops);
9553 }
9554 
9555 static bool isContractable(SDNode *N) {
9556   SDNodeFlags F = N->getFlags();
9557   return F.hasAllowContract() || F.hasAllowReassociation();
9558 }
9559 
9560 /// Try to perform FMA combining on a given FADD node.
9561 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
9562   SDValue N0 = N->getOperand(0);
9563   SDValue N1 = N->getOperand(1);
9564   EVT VT = N->getValueType(0);
9565   SDLoc SL(N);
9566 
9567   const TargetOptions &Options = DAG.getTarget().Options;
9568 
9569   // Floating-point multiply-add with intermediate rounding.
9570   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9571 
9572   // Floating-point multiply-add without intermediate rounding.
9573   bool HasFMA =
9574       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9575       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9576 
9577   // No valid opcode, do not combine.
9578   if (!HasFMAD && !HasFMA)
9579     return SDValue();
9580 
9581   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9582                               Options.UnsafeFPMath || HasFMAD);
9583   // If the addition is not contractable, do not combine.
9584   if (!AllowFusionGlobally && !isContractable(N))
9585     return SDValue();
9586 
9587   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9588   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9589     return SDValue();
9590 
9591   // Always prefer FMAD to FMA for precision.
9592   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9593   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9594 
9595   // Is the node an FMUL and contractable either due to global flags or
9596   // SDNodeFlags.
9597   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9598     if (N.getOpcode() != ISD::FMUL)
9599       return false;
9600     return AllowFusionGlobally || isContractable(N.getNode());
9601   };
9602   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
9603   // prefer to fold the multiply with fewer uses.
9604   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
9605     if (N0.getNode()->use_size() > N1.getNode()->use_size())
9606       std::swap(N0, N1);
9607   }
9608 
9609   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
9610   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9611     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9612                        N0.getOperand(0), N0.getOperand(1), N1);
9613   }
9614 
9615   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
9616   // Note: Commutes FADD operands.
9617   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
9618     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9619                        N1.getOperand(0), N1.getOperand(1), N0);
9620   }
9621 
9622   // Look through FP_EXTEND nodes to do more combining.
9623 
9624   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
9625   if (N0.getOpcode() == ISD::FP_EXTEND) {
9626     SDValue N00 = N0.getOperand(0);
9627     if (isContractableFMUL(N00) &&
9628         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9629       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9630                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9631                                      N00.getOperand(0)),
9632                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9633                                      N00.getOperand(1)), N1);
9634     }
9635   }
9636 
9637   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
9638   // Note: Commutes FADD operands.
9639   if (N1.getOpcode() == ISD::FP_EXTEND) {
9640     SDValue N10 = N1.getOperand(0);
9641     if (isContractableFMUL(N10) &&
9642         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9643       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9644                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9645                                      N10.getOperand(0)),
9646                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9647                                      N10.getOperand(1)), N0);
9648     }
9649   }
9650 
9651   // More folding opportunities when target permits.
9652   if (Aggressive) {
9653     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9654     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9655     // are currently only supported on binary nodes.
9656     if (Options.UnsafeFPMath &&
9657         N0.getOpcode() == PreferredFusedOpcode &&
9658         N0.getOperand(2).getOpcode() == ISD::FMUL &&
9659         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9660       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9661                          N0.getOperand(0), N0.getOperand(1),
9662                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9663                                      N0.getOperand(2).getOperand(0),
9664                                      N0.getOperand(2).getOperand(1),
9665                                      N1));
9666     }
9667 
9668     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9669     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9670     // are currently only supported on binary nodes.
9671     if (Options.UnsafeFPMath &&
9672         N1->getOpcode() == PreferredFusedOpcode &&
9673         N1.getOperand(2).getOpcode() == ISD::FMUL &&
9674         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9675       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9676                          N1.getOperand(0), N1.getOperand(1),
9677                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9678                                      N1.getOperand(2).getOperand(0),
9679                                      N1.getOperand(2).getOperand(1),
9680                                      N0));
9681     }
9682 
9683 
9684     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9685     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
9686     auto FoldFAddFMAFPExtFMul = [&] (
9687       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9688       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9689                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9690                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9691                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9692                                      Z));
9693     };
9694     if (N0.getOpcode() == PreferredFusedOpcode) {
9695       SDValue N02 = N0.getOperand(2);
9696       if (N02.getOpcode() == ISD::FP_EXTEND) {
9697         SDValue N020 = N02.getOperand(0);
9698         if (isContractableFMUL(N020) &&
9699             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9700           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9701                                       N020.getOperand(0), N020.getOperand(1),
9702                                       N1);
9703         }
9704       }
9705     }
9706 
9707     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9708     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9709     // FIXME: This turns two single-precision and one double-precision
9710     // operation into two double-precision operations, which might not be
9711     // interesting for all targets, especially GPUs.
9712     auto FoldFAddFPExtFMAFMul = [&] (
9713       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9714       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9715                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9716                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9717                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9718                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9719                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9720                                      Z));
9721     };
9722     if (N0.getOpcode() == ISD::FP_EXTEND) {
9723       SDValue N00 = N0.getOperand(0);
9724       if (N00.getOpcode() == PreferredFusedOpcode) {
9725         SDValue N002 = N00.getOperand(2);
9726         if (isContractableFMUL(N002) &&
9727             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9728           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9729                                       N002.getOperand(0), N002.getOperand(1),
9730                                       N1);
9731         }
9732       }
9733     }
9734 
9735     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9736     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
9737     if (N1.getOpcode() == PreferredFusedOpcode) {
9738       SDValue N12 = N1.getOperand(2);
9739       if (N12.getOpcode() == ISD::FP_EXTEND) {
9740         SDValue N120 = N12.getOperand(0);
9741         if (isContractableFMUL(N120) &&
9742             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
9743           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9744                                       N120.getOperand(0), N120.getOperand(1),
9745                                       N0);
9746         }
9747       }
9748     }
9749 
9750     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9751     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9752     // FIXME: This turns two single-precision and one double-precision
9753     // operation into two double-precision operations, which might not be
9754     // interesting for all targets, especially GPUs.
9755     if (N1.getOpcode() == ISD::FP_EXTEND) {
9756       SDValue N10 = N1.getOperand(0);
9757       if (N10.getOpcode() == PreferredFusedOpcode) {
9758         SDValue N102 = N10.getOperand(2);
9759         if (isContractableFMUL(N102) &&
9760             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9761           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9762                                       N102.getOperand(0), N102.getOperand(1),
9763                                       N0);
9764         }
9765       }
9766     }
9767   }
9768 
9769   return SDValue();
9770 }
9771 
9772 /// Try to perform FMA combining on a given FSUB node.
9773 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9774   SDValue N0 = N->getOperand(0);
9775   SDValue N1 = N->getOperand(1);
9776   EVT VT = N->getValueType(0);
9777   SDLoc SL(N);
9778 
9779   const TargetOptions &Options = DAG.getTarget().Options;
9780   // Floating-point multiply-add with intermediate rounding.
9781   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9782 
9783   // Floating-point multiply-add without intermediate rounding.
9784   bool HasFMA =
9785       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9786       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9787 
9788   // No valid opcode, do not combine.
9789   if (!HasFMAD && !HasFMA)
9790     return SDValue();
9791 
9792   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9793                               Options.UnsafeFPMath || HasFMAD);
9794   // If the subtraction is not contractable, do not combine.
9795   if (!AllowFusionGlobally && !isContractable(N))
9796     return SDValue();
9797 
9798   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9799   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9800     return SDValue();
9801 
9802   // Always prefer FMAD to FMA for precision.
9803   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9804   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9805 
9806   // Is the node an FMUL and contractable either due to global flags or
9807   // SDNodeFlags.
9808   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9809     if (N.getOpcode() != ISD::FMUL)
9810       return false;
9811     return AllowFusionGlobally || isContractable(N.getNode());
9812   };
9813 
9814   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9815   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9816     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9817                        N0.getOperand(0), N0.getOperand(1),
9818                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9819   }
9820 
9821   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9822   // Note: Commutes FSUB operands.
9823   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9824     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9825                        DAG.getNode(ISD::FNEG, SL, VT,
9826                                    N1.getOperand(0)),
9827                        N1.getOperand(1), N0);
9828 
9829   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9830   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9831       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9832     SDValue N00 = N0.getOperand(0).getOperand(0);
9833     SDValue N01 = N0.getOperand(0).getOperand(1);
9834     return DAG.getNode(PreferredFusedOpcode, SL, VT,
9835                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9836                        DAG.getNode(ISD::FNEG, SL, VT, N1));
9837   }
9838 
9839   // Look through FP_EXTEND nodes to do more combining.
9840 
9841   // fold (fsub (fpext (fmul x, y)), z)
9842   //   -> (fma (fpext x), (fpext y), (fneg z))
9843   if (N0.getOpcode() == ISD::FP_EXTEND) {
9844     SDValue N00 = N0.getOperand(0);
9845     if (isContractableFMUL(N00) &&
9846         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9847       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9848                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9849                                      N00.getOperand(0)),
9850                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9851                                      N00.getOperand(1)),
9852                          DAG.getNode(ISD::FNEG, SL, VT, N1));
9853     }
9854   }
9855 
9856   // fold (fsub x, (fpext (fmul y, z)))
9857   //   -> (fma (fneg (fpext y)), (fpext z), x)
9858   // Note: Commutes FSUB operands.
9859   if (N1.getOpcode() == ISD::FP_EXTEND) {
9860     SDValue N10 = N1.getOperand(0);
9861     if (isContractableFMUL(N10) &&
9862         TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) {
9863       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9864                          DAG.getNode(ISD::FNEG, SL, VT,
9865                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
9866                                                  N10.getOperand(0))),
9867                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9868                                      N10.getOperand(1)),
9869                          N0);
9870     }
9871   }
9872 
9873   // fold (fsub (fpext (fneg (fmul, x, y))), z)
9874   //   -> (fneg (fma (fpext x), (fpext y), z))
9875   // Note: This could be removed with appropriate canonicalization of the
9876   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9877   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9878   // from implementing the canonicalization in visitFSUB.
9879   if (N0.getOpcode() == ISD::FP_EXTEND) {
9880     SDValue N00 = N0.getOperand(0);
9881     if (N00.getOpcode() == ISD::FNEG) {
9882       SDValue N000 = N00.getOperand(0);
9883       if (isContractableFMUL(N000) &&
9884           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9885         return DAG.getNode(ISD::FNEG, SL, VT,
9886                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9887                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9888                                                    N000.getOperand(0)),
9889                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9890                                                    N000.getOperand(1)),
9891                                        N1));
9892       }
9893     }
9894   }
9895 
9896   // fold (fsub (fneg (fpext (fmul, x, y))), z)
9897   //   -> (fneg (fma (fpext x)), (fpext y), z)
9898   // Note: This could be removed with appropriate canonicalization of the
9899   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9900   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9901   // from implementing the canonicalization in visitFSUB.
9902   if (N0.getOpcode() == ISD::FNEG) {
9903     SDValue N00 = N0.getOperand(0);
9904     if (N00.getOpcode() == ISD::FP_EXTEND) {
9905       SDValue N000 = N00.getOperand(0);
9906       if (isContractableFMUL(N000) &&
9907           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) {
9908         return DAG.getNode(ISD::FNEG, SL, VT,
9909                            DAG.getNode(PreferredFusedOpcode, SL, VT,
9910                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9911                                                    N000.getOperand(0)),
9912                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
9913                                                    N000.getOperand(1)),
9914                                        N1));
9915       }
9916     }
9917   }
9918 
9919   // More folding opportunities when target permits.
9920   if (Aggressive) {
9921     // fold (fsub (fma x, y, (fmul u, v)), z)
9922     //   -> (fma x, y (fma u, v, (fneg z)))
9923     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9924     // are currently only supported on binary nodes.
9925     if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9926         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9927         N0.getOperand(2)->hasOneUse()) {
9928       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9929                          N0.getOperand(0), N0.getOperand(1),
9930                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9931                                      N0.getOperand(2).getOperand(0),
9932                                      N0.getOperand(2).getOperand(1),
9933                                      DAG.getNode(ISD::FNEG, SL, VT,
9934                                                  N1)));
9935     }
9936 
9937     // fold (fsub x, (fma y, z, (fmul u, v)))
9938     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
9939     // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9940     // are currently only supported on binary nodes.
9941     if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9942         isContractableFMUL(N1.getOperand(2))) {
9943       SDValue N20 = N1.getOperand(2).getOperand(0);
9944       SDValue N21 = N1.getOperand(2).getOperand(1);
9945       return DAG.getNode(PreferredFusedOpcode, SL, VT,
9946                          DAG.getNode(ISD::FNEG, SL, VT,
9947                                      N1.getOperand(0)),
9948                          N1.getOperand(1),
9949                          DAG.getNode(PreferredFusedOpcode, SL, VT,
9950                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
9951 
9952                                      N21, N0));
9953     }
9954 
9955 
9956     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9957     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9958     if (N0.getOpcode() == PreferredFusedOpcode) {
9959       SDValue N02 = N0.getOperand(2);
9960       if (N02.getOpcode() == ISD::FP_EXTEND) {
9961         SDValue N020 = N02.getOperand(0);
9962         if (isContractableFMUL(N020) &&
9963             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) {
9964           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9965                              N0.getOperand(0), N0.getOperand(1),
9966                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9967                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9968                                                      N020.getOperand(0)),
9969                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9970                                                      N020.getOperand(1)),
9971                                          DAG.getNode(ISD::FNEG, SL, VT,
9972                                                      N1)));
9973         }
9974       }
9975     }
9976 
9977     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9978     //   -> (fma (fpext x), (fpext y),
9979     //           (fma (fpext u), (fpext v), (fneg z)))
9980     // FIXME: This turns two single-precision and one double-precision
9981     // operation into two double-precision operations, which might not be
9982     // interesting for all targets, especially GPUs.
9983     if (N0.getOpcode() == ISD::FP_EXTEND) {
9984       SDValue N00 = N0.getOperand(0);
9985       if (N00.getOpcode() == PreferredFusedOpcode) {
9986         SDValue N002 = N00.getOperand(2);
9987         if (isContractableFMUL(N002) &&
9988             TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) {
9989           return DAG.getNode(PreferredFusedOpcode, SL, VT,
9990                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9991                                          N00.getOperand(0)),
9992                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
9993                                          N00.getOperand(1)),
9994                              DAG.getNode(PreferredFusedOpcode, SL, VT,
9995                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9996                                                      N002.getOperand(0)),
9997                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
9998                                                      N002.getOperand(1)),
9999                                          DAG.getNode(ISD::FNEG, SL, VT,
10000                                                      N1)));
10001         }
10002       }
10003     }
10004 
10005     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
10006     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
10007     if (N1.getOpcode() == PreferredFusedOpcode &&
10008         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
10009       SDValue N120 = N1.getOperand(2).getOperand(0);
10010       if (isContractableFMUL(N120) &&
10011           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) {
10012         SDValue N1200 = N120.getOperand(0);
10013         SDValue N1201 = N120.getOperand(1);
10014         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10015                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
10016                            N1.getOperand(1),
10017                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10018                                        DAG.getNode(ISD::FNEG, SL, VT,
10019                                                    DAG.getNode(ISD::FP_EXTEND, SL,
10020                                                                VT, N1200)),
10021                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10022                                                    N1201),
10023                                        N0));
10024       }
10025     }
10026 
10027     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
10028     //   -> (fma (fneg (fpext y)), (fpext z),
10029     //           (fma (fneg (fpext u)), (fpext v), x))
10030     // FIXME: This turns two single-precision and one double-precision
10031     // operation into two double-precision operations, which might not be
10032     // interesting for all targets, especially GPUs.
10033     if (N1.getOpcode() == ISD::FP_EXTEND &&
10034         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
10035       SDValue CvtSrc = N1.getOperand(0);
10036       SDValue N100 = CvtSrc.getOperand(0);
10037       SDValue N101 = CvtSrc.getOperand(1);
10038       SDValue N102 = CvtSrc.getOperand(2);
10039       if (isContractableFMUL(N102) &&
10040           TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) {
10041         SDValue N1020 = N102.getOperand(0);
10042         SDValue N1021 = N102.getOperand(1);
10043         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10044                            DAG.getNode(ISD::FNEG, SL, VT,
10045                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10046                                                    N100)),
10047                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
10048                            DAG.getNode(PreferredFusedOpcode, SL, VT,
10049                                        DAG.getNode(ISD::FNEG, SL, VT,
10050                                                    DAG.getNode(ISD::FP_EXTEND, SL,
10051                                                                VT, N1020)),
10052                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
10053                                                    N1021),
10054                                        N0));
10055       }
10056     }
10057   }
10058 
10059   return SDValue();
10060 }
10061 
10062 /// Try to perform FMA combining on a given FMUL node based on the distributive
10063 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
10064 /// subtraction instead of addition).
10065 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
10066   SDValue N0 = N->getOperand(0);
10067   SDValue N1 = N->getOperand(1);
10068   EVT VT = N->getValueType(0);
10069   SDLoc SL(N);
10070 
10071   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
10072 
10073   const TargetOptions &Options = DAG.getTarget().Options;
10074 
10075   // The transforms below are incorrect when x == 0 and y == inf, because the
10076   // intermediate multiplication produces a nan.
10077   if (!Options.NoInfsFPMath)
10078     return SDValue();
10079 
10080   // Floating-point multiply-add without intermediate rounding.
10081   bool HasFMA =
10082       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
10083       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
10084       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
10085 
10086   // Floating-point multiply-add with intermediate rounding. This can result
10087   // in a less precise result due to the changed rounding order.
10088   bool HasFMAD = Options.UnsafeFPMath &&
10089                  (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
10090 
10091   // No valid opcode, do not combine.
10092   if (!HasFMAD && !HasFMA)
10093     return SDValue();
10094 
10095   // Always prefer FMAD to FMA for precision.
10096   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
10097   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
10098 
10099   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
10100   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
10101   auto FuseFADD = [&](SDValue X, SDValue Y) {
10102     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
10103       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10104       if (XC1 && XC1->isExactlyValue(+1.0))
10105         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
10106       if (XC1 && XC1->isExactlyValue(-1.0))
10107         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10108                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10109     }
10110     return SDValue();
10111   };
10112 
10113   if (SDValue FMA = FuseFADD(N0, N1))
10114     return FMA;
10115   if (SDValue FMA = FuseFADD(N1, N0))
10116     return FMA;
10117 
10118   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
10119   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
10120   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
10121   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
10122   auto FuseFSUB = [&](SDValue X, SDValue Y) {
10123     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
10124       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
10125       if (XC0 && XC0->isExactlyValue(+1.0))
10126         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10127                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10128                            Y);
10129       if (XC0 && XC0->isExactlyValue(-1.0))
10130         return DAG.getNode(PreferredFusedOpcode, SL, VT,
10131                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
10132                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10133 
10134       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
10135       if (XC1 && XC1->isExactlyValue(+1.0))
10136         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
10137                            DAG.getNode(ISD::FNEG, SL, VT, Y));
10138       if (XC1 && XC1->isExactlyValue(-1.0))
10139         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
10140     }
10141     return SDValue();
10142   };
10143 
10144   if (SDValue FMA = FuseFSUB(N0, N1))
10145     return FMA;
10146   if (SDValue FMA = FuseFSUB(N1, N0))
10147     return FMA;
10148 
10149   return SDValue();
10150 }
10151 
10152 static bool isFMulNegTwo(SDValue &N) {
10153   if (N.getOpcode() != ISD::FMUL)
10154     return false;
10155   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
10156     return CFP->isExactlyValue(-2.0);
10157   return false;
10158 }
10159 
10160 SDValue DAGCombiner::visitFADD(SDNode *N) {
10161   SDValue N0 = N->getOperand(0);
10162   SDValue N1 = N->getOperand(1);
10163   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
10164   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
10165   EVT VT = N->getValueType(0);
10166   SDLoc DL(N);
10167   const TargetOptions &Options = DAG.getTarget().Options;
10168   const SDNodeFlags Flags = N->getFlags();
10169 
10170   // fold vector ops
10171   if (VT.isVector())
10172     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10173       return FoldedVOp;
10174 
10175   // fold (fadd c1, c2) -> c1 + c2
10176   if (N0CFP && N1CFP)
10177     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
10178 
10179   // canonicalize constant to RHS
10180   if (N0CFP && !N1CFP)
10181     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
10182 
10183   if (SDValue NewSel = foldBinOpIntoSelect(N))
10184     return NewSel;
10185 
10186   // fold (fadd A, (fneg B)) -> (fsub A, B)
10187   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10188       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
10189     return DAG.getNode(ISD::FSUB, DL, VT, N0,
10190                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10191 
10192   // fold (fadd (fneg A), B) -> (fsub B, A)
10193   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
10194       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
10195     return DAG.getNode(ISD::FSUB, DL, VT, N1,
10196                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
10197 
10198   // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
10199   // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
10200   if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
10201       (isFMulNegTwo(N1) && N1.hasOneUse())) {
10202     bool N1IsFMul = isFMulNegTwo(N1);
10203     SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
10204     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
10205     return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
10206   }
10207 
10208   // FIXME: Auto-upgrade the target/function-level option.
10209   if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
10210     // fold (fadd A, 0) -> A
10211     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
10212       if (N1C->isZero())
10213         return N0;
10214   }
10215 
10216   // If 'unsafe math' is enabled, fold lots of things.
10217   if (Options.UnsafeFPMath) {
10218     // No FP constant should be created after legalization as Instruction
10219     // Selection pass has a hard time dealing with FP constants.
10220     bool AllowNewConst = (Level < AfterLegalizeDAG);
10221 
10222     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
10223     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
10224         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
10225       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
10226                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
10227                                      Flags),
10228                          Flags);
10229 
10230     // If allowed, fold (fadd (fneg x), x) -> 0.0
10231     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
10232       return DAG.getConstantFP(0.0, DL, VT);
10233 
10234     // If allowed, fold (fadd x, (fneg x)) -> 0.0
10235     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
10236       return DAG.getConstantFP(0.0, DL, VT);
10237 
10238     // We can fold chains of FADD's of the same value into multiplications.
10239     // This transform is not safe in general because we are reducing the number
10240     // of rounding steps.
10241     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
10242       if (N0.getOpcode() == ISD::FMUL) {
10243         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10244         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
10245 
10246         // (fadd (fmul x, c), x) -> (fmul x, c+1)
10247         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
10248           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10249                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10250           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
10251         }
10252 
10253         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
10254         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
10255             N1.getOperand(0) == N1.getOperand(1) &&
10256             N0.getOperand(0) == N1.getOperand(0)) {
10257           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
10258                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10259           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
10260         }
10261       }
10262 
10263       if (N1.getOpcode() == ISD::FMUL) {
10264         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10265         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
10266 
10267         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
10268         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
10269           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10270                                        DAG.getConstantFP(1.0, DL, VT), Flags);
10271           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
10272         }
10273 
10274         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
10275         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
10276             N0.getOperand(0) == N0.getOperand(1) &&
10277             N1.getOperand(0) == N0.getOperand(0)) {
10278           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
10279                                        DAG.getConstantFP(2.0, DL, VT), Flags);
10280           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
10281         }
10282       }
10283 
10284       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
10285         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
10286         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
10287         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
10288             (N0.getOperand(0) == N1)) {
10289           return DAG.getNode(ISD::FMUL, DL, VT,
10290                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
10291         }
10292       }
10293 
10294       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
10295         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
10296         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
10297         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
10298             N1.getOperand(0) == N0) {
10299           return DAG.getNode(ISD::FMUL, DL, VT,
10300                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
10301         }
10302       }
10303 
10304       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
10305       if (AllowNewConst &&
10306           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
10307           N0.getOperand(0) == N0.getOperand(1) &&
10308           N1.getOperand(0) == N1.getOperand(1) &&
10309           N0.getOperand(0) == N1.getOperand(0)) {
10310         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
10311                            DAG.getConstantFP(4.0, DL, VT), Flags);
10312       }
10313     }
10314   } // enable-unsafe-fp-math
10315 
10316   // FADD -> FMA combines:
10317   if (SDValue Fused = visitFADDForFMACombine(N)) {
10318     AddToWorklist(Fused.getNode());
10319     return Fused;
10320   }
10321   return SDValue();
10322 }
10323 
10324 SDValue DAGCombiner::visitFSUB(SDNode *N) {
10325   SDValue N0 = N->getOperand(0);
10326   SDValue N1 = N->getOperand(1);
10327   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10328   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10329   EVT VT = N->getValueType(0);
10330   SDLoc DL(N);
10331   const TargetOptions &Options = DAG.getTarget().Options;
10332   const SDNodeFlags Flags = N->getFlags();
10333 
10334   // fold vector ops
10335   if (VT.isVector())
10336     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10337       return FoldedVOp;
10338 
10339   // fold (fsub c1, c2) -> c1-c2
10340   if (N0CFP && N1CFP)
10341     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
10342 
10343   if (SDValue NewSel = foldBinOpIntoSelect(N))
10344     return NewSel;
10345 
10346   // fold (fsub A, (fneg B)) -> (fadd A, B)
10347   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10348     return DAG.getNode(ISD::FADD, DL, VT, N0,
10349                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
10350 
10351   // FIXME: Auto-upgrade the target/function-level option.
10352   if (Options.NoSignedZerosFPMath  || N->getFlags().hasNoSignedZeros()) {
10353     // (fsub 0, B) -> -B
10354     if (N0CFP && N0CFP->isZero()) {
10355       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
10356         return GetNegatedExpression(N1, DAG, LegalOperations);
10357       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10358         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
10359     }
10360   }
10361 
10362   // If 'unsafe math' is enabled, fold lots of things.
10363   if (Options.UnsafeFPMath) {
10364     // (fsub A, 0) -> A
10365     if (N1CFP && N1CFP->isZero())
10366       return N0;
10367 
10368     // (fsub x, x) -> 0.0
10369     if (N0 == N1)
10370       return DAG.getConstantFP(0.0f, DL, VT);
10371 
10372     // (fsub x, (fadd x, y)) -> (fneg y)
10373     // (fsub x, (fadd y, x)) -> (fneg y)
10374     if (N1.getOpcode() == ISD::FADD) {
10375       SDValue N10 = N1->getOperand(0);
10376       SDValue N11 = N1->getOperand(1);
10377 
10378       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
10379         return GetNegatedExpression(N11, DAG, LegalOperations);
10380 
10381       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
10382         return GetNegatedExpression(N10, DAG, LegalOperations);
10383     }
10384   }
10385 
10386   // FSUB -> FMA combines:
10387   if (SDValue Fused = visitFSUBForFMACombine(N)) {
10388     AddToWorklist(Fused.getNode());
10389     return Fused;
10390   }
10391 
10392   return SDValue();
10393 }
10394 
10395 SDValue DAGCombiner::visitFMUL(SDNode *N) {
10396   SDValue N0 = N->getOperand(0);
10397   SDValue N1 = N->getOperand(1);
10398   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10399   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10400   EVT VT = N->getValueType(0);
10401   SDLoc DL(N);
10402   const TargetOptions &Options = DAG.getTarget().Options;
10403   const SDNodeFlags Flags = N->getFlags();
10404 
10405   // fold vector ops
10406   if (VT.isVector()) {
10407     // This just handles C1 * C2 for vectors. Other vector folds are below.
10408     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10409       return FoldedVOp;
10410   }
10411 
10412   // fold (fmul c1, c2) -> c1*c2
10413   if (N0CFP && N1CFP)
10414     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
10415 
10416   // canonicalize constant to RHS
10417   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10418      !isConstantFPBuildVectorOrConstantFP(N1))
10419     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
10420 
10421   // fold (fmul A, 1.0) -> A
10422   if (N1CFP && N1CFP->isExactlyValue(1.0))
10423     return N0;
10424 
10425   if (SDValue NewSel = foldBinOpIntoSelect(N))
10426     return NewSel;
10427 
10428   if (Options.UnsafeFPMath) {
10429     // fold (fmul A, 0) -> 0
10430     if (N1CFP && N1CFP->isZero())
10431       return N1;
10432 
10433     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
10434     if (N0.getOpcode() == ISD::FMUL) {
10435       // Fold scalars or any vector constants (not just splats).
10436       // This fold is done in general by InstCombine, but extra fmul insts
10437       // may have been generated during lowering.
10438       SDValue N00 = N0.getOperand(0);
10439       SDValue N01 = N0.getOperand(1);
10440       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
10441       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
10442       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
10443 
10444       // Check 1: Make sure that the first operand of the inner multiply is NOT
10445       // a constant. Otherwise, we may induce infinite looping.
10446       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
10447         // Check 2: Make sure that the second operand of the inner multiply and
10448         // the second operand of the outer multiply are constants.
10449         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
10450             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
10451           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
10452           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
10453         }
10454       }
10455     }
10456 
10457     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
10458     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
10459     // during an early run of DAGCombiner can prevent folding with fmuls
10460     // inserted during lowering.
10461     if (N0.getOpcode() == ISD::FADD &&
10462         (N0.getOperand(0) == N0.getOperand(1)) &&
10463         N0.hasOneUse()) {
10464       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
10465       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
10466       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
10467     }
10468   }
10469 
10470   // fold (fmul X, 2.0) -> (fadd X, X)
10471   if (N1CFP && N1CFP->isExactlyValue(+2.0))
10472     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
10473 
10474   // fold (fmul X, -1.0) -> (fneg X)
10475   if (N1CFP && N1CFP->isExactlyValue(-1.0))
10476     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10477       return DAG.getNode(ISD::FNEG, DL, VT, N0);
10478 
10479   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
10480   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10481     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10482       // Both can be negated for free, check to see if at least one is cheaper
10483       // negated.
10484       if (LHSNeg == 2 || RHSNeg == 2)
10485         return DAG.getNode(ISD::FMUL, DL, VT,
10486                            GetNegatedExpression(N0, DAG, LegalOperations),
10487                            GetNegatedExpression(N1, DAG, LegalOperations),
10488                            Flags);
10489     }
10490   }
10491 
10492   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
10493   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
10494   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
10495       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
10496       TLI.isOperationLegal(ISD::FABS, VT)) {
10497     SDValue Select = N0, X = N1;
10498     if (Select.getOpcode() != ISD::SELECT)
10499       std::swap(Select, X);
10500 
10501     SDValue Cond = Select.getOperand(0);
10502     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
10503     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
10504 
10505     if (TrueOpnd && FalseOpnd &&
10506         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
10507         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
10508         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
10509       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10510       switch (CC) {
10511       default: break;
10512       case ISD::SETOLT:
10513       case ISD::SETULT:
10514       case ISD::SETOLE:
10515       case ISD::SETULE:
10516       case ISD::SETLT:
10517       case ISD::SETLE:
10518         std::swap(TrueOpnd, FalseOpnd);
10519         LLVM_FALLTHROUGH;
10520       case ISD::SETOGT:
10521       case ISD::SETUGT:
10522       case ISD::SETOGE:
10523       case ISD::SETUGE:
10524       case ISD::SETGT:
10525       case ISD::SETGE:
10526         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
10527             TLI.isOperationLegal(ISD::FNEG, VT))
10528           return DAG.getNode(ISD::FNEG, DL, VT,
10529                    DAG.getNode(ISD::FABS, DL, VT, X));
10530         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
10531           return DAG.getNode(ISD::FABS, DL, VT, X);
10532 
10533         break;
10534       }
10535     }
10536   }
10537 
10538   // FMUL -> FMA combines:
10539   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
10540     AddToWorklist(Fused.getNode());
10541     return Fused;
10542   }
10543 
10544   return SDValue();
10545 }
10546 
10547 SDValue DAGCombiner::visitFMA(SDNode *N) {
10548   SDValue N0 = N->getOperand(0);
10549   SDValue N1 = N->getOperand(1);
10550   SDValue N2 = N->getOperand(2);
10551   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10552   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10553   EVT VT = N->getValueType(0);
10554   SDLoc DL(N);
10555   const TargetOptions &Options = DAG.getTarget().Options;
10556 
10557   // Constant fold FMA.
10558   if (isa<ConstantFPSDNode>(N0) &&
10559       isa<ConstantFPSDNode>(N1) &&
10560       isa<ConstantFPSDNode>(N2)) {
10561     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
10562   }
10563 
10564   if (Options.UnsafeFPMath) {
10565     if (N0CFP && N0CFP->isZero())
10566       return N2;
10567     if (N1CFP && N1CFP->isZero())
10568       return N2;
10569   }
10570   // TODO: The FMA node should have flags that propagate to these nodes.
10571   if (N0CFP && N0CFP->isExactlyValue(1.0))
10572     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
10573   if (N1CFP && N1CFP->isExactlyValue(1.0))
10574     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
10575 
10576   // Canonicalize (fma c, x, y) -> (fma x, c, y)
10577   if (isConstantFPBuildVectorOrConstantFP(N0) &&
10578      !isConstantFPBuildVectorOrConstantFP(N1))
10579     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
10580 
10581   // TODO: FMA nodes should have flags that propagate to the created nodes.
10582   // For now, create a Flags object for use with reassociation math transforms.
10583   SDNodeFlags Flags;
10584   Flags.setAllowReassociation(true);
10585 
10586   if (Options.UnsafeFPMath) {
10587     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
10588     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
10589         isConstantFPBuildVectorOrConstantFP(N1) &&
10590         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
10591       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10592                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
10593                                      Flags), Flags);
10594     }
10595 
10596     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
10597     if (N0.getOpcode() == ISD::FMUL &&
10598         isConstantFPBuildVectorOrConstantFP(N1) &&
10599         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
10600       return DAG.getNode(ISD::FMA, DL, VT,
10601                          N0.getOperand(0),
10602                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
10603                                      Flags),
10604                          N2);
10605     }
10606   }
10607 
10608   // (fma x, 1, y) -> (fadd x, y)
10609   // (fma x, -1, y) -> (fadd (fneg x), y)
10610   if (N1CFP) {
10611     if (N1CFP->isExactlyValue(1.0))
10612       // TODO: The FMA node should have flags that propagate to this node.
10613       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
10614 
10615     if (N1CFP->isExactlyValue(-1.0) &&
10616         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
10617       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
10618       AddToWorklist(RHSNeg.getNode());
10619       // TODO: The FMA node should have flags that propagate to this node.
10620       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
10621     }
10622 
10623     // fma (fneg x), K, y -> fma x -K, y
10624     if (N0.getOpcode() == ISD::FNEG &&
10625         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10626          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT)))) {
10627       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
10628                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
10629     }
10630   }
10631 
10632   if (Options.UnsafeFPMath) {
10633     // (fma x, c, x) -> (fmul x, (c+1))
10634     if (N1CFP && N0 == N2) {
10635       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10636                          DAG.getNode(ISD::FADD, DL, VT, N1,
10637                                      DAG.getConstantFP(1.0, DL, VT), Flags),
10638                          Flags);
10639     }
10640 
10641     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
10642     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
10643       return DAG.getNode(ISD::FMUL, DL, VT, N0,
10644                          DAG.getNode(ISD::FADD, DL, VT, N1,
10645                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
10646                          Flags);
10647     }
10648   }
10649 
10650   return SDValue();
10651 }
10652 
10653 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10654 // reciprocal.
10655 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
10656 // Notice that this is not always beneficial. One reason is different targets
10657 // may have different costs for FDIV and FMUL, so sometimes the cost of two
10658 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
10659 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
10660 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
10661   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
10662   const SDNodeFlags Flags = N->getFlags();
10663   if (!UnsafeMath && !Flags.hasAllowReciprocal())
10664     return SDValue();
10665 
10666   // Skip if current node is a reciprocal.
10667   SDValue N0 = N->getOperand(0);
10668   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10669   if (N0CFP && N0CFP->isExactlyValue(1.0))
10670     return SDValue();
10671 
10672   // Exit early if the target does not want this transform or if there can't
10673   // possibly be enough uses of the divisor to make the transform worthwhile.
10674   SDValue N1 = N->getOperand(1);
10675   unsigned MinUses = TLI.combineRepeatedFPDivisors();
10676   if (!MinUses || N1->use_size() < MinUses)
10677     return SDValue();
10678 
10679   // Find all FDIV users of the same divisor.
10680   // Use a set because duplicates may be present in the user list.
10681   SetVector<SDNode *> Users;
10682   for (auto *U : N1->uses()) {
10683     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10684       // This division is eligible for optimization only if global unsafe math
10685       // is enabled or if this division allows reciprocal formation.
10686       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10687         Users.insert(U);
10688     }
10689   }
10690 
10691   // Now that we have the actual number of divisor uses, make sure it meets
10692   // the minimum threshold specified by the target.
10693   if (Users.size() < MinUses)
10694     return SDValue();
10695 
10696   EVT VT = N->getValueType(0);
10697   SDLoc DL(N);
10698   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10699   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10700 
10701   // Dividend / Divisor -> Dividend * Reciprocal
10702   for (auto *U : Users) {
10703     SDValue Dividend = U->getOperand(0);
10704     if (Dividend != FPOne) {
10705       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10706                                     Reciprocal, Flags);
10707       CombineTo(U, NewNode);
10708     } else if (U != Reciprocal.getNode()) {
10709       // In the absence of fast-math-flags, this user node is always the
10710       // same node as Reciprocal, but with FMF they may be different nodes.
10711       CombineTo(U, Reciprocal);
10712     }
10713   }
10714   return SDValue(N, 0);  // N was replaced.
10715 }
10716 
10717 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10718   SDValue N0 = N->getOperand(0);
10719   SDValue N1 = N->getOperand(1);
10720   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10721   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10722   EVT VT = N->getValueType(0);
10723   SDLoc DL(N);
10724   const TargetOptions &Options = DAG.getTarget().Options;
10725   SDNodeFlags Flags = N->getFlags();
10726 
10727   // fold vector ops
10728   if (VT.isVector())
10729     if (SDValue FoldedVOp = SimplifyVBinOp(N))
10730       return FoldedVOp;
10731 
10732   // fold (fdiv c1, c2) -> c1/c2
10733   if (N0CFP && N1CFP)
10734     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10735 
10736   if (SDValue NewSel = foldBinOpIntoSelect(N))
10737     return NewSel;
10738 
10739   if (Options.UnsafeFPMath) {
10740     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10741     if (N1CFP) {
10742       // Compute the reciprocal 1.0 / c2.
10743       const APFloat &N1APF = N1CFP->getValueAPF();
10744       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10745       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10746       // Only do the transform if the reciprocal is a legal fp immediate that
10747       // isn't too nasty (eg NaN, denormal, ...).
10748       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10749           (!LegalOperations ||
10750            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10751            // backend)... we should handle this gracefully after Legalize.
10752            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
10753            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
10754            TLI.isFPImmLegal(Recip, VT)))
10755         return DAG.getNode(ISD::FMUL, DL, VT, N0,
10756                            DAG.getConstantFP(Recip, DL, VT), Flags);
10757     }
10758 
10759     // If this FDIV is part of a reciprocal square root, it may be folded
10760     // into a target-specific square root estimate instruction.
10761     if (N1.getOpcode() == ISD::FSQRT) {
10762       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10763         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10764       }
10765     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10766                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10767       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10768                                           Flags)) {
10769         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10770         AddToWorklist(RV.getNode());
10771         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10772       }
10773     } else if (N1.getOpcode() == ISD::FP_ROUND &&
10774                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10775       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10776                                           Flags)) {
10777         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10778         AddToWorklist(RV.getNode());
10779         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10780       }
10781     } else if (N1.getOpcode() == ISD::FMUL) {
10782       // Look through an FMUL. Even though this won't remove the FDIV directly,
10783       // it's still worthwhile to get rid of the FSQRT if possible.
10784       SDValue SqrtOp;
10785       SDValue OtherOp;
10786       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10787         SqrtOp = N1.getOperand(0);
10788         OtherOp = N1.getOperand(1);
10789       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10790         SqrtOp = N1.getOperand(1);
10791         OtherOp = N1.getOperand(0);
10792       }
10793       if (SqrtOp.getNode()) {
10794         // We found a FSQRT, so try to make this fold:
10795         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10796         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10797           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10798           AddToWorklist(RV.getNode());
10799           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10800         }
10801       }
10802     }
10803 
10804     // Fold into a reciprocal estimate and multiply instead of a real divide.
10805     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10806       AddToWorklist(RV.getNode());
10807       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10808     }
10809   }
10810 
10811   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10812   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10813     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10814       // Both can be negated for free, check to see if at least one is cheaper
10815       // negated.
10816       if (LHSNeg == 2 || RHSNeg == 2)
10817         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10818                            GetNegatedExpression(N0, DAG, LegalOperations),
10819                            GetNegatedExpression(N1, DAG, LegalOperations),
10820                            Flags);
10821     }
10822   }
10823 
10824   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10825     return CombineRepeatedDivisors;
10826 
10827   return SDValue();
10828 }
10829 
10830 SDValue DAGCombiner::visitFREM(SDNode *N) {
10831   SDValue N0 = N->getOperand(0);
10832   SDValue N1 = N->getOperand(1);
10833   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10834   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10835   EVT VT = N->getValueType(0);
10836 
10837   // fold (frem c1, c2) -> fmod(c1,c2)
10838   if (N0CFP && N1CFP)
10839     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10840 
10841   if (SDValue NewSel = foldBinOpIntoSelect(N))
10842     return NewSel;
10843 
10844   return SDValue();
10845 }
10846 
10847 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10848   if (!DAG.getTarget().Options.UnsafeFPMath)
10849     return SDValue();
10850 
10851   SDValue N0 = N->getOperand(0);
10852   if (TLI.isFsqrtCheap(N0, DAG))
10853     return SDValue();
10854 
10855   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10856   // For now, create a Flags object for use with reassociation math transforms.
10857   SDNodeFlags Flags;
10858   Flags.setAllowReassociation(true);
10859   return buildSqrtEstimate(N0, Flags);
10860 }
10861 
10862 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10863 /// copysign(x, fp_round(y)) -> copysign(x, y)
10864 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10865   SDValue N1 = N->getOperand(1);
10866   if ((N1.getOpcode() == ISD::FP_EXTEND ||
10867        N1.getOpcode() == ISD::FP_ROUND)) {
10868     // Do not optimize out type conversion of f128 type yet.
10869     // For some targets like x86_64, configuration is changed to keep one f128
10870     // value in one SSE register, but instruction selection cannot handle
10871     // FCOPYSIGN on SSE registers yet.
10872     EVT N1VT = N1->getValueType(0);
10873     EVT N1Op0VT = N1->getOperand(0).getValueType();
10874     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10875   }
10876   return false;
10877 }
10878 
10879 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10880   SDValue N0 = N->getOperand(0);
10881   SDValue N1 = N->getOperand(1);
10882   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10883   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10884   EVT VT = N->getValueType(0);
10885 
10886   if (N0CFP && N1CFP) // Constant fold
10887     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10888 
10889   if (N1CFP) {
10890     const APFloat &V = N1CFP->getValueAPF();
10891     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
10892     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10893     if (!V.isNegative()) {
10894       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10895         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10896     } else {
10897       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10898         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10899                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10900     }
10901   }
10902 
10903   // copysign(fabs(x), y) -> copysign(x, y)
10904   // copysign(fneg(x), y) -> copysign(x, y)
10905   // copysign(copysign(x,z), y) -> copysign(x, y)
10906   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10907       N0.getOpcode() == ISD::FCOPYSIGN)
10908     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10909 
10910   // copysign(x, abs(y)) -> abs(x)
10911   if (N1.getOpcode() == ISD::FABS)
10912     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10913 
10914   // copysign(x, copysign(y,z)) -> copysign(x, z)
10915   if (N1.getOpcode() == ISD::FCOPYSIGN)
10916     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10917 
10918   // copysign(x, fp_extend(y)) -> copysign(x, y)
10919   // copysign(x, fp_round(y)) -> copysign(x, y)
10920   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10921     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10922 
10923   return SDValue();
10924 }
10925 
10926 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
10927                                const TargetLowering &TLI) {
10928   // This optimization is guarded by a function attribute because it may produce
10929   // unexpected results. Ie, programs may be relying on the platform-specific
10930   // undefined behavior when the float-to-int conversion overflows.
10931   const Function &F = DAG.getMachineFunction().getFunction();
10932   Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow");
10933   if (StrictOverflow.getValueAsString().equals("false"))
10934     return SDValue();
10935 
10936   // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
10937   // replacing casts with a libcall.
10938   EVT VT = N->getValueType(0);
10939   if (!TLI.isOperationLegal(ISD::FTRUNC, VT))
10940     return SDValue();
10941 
10942   // fptosi/fptoui round towards zero, so converting from FP to integer and
10943   // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
10944   SDValue N0 = N->getOperand(0);
10945   if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
10946       N0.getOperand(0).getValueType() == VT)
10947     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
10948 
10949   if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
10950       N0.getOperand(0).getValueType() == VT)
10951     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
10952 
10953   return SDValue();
10954 }
10955 
10956 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10957   SDValue N0 = N->getOperand(0);
10958   EVT VT = N->getValueType(0);
10959   EVT OpVT = N0.getValueType();
10960 
10961   // fold (sint_to_fp c1) -> c1fp
10962   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10963       // ...but only if the target supports immediate floating-point values
10964       (!LegalOperations ||
10965        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
10966     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10967 
10968   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10969   // but UINT_TO_FP is legal on this target, try to convert.
10970   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10971       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10972     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10973     if (DAG.SignBitIsZero(N0))
10974       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10975   }
10976 
10977   // The next optimizations are desirable only if SELECT_CC can be lowered.
10978   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10979     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10980     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10981         !VT.isVector() &&
10982         (!LegalOperations ||
10983          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10984       SDLoc DL(N);
10985       SDValue Ops[] =
10986         { N0.getOperand(0), N0.getOperand(1),
10987           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10988           N0.getOperand(2) };
10989       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10990     }
10991 
10992     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10993     //      (select_cc x, y, 1.0, 0.0,, cc)
10994     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10995         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10996         (!LegalOperations ||
10997          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
10998       SDLoc DL(N);
10999       SDValue Ops[] =
11000         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
11001           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
11002           N0.getOperand(0).getOperand(2) };
11003       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
11004     }
11005   }
11006 
11007   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
11008     return FTrunc;
11009 
11010   return SDValue();
11011 }
11012 
11013 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
11014   SDValue N0 = N->getOperand(0);
11015   EVT VT = N->getValueType(0);
11016   EVT OpVT = N0.getValueType();
11017 
11018   // fold (uint_to_fp c1) -> c1fp
11019   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
11020       // ...but only if the target supports immediate floating-point values
11021       (!LegalOperations ||
11022        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
11023     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
11024 
11025   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
11026   // but SINT_TO_FP is legal on this target, try to convert.
11027   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
11028       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
11029     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
11030     if (DAG.SignBitIsZero(N0))
11031       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
11032   }
11033 
11034   // The next optimizations are desirable only if SELECT_CC can be lowered.
11035   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
11036     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
11037     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
11038         (!LegalOperations ||
11039          TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
11040       SDLoc DL(N);
11041       SDValue Ops[] =
11042         { N0.getOperand(0), N0.getOperand(1),
11043           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
11044           N0.getOperand(2) };
11045       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
11046     }
11047   }
11048 
11049   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
11050     return FTrunc;
11051 
11052   return SDValue();
11053 }
11054 
11055 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
11056 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
11057   SDValue N0 = N->getOperand(0);
11058   EVT VT = N->getValueType(0);
11059 
11060   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
11061     return SDValue();
11062 
11063   SDValue Src = N0.getOperand(0);
11064   EVT SrcVT = Src.getValueType();
11065   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
11066   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
11067 
11068   // We can safely assume the conversion won't overflow the output range,
11069   // because (for example) (uint8_t)18293.f is undefined behavior.
11070 
11071   // Since we can assume the conversion won't overflow, our decision as to
11072   // whether the input will fit in the float should depend on the minimum
11073   // of the input range and output range.
11074 
11075   // This means this is also safe for a signed input and unsigned output, since
11076   // a negative input would lead to undefined behavior.
11077   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
11078   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
11079   unsigned ActualSize = std::min(InputSize, OutputSize);
11080   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
11081 
11082   // We can only fold away the float conversion if the input range can be
11083   // represented exactly in the float range.
11084   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
11085     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
11086       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
11087                                                        : ISD::ZERO_EXTEND;
11088       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
11089     }
11090     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
11091       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
11092     return DAG.getBitcast(VT, Src);
11093   }
11094   return SDValue();
11095 }
11096 
11097 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
11098   SDValue N0 = N->getOperand(0);
11099   EVT VT = N->getValueType(0);
11100 
11101   // fold (fp_to_sint c1fp) -> c1
11102   if (isConstantFPBuildVectorOrConstantFP(N0))
11103     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
11104 
11105   return FoldIntToFPToInt(N, DAG);
11106 }
11107 
11108 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
11109   SDValue N0 = N->getOperand(0);
11110   EVT VT = N->getValueType(0);
11111 
11112   // fold (fp_to_uint c1fp) -> c1
11113   if (isConstantFPBuildVectorOrConstantFP(N0))
11114     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
11115 
11116   return FoldIntToFPToInt(N, DAG);
11117 }
11118 
11119 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
11120   SDValue N0 = N->getOperand(0);
11121   SDValue N1 = N->getOperand(1);
11122   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11123   EVT VT = N->getValueType(0);
11124 
11125   // fold (fp_round c1fp) -> c1fp
11126   if (N0CFP)
11127     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
11128 
11129   // fold (fp_round (fp_extend x)) -> x
11130   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
11131     return N0.getOperand(0);
11132 
11133   // fold (fp_round (fp_round x)) -> (fp_round x)
11134   if (N0.getOpcode() == ISD::FP_ROUND) {
11135     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
11136     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
11137 
11138     // Skip this folding if it results in an fp_round from f80 to f16.
11139     //
11140     // f80 to f16 always generates an expensive (and as yet, unimplemented)
11141     // libcall to __truncxfhf2 instead of selecting native f16 conversion
11142     // instructions from f32 or f64.  Moreover, the first (value-preserving)
11143     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
11144     // x86.
11145     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
11146       return SDValue();
11147 
11148     // If the first fp_round isn't a value preserving truncation, it might
11149     // introduce a tie in the second fp_round, that wouldn't occur in the
11150     // single-step fp_round we want to fold to.
11151     // In other words, double rounding isn't the same as rounding.
11152     // Also, this is a value preserving truncation iff both fp_round's are.
11153     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
11154       SDLoc DL(N);
11155       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
11156                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
11157     }
11158   }
11159 
11160   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
11161   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
11162     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
11163                               N0.getOperand(0), N1);
11164     AddToWorklist(Tmp.getNode());
11165     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
11166                        Tmp, N0.getOperand(1));
11167   }
11168 
11169   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11170     return NewVSel;
11171 
11172   return SDValue();
11173 }
11174 
11175 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
11176   SDValue N0 = N->getOperand(0);
11177   EVT VT = N->getValueType(0);
11178   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
11179   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
11180 
11181   // fold (fp_round_inreg c1fp) -> c1fp
11182   if (N0CFP && isTypeLegal(EVT)) {
11183     SDLoc DL(N);
11184     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
11185     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
11186   }
11187 
11188   return SDValue();
11189 }
11190 
11191 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
11192   SDValue N0 = N->getOperand(0);
11193   EVT VT = N->getValueType(0);
11194 
11195   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
11196   if (N->hasOneUse() &&
11197       N->use_begin()->getOpcode() == ISD::FP_ROUND)
11198     return SDValue();
11199 
11200   // fold (fp_extend c1fp) -> c1fp
11201   if (isConstantFPBuildVectorOrConstantFP(N0))
11202     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
11203 
11204   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
11205   if (N0.getOpcode() == ISD::FP16_TO_FP &&
11206       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
11207     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
11208 
11209   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
11210   // value of X.
11211   if (N0.getOpcode() == ISD::FP_ROUND
11212       && N0.getConstantOperandVal(1) == 1) {
11213     SDValue In = N0.getOperand(0);
11214     if (In.getValueType() == VT) return In;
11215     if (VT.bitsLT(In.getValueType()))
11216       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
11217                          In, N0.getOperand(1));
11218     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
11219   }
11220 
11221   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
11222   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11223        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
11224     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11225     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
11226                                      LN0->getChain(),
11227                                      LN0->getBasePtr(), N0.getValueType(),
11228                                      LN0->getMemOperand());
11229     CombineTo(N, ExtLoad);
11230     CombineTo(N0.getNode(),
11231               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
11232                           N0.getValueType(), ExtLoad,
11233                           DAG.getIntPtrConstant(1, SDLoc(N0))),
11234               ExtLoad.getValue(1));
11235     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
11236   }
11237 
11238   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11239     return NewVSel;
11240 
11241   return SDValue();
11242 }
11243 
11244 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
11245   SDValue N0 = N->getOperand(0);
11246   EVT VT = N->getValueType(0);
11247 
11248   // fold (fceil c1) -> fceil(c1)
11249   if (isConstantFPBuildVectorOrConstantFP(N0))
11250     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
11251 
11252   return SDValue();
11253 }
11254 
11255 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
11256   SDValue N0 = N->getOperand(0);
11257   EVT VT = N->getValueType(0);
11258 
11259   // fold (ftrunc c1) -> ftrunc(c1)
11260   if (isConstantFPBuildVectorOrConstantFP(N0))
11261     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
11262 
11263   // fold ftrunc (known rounded int x) -> x
11264   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
11265   // likely to be generated to extract integer from a rounded floating value.
11266   switch (N0.getOpcode()) {
11267   default: break;
11268   case ISD::FRINT:
11269   case ISD::FTRUNC:
11270   case ISD::FNEARBYINT:
11271   case ISD::FFLOOR:
11272   case ISD::FCEIL:
11273     return N0;
11274   }
11275 
11276   return SDValue();
11277 }
11278 
11279 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
11280   SDValue N0 = N->getOperand(0);
11281   EVT VT = N->getValueType(0);
11282 
11283   // fold (ffloor c1) -> ffloor(c1)
11284   if (isConstantFPBuildVectorOrConstantFP(N0))
11285     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
11286 
11287   return SDValue();
11288 }
11289 
11290 // FIXME: FNEG and FABS have a lot in common; refactor.
11291 SDValue DAGCombiner::visitFNEG(SDNode *N) {
11292   SDValue N0 = N->getOperand(0);
11293   EVT VT = N->getValueType(0);
11294 
11295   // Constant fold FNEG.
11296   if (isConstantFPBuildVectorOrConstantFP(N0))
11297     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
11298 
11299   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
11300                          &DAG.getTarget().Options))
11301     return GetNegatedExpression(N0, DAG, LegalOperations);
11302 
11303   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
11304   // constant pool values.
11305   if (!TLI.isFNegFree(VT) &&
11306       N0.getOpcode() == ISD::BITCAST &&
11307       N0.getNode()->hasOneUse()) {
11308     SDValue Int = N0.getOperand(0);
11309     EVT IntVT = Int.getValueType();
11310     if (IntVT.isInteger() && !IntVT.isVector()) {
11311       APInt SignMask;
11312       if (N0.getValueType().isVector()) {
11313         // For a vector, get a mask such as 0x80... per scalar element
11314         // and splat it.
11315         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
11316         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11317       } else {
11318         // For a scalar, just generate 0x80...
11319         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
11320       }
11321       SDLoc DL0(N0);
11322       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
11323                         DAG.getConstant(SignMask, DL0, IntVT));
11324       AddToWorklist(Int.getNode());
11325       return DAG.getBitcast(VT, Int);
11326     }
11327   }
11328 
11329   // (fneg (fmul c, x)) -> (fmul -c, x)
11330   if (N0.getOpcode() == ISD::FMUL &&
11331       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
11332     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
11333     if (CFP1) {
11334       APFloat CVal = CFP1->getValueAPF();
11335       CVal.changeSign();
11336       if (Level >= AfterLegalizeDAG &&
11337           (TLI.isFPImmLegal(CVal, VT) ||
11338            TLI.isOperationLegal(ISD::ConstantFP, VT)))
11339         return DAG.getNode(
11340             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
11341             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
11342             N0->getFlags());
11343     }
11344   }
11345 
11346   return SDValue();
11347 }
11348 
11349 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
11350   SDValue N0 = N->getOperand(0);
11351   SDValue N1 = N->getOperand(1);
11352   EVT VT = N->getValueType(0);
11353   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11354   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11355 
11356   if (N0CFP && N1CFP) {
11357     const APFloat &C0 = N0CFP->getValueAPF();
11358     const APFloat &C1 = N1CFP->getValueAPF();
11359     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
11360   }
11361 
11362   // Canonicalize to constant on RHS.
11363   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11364      !isConstantFPBuildVectorOrConstantFP(N1))
11365     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
11366 
11367   return SDValue();
11368 }
11369 
11370 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
11371   SDValue N0 = N->getOperand(0);
11372   SDValue N1 = N->getOperand(1);
11373   EVT VT = N->getValueType(0);
11374   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
11375   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
11376 
11377   if (N0CFP && N1CFP) {
11378     const APFloat &C0 = N0CFP->getValueAPF();
11379     const APFloat &C1 = N1CFP->getValueAPF();
11380     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
11381   }
11382 
11383   // Canonicalize to constant on RHS.
11384   if (isConstantFPBuildVectorOrConstantFP(N0) &&
11385      !isConstantFPBuildVectorOrConstantFP(N1))
11386     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
11387 
11388   return SDValue();
11389 }
11390 
11391 SDValue DAGCombiner::visitFABS(SDNode *N) {
11392   SDValue N0 = N->getOperand(0);
11393   EVT VT = N->getValueType(0);
11394 
11395   // fold (fabs c1) -> fabs(c1)
11396   if (isConstantFPBuildVectorOrConstantFP(N0))
11397     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
11398 
11399   // fold (fabs (fabs x)) -> (fabs x)
11400   if (N0.getOpcode() == ISD::FABS)
11401     return N->getOperand(0);
11402 
11403   // fold (fabs (fneg x)) -> (fabs x)
11404   // fold (fabs (fcopysign x, y)) -> (fabs x)
11405   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
11406     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
11407 
11408   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
11409   // constant pool values.
11410   if (!TLI.isFAbsFree(VT) &&
11411       N0.getOpcode() == ISD::BITCAST &&
11412       N0.getNode()->hasOneUse()) {
11413     SDValue Int = N0.getOperand(0);
11414     EVT IntVT = Int.getValueType();
11415     if (IntVT.isInteger() && !IntVT.isVector()) {
11416       APInt SignMask;
11417       if (N0.getValueType().isVector()) {
11418         // For a vector, get a mask such as 0x7f... per scalar element
11419         // and splat it.
11420         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
11421         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
11422       } else {
11423         // For a scalar, just generate 0x7f...
11424         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
11425       }
11426       SDLoc DL(N0);
11427       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
11428                         DAG.getConstant(SignMask, DL, IntVT));
11429       AddToWorklist(Int.getNode());
11430       return DAG.getBitcast(N->getValueType(0), Int);
11431     }
11432   }
11433 
11434   return SDValue();
11435 }
11436 
11437 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
11438   SDValue Chain = N->getOperand(0);
11439   SDValue N1 = N->getOperand(1);
11440   SDValue N2 = N->getOperand(2);
11441 
11442   // If N is a constant we could fold this into a fallthrough or unconditional
11443   // branch. However that doesn't happen very often in normal code, because
11444   // Instcombine/SimplifyCFG should have handled the available opportunities.
11445   // If we did this folding here, it would be necessary to update the
11446   // MachineBasicBlock CFG, which is awkward.
11447 
11448   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
11449   // on the target.
11450   if (N1.getOpcode() == ISD::SETCC &&
11451       TLI.isOperationLegalOrCustom(ISD::BR_CC,
11452                                    N1.getOperand(0).getValueType())) {
11453     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11454                        Chain, N1.getOperand(2),
11455                        N1.getOperand(0), N1.getOperand(1), N2);
11456   }
11457 
11458   if (N1.hasOneUse()) {
11459     if (SDValue NewN1 = rebuildSetCC(N1))
11460       return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2);
11461   }
11462 
11463   return SDValue();
11464 }
11465 
11466 SDValue DAGCombiner::rebuildSetCC(SDValue N) {
11467   if (N.getOpcode() == ISD::SRL ||
11468       (N.getOpcode() == ISD::TRUNCATE &&
11469        (N.getOperand(0).hasOneUse() &&
11470         N.getOperand(0).getOpcode() == ISD::SRL))) {
11471     // Look pass the truncate.
11472     if (N.getOpcode() == ISD::TRUNCATE)
11473       N = N.getOperand(0);
11474 
11475     // Match this pattern so that we can generate simpler code:
11476     //
11477     //   %a = ...
11478     //   %b = and i32 %a, 2
11479     //   %c = srl i32 %b, 1
11480     //   brcond i32 %c ...
11481     //
11482     // into
11483     //
11484     //   %a = ...
11485     //   %b = and i32 %a, 2
11486     //   %c = setcc eq %b, 0
11487     //   brcond %c ...
11488     //
11489     // This applies only when the AND constant value has one bit set and the
11490     // SRL constant is equal to the log2 of the AND constant. The back-end is
11491     // smart enough to convert the result into a TEST/JMP sequence.
11492     SDValue Op0 = N.getOperand(0);
11493     SDValue Op1 = N.getOperand(1);
11494 
11495     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
11496       SDValue AndOp1 = Op0.getOperand(1);
11497 
11498       if (AndOp1.getOpcode() == ISD::Constant) {
11499         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
11500 
11501         if (AndConst.isPowerOf2() &&
11502             cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
11503           SDLoc DL(N);
11504           return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
11505                               Op0, DAG.getConstant(0, DL, Op0.getValueType()),
11506                               ISD::SETNE);
11507         }
11508       }
11509     }
11510   }
11511 
11512   // Transform br(xor(x, y)) -> br(x != y)
11513   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
11514   if (N.getOpcode() == ISD::XOR) {
11515     // Because we may call this on a speculatively constructed
11516     // SimplifiedSetCC Node, we need to simplify this node first.
11517     // Ideally this should be folded into SimplifySetCC and not
11518     // here. For now, grab a handle to N so we don't lose it from
11519     // replacements interal to the visit.
11520     HandleSDNode XORHandle(N);
11521     while (N.getOpcode() == ISD::XOR) {
11522       SDValue Tmp = visitXOR(N.getNode());
11523       // No simplification done.
11524       if (!Tmp.getNode())
11525         break;
11526       // Returning N is form in-visit replacement that may invalidated
11527       // N. Grab value from Handle.
11528       if (Tmp.getNode() == N.getNode())
11529         N = XORHandle.getValue();
11530       else // Node simplified. Try simplifying again.
11531         N = Tmp;
11532     }
11533 
11534     if (N.getOpcode() != ISD::XOR)
11535       return N;
11536 
11537     SDNode *TheXor = N.getNode();
11538 
11539     SDValue Op0 = TheXor->getOperand(0);
11540     SDValue Op1 = TheXor->getOperand(1);
11541 
11542     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
11543       bool Equal = false;
11544       if (isOneConstant(Op0) && Op0.hasOneUse() &&
11545           Op0.getOpcode() == ISD::XOR) {
11546         TheXor = Op0.getNode();
11547         Equal = true;
11548       }
11549 
11550       EVT SetCCVT = N.getValueType();
11551       if (LegalTypes)
11552         SetCCVT = getSetCCResultType(SetCCVT);
11553       // Replace the uses of XOR with SETCC
11554       return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1,
11555                           Equal ? ISD::SETEQ : ISD::SETNE);
11556     }
11557   }
11558 
11559   return SDValue();
11560 }
11561 
11562 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
11563 //
11564 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
11565   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
11566   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
11567 
11568   // If N is a constant we could fold this into a fallthrough or unconditional
11569   // branch. However that doesn't happen very often in normal code, because
11570   // Instcombine/SimplifyCFG should have handled the available opportunities.
11571   // If we did this folding here, it would be necessary to update the
11572   // MachineBasicBlock CFG, which is awkward.
11573 
11574   // Use SimplifySetCC to simplify SETCC's.
11575   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
11576                                CondLHS, CondRHS, CC->get(), SDLoc(N),
11577                                false);
11578   if (Simp.getNode()) AddToWorklist(Simp.getNode());
11579 
11580   // fold to a simpler setcc
11581   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
11582     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
11583                        N->getOperand(0), Simp.getOperand(2),
11584                        Simp.getOperand(0), Simp.getOperand(1),
11585                        N->getOperand(4));
11586 
11587   return SDValue();
11588 }
11589 
11590 /// Return true if 'Use' is a load or a store that uses N as its base pointer
11591 /// and that N may be folded in the load / store addressing mode.
11592 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
11593                                     SelectionDAG &DAG,
11594                                     const TargetLowering &TLI) {
11595   EVT VT;
11596   unsigned AS;
11597 
11598   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
11599     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
11600       return false;
11601     VT = LD->getMemoryVT();
11602     AS = LD->getAddressSpace();
11603   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
11604     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
11605       return false;
11606     VT = ST->getMemoryVT();
11607     AS = ST->getAddressSpace();
11608   } else
11609     return false;
11610 
11611   TargetLowering::AddrMode AM;
11612   if (N->getOpcode() == ISD::ADD) {
11613     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11614     if (Offset)
11615       // [reg +/- imm]
11616       AM.BaseOffs = Offset->getSExtValue();
11617     else
11618       // [reg +/- reg]
11619       AM.Scale = 1;
11620   } else if (N->getOpcode() == ISD::SUB) {
11621     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
11622     if (Offset)
11623       // [reg +/- imm]
11624       AM.BaseOffs = -Offset->getSExtValue();
11625     else
11626       // [reg +/- reg]
11627       AM.Scale = 1;
11628   } else
11629     return false;
11630 
11631   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
11632                                    VT.getTypeForEVT(*DAG.getContext()), AS);
11633 }
11634 
11635 /// Try turning a load/store into a pre-indexed load/store when the base
11636 /// pointer is an add or subtract and it has other uses besides the load/store.
11637 /// After the transformation, the new indexed load/store has effectively folded
11638 /// the add/subtract in and all of its other uses are redirected to the
11639 /// new load/store.
11640 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
11641   if (Level < AfterLegalizeDAG)
11642     return false;
11643 
11644   bool isLoad = true;
11645   SDValue Ptr;
11646   EVT VT;
11647   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11648     if (LD->isIndexed())
11649       return false;
11650     VT = LD->getMemoryVT();
11651     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
11652         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
11653       return false;
11654     Ptr = LD->getBasePtr();
11655   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11656     if (ST->isIndexed())
11657       return false;
11658     VT = ST->getMemoryVT();
11659     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
11660         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
11661       return false;
11662     Ptr = ST->getBasePtr();
11663     isLoad = false;
11664   } else {
11665     return false;
11666   }
11667 
11668   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
11669   // out.  There is no reason to make this a preinc/predec.
11670   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
11671       Ptr.getNode()->hasOneUse())
11672     return false;
11673 
11674   // Ask the target to do addressing mode selection.
11675   SDValue BasePtr;
11676   SDValue Offset;
11677   ISD::MemIndexedMode AM = ISD::UNINDEXED;
11678   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
11679     return false;
11680 
11681   // Backends without true r+i pre-indexed forms may need to pass a
11682   // constant base with a variable offset so that constant coercion
11683   // will work with the patterns in canonical form.
11684   bool Swapped = false;
11685   if (isa<ConstantSDNode>(BasePtr)) {
11686     std::swap(BasePtr, Offset);
11687     Swapped = true;
11688   }
11689 
11690   // Don't create a indexed load / store with zero offset.
11691   if (isNullConstant(Offset))
11692     return false;
11693 
11694   // Try turning it into a pre-indexed load / store except when:
11695   // 1) The new base ptr is a frame index.
11696   // 2) If N is a store and the new base ptr is either the same as or is a
11697   //    predecessor of the value being stored.
11698   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
11699   //    that would create a cycle.
11700   // 4) All uses are load / store ops that use it as old base ptr.
11701 
11702   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
11703   // (plus the implicit offset) to a register to preinc anyway.
11704   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11705     return false;
11706 
11707   // Check #2.
11708   if (!isLoad) {
11709     SDValue Val = cast<StoreSDNode>(N)->getValue();
11710     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11711       return false;
11712   }
11713 
11714   // Caches for hasPredecessorHelper.
11715   SmallPtrSet<const SDNode *, 32> Visited;
11716   SmallVector<const SDNode *, 16> Worklist;
11717   Worklist.push_back(N);
11718 
11719   // If the offset is a constant, there may be other adds of constants that
11720   // can be folded with this one. We should do this to avoid having to keep
11721   // a copy of the original base pointer.
11722   SmallVector<SDNode *, 16> OtherUses;
11723   if (isa<ConstantSDNode>(Offset))
11724     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11725                               UE = BasePtr.getNode()->use_end();
11726          UI != UE; ++UI) {
11727       SDUse &Use = UI.getUse();
11728       // Skip the use that is Ptr and uses of other results from BasePtr's
11729       // node (important for nodes that return multiple results).
11730       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11731         continue;
11732 
11733       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11734         continue;
11735 
11736       if (Use.getUser()->getOpcode() != ISD::ADD &&
11737           Use.getUser()->getOpcode() != ISD::SUB) {
11738         OtherUses.clear();
11739         break;
11740       }
11741 
11742       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11743       if (!isa<ConstantSDNode>(Op1)) {
11744         OtherUses.clear();
11745         break;
11746       }
11747 
11748       // FIXME: In some cases, we can be smarter about this.
11749       if (Op1.getValueType() != Offset.getValueType()) {
11750         OtherUses.clear();
11751         break;
11752       }
11753 
11754       OtherUses.push_back(Use.getUser());
11755     }
11756 
11757   if (Swapped)
11758     std::swap(BasePtr, Offset);
11759 
11760   // Now check for #3 and #4.
11761   bool RealUse = false;
11762 
11763   for (SDNode *Use : Ptr.getNode()->uses()) {
11764     if (Use == N)
11765       continue;
11766     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11767       return false;
11768 
11769     // If Ptr may be folded in addressing mode of other use, then it's
11770     // not profitable to do this transformation.
11771     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11772       RealUse = true;
11773   }
11774 
11775   if (!RealUse)
11776     return false;
11777 
11778   SDValue Result;
11779   if (isLoad)
11780     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11781                                 BasePtr, Offset, AM);
11782   else
11783     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11784                                  BasePtr, Offset, AM);
11785   ++PreIndexedNodes;
11786   ++NodesCombined;
11787   LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
11788              Result.getNode()->dump(&DAG); dbgs() << '\n');
11789   WorklistRemover DeadNodes(*this);
11790   if (isLoad) {
11791     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11792     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11793   } else {
11794     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11795   }
11796 
11797   // Finally, since the node is now dead, remove it from the graph.
11798   deleteAndRecombine(N);
11799 
11800   if (Swapped)
11801     std::swap(BasePtr, Offset);
11802 
11803   // Replace other uses of BasePtr that can be updated to use Ptr
11804   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11805     unsigned OffsetIdx = 1;
11806     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11807       OffsetIdx = 0;
11808     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11809            BasePtr.getNode() && "Expected BasePtr operand");
11810 
11811     // We need to replace ptr0 in the following expression:
11812     //   x0 * offset0 + y0 * ptr0 = t0
11813     // knowing that
11814     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11815     //
11816     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11817     // indexed load/store and the expression that needs to be re-written.
11818     //
11819     // Therefore, we have:
11820     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11821 
11822     ConstantSDNode *CN =
11823       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11824     int X0, X1, Y0, Y1;
11825     const APInt &Offset0 = CN->getAPIntValue();
11826     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11827 
11828     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11829     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11830     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11831     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11832 
11833     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11834 
11835     APInt CNV = Offset0;
11836     if (X0 < 0) CNV = -CNV;
11837     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11838     else CNV = CNV - Offset1;
11839 
11840     SDLoc DL(OtherUses[i]);
11841 
11842     // We can now generate the new expression.
11843     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11844     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11845 
11846     SDValue NewUse = DAG.getNode(Opcode,
11847                                  DL,
11848                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11849     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11850     deleteAndRecombine(OtherUses[i]);
11851   }
11852 
11853   // Replace the uses of Ptr with uses of the updated base value.
11854   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11855   deleteAndRecombine(Ptr.getNode());
11856   AddToWorklist(Result.getNode());
11857 
11858   return true;
11859 }
11860 
11861 /// Try to combine a load/store with a add/sub of the base pointer node into a
11862 /// post-indexed load/store. The transformation folded the add/subtract into the
11863 /// new indexed load/store effectively and all of its uses are redirected to the
11864 /// new load/store.
11865 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11866   if (Level < AfterLegalizeDAG)
11867     return false;
11868 
11869   bool isLoad = true;
11870   SDValue Ptr;
11871   EVT VT;
11872   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
11873     if (LD->isIndexed())
11874       return false;
11875     VT = LD->getMemoryVT();
11876     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11877         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11878       return false;
11879     Ptr = LD->getBasePtr();
11880   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
11881     if (ST->isIndexed())
11882       return false;
11883     VT = ST->getMemoryVT();
11884     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11885         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11886       return false;
11887     Ptr = ST->getBasePtr();
11888     isLoad = false;
11889   } else {
11890     return false;
11891   }
11892 
11893   if (Ptr.getNode()->hasOneUse())
11894     return false;
11895 
11896   for (SDNode *Op : Ptr.getNode()->uses()) {
11897     if (Op == N ||
11898         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11899       continue;
11900 
11901     SDValue BasePtr;
11902     SDValue Offset;
11903     ISD::MemIndexedMode AM = ISD::UNINDEXED;
11904     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11905       // Don't create a indexed load / store with zero offset.
11906       if (isNullConstant(Offset))
11907         continue;
11908 
11909       // Try turning it into a post-indexed load / store except when
11910       // 1) All uses are load / store ops that use it as base ptr (and
11911       //    it may be folded as addressing mmode).
11912       // 2) Op must be independent of N, i.e. Op is neither a predecessor
11913       //    nor a successor of N. Otherwise, if Op is folded that would
11914       //    create a cycle.
11915 
11916       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11917         continue;
11918 
11919       // Check for #1.
11920       bool TryNext = false;
11921       for (SDNode *Use : BasePtr.getNode()->uses()) {
11922         if (Use == Ptr.getNode())
11923           continue;
11924 
11925         // If all the uses are load / store addresses, then don't do the
11926         // transformation.
11927         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11928           bool RealUse = false;
11929           for (SDNode *UseUse : Use->uses()) {
11930             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11931               RealUse = true;
11932           }
11933 
11934           if (!RealUse) {
11935             TryNext = true;
11936             break;
11937           }
11938         }
11939       }
11940 
11941       if (TryNext)
11942         continue;
11943 
11944       // Check for #2
11945       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11946         SDValue Result = isLoad
11947           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11948                                BasePtr, Offset, AM)
11949           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11950                                 BasePtr, Offset, AM);
11951         ++PostIndexedNodes;
11952         ++NodesCombined;
11953         LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);
11954                    dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);
11955                    dbgs() << '\n');
11956         WorklistRemover DeadNodes(*this);
11957         if (isLoad) {
11958           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11959           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11960         } else {
11961           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11962         }
11963 
11964         // Finally, since the node is now dead, remove it from the graph.
11965         deleteAndRecombine(N);
11966 
11967         // Replace the uses of Use with uses of the updated base value.
11968         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11969                                       Result.getValue(isLoad ? 1 : 0));
11970         deleteAndRecombine(Op);
11971         return true;
11972       }
11973     }
11974   }
11975 
11976   return false;
11977 }
11978 
11979 /// Return the base-pointer arithmetic from an indexed \p LD.
11980 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11981   ISD::MemIndexedMode AM = LD->getAddressingMode();
11982   assert(AM != ISD::UNINDEXED);
11983   SDValue BP = LD->getOperand(1);
11984   SDValue Inc = LD->getOperand(2);
11985 
11986   // Some backends use TargetConstants for load offsets, but don't expect
11987   // TargetConstants in general ADD nodes. We can convert these constants into
11988   // regular Constants (if the constant is not opaque).
11989   assert((Inc.getOpcode() != ISD::TargetConstant ||
11990           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11991          "Cannot split out indexing using opaque target constants");
11992   if (Inc.getOpcode() == ISD::TargetConstant) {
11993     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11994     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11995                           ConstInc->getValueType(0));
11996   }
11997 
11998   unsigned Opc =
11999       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
12000   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
12001 }
12002 
12003 SDValue DAGCombiner::visitLOAD(SDNode *N) {
12004   LoadSDNode *LD  = cast<LoadSDNode>(N);
12005   SDValue Chain = LD->getChain();
12006   SDValue Ptr   = LD->getBasePtr();
12007 
12008   // If load is not volatile and there are no uses of the loaded value (and
12009   // the updated indexed value in case of indexed loads), change uses of the
12010   // chain value into uses of the chain input (i.e. delete the dead load).
12011   if (!LD->isVolatile()) {
12012     if (N->getValueType(1) == MVT::Other) {
12013       // Unindexed loads.
12014       if (!N->hasAnyUseOfValue(0)) {
12015         // It's not safe to use the two value CombineTo variant here. e.g.
12016         // v1, chain2 = load chain1, loc
12017         // v2, chain3 = load chain2, loc
12018         // v3         = add v2, c
12019         // Now we replace use of chain2 with chain1.  This makes the second load
12020         // isomorphic to the one we are deleting, and thus makes this load live.
12021         LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
12022                    dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);
12023                    dbgs() << "\n");
12024         WorklistRemover DeadNodes(*this);
12025         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12026         AddUsersToWorklist(Chain.getNode());
12027         if (N->use_empty())
12028           deleteAndRecombine(N);
12029 
12030         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
12031       }
12032     } else {
12033       // Indexed loads.
12034       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
12035 
12036       // If this load has an opaque TargetConstant offset, then we cannot split
12037       // the indexing into an add/sub directly (that TargetConstant may not be
12038       // valid for a different type of node, and we cannot convert an opaque
12039       // target constant into a regular constant).
12040       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
12041                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
12042 
12043       if (!N->hasAnyUseOfValue(0) &&
12044           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
12045         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
12046         SDValue Index;
12047         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
12048           Index = SplitIndexingFromLoad(LD);
12049           // Try to fold the base pointer arithmetic into subsequent loads and
12050           // stores.
12051           AddUsersToWorklist(N);
12052         } else
12053           Index = DAG.getUNDEF(N->getValueType(1));
12054         LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
12055                    dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);
12056                    dbgs() << " and 2 other values\n");
12057         WorklistRemover DeadNodes(*this);
12058         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
12059         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
12060         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
12061         deleteAndRecombine(N);
12062         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
12063       }
12064     }
12065   }
12066 
12067   // If this load is directly stored, replace the load value with the stored
12068   // value.
12069   // TODO: Handle store large -> read small portion.
12070   // TODO: Handle TRUNCSTORE/LOADEXT
12071   if (OptLevel != CodeGenOpt::None &&
12072       ISD::isNormalLoad(N) && !LD->isVolatile()) {
12073     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
12074       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
12075       if (PrevST->getBasePtr() == Ptr &&
12076           PrevST->getValue().getValueType() == N->getValueType(0))
12077         return CombineTo(N, PrevST->getOperand(1), Chain);
12078     }
12079   }
12080 
12081   // Try to infer better alignment information than the load already has.
12082   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
12083     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12084       if (Align > LD->getMemOperand()->getBaseAlignment()) {
12085         SDValue NewLoad = DAG.getExtLoad(
12086             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
12087             LD->getPointerInfo(), LD->getMemoryVT(), Align,
12088             LD->getMemOperand()->getFlags(), LD->getAAInfo());
12089         if (NewLoad.getNode() != N)
12090           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
12091       }
12092     }
12093   }
12094 
12095   if (LD->isUnindexed()) {
12096     // Walk up chain skipping non-aliasing memory nodes.
12097     SDValue BetterChain = FindBetterChain(N, Chain);
12098 
12099     // If there is a better chain.
12100     if (Chain != BetterChain) {
12101       SDValue ReplLoad;
12102 
12103       // Replace the chain to void dependency.
12104       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
12105         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
12106                                BetterChain, Ptr, LD->getMemOperand());
12107       } else {
12108         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
12109                                   LD->getValueType(0),
12110                                   BetterChain, Ptr, LD->getMemoryVT(),
12111                                   LD->getMemOperand());
12112       }
12113 
12114       // Create token factor to keep old chain connected.
12115       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
12116                                   MVT::Other, Chain, ReplLoad.getValue(1));
12117 
12118       // Replace uses with load result and token factor
12119       return CombineTo(N, ReplLoad.getValue(0), Token);
12120     }
12121   }
12122 
12123   // Try transforming N to an indexed load.
12124   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12125     return SDValue(N, 0);
12126 
12127   // Try to slice up N to more direct loads if the slices are mapped to
12128   // different register banks or pairing can take place.
12129   if (SliceUpLoad(N))
12130     return SDValue(N, 0);
12131 
12132   return SDValue();
12133 }
12134 
12135 namespace {
12136 
12137 /// Helper structure used to slice a load in smaller loads.
12138 /// Basically a slice is obtained from the following sequence:
12139 /// Origin = load Ty1, Base
12140 /// Shift = srl Ty1 Origin, CstTy Amount
12141 /// Inst = trunc Shift to Ty2
12142 ///
12143 /// Then, it will be rewritten into:
12144 /// Slice = load SliceTy, Base + SliceOffset
12145 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
12146 ///
12147 /// SliceTy is deduced from the number of bits that are actually used to
12148 /// build Inst.
12149 struct LoadedSlice {
12150   /// Helper structure used to compute the cost of a slice.
12151   struct Cost {
12152     /// Are we optimizing for code size.
12153     bool ForCodeSize;
12154 
12155     /// Various cost.
12156     unsigned Loads = 0;
12157     unsigned Truncates = 0;
12158     unsigned CrossRegisterBanksCopies = 0;
12159     unsigned ZExts = 0;
12160     unsigned Shift = 0;
12161 
12162     Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {}
12163 
12164     /// Get the cost of one isolated slice.
12165     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
12166         : ForCodeSize(ForCodeSize), Loads(1) {
12167       EVT TruncType = LS.Inst->getValueType(0);
12168       EVT LoadedType = LS.getLoadedType();
12169       if (TruncType != LoadedType &&
12170           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
12171         ZExts = 1;
12172     }
12173 
12174     /// Account for slicing gain in the current cost.
12175     /// Slicing provide a few gains like removing a shift or a
12176     /// truncate. This method allows to grow the cost of the original
12177     /// load with the gain from this slice.
12178     void addSliceGain(const LoadedSlice &LS) {
12179       // Each slice saves a truncate.
12180       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
12181       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
12182                               LS.Inst->getValueType(0)))
12183         ++Truncates;
12184       // If there is a shift amount, this slice gets rid of it.
12185       if (LS.Shift)
12186         ++Shift;
12187       // If this slice can merge a cross register bank copy, account for it.
12188       if (LS.canMergeExpensiveCrossRegisterBankCopy())
12189         ++CrossRegisterBanksCopies;
12190     }
12191 
12192     Cost &operator+=(const Cost &RHS) {
12193       Loads += RHS.Loads;
12194       Truncates += RHS.Truncates;
12195       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
12196       ZExts += RHS.ZExts;
12197       Shift += RHS.Shift;
12198       return *this;
12199     }
12200 
12201     bool operator==(const Cost &RHS) const {
12202       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
12203              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
12204              ZExts == RHS.ZExts && Shift == RHS.Shift;
12205     }
12206 
12207     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
12208 
12209     bool operator<(const Cost &RHS) const {
12210       // Assume cross register banks copies are as expensive as loads.
12211       // FIXME: Do we want some more target hooks?
12212       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
12213       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
12214       // Unless we are optimizing for code size, consider the
12215       // expensive operation first.
12216       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
12217         return ExpensiveOpsLHS < ExpensiveOpsRHS;
12218       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
12219              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
12220     }
12221 
12222     bool operator>(const Cost &RHS) const { return RHS < *this; }
12223 
12224     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
12225 
12226     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
12227   };
12228 
12229   // The last instruction that represent the slice. This should be a
12230   // truncate instruction.
12231   SDNode *Inst;
12232 
12233   // The original load instruction.
12234   LoadSDNode *Origin;
12235 
12236   // The right shift amount in bits from the original load.
12237   unsigned Shift;
12238 
12239   // The DAG from which Origin came from.
12240   // This is used to get some contextual information about legal types, etc.
12241   SelectionDAG *DAG;
12242 
12243   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
12244               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
12245       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
12246 
12247   /// Get the bits used in a chunk of bits \p BitWidth large.
12248   /// \return Result is \p BitWidth and has used bits set to 1 and
12249   ///         not used bits set to 0.
12250   APInt getUsedBits() const {
12251     // Reproduce the trunc(lshr) sequence:
12252     // - Start from the truncated value.
12253     // - Zero extend to the desired bit width.
12254     // - Shift left.
12255     assert(Origin && "No original load to compare against.");
12256     unsigned BitWidth = Origin->getValueSizeInBits(0);
12257     assert(Inst && "This slice is not bound to an instruction");
12258     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
12259            "Extracted slice is bigger than the whole type!");
12260     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
12261     UsedBits.setAllBits();
12262     UsedBits = UsedBits.zext(BitWidth);
12263     UsedBits <<= Shift;
12264     return UsedBits;
12265   }
12266 
12267   /// Get the size of the slice to be loaded in bytes.
12268   unsigned getLoadedSize() const {
12269     unsigned SliceSize = getUsedBits().countPopulation();
12270     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
12271     return SliceSize / 8;
12272   }
12273 
12274   /// Get the type that will be loaded for this slice.
12275   /// Note: This may not be the final type for the slice.
12276   EVT getLoadedType() const {
12277     assert(DAG && "Missing context");
12278     LLVMContext &Ctxt = *DAG->getContext();
12279     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
12280   }
12281 
12282   /// Get the alignment of the load used for this slice.
12283   unsigned getAlignment() const {
12284     unsigned Alignment = Origin->getAlignment();
12285     unsigned Offset = getOffsetFromBase();
12286     if (Offset != 0)
12287       Alignment = MinAlign(Alignment, Alignment + Offset);
12288     return Alignment;
12289   }
12290 
12291   /// Check if this slice can be rewritten with legal operations.
12292   bool isLegal() const {
12293     // An invalid slice is not legal.
12294     if (!Origin || !Inst || !DAG)
12295       return false;
12296 
12297     // Offsets are for indexed load only, we do not handle that.
12298     if (!Origin->getOffset().isUndef())
12299       return false;
12300 
12301     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12302 
12303     // Check that the type is legal.
12304     EVT SliceType = getLoadedType();
12305     if (!TLI.isTypeLegal(SliceType))
12306       return false;
12307 
12308     // Check that the load is legal for this type.
12309     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
12310       return false;
12311 
12312     // Check that the offset can be computed.
12313     // 1. Check its type.
12314     EVT PtrType = Origin->getBasePtr().getValueType();
12315     if (PtrType == MVT::Untyped || PtrType.isExtended())
12316       return false;
12317 
12318     // 2. Check that it fits in the immediate.
12319     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
12320       return false;
12321 
12322     // 3. Check that the computation is legal.
12323     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
12324       return false;
12325 
12326     // Check that the zext is legal if it needs one.
12327     EVT TruncateType = Inst->getValueType(0);
12328     if (TruncateType != SliceType &&
12329         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
12330       return false;
12331 
12332     return true;
12333   }
12334 
12335   /// Get the offset in bytes of this slice in the original chunk of
12336   /// bits.
12337   /// \pre DAG != nullptr.
12338   uint64_t getOffsetFromBase() const {
12339     assert(DAG && "Missing context.");
12340     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
12341     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
12342     uint64_t Offset = Shift / 8;
12343     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
12344     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
12345            "The size of the original loaded type is not a multiple of a"
12346            " byte.");
12347     // If Offset is bigger than TySizeInBytes, it means we are loading all
12348     // zeros. This should have been optimized before in the process.
12349     assert(TySizeInBytes > Offset &&
12350            "Invalid shift amount for given loaded size");
12351     if (IsBigEndian)
12352       Offset = TySizeInBytes - Offset - getLoadedSize();
12353     return Offset;
12354   }
12355 
12356   /// Generate the sequence of instructions to load the slice
12357   /// represented by this object and redirect the uses of this slice to
12358   /// this new sequence of instructions.
12359   /// \pre this->Inst && this->Origin are valid Instructions and this
12360   /// object passed the legal check: LoadedSlice::isLegal returned true.
12361   /// \return The last instruction of the sequence used to load the slice.
12362   SDValue loadSlice() const {
12363     assert(Inst && Origin && "Unable to replace a non-existing slice.");
12364     const SDValue &OldBaseAddr = Origin->getBasePtr();
12365     SDValue BaseAddr = OldBaseAddr;
12366     // Get the offset in that chunk of bytes w.r.t. the endianness.
12367     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
12368     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
12369     if (Offset) {
12370       // BaseAddr = BaseAddr + Offset.
12371       EVT ArithType = BaseAddr.getValueType();
12372       SDLoc DL(Origin);
12373       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
12374                               DAG->getConstant(Offset, DL, ArithType));
12375     }
12376 
12377     // Create the type of the loaded slice according to its size.
12378     EVT SliceType = getLoadedType();
12379 
12380     // Create the load for the slice.
12381     SDValue LastInst =
12382         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
12383                      Origin->getPointerInfo().getWithOffset(Offset),
12384                      getAlignment(), Origin->getMemOperand()->getFlags());
12385     // If the final type is not the same as the loaded type, this means that
12386     // we have to pad with zero. Create a zero extend for that.
12387     EVT FinalType = Inst->getValueType(0);
12388     if (SliceType != FinalType)
12389       LastInst =
12390           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
12391     return LastInst;
12392   }
12393 
12394   /// Check if this slice can be merged with an expensive cross register
12395   /// bank copy. E.g.,
12396   /// i = load i32
12397   /// f = bitcast i32 i to float
12398   bool canMergeExpensiveCrossRegisterBankCopy() const {
12399     if (!Inst || !Inst->hasOneUse())
12400       return false;
12401     SDNode *Use = *Inst->use_begin();
12402     if (Use->getOpcode() != ISD::BITCAST)
12403       return false;
12404     assert(DAG && "Missing context");
12405     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
12406     EVT ResVT = Use->getValueType(0);
12407     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
12408     const TargetRegisterClass *ArgRC =
12409         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
12410     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
12411       return false;
12412 
12413     // At this point, we know that we perform a cross-register-bank copy.
12414     // Check if it is expensive.
12415     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
12416     // Assume bitcasts are cheap, unless both register classes do not
12417     // explicitly share a common sub class.
12418     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
12419       return false;
12420 
12421     // Check if it will be merged with the load.
12422     // 1. Check the alignment constraint.
12423     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
12424         ResVT.getTypeForEVT(*DAG->getContext()));
12425 
12426     if (RequiredAlignment > getAlignment())
12427       return false;
12428 
12429     // 2. Check that the load is a legal operation for that type.
12430     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
12431       return false;
12432 
12433     // 3. Check that we do not have a zext in the way.
12434     if (Inst->getValueType(0) != getLoadedType())
12435       return false;
12436 
12437     return true;
12438   }
12439 };
12440 
12441 } // end anonymous namespace
12442 
12443 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
12444 /// \p UsedBits looks like 0..0 1..1 0..0.
12445 static bool areUsedBitsDense(const APInt &UsedBits) {
12446   // If all the bits are one, this is dense!
12447   if (UsedBits.isAllOnesValue())
12448     return true;
12449 
12450   // Get rid of the unused bits on the right.
12451   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
12452   // Get rid of the unused bits on the left.
12453   if (NarrowedUsedBits.countLeadingZeros())
12454     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
12455   // Check that the chunk of bits is completely used.
12456   return NarrowedUsedBits.isAllOnesValue();
12457 }
12458 
12459 /// Check whether or not \p First and \p Second are next to each other
12460 /// in memory. This means that there is no hole between the bits loaded
12461 /// by \p First and the bits loaded by \p Second.
12462 static bool areSlicesNextToEachOther(const LoadedSlice &First,
12463                                      const LoadedSlice &Second) {
12464   assert(First.Origin == Second.Origin && First.Origin &&
12465          "Unable to match different memory origins.");
12466   APInt UsedBits = First.getUsedBits();
12467   assert((UsedBits & Second.getUsedBits()) == 0 &&
12468          "Slices are not supposed to overlap.");
12469   UsedBits |= Second.getUsedBits();
12470   return areUsedBitsDense(UsedBits);
12471 }
12472 
12473 /// Adjust the \p GlobalLSCost according to the target
12474 /// paring capabilities and the layout of the slices.
12475 /// \pre \p GlobalLSCost should account for at least as many loads as
12476 /// there is in the slices in \p LoadedSlices.
12477 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12478                                  LoadedSlice::Cost &GlobalLSCost) {
12479   unsigned NumberOfSlices = LoadedSlices.size();
12480   // If there is less than 2 elements, no pairing is possible.
12481   if (NumberOfSlices < 2)
12482     return;
12483 
12484   // Sort the slices so that elements that are likely to be next to each
12485   // other in memory are next to each other in the list.
12486   llvm::sort(LoadedSlices.begin(), LoadedSlices.end(),
12487              [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
12488     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
12489     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
12490   });
12491   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
12492   // First (resp. Second) is the first (resp. Second) potentially candidate
12493   // to be placed in a paired load.
12494   const LoadedSlice *First = nullptr;
12495   const LoadedSlice *Second = nullptr;
12496   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
12497                 // Set the beginning of the pair.
12498                                                            First = Second) {
12499     Second = &LoadedSlices[CurrSlice];
12500 
12501     // If First is NULL, it means we start a new pair.
12502     // Get to the next slice.
12503     if (!First)
12504       continue;
12505 
12506     EVT LoadedType = First->getLoadedType();
12507 
12508     // If the types of the slices are different, we cannot pair them.
12509     if (LoadedType != Second->getLoadedType())
12510       continue;
12511 
12512     // Check if the target supplies paired loads for this type.
12513     unsigned RequiredAlignment = 0;
12514     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
12515       // move to the next pair, this type is hopeless.
12516       Second = nullptr;
12517       continue;
12518     }
12519     // Check if we meet the alignment requirement.
12520     if (RequiredAlignment > First->getAlignment())
12521       continue;
12522 
12523     // Check that both loads are next to each other in memory.
12524     if (!areSlicesNextToEachOther(*First, *Second))
12525       continue;
12526 
12527     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
12528     --GlobalLSCost.Loads;
12529     // Move to the next pair.
12530     Second = nullptr;
12531   }
12532 }
12533 
12534 /// Check the profitability of all involved LoadedSlice.
12535 /// Currently, it is considered profitable if there is exactly two
12536 /// involved slices (1) which are (2) next to each other in memory, and
12537 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
12538 ///
12539 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
12540 /// the elements themselves.
12541 ///
12542 /// FIXME: When the cost model will be mature enough, we can relax
12543 /// constraints (1) and (2).
12544 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
12545                                 const APInt &UsedBits, bool ForCodeSize) {
12546   unsigned NumberOfSlices = LoadedSlices.size();
12547   if (StressLoadSlicing)
12548     return NumberOfSlices > 1;
12549 
12550   // Check (1).
12551   if (NumberOfSlices != 2)
12552     return false;
12553 
12554   // Check (2).
12555   if (!areUsedBitsDense(UsedBits))
12556     return false;
12557 
12558   // Check (3).
12559   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
12560   // The original code has one big load.
12561   OrigCost.Loads = 1;
12562   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
12563     const LoadedSlice &LS = LoadedSlices[CurrSlice];
12564     // Accumulate the cost of all the slices.
12565     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
12566     GlobalSlicingCost += SliceCost;
12567 
12568     // Account as cost in the original configuration the gain obtained
12569     // with the current slices.
12570     OrigCost.addSliceGain(LS);
12571   }
12572 
12573   // If the target supports paired load, adjust the cost accordingly.
12574   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
12575   return OrigCost > GlobalSlicingCost;
12576 }
12577 
12578 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
12579 /// operations, split it in the various pieces being extracted.
12580 ///
12581 /// This sort of thing is introduced by SROA.
12582 /// This slicing takes care not to insert overlapping loads.
12583 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
12584 bool DAGCombiner::SliceUpLoad(SDNode *N) {
12585   if (Level < AfterLegalizeDAG)
12586     return false;
12587 
12588   LoadSDNode *LD = cast<LoadSDNode>(N);
12589   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
12590       !LD->getValueType(0).isInteger())
12591     return false;
12592 
12593   // Keep track of already used bits to detect overlapping values.
12594   // In that case, we will just abort the transformation.
12595   APInt UsedBits(LD->getValueSizeInBits(0), 0);
12596 
12597   SmallVector<LoadedSlice, 4> LoadedSlices;
12598 
12599   // Check if this load is used as several smaller chunks of bits.
12600   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
12601   // of computation for each trunc.
12602   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
12603        UI != UIEnd; ++UI) {
12604     // Skip the uses of the chain.
12605     if (UI.getUse().getResNo() != 0)
12606       continue;
12607 
12608     SDNode *User = *UI;
12609     unsigned Shift = 0;
12610 
12611     // Check if this is a trunc(lshr).
12612     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
12613         isa<ConstantSDNode>(User->getOperand(1))) {
12614       Shift = User->getConstantOperandVal(1);
12615       User = *User->use_begin();
12616     }
12617 
12618     // At this point, User is a Truncate, iff we encountered, trunc or
12619     // trunc(lshr).
12620     if (User->getOpcode() != ISD::TRUNCATE)
12621       return false;
12622 
12623     // The width of the type must be a power of 2 and greater than 8-bits.
12624     // Otherwise the load cannot be represented in LLVM IR.
12625     // Moreover, if we shifted with a non-8-bits multiple, the slice
12626     // will be across several bytes. We do not support that.
12627     unsigned Width = User->getValueSizeInBits(0);
12628     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
12629       return false;
12630 
12631     // Build the slice for this chain of computations.
12632     LoadedSlice LS(User, LD, Shift, &DAG);
12633     APInt CurrentUsedBits = LS.getUsedBits();
12634 
12635     // Check if this slice overlaps with another.
12636     if ((CurrentUsedBits & UsedBits) != 0)
12637       return false;
12638     // Update the bits used globally.
12639     UsedBits |= CurrentUsedBits;
12640 
12641     // Check if the new slice would be legal.
12642     if (!LS.isLegal())
12643       return false;
12644 
12645     // Record the slice.
12646     LoadedSlices.push_back(LS);
12647   }
12648 
12649   // Abort slicing if it does not seem to be profitable.
12650   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
12651     return false;
12652 
12653   ++SlicedLoads;
12654 
12655   // Rewrite each chain to use an independent load.
12656   // By construction, each chain can be represented by a unique load.
12657 
12658   // Prepare the argument for the new token factor for all the slices.
12659   SmallVector<SDValue, 8> ArgChains;
12660   for (SmallVectorImpl<LoadedSlice>::const_iterator
12661            LSIt = LoadedSlices.begin(),
12662            LSItEnd = LoadedSlices.end();
12663        LSIt != LSItEnd; ++LSIt) {
12664     SDValue SliceInst = LSIt->loadSlice();
12665     CombineTo(LSIt->Inst, SliceInst, true);
12666     if (SliceInst.getOpcode() != ISD::LOAD)
12667       SliceInst = SliceInst.getOperand(0);
12668     assert(SliceInst->getOpcode() == ISD::LOAD &&
12669            "It takes more than a zext to get to the loaded slice!!");
12670     ArgChains.push_back(SliceInst.getValue(1));
12671   }
12672 
12673   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
12674                               ArgChains);
12675   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
12676   AddToWorklist(Chain.getNode());
12677   return true;
12678 }
12679 
12680 /// Check to see if V is (and load (ptr), imm), where the load is having
12681 /// specific bytes cleared out.  If so, return the byte size being masked out
12682 /// and the shift amount.
12683 static std::pair<unsigned, unsigned>
12684 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
12685   std::pair<unsigned, unsigned> Result(0, 0);
12686 
12687   // Check for the structure we're looking for.
12688   if (V->getOpcode() != ISD::AND ||
12689       !isa<ConstantSDNode>(V->getOperand(1)) ||
12690       !ISD::isNormalLoad(V->getOperand(0).getNode()))
12691     return Result;
12692 
12693   // Check the chain and pointer.
12694   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
12695   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
12696 
12697   // The store should be chained directly to the load or be an operand of a
12698   // tokenfactor.
12699   if (LD == Chain.getNode())
12700     ; // ok.
12701   else if (Chain->getOpcode() != ISD::TokenFactor)
12702     return Result; // Fail.
12703   else {
12704     bool isOk = false;
12705     for (const SDValue &ChainOp : Chain->op_values())
12706       if (ChainOp.getNode() == LD) {
12707         isOk = true;
12708         break;
12709       }
12710     if (!isOk) return Result;
12711   }
12712 
12713   // This only handles simple types.
12714   if (V.getValueType() != MVT::i16 &&
12715       V.getValueType() != MVT::i32 &&
12716       V.getValueType() != MVT::i64)
12717     return Result;
12718 
12719   // Check the constant mask.  Invert it so that the bits being masked out are
12720   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
12721   // follow the sign bit for uniformity.
12722   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12723   unsigned NotMaskLZ = countLeadingZeros(NotMask);
12724   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
12725   unsigned NotMaskTZ = countTrailingZeros(NotMask);
12726   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
12727   if (NotMaskLZ == 64) return Result;  // All zero mask.
12728 
12729   // See if we have a continuous run of bits.  If so, we have 0*1+0*
12730   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12731     return Result;
12732 
12733   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12734   if (V.getValueType() != MVT::i64 && NotMaskLZ)
12735     NotMaskLZ -= 64-V.getValueSizeInBits();
12736 
12737   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12738   switch (MaskedBytes) {
12739   case 1:
12740   case 2:
12741   case 4: break;
12742   default: return Result; // All one mask, or 5-byte mask.
12743   }
12744 
12745   // Verify that the first bit starts at a multiple of mask so that the access
12746   // is aligned the same as the access width.
12747   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12748 
12749   Result.first = MaskedBytes;
12750   Result.second = NotMaskTZ/8;
12751   return Result;
12752 }
12753 
12754 /// Check to see if IVal is something that provides a value as specified by
12755 /// MaskInfo. If so, replace the specified store with a narrower store of
12756 /// truncated IVal.
12757 static SDNode *
12758 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12759                                 SDValue IVal, StoreSDNode *St,
12760                                 DAGCombiner *DC) {
12761   unsigned NumBytes = MaskInfo.first;
12762   unsigned ByteShift = MaskInfo.second;
12763   SelectionDAG &DAG = DC->getDAG();
12764 
12765   // Check to see if IVal is all zeros in the part being masked in by the 'or'
12766   // that uses this.  If not, this is not a replacement.
12767   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12768                                   ByteShift*8, (ByteShift+NumBytes)*8);
12769   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12770 
12771   // Check that it is legal on the target to do this.  It is legal if the new
12772   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12773   // legalization.
12774   MVT VT = MVT::getIntegerVT(NumBytes*8);
12775   if (!DC->isTypeLegal(VT))
12776     return nullptr;
12777 
12778   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
12779   // shifted by ByteShift and truncated down to NumBytes.
12780   if (ByteShift) {
12781     SDLoc DL(IVal);
12782     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12783                        DAG.getConstant(ByteShift*8, DL,
12784                                     DC->getShiftAmountTy(IVal.getValueType())));
12785   }
12786 
12787   // Figure out the offset for the store and the alignment of the access.
12788   unsigned StOffset;
12789   unsigned NewAlign = St->getAlignment();
12790 
12791   if (DAG.getDataLayout().isLittleEndian())
12792     StOffset = ByteShift;
12793   else
12794     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12795 
12796   SDValue Ptr = St->getBasePtr();
12797   if (StOffset) {
12798     SDLoc DL(IVal);
12799     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12800                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12801     NewAlign = MinAlign(NewAlign, StOffset);
12802   }
12803 
12804   // Truncate down to the new size.
12805   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12806 
12807   ++OpsNarrowed;
12808   return DAG
12809       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12810                 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12811       .getNode();
12812 }
12813 
12814 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12815 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12816 /// narrowing the load and store if it would end up being a win for performance
12817 /// or code size.
12818 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12819   StoreSDNode *ST  = cast<StoreSDNode>(N);
12820   if (ST->isVolatile())
12821     return SDValue();
12822 
12823   SDValue Chain = ST->getChain();
12824   SDValue Value = ST->getValue();
12825   SDValue Ptr   = ST->getBasePtr();
12826   EVT VT = Value.getValueType();
12827 
12828   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12829     return SDValue();
12830 
12831   unsigned Opc = Value.getOpcode();
12832 
12833   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12834   // is a byte mask indicating a consecutive number of bytes, check to see if
12835   // Y is known to provide just those bytes.  If so, we try to replace the
12836   // load + replace + store sequence with a single (narrower) store, which makes
12837   // the load dead.
12838   if (Opc == ISD::OR) {
12839     std::pair<unsigned, unsigned> MaskedLoad;
12840     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12841     if (MaskedLoad.first)
12842       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12843                                                   Value.getOperand(1), ST,this))
12844         return SDValue(NewST, 0);
12845 
12846     // Or is commutative, so try swapping X and Y.
12847     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12848     if (MaskedLoad.first)
12849       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12850                                                   Value.getOperand(0), ST,this))
12851         return SDValue(NewST, 0);
12852   }
12853 
12854   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12855       Value.getOperand(1).getOpcode() != ISD::Constant)
12856     return SDValue();
12857 
12858   SDValue N0 = Value.getOperand(0);
12859   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12860       Chain == SDValue(N0.getNode(), 1)) {
12861     LoadSDNode *LD = cast<LoadSDNode>(N0);
12862     if (LD->getBasePtr() != Ptr ||
12863         LD->getPointerInfo().getAddrSpace() !=
12864         ST->getPointerInfo().getAddrSpace())
12865       return SDValue();
12866 
12867     // Find the type to narrow it the load / op / store to.
12868     SDValue N1 = Value.getOperand(1);
12869     unsigned BitWidth = N1.getValueSizeInBits();
12870     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12871     if (Opc == ISD::AND)
12872       Imm ^= APInt::getAllOnesValue(BitWidth);
12873     if (Imm == 0 || Imm.isAllOnesValue())
12874       return SDValue();
12875     unsigned ShAmt = Imm.countTrailingZeros();
12876     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12877     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12878     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12879     // The narrowing should be profitable, the load/store operation should be
12880     // legal (or custom) and the store size should be equal to the NewVT width.
12881     while (NewBW < BitWidth &&
12882            (NewVT.getStoreSizeInBits() != NewBW ||
12883             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12884             !TLI.isNarrowingProfitable(VT, NewVT))) {
12885       NewBW = NextPowerOf2(NewBW);
12886       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12887     }
12888     if (NewBW >= BitWidth)
12889       return SDValue();
12890 
12891     // If the lsb changed does not start at the type bitwidth boundary,
12892     // start at the previous one.
12893     if (ShAmt % NewBW)
12894       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12895     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12896                                    std::min(BitWidth, ShAmt + NewBW));
12897     if ((Imm & Mask) == Imm) {
12898       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12899       if (Opc == ISD::AND)
12900         NewImm ^= APInt::getAllOnesValue(NewBW);
12901       uint64_t PtrOff = ShAmt / 8;
12902       // For big endian targets, we need to adjust the offset to the pointer to
12903       // load the correct bytes.
12904       if (DAG.getDataLayout().isBigEndian())
12905         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12906 
12907       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12908       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12909       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12910         return SDValue();
12911 
12912       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12913                                    Ptr.getValueType(), Ptr,
12914                                    DAG.getConstant(PtrOff, SDLoc(LD),
12915                                                    Ptr.getValueType()));
12916       SDValue NewLD =
12917           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12918                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12919                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
12920       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12921                                    DAG.getConstant(NewImm, SDLoc(Value),
12922                                                    NewVT));
12923       SDValue NewST =
12924           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12925                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12926 
12927       AddToWorklist(NewPtr.getNode());
12928       AddToWorklist(NewLD.getNode());
12929       AddToWorklist(NewVal.getNode());
12930       WorklistRemover DeadNodes(*this);
12931       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12932       ++OpsNarrowed;
12933       return NewST;
12934     }
12935   }
12936 
12937   return SDValue();
12938 }
12939 
12940 /// For a given floating point load / store pair, if the load value isn't used
12941 /// by any other operations, then consider transforming the pair to integer
12942 /// load / store operations if the target deems the transformation profitable.
12943 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12944   StoreSDNode *ST  = cast<StoreSDNode>(N);
12945   SDValue Chain = ST->getChain();
12946   SDValue Value = ST->getValue();
12947   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12948       Value.hasOneUse() &&
12949       Chain == SDValue(Value.getNode(), 1)) {
12950     LoadSDNode *LD = cast<LoadSDNode>(Value);
12951     EVT VT = LD->getMemoryVT();
12952     if (!VT.isFloatingPoint() ||
12953         VT != ST->getMemoryVT() ||
12954         LD->isNonTemporal() ||
12955         ST->isNonTemporal() ||
12956         LD->getPointerInfo().getAddrSpace() != 0 ||
12957         ST->getPointerInfo().getAddrSpace() != 0)
12958       return SDValue();
12959 
12960     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12961     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12962         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12963         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12964         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12965       return SDValue();
12966 
12967     unsigned LDAlign = LD->getAlignment();
12968     unsigned STAlign = ST->getAlignment();
12969     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12970     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12971     if (LDAlign < ABIAlign || STAlign < ABIAlign)
12972       return SDValue();
12973 
12974     SDValue NewLD =
12975         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12976                     LD->getPointerInfo(), LDAlign);
12977 
12978     SDValue NewST =
12979         DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12980                      ST->getPointerInfo(), STAlign);
12981 
12982     AddToWorklist(NewLD.getNode());
12983     AddToWorklist(NewST.getNode());
12984     WorklistRemover DeadNodes(*this);
12985     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12986     ++LdStFP2Int;
12987     return NewST;
12988   }
12989 
12990   return SDValue();
12991 }
12992 
12993 // This is a helper function for visitMUL to check the profitability
12994 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12995 // MulNode is the original multiply, AddNode is (add x, c1),
12996 // and ConstNode is c2.
12997 //
12998 // If the (add x, c1) has multiple uses, we could increase
12999 // the number of adds if we make this transformation.
13000 // It would only be worth doing this if we can remove a
13001 // multiply in the process. Check for that here.
13002 // To illustrate:
13003 //     (A + c1) * c3
13004 //     (A + c2) * c3
13005 // We're checking for cases where we have common "c3 * A" expressions.
13006 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
13007                                               SDValue &AddNode,
13008                                               SDValue &ConstNode) {
13009   APInt Val;
13010 
13011   // If the add only has one use, this would be OK to do.
13012   if (AddNode.getNode()->hasOneUse())
13013     return true;
13014 
13015   // Walk all the users of the constant with which we're multiplying.
13016   for (SDNode *Use : ConstNode->uses()) {
13017     if (Use == MulNode) // This use is the one we're on right now. Skip it.
13018       continue;
13019 
13020     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
13021       SDNode *OtherOp;
13022       SDNode *MulVar = AddNode.getOperand(0).getNode();
13023 
13024       // OtherOp is what we're multiplying against the constant.
13025       if (Use->getOperand(0) == ConstNode)
13026         OtherOp = Use->getOperand(1).getNode();
13027       else
13028         OtherOp = Use->getOperand(0).getNode();
13029 
13030       // Check to see if multiply is with the same operand of our "add".
13031       //
13032       //     ConstNode  = CONST
13033       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
13034       //     ...
13035       //     AddNode  = (A + c1)  <-- MulVar is A.
13036       //         = AddNode * ConstNode   <-- current visiting instruction.
13037       //
13038       // If we make this transformation, we will have a common
13039       // multiply (ConstNode * A) that we can save.
13040       if (OtherOp == MulVar)
13041         return true;
13042 
13043       // Now check to see if a future expansion will give us a common
13044       // multiply.
13045       //
13046       //     ConstNode  = CONST
13047       //     AddNode    = (A + c1)
13048       //     ...   = AddNode * ConstNode <-- current visiting instruction.
13049       //     ...
13050       //     OtherOp = (A + c2)
13051       //     Use     = OtherOp * ConstNode <-- visiting Use.
13052       //
13053       // If we make this transformation, we will have a common
13054       // multiply (CONST * A) after we also do the same transformation
13055       // to the "t2" instruction.
13056       if (OtherOp->getOpcode() == ISD::ADD &&
13057           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
13058           OtherOp->getOperand(0).getNode() == MulVar)
13059         return true;
13060     }
13061   }
13062 
13063   // Didn't find a case where this would be profitable.
13064   return false;
13065 }
13066 
13067 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
13068                                          unsigned NumStores) {
13069   SmallVector<SDValue, 8> Chains;
13070   SmallPtrSet<const SDNode *, 8> Visited;
13071   SDLoc StoreDL(StoreNodes[0].MemNode);
13072 
13073   for (unsigned i = 0; i < NumStores; ++i) {
13074     Visited.insert(StoreNodes[i].MemNode);
13075   }
13076 
13077   // don't include nodes that are children
13078   for (unsigned i = 0; i < NumStores; ++i) {
13079     if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
13080       Chains.push_back(StoreNodes[i].MemNode->getChain());
13081   }
13082 
13083   assert(Chains.size() > 0 && "Chain should have generated a chain");
13084   return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
13085 }
13086 
13087 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
13088     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
13089     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
13090   // Make sure we have something to merge.
13091   if (NumStores < 2)
13092     return false;
13093 
13094   // The latest Node in the DAG.
13095   SDLoc DL(StoreNodes[0].MemNode);
13096 
13097   int64_t ElementSizeBits = MemVT.getStoreSizeInBits();
13098   unsigned SizeInBits = NumStores * ElementSizeBits;
13099   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13100 
13101   EVT StoreTy;
13102   if (UseVector) {
13103     unsigned Elts = NumStores * NumMemElts;
13104     // Get the type for the merged vector store.
13105     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13106   } else
13107     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
13108 
13109   SDValue StoredVal;
13110   if (UseVector) {
13111     if (IsConstantSrc) {
13112       SmallVector<SDValue, 8> BuildVector;
13113       for (unsigned I = 0; I != NumStores; ++I) {
13114         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
13115         SDValue Val = St->getValue();
13116         // If constant is of the wrong type, convert it now.
13117         if (MemVT != Val.getValueType()) {
13118           Val = peekThroughBitcast(Val);
13119           // Deal with constants of wrong size.
13120           if (ElementSizeBits != Val.getValueSizeInBits()) {
13121             EVT IntMemVT =
13122                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
13123             if (isa<ConstantFPSDNode>(Val)) {
13124               // Not clear how to truncate FP values.
13125               return false;
13126             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
13127               Val = DAG.getConstant(C->getAPIntValue()
13128                                         .zextOrTrunc(Val.getValueSizeInBits())
13129                                         .zextOrTrunc(ElementSizeBits),
13130                                     SDLoc(C), IntMemVT);
13131           }
13132           // Make sure correctly size type is the correct type.
13133           Val = DAG.getBitcast(MemVT, Val);
13134         }
13135         BuildVector.push_back(Val);
13136       }
13137       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13138                                                : ISD::BUILD_VECTOR,
13139                               DL, StoreTy, BuildVector);
13140     } else {
13141       SmallVector<SDValue, 8> Ops;
13142       for (unsigned i = 0; i < NumStores; ++i) {
13143         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13144         SDValue Val = peekThroughBitcast(St->getValue());
13145         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
13146         // type MemVT. If the underlying value is not the correct
13147         // type, but it is an extraction of an appropriate vector we
13148         // can recast Val to be of the correct type. This may require
13149         // converting between EXTRACT_VECTOR_ELT and
13150         // EXTRACT_SUBVECTOR.
13151         if ((MemVT != Val.getValueType()) &&
13152             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13153              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
13154           SDValue Vec = Val.getOperand(0);
13155           EVT MemVTScalarTy = MemVT.getScalarType();
13156           // We may need to add a bitcast here to get types to line up.
13157           if (MemVTScalarTy != Vec.getValueType()) {
13158             unsigned Elts = Vec.getValueType().getSizeInBits() /
13159                             MemVTScalarTy.getSizeInBits();
13160             EVT NewVecTy =
13161                 EVT::getVectorVT(*DAG.getContext(), MemVTScalarTy, Elts);
13162             Vec = DAG.getBitcast(NewVecTy, Vec);
13163           }
13164           auto OpC = (MemVT.isVector()) ? ISD::EXTRACT_SUBVECTOR
13165                                         : ISD::EXTRACT_VECTOR_ELT;
13166           Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Val.getOperand(1));
13167         }
13168         Ops.push_back(Val);
13169       }
13170 
13171       // Build the extracted vector elements back into a vector.
13172       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
13173                                                : ISD::BUILD_VECTOR,
13174                               DL, StoreTy, Ops);
13175     }
13176   } else {
13177     // We should always use a vector store when merging extracted vector
13178     // elements, so this path implies a store of constants.
13179     assert(IsConstantSrc && "Merged vector elements should use vector store");
13180 
13181     APInt StoreInt(SizeInBits, 0);
13182 
13183     // Construct a single integer constant which is made of the smaller
13184     // constant inputs.
13185     bool IsLE = DAG.getDataLayout().isLittleEndian();
13186     for (unsigned i = 0; i < NumStores; ++i) {
13187       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
13188       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
13189 
13190       SDValue Val = St->getValue();
13191       Val = peekThroughBitcast(Val);
13192       StoreInt <<= ElementSizeBits;
13193       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
13194         StoreInt |= C->getAPIntValue()
13195                         .zextOrTrunc(ElementSizeBits)
13196                         .zextOrTrunc(SizeInBits);
13197       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
13198         StoreInt |= C->getValueAPF()
13199                         .bitcastToAPInt()
13200                         .zextOrTrunc(ElementSizeBits)
13201                         .zextOrTrunc(SizeInBits);
13202         // If fp truncation is necessary give up for now.
13203         if (MemVT.getSizeInBits() != ElementSizeBits)
13204           return false;
13205       } else {
13206         llvm_unreachable("Invalid constant element type");
13207       }
13208     }
13209 
13210     // Create the new Load and Store operations.
13211     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
13212   }
13213 
13214   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13215   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
13216 
13217   // make sure we use trunc store if it's necessary to be legal.
13218   SDValue NewStore;
13219   if (!UseTrunc) {
13220     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
13221                             FirstInChain->getPointerInfo(),
13222                             FirstInChain->getAlignment());
13223   } else { // Must be realized as a trunc store
13224     EVT LegalizedStoredValueTy =
13225         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
13226     unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
13227     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
13228     SDValue ExtendedStoreVal =
13229         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
13230                         LegalizedStoredValueTy);
13231     NewStore = DAG.getTruncStore(
13232         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
13233         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
13234         FirstInChain->getAlignment(),
13235         FirstInChain->getMemOperand()->getFlags());
13236   }
13237 
13238   // Replace all merged stores with the new store.
13239   for (unsigned i = 0; i < NumStores; ++i)
13240     CombineTo(StoreNodes[i].MemNode, NewStore);
13241 
13242   AddToWorklist(NewChain.getNode());
13243   return true;
13244 }
13245 
13246 void DAGCombiner::getStoreMergeCandidates(
13247     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
13248     SDNode *&RootNode) {
13249   // This holds the base pointer, index, and the offset in bytes from the base
13250   // pointer.
13251   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
13252   EVT MemVT = St->getMemoryVT();
13253 
13254   SDValue Val = peekThroughBitcast(St->getValue());
13255   // We must have a base and an offset.
13256   if (!BasePtr.getBase().getNode())
13257     return;
13258 
13259   // Do not handle stores to undef base pointers.
13260   if (BasePtr.getBase().isUndef())
13261     return;
13262 
13263   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
13264   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13265                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13266   bool IsLoadSrc = isa<LoadSDNode>(Val);
13267   BaseIndexOffset LBasePtr;
13268   // Match on loadbaseptr if relevant.
13269   EVT LoadVT;
13270   if (IsLoadSrc) {
13271     auto *Ld = cast<LoadSDNode>(Val);
13272     LBasePtr = BaseIndexOffset::match(Ld, DAG);
13273     LoadVT = Ld->getMemoryVT();
13274     // Load and store should be the same type.
13275     if (MemVT != LoadVT)
13276       return;
13277     // Loads must only have one use.
13278     if (!Ld->hasNUsesOfValue(1, 0))
13279       return;
13280     // The memory operands must not be volatile.
13281     if (Ld->isVolatile() || Ld->isIndexed())
13282       return;
13283   }
13284   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
13285                             int64_t &Offset) -> bool {
13286     if (Other->isVolatile() || Other->isIndexed())
13287       return false;
13288     SDValue Val = peekThroughBitcast(Other->getValue());
13289     // Allow merging constants of different types as integers.
13290     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
13291                                            : Other->getMemoryVT() != MemVT;
13292     if (IsLoadSrc) {
13293       if (NoTypeMatch)
13294         return false;
13295       // The Load's Base Ptr must also match
13296       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) {
13297         auto LPtr = BaseIndexOffset::match(OtherLd, DAG);
13298         if (LoadVT != OtherLd->getMemoryVT())
13299           return false;
13300         // Loads must only have one use.
13301         if (!OtherLd->hasNUsesOfValue(1, 0))
13302           return false;
13303         // The memory operands must not be volatile.
13304         if (OtherLd->isVolatile() || OtherLd->isIndexed())
13305           return false;
13306         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
13307           return false;
13308       } else
13309         return false;
13310     }
13311     if (IsConstantSrc) {
13312       if (NoTypeMatch)
13313         return false;
13314       if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val)))
13315         return false;
13316     }
13317     if (IsExtractVecSrc) {
13318       // Do not merge truncated stores here.
13319       if (Other->isTruncatingStore())
13320         return false;
13321       if (!MemVT.bitsEq(Val.getValueType()))
13322         return false;
13323       if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13324           Val.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13325         return false;
13326     }
13327     Ptr = BaseIndexOffset::match(Other, DAG);
13328     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
13329   };
13330 
13331   // We looking for a root node which is an ancestor to all mergable
13332   // stores. We search up through a load, to our root and then down
13333   // through all children. For instance we will find Store{1,2,3} if
13334   // St is Store1, Store2. or Store3 where the root is not a load
13335   // which always true for nonvolatile ops. TODO: Expand
13336   // the search to find all valid candidates through multiple layers of loads.
13337   //
13338   // Root
13339   // |-------|-------|
13340   // Load    Load    Store3
13341   // |       |
13342   // Store1   Store2
13343   //
13344   // FIXME: We should be able to climb and
13345   // descend TokenFactors to find candidates as well.
13346 
13347   RootNode = St->getChain().getNode();
13348 
13349   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
13350     RootNode = Ldn->getChain().getNode();
13351     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13352       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
13353         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
13354           if (I2.getOperandNo() == 0)
13355             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
13356               BaseIndexOffset Ptr;
13357               int64_t PtrDiff;
13358               if (CandidateMatch(OtherST, Ptr, PtrDiff))
13359                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13360             }
13361   } else
13362     for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
13363       if (I.getOperandNo() == 0)
13364         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
13365           BaseIndexOffset Ptr;
13366           int64_t PtrDiff;
13367           if (CandidateMatch(OtherST, Ptr, PtrDiff))
13368             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
13369         }
13370 }
13371 
13372 // We need to check that merging these stores does not cause a loop in
13373 // the DAG. Any store candidate may depend on another candidate
13374 // indirectly through its operand (we already consider dependencies
13375 // through the chain). Check in parallel by searching up from
13376 // non-chain operands of candidates.
13377 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
13378     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
13379     SDNode *RootNode) {
13380   // FIXME: We should be able to truncate a full search of
13381   // predecessors by doing a BFS and keeping tabs the originating
13382   // stores from which worklist nodes come from in a similar way to
13383   // TokenFactor simplfication.
13384 
13385   SmallPtrSet<const SDNode *, 32> Visited;
13386   SmallVector<const SDNode *, 8> Worklist;
13387 
13388   // RootNode is a predecessor to all candidates so we need not search
13389   // past it. Add RootNode (peeking through TokenFactors). Do not count
13390   // these towards size check.
13391 
13392   Worklist.push_back(RootNode);
13393   while (!Worklist.empty()) {
13394     auto N = Worklist.pop_back_val();
13395     if (N->getOpcode() == ISD::TokenFactor) {
13396       for (SDValue Op : N->ops())
13397         Worklist.push_back(Op.getNode());
13398     }
13399     Visited.insert(N);
13400   }
13401 
13402   // Don't count pruning nodes towards max.
13403   unsigned int Max = 1024 + Visited.size();
13404   // Search Ops of store candidates.
13405   for (unsigned i = 0; i < NumStores; ++i) {
13406     SDNode *N = StoreNodes[i].MemNode;
13407     // Of the 4 Store Operands:
13408     //   * Chain (Op 0) -> We have already considered these
13409     //                    in candidate selection and can be
13410     //                    safely ignored
13411     //   * Value (Op 1) -> Cycles may happen (e.g. through load chains)
13412     //   * Address (Op 2) -> Merged addresses may only vary by a fixed constant
13413     //                      and so no cycles are possible.
13414     //   * (Op 3) -> appears to always be undef. Cannot be source of cycle.
13415     //
13416     // Thus we need only check predecessors of the value operands.
13417     auto *Op = N->getOperand(1).getNode();
13418     if (Visited.insert(Op).second)
13419       Worklist.push_back(Op);
13420   }
13421   // Search through DAG. We can stop early if we find a store node.
13422   for (unsigned i = 0; i < NumStores; ++i)
13423     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
13424                                      Max))
13425       return false;
13426   return true;
13427 }
13428 
13429 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
13430   if (OptLevel == CodeGenOpt::None)
13431     return false;
13432 
13433   EVT MemVT = St->getMemoryVT();
13434   int64_t ElementSizeBytes = MemVT.getStoreSize();
13435   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
13436 
13437   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
13438     return false;
13439 
13440   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
13441       Attribute::NoImplicitFloat);
13442 
13443   // This function cannot currently deal with non-byte-sized memory sizes.
13444   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
13445     return false;
13446 
13447   if (!MemVT.isSimple())
13448     return false;
13449 
13450   // Perform an early exit check. Do not bother looking at stored values that
13451   // are not constants, loads, or extracted vector elements.
13452   SDValue StoredVal = peekThroughBitcast(St->getValue());
13453   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
13454   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
13455                        isa<ConstantFPSDNode>(StoredVal);
13456   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
13457                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
13458 
13459   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
13460     return false;
13461 
13462   SmallVector<MemOpLink, 8> StoreNodes;
13463   SDNode *RootNode;
13464   // Find potential store merge candidates by searching through chain sub-DAG
13465   getStoreMergeCandidates(St, StoreNodes, RootNode);
13466 
13467   // Check if there is anything to merge.
13468   if (StoreNodes.size() < 2)
13469     return false;
13470 
13471   // Sort the memory operands according to their distance from the
13472   // base pointer.
13473   llvm::sort(StoreNodes.begin(), StoreNodes.end(),
13474              [](MemOpLink LHS, MemOpLink RHS) {
13475                return LHS.OffsetFromBase < RHS.OffsetFromBase;
13476              });
13477 
13478   // Store Merge attempts to merge the lowest stores. This generally
13479   // works out as if successful, as the remaining stores are checked
13480   // after the first collection of stores is merged. However, in the
13481   // case that a non-mergeable store is found first, e.g., {p[-2],
13482   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
13483   // mergeable cases. To prevent this, we prune such stores from the
13484   // front of StoreNodes here.
13485 
13486   bool RV = false;
13487   while (StoreNodes.size() > 1) {
13488     unsigned StartIdx = 0;
13489     while ((StartIdx + 1 < StoreNodes.size()) &&
13490            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
13491                StoreNodes[StartIdx + 1].OffsetFromBase)
13492       ++StartIdx;
13493 
13494     // Bail if we don't have enough candidates to merge.
13495     if (StartIdx + 1 >= StoreNodes.size())
13496       return RV;
13497 
13498     if (StartIdx)
13499       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
13500 
13501     // Scan the memory operations on the chain and find the first
13502     // non-consecutive store memory address.
13503     unsigned NumConsecutiveStores = 1;
13504     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
13505     // Check that the addresses are consecutive starting from the second
13506     // element in the list of stores.
13507     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
13508       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
13509       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13510         break;
13511       NumConsecutiveStores = i + 1;
13512     }
13513 
13514     if (NumConsecutiveStores < 2) {
13515       StoreNodes.erase(StoreNodes.begin(),
13516                        StoreNodes.begin() + NumConsecutiveStores);
13517       continue;
13518     }
13519 
13520     // The node with the lowest store address.
13521     LLVMContext &Context = *DAG.getContext();
13522     const DataLayout &DL = DAG.getDataLayout();
13523 
13524     // Store the constants into memory as one consecutive store.
13525     if (IsConstantSrc) {
13526       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13527       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13528       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13529       unsigned LastLegalType = 1;
13530       unsigned LastLegalVectorType = 1;
13531       bool LastIntegerTrunc = false;
13532       bool NonZero = false;
13533       unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
13534       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13535         StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
13536         SDValue StoredVal = ST->getValue();
13537         bool IsElementZero = false;
13538         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
13539           IsElementZero = C->isNullValue();
13540         else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
13541           IsElementZero = C->getConstantFPValue()->isNullValue();
13542         if (IsElementZero) {
13543           if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
13544             FirstZeroAfterNonZero = i;
13545         }
13546         NonZero |= !IsElementZero;
13547 
13548         // Find a legal type for the constant store.
13549         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13550         EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13551         bool IsFast = false;
13552         if (TLI.isTypeLegal(StoreTy) &&
13553             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13554             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13555                                    FirstStoreAlign, &IsFast) &&
13556             IsFast) {
13557           LastIntegerTrunc = false;
13558           LastLegalType = i + 1;
13559           // Or check whether a truncstore is legal.
13560         } else if (TLI.getTypeAction(Context, StoreTy) ==
13561                    TargetLowering::TypePromoteInteger) {
13562           EVT LegalizedStoredValueTy =
13563               TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
13564           if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13565               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13566               TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13567                                      FirstStoreAlign, &IsFast) &&
13568               IsFast) {
13569             LastIntegerTrunc = true;
13570             LastLegalType = i + 1;
13571           }
13572         }
13573 
13574         // We only use vectors if the constant is known to be zero or the target
13575         // allows it and the function is not marked with the noimplicitfloat
13576         // attribute.
13577         if ((!NonZero ||
13578              TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
13579             !NoVectors) {
13580           // Find a legal type for the vector store.
13581           unsigned Elts = (i + 1) * NumMemElts;
13582           EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13583           if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
13584               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13585               TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13586                                      FirstStoreAlign, &IsFast) &&
13587               IsFast)
13588             LastLegalVectorType = i + 1;
13589         }
13590       }
13591 
13592       bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
13593       unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
13594 
13595       // Check if we found a legal integer type that creates a meaningful merge.
13596       if (NumElem < 2) {
13597         // We know that candidate stores are in order and of correct
13598         // shape. While there is no mergeable sequence from the
13599         // beginning one may start later in the sequence. The only
13600         // reason a merge of size N could have failed where another of
13601         // the same size would not have, is if the alignment has
13602         // improved or we've dropped a non-zero value. Drop as many
13603         // candidates as we can here.
13604         unsigned NumSkip = 1;
13605         while (
13606             (NumSkip < NumConsecutiveStores) &&
13607             (NumSkip < FirstZeroAfterNonZero) &&
13608             (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) {
13609           NumSkip++;
13610         }
13611         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13612         continue;
13613       }
13614 
13615       // Check that we can merge these candidates without causing a cycle.
13616       if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
13617                                                     RootNode)) {
13618         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13619         continue;
13620       }
13621 
13622       bool Merged = MergeStoresOfConstantsOrVecElts(
13623           StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
13624       RV |= Merged;
13625 
13626       // Remove merged stores for next iteration.
13627       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13628       continue;
13629     }
13630 
13631     // When extracting multiple vector elements, try to store them
13632     // in one vector store rather than a sequence of scalar stores.
13633     if (IsExtractVecSrc) {
13634       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13635       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13636       unsigned FirstStoreAlign = FirstInChain->getAlignment();
13637       unsigned NumStoresToMerge = 1;
13638       for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13639         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13640         SDValue StVal = peekThroughBitcast(St->getValue());
13641         // This restriction could be loosened.
13642         // Bail out if any stored values are not elements extracted from a
13643         // vector. It should be possible to handle mixed sources, but load
13644         // sources need more careful handling (see the block of code below that
13645         // handles consecutive loads).
13646         if (StVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
13647             StVal.getOpcode() != ISD::EXTRACT_SUBVECTOR)
13648           return RV;
13649 
13650         // Find a legal type for the vector store.
13651         unsigned Elts = (i + 1) * NumMemElts;
13652         EVT Ty =
13653             EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
13654         bool IsFast;
13655         if (TLI.isTypeLegal(Ty) &&
13656             TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
13657             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
13658                                    FirstStoreAlign, &IsFast) &&
13659             IsFast)
13660           NumStoresToMerge = i + 1;
13661       }
13662 
13663       // Check if we found a legal integer type that creates a meaningful merge.
13664       if (NumStoresToMerge < 2) {
13665         // We know that candidate stores are in order and of correct
13666         // shape. While there is no mergeable sequence from the
13667         // beginning one may start later in the sequence. The only
13668         // reason a merge of size N could have failed where another of
13669         // the same size would not have, is if the alignment has
13670         // improved. Drop as many candidates as we can here.
13671         unsigned NumSkip = 1;
13672         while ((NumSkip < NumConsecutiveStores) &&
13673                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13674           NumSkip++;
13675 
13676         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13677         continue;
13678       }
13679 
13680       // Check that we can merge these candidates without causing a cycle.
13681       if (!checkMergeStoreCandidatesForDependencies(
13682               StoreNodes, NumStoresToMerge, RootNode)) {
13683         StoreNodes.erase(StoreNodes.begin(),
13684                          StoreNodes.begin() + NumStoresToMerge);
13685         continue;
13686       }
13687 
13688       bool Merged = MergeStoresOfConstantsOrVecElts(
13689           StoreNodes, MemVT, NumStoresToMerge, false, true, false);
13690       if (!Merged) {
13691         StoreNodes.erase(StoreNodes.begin(),
13692                          StoreNodes.begin() + NumStoresToMerge);
13693         continue;
13694       }
13695       // Remove merged stores for next iteration.
13696       StoreNodes.erase(StoreNodes.begin(),
13697                        StoreNodes.begin() + NumStoresToMerge);
13698       RV = true;
13699       continue;
13700     }
13701 
13702     // Below we handle the case of multiple consecutive stores that
13703     // come from multiple consecutive loads. We merge them into a single
13704     // wide load and a single wide store.
13705 
13706     // Look for load nodes which are used by the stored values.
13707     SmallVector<MemOpLink, 8> LoadNodes;
13708 
13709     // Find acceptable loads. Loads need to have the same chain (token factor),
13710     // must not be zext, volatile, indexed, and they must be consecutive.
13711     BaseIndexOffset LdBasePtr;
13712     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
13713       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
13714       SDValue Val = peekThroughBitcast(St->getValue());
13715       LoadSDNode *Ld = cast<LoadSDNode>(Val);
13716 
13717       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
13718       // If this is not the first ptr that we check.
13719       int64_t LdOffset = 0;
13720       if (LdBasePtr.getBase().getNode()) {
13721         // The base ptr must be the same.
13722         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
13723           break;
13724       } else {
13725         // Check that all other base pointers are the same as this one.
13726         LdBasePtr = LdPtr;
13727       }
13728 
13729       // We found a potential memory operand to merge.
13730       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
13731     }
13732 
13733     if (LoadNodes.size() < 2) {
13734       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13735       continue;
13736     }
13737 
13738     // If we have load/store pair instructions and we only have two values,
13739     // don't bother merging.
13740     unsigned RequiredAlignment;
13741     if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
13742         StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
13743       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
13744       continue;
13745     }
13746     LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
13747     unsigned FirstStoreAS = FirstInChain->getAddressSpace();
13748     unsigned FirstStoreAlign = FirstInChain->getAlignment();
13749     LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
13750     unsigned FirstLoadAS = FirstLoad->getAddressSpace();
13751     unsigned FirstLoadAlign = FirstLoad->getAlignment();
13752 
13753     // Scan the memory operations on the chain and find the first
13754     // non-consecutive load memory address. These variables hold the index in
13755     // the store node array.
13756     unsigned LastConsecutiveLoad = 1;
13757     // This variable refers to the size and not index in the array.
13758     unsigned LastLegalVectorType = 1;
13759     unsigned LastLegalIntegerType = 1;
13760     bool isDereferenceable = true;
13761     bool DoIntegerTruncate = false;
13762     StartAddress = LoadNodes[0].OffsetFromBase;
13763     SDValue FirstChain = FirstLoad->getChain();
13764     for (unsigned i = 1; i < LoadNodes.size(); ++i) {
13765       // All loads must share the same chain.
13766       if (LoadNodes[i].MemNode->getChain() != FirstChain)
13767         break;
13768 
13769       int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
13770       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
13771         break;
13772       LastConsecutiveLoad = i;
13773 
13774       if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
13775         isDereferenceable = false;
13776 
13777       // Find a legal type for the vector store.
13778       unsigned Elts = (i + 1) * NumMemElts;
13779       EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13780 
13781       bool IsFastSt, IsFastLd;
13782       if (TLI.isTypeLegal(StoreTy) &&
13783           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13784           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13785                                  FirstStoreAlign, &IsFastSt) &&
13786           IsFastSt &&
13787           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13788                                  FirstLoadAlign, &IsFastLd) &&
13789           IsFastLd) {
13790         LastLegalVectorType = i + 1;
13791       }
13792 
13793       // Find a legal type for the integer store.
13794       unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
13795       StoreTy = EVT::getIntegerVT(Context, SizeInBits);
13796       if (TLI.isTypeLegal(StoreTy) &&
13797           TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
13798           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13799                                  FirstStoreAlign, &IsFastSt) &&
13800           IsFastSt &&
13801           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13802                                  FirstLoadAlign, &IsFastLd) &&
13803           IsFastLd) {
13804         LastLegalIntegerType = i + 1;
13805         DoIntegerTruncate = false;
13806         // Or check whether a truncstore and extload is legal.
13807       } else if (TLI.getTypeAction(Context, StoreTy) ==
13808                  TargetLowering::TypePromoteInteger) {
13809         EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
13810         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13811             TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13812             TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13813                                StoreTy) &&
13814             TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13815                                StoreTy) &&
13816             TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13817             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
13818                                    FirstStoreAlign, &IsFastSt) &&
13819             IsFastSt &&
13820             TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13821                                    FirstLoadAlign, &IsFastLd) &&
13822             IsFastLd) {
13823           LastLegalIntegerType = i + 1;
13824           DoIntegerTruncate = true;
13825         }
13826       }
13827     }
13828 
13829     // Only use vector types if the vector type is larger than the integer type.
13830     // If they are the same, use integers.
13831     bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13832     unsigned LastLegalType =
13833         std::max(LastLegalVectorType, LastLegalIntegerType);
13834 
13835     // We add +1 here because the LastXXX variables refer to location while
13836     // the NumElem refers to array/index size.
13837     unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13838     NumElem = std::min(LastLegalType, NumElem);
13839 
13840     if (NumElem < 2) {
13841       // We know that candidate stores are in order and of correct
13842       // shape. While there is no mergeable sequence from the
13843       // beginning one may start later in the sequence. The only
13844       // reason a merge of size N could have failed where another of
13845       // the same size would not have is if the alignment or either
13846       // the load or store has improved. Drop as many candidates as we
13847       // can here.
13848       unsigned NumSkip = 1;
13849       while ((NumSkip < LoadNodes.size()) &&
13850              (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
13851              (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
13852         NumSkip++;
13853       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
13854       continue;
13855     }
13856 
13857     // Check that we can merge these candidates without causing a cycle.
13858     if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
13859                                                   RootNode)) {
13860       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13861       continue;
13862     }
13863 
13864     // Find if it is better to use vectors or integers to load and store
13865     // to memory.
13866     EVT JointMemOpVT;
13867     if (UseVectorTy) {
13868       // Find a legal type for the vector store.
13869       unsigned Elts = NumElem * NumMemElts;
13870       JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
13871     } else {
13872       unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13873       JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13874     }
13875 
13876     SDLoc LoadDL(LoadNodes[0].MemNode);
13877     SDLoc StoreDL(StoreNodes[0].MemNode);
13878 
13879     // The merged loads are required to have the same incoming chain, so
13880     // using the first's chain is acceptable.
13881 
13882     SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13883     AddToWorklist(NewStoreChain.getNode());
13884 
13885     MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13886                                           MachineMemOperand::MODereferenceable:
13887                                           MachineMemOperand::MONone;
13888 
13889     SDValue NewLoad, NewStore;
13890     if (UseVectorTy || !DoIntegerTruncate) {
13891       NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13892                             FirstLoad->getBasePtr(),
13893                             FirstLoad->getPointerInfo(), FirstLoadAlign,
13894                             MMOFlags);
13895       NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13896                               FirstInChain->getBasePtr(),
13897                               FirstInChain->getPointerInfo(), FirstStoreAlign);
13898     } else { // This must be the truncstore/extload case
13899       EVT ExtendedTy =
13900           TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13901       NewLoad =
13902           DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13903                          FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13904                          JointMemOpVT, FirstLoadAlign, MMOFlags);
13905       NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13906                                    FirstInChain->getBasePtr(),
13907                                    FirstInChain->getPointerInfo(), JointMemOpVT,
13908                                    FirstInChain->getAlignment(),
13909                                    FirstInChain->getMemOperand()->getFlags());
13910     }
13911 
13912     // Transfer chain users from old loads to the new load.
13913     for (unsigned i = 0; i < NumElem; ++i) {
13914       LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13915       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13916                                     SDValue(NewLoad.getNode(), 1));
13917     }
13918 
13919     // Replace the all stores with the new store. Recursively remove
13920     // corresponding value if its no longer used.
13921     for (unsigned i = 0; i < NumElem; ++i) {
13922       SDValue Val = StoreNodes[i].MemNode->getOperand(1);
13923       CombineTo(StoreNodes[i].MemNode, NewStore);
13924       if (Val.getNode()->use_empty())
13925         recursivelyDeleteUnusedNodes(Val.getNode());
13926     }
13927 
13928     RV = true;
13929     StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13930   }
13931   return RV;
13932 }
13933 
13934 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13935   SDLoc SL(ST);
13936   SDValue ReplStore;
13937 
13938   // Replace the chain to avoid dependency.
13939   if (ST->isTruncatingStore()) {
13940     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13941                                   ST->getBasePtr(), ST->getMemoryVT(),
13942                                   ST->getMemOperand());
13943   } else {
13944     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13945                              ST->getMemOperand());
13946   }
13947 
13948   // Create token to keep both nodes around.
13949   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13950                               MVT::Other, ST->getChain(), ReplStore);
13951 
13952   // Make sure the new and old chains are cleaned up.
13953   AddToWorklist(Token.getNode());
13954 
13955   // Don't add users to work list.
13956   return CombineTo(ST, Token, false);
13957 }
13958 
13959 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13960   SDValue Value = ST->getValue();
13961   if (Value.getOpcode() == ISD::TargetConstantFP)
13962     return SDValue();
13963 
13964   SDLoc DL(ST);
13965 
13966   SDValue Chain = ST->getChain();
13967   SDValue Ptr = ST->getBasePtr();
13968 
13969   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13970 
13971   // NOTE: If the original store is volatile, this transform must not increase
13972   // the number of stores.  For example, on x86-32 an f64 can be stored in one
13973   // processor operation but an i64 (which is not legal) requires two.  So the
13974   // transform should not be done in this case.
13975 
13976   SDValue Tmp;
13977   switch (CFP->getSimpleValueType(0).SimpleTy) {
13978   default:
13979     llvm_unreachable("Unknown FP type");
13980   case MVT::f16:    // We don't do this for these yet.
13981   case MVT::f80:
13982   case MVT::f128:
13983   case MVT::ppcf128:
13984     return SDValue();
13985   case MVT::f32:
13986     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13987         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13988       ;
13989       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13990                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13991                             MVT::i32);
13992       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13993     }
13994 
13995     return SDValue();
13996   case MVT::f64:
13997     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13998          !ST->isVolatile()) ||
13999         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
14000       ;
14001       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
14002                             getZExtValue(), SDLoc(CFP), MVT::i64);
14003       return DAG.getStore(Chain, DL, Tmp,
14004                           Ptr, ST->getMemOperand());
14005     }
14006 
14007     if (!ST->isVolatile() &&
14008         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
14009       // Many FP stores are not made apparent until after legalize, e.g. for
14010       // argument passing.  Since this is so common, custom legalize the
14011       // 64-bit integer store into two 32-bit stores.
14012       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
14013       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
14014       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
14015       if (DAG.getDataLayout().isBigEndian())
14016         std::swap(Lo, Hi);
14017 
14018       unsigned Alignment = ST->getAlignment();
14019       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14020       AAMDNodes AAInfo = ST->getAAInfo();
14021 
14022       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14023                                  ST->getAlignment(), MMOFlags, AAInfo);
14024       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14025                         DAG.getConstant(4, DL, Ptr.getValueType()));
14026       Alignment = MinAlign(Alignment, 4U);
14027       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
14028                                  ST->getPointerInfo().getWithOffset(4),
14029                                  Alignment, MMOFlags, AAInfo);
14030       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14031                          St0, St1);
14032     }
14033 
14034     return SDValue();
14035   }
14036 }
14037 
14038 SDValue DAGCombiner::visitSTORE(SDNode *N) {
14039   StoreSDNode *ST  = cast<StoreSDNode>(N);
14040   SDValue Chain = ST->getChain();
14041   SDValue Value = ST->getValue();
14042   SDValue Ptr   = ST->getBasePtr();
14043 
14044   // If this is a store of a bit convert, store the input value if the
14045   // resultant store does not need a higher alignment than the original.
14046   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
14047       ST->isUnindexed()) {
14048     EVT SVT = Value.getOperand(0).getValueType();
14049     if (((!LegalOperations && !ST->isVolatile()) ||
14050          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
14051         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
14052       unsigned OrigAlign = ST->getAlignment();
14053       bool Fast = false;
14054       if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
14055                                  ST->getAddressSpace(), OrigAlign, &Fast) &&
14056           Fast) {
14057         return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
14058                             ST->getPointerInfo(), OrigAlign,
14059                             ST->getMemOperand()->getFlags(), ST->getAAInfo());
14060       }
14061     }
14062   }
14063 
14064   // Turn 'store undef, Ptr' -> nothing.
14065   if (Value.isUndef() && ST->isUnindexed())
14066     return Chain;
14067 
14068   // Try to infer better alignment information than the store already has.
14069   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
14070     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
14071       if (Align > ST->getAlignment()) {
14072         SDValue NewStore =
14073             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
14074                               ST->getMemoryVT(), Align,
14075                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
14076         if (NewStore.getNode() != N)
14077           return CombineTo(ST, NewStore, true);
14078       }
14079     }
14080   }
14081 
14082   // Try transforming a pair floating point load / store ops to integer
14083   // load / store ops.
14084   if (SDValue NewST = TransformFPLoadStorePair(N))
14085     return NewST;
14086 
14087   if (ST->isUnindexed()) {
14088     // Walk up chain skipping non-aliasing memory nodes, on this store and any
14089     // adjacent stores.
14090     if (findBetterNeighborChains(ST)) {
14091       // replaceStoreChain uses CombineTo, which handled all of the worklist
14092       // manipulation. Return the original node to not do anything else.
14093       return SDValue(ST, 0);
14094     }
14095     Chain = ST->getChain();
14096   }
14097 
14098   // FIXME: is there such a thing as a truncating indexed store?
14099   if (ST->isTruncatingStore() && ST->isUnindexed() &&
14100       Value.getValueType().isInteger()) {
14101     // See if we can simplify the input to this truncstore with knowledge that
14102     // only the low bits are being used.  For example:
14103     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
14104     SDValue Shorter = DAG.GetDemandedBits(
14105         Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
14106                                     ST->getMemoryVT().getScalarSizeInBits()));
14107     AddToWorklist(Value.getNode());
14108     if (Shorter.getNode())
14109       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
14110                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
14111 
14112     // Otherwise, see if we can simplify the operation with
14113     // SimplifyDemandedBits, which only works if the value has a single use.
14114     if (SimplifyDemandedBits(
14115             Value,
14116             APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
14117                                  ST->getMemoryVT().getScalarSizeInBits()))) {
14118       // Re-visit the store if anything changed and the store hasn't been merged
14119       // with another node (N is deleted) SimplifyDemandedBits will add Value's
14120       // node back to the worklist if necessary, but we also need to re-visit
14121       // the Store node itself.
14122       if (N->getOpcode() != ISD::DELETED_NODE)
14123         AddToWorklist(N);
14124       return SDValue(N, 0);
14125     }
14126   }
14127 
14128   // If this is a load followed by a store to the same location, then the store
14129   // is dead/noop.
14130   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
14131     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
14132         ST->isUnindexed() && !ST->isVolatile() &&
14133         // There can't be any side effects between the load and store, such as
14134         // a call or store.
14135         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
14136       // The store is dead, remove it.
14137       return Chain;
14138     }
14139   }
14140 
14141   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
14142     if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
14143         !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
14144         ST->getMemoryVT() == ST1->getMemoryVT()) {
14145       // If this is a store followed by a store with the same value to the same
14146       // location, then the store is dead/noop.
14147       if (ST1->getValue() == Value) {
14148         // The store is dead, remove it.
14149         return Chain;
14150       }
14151 
14152       // If this is a store who's preceeding store to the same location
14153       // and no one other node is chained to that store we can effectively
14154       // drop the store. Do not remove stores to undef as they may be used as
14155       // data sinks.
14156       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
14157           !ST1->getBasePtr().isUndef()) {
14158         // ST1 is fully overwritten and can be elided. Combine with it's chain
14159         // value.
14160         CombineTo(ST1, ST1->getChain());
14161         return SDValue();
14162       }
14163     }
14164   }
14165 
14166   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
14167   // truncating store.  We can do this even if this is already a truncstore.
14168   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
14169       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
14170       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
14171                             ST->getMemoryVT())) {
14172     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
14173                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
14174   }
14175 
14176   // Always perform this optimization before types are legal. If the target
14177   // prefers, also try this after legalization to catch stores that were created
14178   // by intrinsics or other nodes.
14179   if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) {
14180     while (true) {
14181       // There can be multiple store sequences on the same chain.
14182       // Keep trying to merge store sequences until we are unable to do so
14183       // or until we merge the last store on the chain.
14184       bool Changed = MergeConsecutiveStores(ST);
14185       if (!Changed) break;
14186       // Return N as merge only uses CombineTo and no worklist clean
14187       // up is necessary.
14188       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
14189         return SDValue(N, 0);
14190     }
14191   }
14192 
14193   // Try transforming N to an indexed store.
14194   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14195     return SDValue(N, 0);
14196 
14197   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
14198   //
14199   // Make sure to do this only after attempting to merge stores in order to
14200   //  avoid changing the types of some subset of stores due to visit order,
14201   //  preventing their merging.
14202   if (isa<ConstantFPSDNode>(ST->getValue())) {
14203     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
14204       return NewSt;
14205   }
14206 
14207   if (SDValue NewSt = splitMergedValStore(ST))
14208     return NewSt;
14209 
14210   return ReduceLoadOpStoreWidth(N);
14211 }
14212 
14213 /// For the instruction sequence of store below, F and I values
14214 /// are bundled together as an i64 value before being stored into memory.
14215 /// Sometimes it is more efficent to generate separate stores for F and I,
14216 /// which can remove the bitwise instructions or sink them to colder places.
14217 ///
14218 ///   (store (or (zext (bitcast F to i32) to i64),
14219 ///              (shl (zext I to i64), 32)), addr)  -->
14220 ///   (store F, addr) and (store I, addr+4)
14221 ///
14222 /// Similarly, splitting for other merged store can also be beneficial, like:
14223 /// For pair of {i32, i32}, i64 store --> two i32 stores.
14224 /// For pair of {i32, i16}, i64 store --> two i32 stores.
14225 /// For pair of {i16, i16}, i32 store --> two i16 stores.
14226 /// For pair of {i16, i8},  i32 store --> two i16 stores.
14227 /// For pair of {i8, i8},   i16 store --> two i8 stores.
14228 ///
14229 /// We allow each target to determine specifically which kind of splitting is
14230 /// supported.
14231 ///
14232 /// The store patterns are commonly seen from the simple code snippet below
14233 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
14234 ///   void goo(const std::pair<int, float> &);
14235 ///   hoo() {
14236 ///     ...
14237 ///     goo(std::make_pair(tmp, ftmp));
14238 ///     ...
14239 ///   }
14240 ///
14241 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
14242   if (OptLevel == CodeGenOpt::None)
14243     return SDValue();
14244 
14245   SDValue Val = ST->getValue();
14246   SDLoc DL(ST);
14247 
14248   // Match OR operand.
14249   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
14250     return SDValue();
14251 
14252   // Match SHL operand and get Lower and Higher parts of Val.
14253   SDValue Op1 = Val.getOperand(0);
14254   SDValue Op2 = Val.getOperand(1);
14255   SDValue Lo, Hi;
14256   if (Op1.getOpcode() != ISD::SHL) {
14257     std::swap(Op1, Op2);
14258     if (Op1.getOpcode() != ISD::SHL)
14259       return SDValue();
14260   }
14261   Lo = Op2;
14262   Hi = Op1.getOperand(0);
14263   if (!Op1.hasOneUse())
14264     return SDValue();
14265 
14266   // Match shift amount to HalfValBitSize.
14267   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
14268   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
14269   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
14270     return SDValue();
14271 
14272   // Lo and Hi are zero-extended from int with size less equal than 32
14273   // to i64.
14274   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
14275       !Lo.getOperand(0).getValueType().isScalarInteger() ||
14276       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
14277       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
14278       !Hi.getOperand(0).getValueType().isScalarInteger() ||
14279       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
14280     return SDValue();
14281 
14282   // Use the EVT of low and high parts before bitcast as the input
14283   // of target query.
14284   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
14285                   ? Lo.getOperand(0).getValueType()
14286                   : Lo.getValueType();
14287   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
14288                    ? Hi.getOperand(0).getValueType()
14289                    : Hi.getValueType();
14290   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
14291     return SDValue();
14292 
14293   // Start to split store.
14294   unsigned Alignment = ST->getAlignment();
14295   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
14296   AAMDNodes AAInfo = ST->getAAInfo();
14297 
14298   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
14299   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
14300   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
14301   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
14302 
14303   SDValue Chain = ST->getChain();
14304   SDValue Ptr = ST->getBasePtr();
14305   // Lower value store.
14306   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
14307                              ST->getAlignment(), MMOFlags, AAInfo);
14308   Ptr =
14309       DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
14310                   DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
14311   // Higher value store.
14312   SDValue St1 =
14313       DAG.getStore(St0, DL, Hi, Ptr,
14314                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
14315                    Alignment / 2, MMOFlags, AAInfo);
14316   return St1;
14317 }
14318 
14319 /// Convert a disguised subvector insertion into a shuffle:
14320 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
14321 /// bitcast(shuffle (bitcast V), (extended X), Mask)
14322 /// Note: We do not use an insert_subvector node because that requires a legal
14323 /// subvector type.
14324 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
14325   SDValue InsertVal = N->getOperand(1);
14326   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
14327       !InsertVal.getOperand(0).getValueType().isVector())
14328     return SDValue();
14329 
14330   SDValue SubVec = InsertVal.getOperand(0);
14331   SDValue DestVec = N->getOperand(0);
14332   EVT SubVecVT = SubVec.getValueType();
14333   EVT VT = DestVec.getValueType();
14334   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
14335   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
14336   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
14337 
14338   // Step 1: Create a shuffle mask that implements this insert operation. The
14339   // vector that we are inserting into will be operand 0 of the shuffle, so
14340   // those elements are just 'i'. The inserted subvector is in the first
14341   // positions of operand 1 of the shuffle. Example:
14342   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
14343   SmallVector<int, 16> Mask(NumMaskVals);
14344   for (unsigned i = 0; i != NumMaskVals; ++i) {
14345     if (i / NumSrcElts == InsIndex)
14346       Mask[i] = (i % NumSrcElts) + NumMaskVals;
14347     else
14348       Mask[i] = i;
14349   }
14350 
14351   // Bail out if the target can not handle the shuffle we want to create.
14352   EVT SubVecEltVT = SubVecVT.getVectorElementType();
14353   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
14354   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
14355     return SDValue();
14356 
14357   // Step 2: Create a wide vector from the inserted source vector by appending
14358   // undefined elements. This is the same size as our destination vector.
14359   SDLoc DL(N);
14360   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
14361   ConcatOps[0] = SubVec;
14362   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
14363 
14364   // Step 3: Shuffle in the padded subvector.
14365   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
14366   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
14367   AddToWorklist(PaddedSubV.getNode());
14368   AddToWorklist(DestVecBC.getNode());
14369   AddToWorklist(Shuf.getNode());
14370   return DAG.getBitcast(VT, Shuf);
14371 }
14372 
14373 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
14374   SDValue InVec = N->getOperand(0);
14375   SDValue InVal = N->getOperand(1);
14376   SDValue EltNo = N->getOperand(2);
14377   SDLoc DL(N);
14378 
14379   // If the inserted element is an UNDEF, just use the input vector.
14380   if (InVal.isUndef())
14381     return InVec;
14382 
14383   EVT VT = InVec.getValueType();
14384 
14385   // Remove redundant insertions:
14386   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
14387   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14388       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
14389     return InVec;
14390 
14391   // We must know which element is being inserted for folds below here.
14392   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14393   if (!IndexC)
14394     return SDValue();
14395   unsigned Elt = IndexC->getZExtValue();
14396 
14397   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
14398     return Shuf;
14399 
14400   // Canonicalize insert_vector_elt dag nodes.
14401   // Example:
14402   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
14403   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
14404   //
14405   // Do this only if the child insert_vector node has one use; also
14406   // do this only if indices are both constants and Idx1 < Idx0.
14407   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
14408       && isa<ConstantSDNode>(InVec.getOperand(2))) {
14409     unsigned OtherElt = InVec.getConstantOperandVal(2);
14410     if (Elt < OtherElt) {
14411       // Swap nodes.
14412       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
14413                                   InVec.getOperand(0), InVal, EltNo);
14414       AddToWorklist(NewOp.getNode());
14415       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
14416                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
14417     }
14418   }
14419 
14420   // If we can't generate a legal BUILD_VECTOR, exit
14421   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
14422     return SDValue();
14423 
14424   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
14425   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
14426   // vector elements.
14427   SmallVector<SDValue, 8> Ops;
14428   // Do not combine these two vectors if the output vector will not replace
14429   // the input vector.
14430   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
14431     Ops.append(InVec.getNode()->op_begin(),
14432                InVec.getNode()->op_end());
14433   } else if (InVec.isUndef()) {
14434     unsigned NElts = VT.getVectorNumElements();
14435     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
14436   } else {
14437     return SDValue();
14438   }
14439 
14440   // Insert the element
14441   if (Elt < Ops.size()) {
14442     // All the operands of BUILD_VECTOR must have the same type;
14443     // we enforce that here.
14444     EVT OpVT = Ops[0].getValueType();
14445     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
14446   }
14447 
14448   // Return the new vector
14449   return DAG.getBuildVector(VT, DL, Ops);
14450 }
14451 
14452 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
14453     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
14454   assert(!OriginalLoad->isVolatile());
14455 
14456   EVT ResultVT = EVE->getValueType(0);
14457   EVT VecEltVT = InVecVT.getVectorElementType();
14458   unsigned Align = OriginalLoad->getAlignment();
14459   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
14460       VecEltVT.getTypeForEVT(*DAG.getContext()));
14461 
14462   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14463     return SDValue();
14464 
14465   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
14466     ISD::NON_EXTLOAD : ISD::EXTLOAD;
14467   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
14468     return SDValue();
14469 
14470   Align = NewAlign;
14471 
14472   SDValue NewPtr = OriginalLoad->getBasePtr();
14473   SDValue Offset;
14474   EVT PtrType = NewPtr.getValueType();
14475   MachinePointerInfo MPI;
14476   SDLoc DL(EVE);
14477   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14478     int Elt = ConstEltNo->getZExtValue();
14479     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
14480     Offset = DAG.getConstant(PtrOff, DL, PtrType);
14481     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
14482   } else {
14483     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
14484     Offset = DAG.getNode(
14485         ISD::MUL, DL, PtrType, Offset,
14486         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
14487     MPI = OriginalLoad->getPointerInfo();
14488   }
14489   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
14490 
14491   // The replacement we need to do here is a little tricky: we need to
14492   // replace an extractelement of a load with a load.
14493   // Use ReplaceAllUsesOfValuesWith to do the replacement.
14494   // Note that this replacement assumes that the extractvalue is the only
14495   // use of the load; that's okay because we don't want to perform this
14496   // transformation in other cases anyway.
14497   SDValue Load;
14498   SDValue Chain;
14499   if (ResultVT.bitsGT(VecEltVT)) {
14500     // If the result type of vextract is wider than the load, then issue an
14501     // extending load instead.
14502     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
14503                                                   VecEltVT)
14504                                    ? ISD::ZEXTLOAD
14505                                    : ISD::EXTLOAD;
14506     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
14507                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
14508                           Align, OriginalLoad->getMemOperand()->getFlags(),
14509                           OriginalLoad->getAAInfo());
14510     Chain = Load.getValue(1);
14511   } else {
14512     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
14513                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
14514                        OriginalLoad->getAAInfo());
14515     Chain = Load.getValue(1);
14516     if (ResultVT.bitsLT(VecEltVT))
14517       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
14518     else
14519       Load = DAG.getBitcast(ResultVT, Load);
14520   }
14521   WorklistRemover DeadNodes(*this);
14522   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
14523   SDValue To[] = { Load, Chain };
14524   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
14525   // Since we're explicitly calling ReplaceAllUses, add the new node to the
14526   // worklist explicitly as well.
14527   AddToWorklist(Load.getNode());
14528   AddUsersToWorklist(Load.getNode()); // Add users too
14529   // Make sure to revisit this node to clean it up; it will usually be dead.
14530   AddToWorklist(EVE);
14531   ++OpsNarrowed;
14532   return SDValue(EVE, 0);
14533 }
14534 
14535 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
14536   // (vextract (scalar_to_vector val, 0) -> val
14537   SDValue InVec = N->getOperand(0);
14538   EVT VT = InVec.getValueType();
14539   EVT NVT = N->getValueType(0);
14540 
14541   if (InVec.isUndef())
14542     return DAG.getUNDEF(NVT);
14543 
14544   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14545     // Check if the result type doesn't match the inserted element type. A
14546     // SCALAR_TO_VECTOR may truncate the inserted element and the
14547     // EXTRACT_VECTOR_ELT may widen the extracted vector.
14548     SDValue InOp = InVec.getOperand(0);
14549     if (InOp.getValueType() != NVT) {
14550       assert(InOp.getValueType().isInteger() && NVT.isInteger());
14551       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
14552     }
14553     return InOp;
14554   }
14555 
14556   SDValue EltNo = N->getOperand(1);
14557   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
14558 
14559   // extract_vector_elt of out-of-bounds element -> UNDEF
14560   if (ConstEltNo && ConstEltNo->getAPIntValue().uge(VT.getVectorNumElements()))
14561     return DAG.getUNDEF(NVT);
14562 
14563   // extract_vector_elt (build_vector x, y), 1 -> y
14564   if (ConstEltNo &&
14565       InVec.getOpcode() == ISD::BUILD_VECTOR &&
14566       TLI.isTypeLegal(VT) &&
14567       (InVec.hasOneUse() ||
14568        TLI.aggressivelyPreferBuildVectorSources(VT))) {
14569     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
14570     EVT InEltVT = Elt.getValueType();
14571 
14572     // Sometimes build_vector's scalar input types do not match result type.
14573     if (NVT == InEltVT)
14574       return Elt;
14575 
14576     // TODO: It may be useful to truncate if free if the build_vector implicitly
14577     // converts.
14578   }
14579 
14580   // extract_vector_elt (v2i32 (bitcast i64:x)), EltTrunc -> i32 (trunc i64:x)
14581   bool isLE = DAG.getDataLayout().isLittleEndian();
14582   unsigned EltTrunc = isLE ? 0 : VT.getVectorNumElements() - 1;
14583   if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
14584       ConstEltNo->getZExtValue() == EltTrunc && VT.isInteger()) {
14585     SDValue BCSrc = InVec.getOperand(0);
14586     if (BCSrc.getValueType().isScalarInteger())
14587       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
14588   }
14589 
14590   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
14591   //
14592   // This only really matters if the index is non-constant since other combines
14593   // on the constant elements already work.
14594   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
14595       EltNo == InVec.getOperand(2)) {
14596     SDValue Elt = InVec.getOperand(1);
14597     return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
14598   }
14599 
14600   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
14601   // We only perform this optimization before the op legalization phase because
14602   // we may introduce new vector instructions which are not backed by TD
14603   // patterns. For example on AVX, extracting elements from a wide vector
14604   // without using extract_subvector. However, if we can find an underlying
14605   // scalar value, then we can always use that.
14606   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
14607     int NumElem = VT.getVectorNumElements();
14608     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
14609     // Find the new index to extract from.
14610     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
14611 
14612     // Extracting an undef index is undef.
14613     if (OrigElt == -1)
14614       return DAG.getUNDEF(NVT);
14615 
14616     // Select the right vector half to extract from.
14617     SDValue SVInVec;
14618     if (OrigElt < NumElem) {
14619       SVInVec = InVec->getOperand(0);
14620     } else {
14621       SVInVec = InVec->getOperand(1);
14622       OrigElt -= NumElem;
14623     }
14624 
14625     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
14626       SDValue InOp = SVInVec.getOperand(OrigElt);
14627       if (InOp.getValueType() != NVT) {
14628         assert(InOp.getValueType().isInteger() && NVT.isInteger());
14629         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
14630       }
14631 
14632       return InOp;
14633     }
14634 
14635     // FIXME: We should handle recursing on other vector shuffles and
14636     // scalar_to_vector here as well.
14637 
14638     if (!LegalOperations ||
14639         // FIXME: Should really be just isOperationLegalOrCustom.
14640         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VT) ||
14641         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VT)) {
14642       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14643       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
14644                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
14645     }
14646   }
14647 
14648   bool BCNumEltsChanged = false;
14649   EVT ExtVT = VT.getVectorElementType();
14650   EVT LVT = ExtVT;
14651 
14652   // If the result of load has to be truncated, then it's not necessarily
14653   // profitable.
14654   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
14655     return SDValue();
14656 
14657   if (InVec.getOpcode() == ISD::BITCAST) {
14658     // Don't duplicate a load with other uses.
14659     if (!InVec.hasOneUse())
14660       return SDValue();
14661 
14662     EVT BCVT = InVec.getOperand(0).getValueType();
14663     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
14664       return SDValue();
14665     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
14666       BCNumEltsChanged = true;
14667     InVec = InVec.getOperand(0);
14668     ExtVT = BCVT.getVectorElementType();
14669   }
14670 
14671   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
14672   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
14673       ISD::isNormalLoad(InVec.getNode()) &&
14674       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
14675     SDValue Index = N->getOperand(1);
14676     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
14677       if (!OrigLoad->isVolatile()) {
14678         return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
14679                                                              OrigLoad);
14680       }
14681     }
14682   }
14683 
14684   // Perform only after legalization to ensure build_vector / vector_shuffle
14685   // optimizations have already been done.
14686   if (!LegalOperations) return SDValue();
14687 
14688   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
14689   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
14690   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
14691 
14692   if (ConstEltNo) {
14693     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14694 
14695     LoadSDNode *LN0 = nullptr;
14696     const ShuffleVectorSDNode *SVN = nullptr;
14697     if (ISD::isNormalLoad(InVec.getNode())) {
14698       LN0 = cast<LoadSDNode>(InVec);
14699     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14700                InVec.getOperand(0).getValueType() == ExtVT &&
14701                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
14702       // Don't duplicate a load with other uses.
14703       if (!InVec.hasOneUse())
14704         return SDValue();
14705 
14706       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
14707     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
14708       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
14709       // =>
14710       // (load $addr+1*size)
14711 
14712       // Don't duplicate a load with other uses.
14713       if (!InVec.hasOneUse())
14714         return SDValue();
14715 
14716       // If the bit convert changed the number of elements, it is unsafe
14717       // to examine the mask.
14718       if (BCNumEltsChanged)
14719         return SDValue();
14720 
14721       // Select the input vector, guarding against out of range extract vector.
14722       unsigned NumElems = VT.getVectorNumElements();
14723       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
14724       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
14725 
14726       if (InVec.getOpcode() == ISD::BITCAST) {
14727         // Don't duplicate a load with other uses.
14728         if (!InVec.hasOneUse())
14729           return SDValue();
14730 
14731         InVec = InVec.getOperand(0);
14732       }
14733       if (ISD::isNormalLoad(InVec.getNode())) {
14734         LN0 = cast<LoadSDNode>(InVec);
14735         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
14736         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
14737       }
14738     }
14739 
14740     // Make sure we found a non-volatile load and the extractelement is
14741     // the only use.
14742     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
14743       return SDValue();
14744 
14745     // If Idx was -1 above, Elt is going to be -1, so just return undef.
14746     if (Elt == -1)
14747       return DAG.getUNDEF(LVT);
14748 
14749     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
14750   }
14751 
14752   return SDValue();
14753 }
14754 
14755 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
14756 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
14757   // We perform this optimization post type-legalization because
14758   // the type-legalizer often scalarizes integer-promoted vectors.
14759   // Performing this optimization before may create bit-casts which
14760   // will be type-legalized to complex code sequences.
14761   // We perform this optimization only before the operation legalizer because we
14762   // may introduce illegal operations.
14763   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
14764     return SDValue();
14765 
14766   unsigned NumInScalars = N->getNumOperands();
14767   SDLoc DL(N);
14768   EVT VT = N->getValueType(0);
14769 
14770   // Check to see if this is a BUILD_VECTOR of a bunch of values
14771   // which come from any_extend or zero_extend nodes. If so, we can create
14772   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
14773   // optimizations. We do not handle sign-extend because we can't fill the sign
14774   // using shuffles.
14775   EVT SourceType = MVT::Other;
14776   bool AllAnyExt = true;
14777 
14778   for (unsigned i = 0; i != NumInScalars; ++i) {
14779     SDValue In = N->getOperand(i);
14780     // Ignore undef inputs.
14781     if (In.isUndef()) continue;
14782 
14783     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
14784     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
14785 
14786     // Abort if the element is not an extension.
14787     if (!ZeroExt && !AnyExt) {
14788       SourceType = MVT::Other;
14789       break;
14790     }
14791 
14792     // The input is a ZeroExt or AnyExt. Check the original type.
14793     EVT InTy = In.getOperand(0).getValueType();
14794 
14795     // Check that all of the widened source types are the same.
14796     if (SourceType == MVT::Other)
14797       // First time.
14798       SourceType = InTy;
14799     else if (InTy != SourceType) {
14800       // Multiple income types. Abort.
14801       SourceType = MVT::Other;
14802       break;
14803     }
14804 
14805     // Check if all of the extends are ANY_EXTENDs.
14806     AllAnyExt &= AnyExt;
14807   }
14808 
14809   // In order to have valid types, all of the inputs must be extended from the
14810   // same source type and all of the inputs must be any or zero extend.
14811   // Scalar sizes must be a power of two.
14812   EVT OutScalarTy = VT.getScalarType();
14813   bool ValidTypes = SourceType != MVT::Other &&
14814                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
14815                  isPowerOf2_32(SourceType.getSizeInBits());
14816 
14817   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
14818   // turn into a single shuffle instruction.
14819   if (!ValidTypes)
14820     return SDValue();
14821 
14822   bool isLE = DAG.getDataLayout().isLittleEndian();
14823   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
14824   assert(ElemRatio > 1 && "Invalid element size ratio");
14825   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
14826                                DAG.getConstant(0, DL, SourceType);
14827 
14828   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
14829   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
14830 
14831   // Populate the new build_vector
14832   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14833     SDValue Cast = N->getOperand(i);
14834     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
14835             Cast.getOpcode() == ISD::ZERO_EXTEND ||
14836             Cast.isUndef()) && "Invalid cast opcode");
14837     SDValue In;
14838     if (Cast.isUndef())
14839       In = DAG.getUNDEF(SourceType);
14840     else
14841       In = Cast->getOperand(0);
14842     unsigned Index = isLE ? (i * ElemRatio) :
14843                             (i * ElemRatio + (ElemRatio - 1));
14844 
14845     assert(Index < Ops.size() && "Invalid index");
14846     Ops[Index] = In;
14847   }
14848 
14849   // The type of the new BUILD_VECTOR node.
14850   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
14851   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
14852          "Invalid vector size");
14853   // Check if the new vector type is legal.
14854   if (!isTypeLegal(VecVT)) return SDValue();
14855 
14856   // Make the new BUILD_VECTOR.
14857   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
14858 
14859   // The new BUILD_VECTOR node has the potential to be further optimized.
14860   AddToWorklist(BV.getNode());
14861   // Bitcast to the desired type.
14862   return DAG.getBitcast(VT, BV);
14863 }
14864 
14865 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
14866   EVT VT = N->getValueType(0);
14867 
14868   unsigned NumInScalars = N->getNumOperands();
14869   SDLoc DL(N);
14870 
14871   EVT SrcVT = MVT::Other;
14872   unsigned Opcode = ISD::DELETED_NODE;
14873   unsigned NumDefs = 0;
14874 
14875   for (unsigned i = 0; i != NumInScalars; ++i) {
14876     SDValue In = N->getOperand(i);
14877     unsigned Opc = In.getOpcode();
14878 
14879     if (Opc == ISD::UNDEF)
14880       continue;
14881 
14882     // If all scalar values are floats and converted from integers.
14883     if (Opcode == ISD::DELETED_NODE &&
14884         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
14885       Opcode = Opc;
14886     }
14887 
14888     if (Opc != Opcode)
14889       return SDValue();
14890 
14891     EVT InVT = In.getOperand(0).getValueType();
14892 
14893     // If all scalar values are typed differently, bail out. It's chosen to
14894     // simplify BUILD_VECTOR of integer types.
14895     if (SrcVT == MVT::Other)
14896       SrcVT = InVT;
14897     if (SrcVT != InVT)
14898       return SDValue();
14899     NumDefs++;
14900   }
14901 
14902   // If the vector has just one element defined, it's not worth to fold it into
14903   // a vectorized one.
14904   if (NumDefs < 2)
14905     return SDValue();
14906 
14907   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
14908          && "Should only handle conversion from integer to float.");
14909   assert(SrcVT != MVT::Other && "Cannot determine source type!");
14910 
14911   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14912 
14913   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14914     return SDValue();
14915 
14916   // Just because the floating-point vector type is legal does not necessarily
14917   // mean that the corresponding integer vector type is.
14918   if (!isTypeLegal(NVT))
14919     return SDValue();
14920 
14921   SmallVector<SDValue, 8> Opnds;
14922   for (unsigned i = 0; i != NumInScalars; ++i) {
14923     SDValue In = N->getOperand(i);
14924 
14925     if (In.isUndef())
14926       Opnds.push_back(DAG.getUNDEF(SrcVT));
14927     else
14928       Opnds.push_back(In.getOperand(0));
14929   }
14930   SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14931   AddToWorklist(BV.getNode());
14932 
14933   return DAG.getNode(Opcode, DL, VT, BV);
14934 }
14935 
14936 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14937                                            ArrayRef<int> VectorMask,
14938                                            SDValue VecIn1, SDValue VecIn2,
14939                                            unsigned LeftIdx) {
14940   MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14941   SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14942 
14943   EVT VT = N->getValueType(0);
14944   EVT InVT1 = VecIn1.getValueType();
14945   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14946 
14947   unsigned Vec2Offset = 0;
14948   unsigned NumElems = VT.getVectorNumElements();
14949   unsigned ShuffleNumElems = NumElems;
14950 
14951   // In case both the input vectors are extracted from same base
14952   // vector we do not need extra addend (Vec2Offset) while
14953   // computing shuffle mask.
14954   if (!VecIn2 || !(VecIn1.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14955       !(VecIn2.getOpcode() == ISD::EXTRACT_SUBVECTOR) ||
14956       !(VecIn1.getOperand(0) == VecIn2.getOperand(0)))
14957     Vec2Offset = InVT1.getVectorNumElements();
14958 
14959   // We can't generate a shuffle node with mismatched input and output types.
14960   // Try to make the types match the type of the output.
14961   if (InVT1 != VT || InVT2 != VT) {
14962     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14963       // If the output vector length is a multiple of both input lengths,
14964       // we can concatenate them and pad the rest with undefs.
14965       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14966       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14967       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14968       ConcatOps[0] = VecIn1;
14969       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14970       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14971       VecIn2 = SDValue();
14972     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14973       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
14974         return SDValue();
14975 
14976       if (!VecIn2.getNode()) {
14977         // If we only have one input vector, and it's twice the size of the
14978         // output, split it in two.
14979         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14980                              DAG.getConstant(NumElems, DL, IdxTy));
14981         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14982         // Since we now have shorter input vectors, adjust the offset of the
14983         // second vector's start.
14984         Vec2Offset = NumElems;
14985       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14986         // VecIn1 is wider than the output, and we have another, possibly
14987         // smaller input. Pad the smaller input with undefs, shuffle at the
14988         // input vector width, and extract the output.
14989         // The shuffle type is different than VT, so check legality again.
14990         if (LegalOperations &&
14991             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14992           return SDValue();
14993 
14994         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14995         // lower it back into a BUILD_VECTOR. So if the inserted type is
14996         // illegal, don't even try.
14997         if (InVT1 != InVT2) {
14998           if (!TLI.isTypeLegal(InVT2))
14999             return SDValue();
15000           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
15001                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
15002         }
15003         ShuffleNumElems = NumElems * 2;
15004       } else {
15005         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
15006         // than VecIn1. We can't handle this for now - this case will disappear
15007         // when we start sorting the vectors by type.
15008         return SDValue();
15009       }
15010     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
15011                InVT1.getSizeInBits() == VT.getSizeInBits()) {
15012       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
15013       ConcatOps[0] = VecIn2;
15014       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
15015     } else {
15016       // TODO: Support cases where the length mismatch isn't exactly by a
15017       // factor of 2.
15018       // TODO: Move this check upwards, so that if we have bad type
15019       // mismatches, we don't create any DAG nodes.
15020       return SDValue();
15021     }
15022   }
15023 
15024   // Initialize mask to undef.
15025   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
15026 
15027   // Only need to run up to the number of elements actually used, not the
15028   // total number of elements in the shuffle - if we are shuffling a wider
15029   // vector, the high lanes should be set to undef.
15030   for (unsigned i = 0; i != NumElems; ++i) {
15031     if (VectorMask[i] <= 0)
15032       continue;
15033 
15034     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
15035     if (VectorMask[i] == (int)LeftIdx) {
15036       Mask[i] = ExtIndex;
15037     } else if (VectorMask[i] == (int)LeftIdx + 1) {
15038       Mask[i] = Vec2Offset + ExtIndex;
15039     }
15040   }
15041 
15042   // The type the input vectors may have changed above.
15043   InVT1 = VecIn1.getValueType();
15044 
15045   // If we already have a VecIn2, it should have the same type as VecIn1.
15046   // If we don't, get an undef/zero vector of the appropriate type.
15047   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
15048   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
15049 
15050   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
15051   if (ShuffleNumElems > NumElems)
15052     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
15053 
15054   return Shuffle;
15055 }
15056 
15057 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
15058 // operations. If the types of the vectors we're extracting from allow it,
15059 // turn this into a vector_shuffle node.
15060 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
15061   SDLoc DL(N);
15062   EVT VT = N->getValueType(0);
15063 
15064   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
15065   if (!isTypeLegal(VT))
15066     return SDValue();
15067 
15068   // May only combine to shuffle after legalize if shuffle is legal.
15069   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
15070     return SDValue();
15071 
15072   bool UsesZeroVector = false;
15073   unsigned NumElems = N->getNumOperands();
15074 
15075   // Record, for each element of the newly built vector, which input vector
15076   // that element comes from. -1 stands for undef, 0 for the zero vector,
15077   // and positive values for the input vectors.
15078   // VectorMask maps each element to its vector number, and VecIn maps vector
15079   // numbers to their initial SDValues.
15080 
15081   SmallVector<int, 8> VectorMask(NumElems, -1);
15082   SmallVector<SDValue, 8> VecIn;
15083   VecIn.push_back(SDValue());
15084 
15085   for (unsigned i = 0; i != NumElems; ++i) {
15086     SDValue Op = N->getOperand(i);
15087 
15088     if (Op.isUndef())
15089       continue;
15090 
15091     // See if we can use a blend with a zero vector.
15092     // TODO: Should we generalize this to a blend with an arbitrary constant
15093     // vector?
15094     if (isNullConstant(Op) || isNullFPConstant(Op)) {
15095       UsesZeroVector = true;
15096       VectorMask[i] = 0;
15097       continue;
15098     }
15099 
15100     // Not an undef or zero. If the input is something other than an
15101     // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
15102     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15103         !isa<ConstantSDNode>(Op.getOperand(1)))
15104       return SDValue();
15105     SDValue ExtractedFromVec = Op.getOperand(0);
15106 
15107     APInt ExtractIdx = cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue();
15108     if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
15109       return SDValue();
15110 
15111     // All inputs must have the same element type as the output.
15112     if (VT.getVectorElementType() !=
15113         ExtractedFromVec.getValueType().getVectorElementType())
15114       return SDValue();
15115 
15116     // Have we seen this input vector before?
15117     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
15118     // a map back from SDValues to numbers isn't worth it.
15119     unsigned Idx = std::distance(
15120         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
15121     if (Idx == VecIn.size())
15122       VecIn.push_back(ExtractedFromVec);
15123 
15124     VectorMask[i] = Idx;
15125   }
15126 
15127   // If we didn't find at least one input vector, bail out.
15128   if (VecIn.size() < 2)
15129     return SDValue();
15130 
15131   // If all the Operands of BUILD_VECTOR extract from same
15132   // vector, then split the vector efficiently based on the maximum
15133   // vector access index and adjust the VectorMask and
15134   // VecIn accordingly.
15135   if (VecIn.size() == 2) {
15136     unsigned MaxIndex = 0;
15137     unsigned NearestPow2 = 0;
15138     SDValue Vec = VecIn.back();
15139     EVT InVT = Vec.getValueType();
15140     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
15141     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
15142 
15143     for (unsigned i = 0; i < NumElems; i++) {
15144       if (VectorMask[i] <= 0)
15145         continue;
15146       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
15147       IndexVec[i] = Index;
15148       MaxIndex = std::max(MaxIndex, Index);
15149     }
15150 
15151     NearestPow2 = PowerOf2Ceil(MaxIndex);
15152     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
15153         NumElems * 2 < NearestPow2) {
15154       unsigned SplitSize = NearestPow2 / 2;
15155       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
15156                                      InVT.getVectorElementType(), SplitSize);
15157       if (TLI.isTypeLegal(SplitVT)) {
15158         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15159                                      DAG.getConstant(SplitSize, DL, IdxTy));
15160         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
15161                                      DAG.getConstant(0, DL, IdxTy));
15162         VecIn.pop_back();
15163         VecIn.push_back(VecIn1);
15164         VecIn.push_back(VecIn2);
15165 
15166         for (unsigned i = 0; i < NumElems; i++) {
15167           if (VectorMask[i] <= 0)
15168             continue;
15169           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
15170         }
15171       }
15172     }
15173   }
15174 
15175   // TODO: We want to sort the vectors by descending length, so that adjacent
15176   // pairs have similar length, and the longer vector is always first in the
15177   // pair.
15178 
15179   // TODO: Should this fire if some of the input vectors has illegal type (like
15180   // it does now), or should we let legalization run its course first?
15181 
15182   // Shuffle phase:
15183   // Take pairs of vectors, and shuffle them so that the result has elements
15184   // from these vectors in the correct places.
15185   // For example, given:
15186   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
15187   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
15188   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
15189   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
15190   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
15191   // We will generate:
15192   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
15193   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
15194   SmallVector<SDValue, 4> Shuffles;
15195   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
15196     unsigned LeftIdx = 2 * In + 1;
15197     SDValue VecLeft = VecIn[LeftIdx];
15198     SDValue VecRight =
15199         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
15200 
15201     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
15202                                                 VecRight, LeftIdx))
15203       Shuffles.push_back(Shuffle);
15204     else
15205       return SDValue();
15206   }
15207 
15208   // If we need the zero vector as an "ingredient" in the blend tree, add it
15209   // to the list of shuffles.
15210   if (UsesZeroVector)
15211     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
15212                                       : DAG.getConstantFP(0.0, DL, VT));
15213 
15214   // If we only have one shuffle, we're done.
15215   if (Shuffles.size() == 1)
15216     return Shuffles[0];
15217 
15218   // Update the vector mask to point to the post-shuffle vectors.
15219   for (int &Vec : VectorMask)
15220     if (Vec == 0)
15221       Vec = Shuffles.size() - 1;
15222     else
15223       Vec = (Vec - 1) / 2;
15224 
15225   // More than one shuffle. Generate a binary tree of blends, e.g. if from
15226   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
15227   // generate:
15228   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
15229   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
15230   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
15231   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
15232   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
15233   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
15234   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
15235 
15236   // Make sure the initial size of the shuffle list is even.
15237   if (Shuffles.size() % 2)
15238     Shuffles.push_back(DAG.getUNDEF(VT));
15239 
15240   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
15241     if (CurSize % 2) {
15242       Shuffles[CurSize] = DAG.getUNDEF(VT);
15243       CurSize++;
15244     }
15245     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
15246       int Left = 2 * In;
15247       int Right = 2 * In + 1;
15248       SmallVector<int, 8> Mask(NumElems, -1);
15249       for (unsigned i = 0; i != NumElems; ++i) {
15250         if (VectorMask[i] == Left) {
15251           Mask[i] = i;
15252           VectorMask[i] = In;
15253         } else if (VectorMask[i] == Right) {
15254           Mask[i] = i + NumElems;
15255           VectorMask[i] = In;
15256         }
15257       }
15258 
15259       Shuffles[In] =
15260           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
15261     }
15262   }
15263   return Shuffles[0];
15264 }
15265 
15266 // Try to turn a build vector of zero extends of extract vector elts into a
15267 // a vector zero extend and possibly an extract subvector.
15268 // TODO: Support sign extend or any extend?
15269 // TODO: Allow undef elements?
15270 // TODO: Don't require the extracts to start at element 0.
15271 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
15272   if (LegalOperations)
15273     return SDValue();
15274 
15275   EVT VT = N->getValueType(0);
15276 
15277   SDValue Op0 = N->getOperand(0);
15278   auto checkElem = [&](SDValue Op) -> int64_t {
15279     if (Op.getOpcode() == ISD::ZERO_EXTEND &&
15280         Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15281         Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
15282       if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
15283         return C->getZExtValue();
15284     return -1;
15285   };
15286 
15287   // Make sure the first element matches
15288   // (zext (extract_vector_elt X, C))
15289   int64_t Offset = checkElem(Op0);
15290   if (Offset < 0)
15291     return SDValue();
15292 
15293   unsigned NumElems = N->getNumOperands();
15294   SDValue In = Op0.getOperand(0).getOperand(0);
15295   EVT InSVT = In.getValueType().getScalarType();
15296   EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
15297 
15298   // Don't create an illegal input type after type legalization.
15299   if (LegalTypes && !TLI.isTypeLegal(InVT))
15300     return SDValue();
15301 
15302   // Ensure all the elements come from the same vector and are adjacent.
15303   for (unsigned i = 1; i != NumElems; ++i) {
15304     if ((Offset + i) != checkElem(N->getOperand(i)))
15305       return SDValue();
15306   }
15307 
15308   SDLoc DL(N);
15309   In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
15310                    Op0.getOperand(0).getOperand(1));
15311   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, In);
15312 }
15313 
15314 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
15315   EVT VT = N->getValueType(0);
15316 
15317   // A vector built entirely of undefs is undef.
15318   if (ISD::allOperandsUndef(N))
15319     return DAG.getUNDEF(VT);
15320 
15321   // If this is a splat of a bitcast from another vector, change to a
15322   // concat_vector.
15323   // For example:
15324   //   (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
15325   //     (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
15326   //
15327   // If X is a build_vector itself, the concat can become a larger build_vector.
15328   // TODO: Maybe this is useful for non-splat too?
15329   if (!LegalOperations) {
15330     if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
15331       Splat = peekThroughBitcast(Splat);
15332       EVT SrcVT = Splat.getValueType();
15333       if (SrcVT.isVector()) {
15334         unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
15335         EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
15336                                      SrcVT.getVectorElementType(), NumElts);
15337         SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
15338         SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), NewVT, Ops);
15339         return DAG.getBitcast(VT, Concat);
15340       }
15341     }
15342   }
15343 
15344   // Check if we can express BUILD VECTOR via subvector extract.
15345   if (!LegalTypes && (N->getNumOperands() > 1)) {
15346     SDValue Op0 = N->getOperand(0);
15347     auto checkElem = [&](SDValue Op) -> uint64_t {
15348       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
15349           (Op0.getOperand(0) == Op.getOperand(0)))
15350         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
15351           return CNode->getZExtValue();
15352       return -1;
15353     };
15354 
15355     int Offset = checkElem(Op0);
15356     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
15357       if (Offset + i != checkElem(N->getOperand(i))) {
15358         Offset = -1;
15359         break;
15360       }
15361     }
15362 
15363     if ((Offset == 0) &&
15364         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
15365       return Op0.getOperand(0);
15366     if ((Offset != -1) &&
15367         ((Offset % N->getValueType(0).getVectorNumElements()) ==
15368          0)) // IDX must be multiple of output size.
15369       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
15370                          Op0.getOperand(0), Op0.getOperand(1));
15371   }
15372 
15373   if (SDValue V = convertBuildVecZextToZext(N))
15374     return V;
15375 
15376   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
15377     return V;
15378 
15379   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
15380     return V;
15381 
15382   if (SDValue V = reduceBuildVecToShuffle(N))
15383     return V;
15384 
15385   return SDValue();
15386 }
15387 
15388 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
15389   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15390   EVT OpVT = N->getOperand(0).getValueType();
15391 
15392   // If the operands are legal vectors, leave them alone.
15393   if (TLI.isTypeLegal(OpVT))
15394     return SDValue();
15395 
15396   SDLoc DL(N);
15397   EVT VT = N->getValueType(0);
15398   SmallVector<SDValue, 8> Ops;
15399 
15400   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
15401   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15402 
15403   // Keep track of what we encounter.
15404   bool AnyInteger = false;
15405   bool AnyFP = false;
15406   for (const SDValue &Op : N->ops()) {
15407     if (ISD::BITCAST == Op.getOpcode() &&
15408         !Op.getOperand(0).getValueType().isVector())
15409       Ops.push_back(Op.getOperand(0));
15410     else if (ISD::UNDEF == Op.getOpcode())
15411       Ops.push_back(ScalarUndef);
15412     else
15413       return SDValue();
15414 
15415     // Note whether we encounter an integer or floating point scalar.
15416     // If it's neither, bail out, it could be something weird like x86mmx.
15417     EVT LastOpVT = Ops.back().getValueType();
15418     if (LastOpVT.isFloatingPoint())
15419       AnyFP = true;
15420     else if (LastOpVT.isInteger())
15421       AnyInteger = true;
15422     else
15423       return SDValue();
15424   }
15425 
15426   // If any of the operands is a floating point scalar bitcast to a vector,
15427   // use floating point types throughout, and bitcast everything.
15428   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
15429   if (AnyFP) {
15430     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
15431     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
15432     if (AnyInteger) {
15433       for (SDValue &Op : Ops) {
15434         if (Op.getValueType() == SVT)
15435           continue;
15436         if (Op.isUndef())
15437           Op = ScalarUndef;
15438         else
15439           Op = DAG.getBitcast(SVT, Op);
15440       }
15441     }
15442   }
15443 
15444   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
15445                                VT.getSizeInBits() / SVT.getSizeInBits());
15446   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
15447 }
15448 
15449 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
15450 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
15451 // most two distinct vectors the same size as the result, attempt to turn this
15452 // into a legal shuffle.
15453 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
15454   EVT VT = N->getValueType(0);
15455   EVT OpVT = N->getOperand(0).getValueType();
15456   int NumElts = VT.getVectorNumElements();
15457   int NumOpElts = OpVT.getVectorNumElements();
15458 
15459   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
15460   SmallVector<int, 8> Mask;
15461 
15462   for (SDValue Op : N->ops()) {
15463     // Peek through any bitcast.
15464     Op = peekThroughBitcast(Op);
15465 
15466     // UNDEF nodes convert to UNDEF shuffle mask values.
15467     if (Op.isUndef()) {
15468       Mask.append((unsigned)NumOpElts, -1);
15469       continue;
15470     }
15471 
15472     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15473       return SDValue();
15474 
15475     // What vector are we extracting the subvector from and at what index?
15476     SDValue ExtVec = Op.getOperand(0);
15477 
15478     // We want the EVT of the original extraction to correctly scale the
15479     // extraction index.
15480     EVT ExtVT = ExtVec.getValueType();
15481 
15482     // Peek through any bitcast.
15483     ExtVec = peekThroughBitcast(ExtVec);
15484 
15485     // UNDEF nodes convert to UNDEF shuffle mask values.
15486     if (ExtVec.isUndef()) {
15487       Mask.append((unsigned)NumOpElts, -1);
15488       continue;
15489     }
15490 
15491     if (!isa<ConstantSDNode>(Op.getOperand(1)))
15492       return SDValue();
15493     int ExtIdx = Op.getConstantOperandVal(1);
15494 
15495     // Ensure that we are extracting a subvector from a vector the same
15496     // size as the result.
15497     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
15498       return SDValue();
15499 
15500     // Scale the subvector index to account for any bitcast.
15501     int NumExtElts = ExtVT.getVectorNumElements();
15502     if (0 == (NumExtElts % NumElts))
15503       ExtIdx /= (NumExtElts / NumElts);
15504     else if (0 == (NumElts % NumExtElts))
15505       ExtIdx *= (NumElts / NumExtElts);
15506     else
15507       return SDValue();
15508 
15509     // At most we can reference 2 inputs in the final shuffle.
15510     if (SV0.isUndef() || SV0 == ExtVec) {
15511       SV0 = ExtVec;
15512       for (int i = 0; i != NumOpElts; ++i)
15513         Mask.push_back(i + ExtIdx);
15514     } else if (SV1.isUndef() || SV1 == ExtVec) {
15515       SV1 = ExtVec;
15516       for (int i = 0; i != NumOpElts; ++i)
15517         Mask.push_back(i + ExtIdx + NumElts);
15518     } else {
15519       return SDValue();
15520     }
15521   }
15522 
15523   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
15524     return SDValue();
15525 
15526   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
15527                               DAG.getBitcast(VT, SV1), Mask);
15528 }
15529 
15530 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
15531   // If we only have one input vector, we don't need to do any concatenation.
15532   if (N->getNumOperands() == 1)
15533     return N->getOperand(0);
15534 
15535   // Check if all of the operands are undefs.
15536   EVT VT = N->getValueType(0);
15537   if (ISD::allOperandsUndef(N))
15538     return DAG.getUNDEF(VT);
15539 
15540   // Optimize concat_vectors where all but the first of the vectors are undef.
15541   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
15542         return Op.isUndef();
15543       })) {
15544     SDValue In = N->getOperand(0);
15545     assert(In.getValueType().isVector() && "Must concat vectors");
15546 
15547     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
15548     if (In->getOpcode() == ISD::BITCAST &&
15549         !In->getOperand(0).getValueType().isVector()) {
15550       SDValue Scalar = In->getOperand(0);
15551 
15552       // If the bitcast type isn't legal, it might be a trunc of a legal type;
15553       // look through the trunc so we can still do the transform:
15554       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
15555       if (Scalar->getOpcode() == ISD::TRUNCATE &&
15556           !TLI.isTypeLegal(Scalar.getValueType()) &&
15557           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
15558         Scalar = Scalar->getOperand(0);
15559 
15560       EVT SclTy = Scalar->getValueType(0);
15561 
15562       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
15563         return SDValue();
15564 
15565       // Bail out if the vector size is not a multiple of the scalar size.
15566       if (VT.getSizeInBits() % SclTy.getSizeInBits())
15567         return SDValue();
15568 
15569       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
15570       if (VNTNumElms < 2)
15571         return SDValue();
15572 
15573       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
15574       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
15575         return SDValue();
15576 
15577       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
15578       return DAG.getBitcast(VT, Res);
15579     }
15580   }
15581 
15582   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
15583   // We have already tested above for an UNDEF only concatenation.
15584   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
15585   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
15586   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
15587     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
15588   };
15589   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
15590     SmallVector<SDValue, 8> Opnds;
15591     EVT SVT = VT.getScalarType();
15592 
15593     EVT MinVT = SVT;
15594     if (!SVT.isFloatingPoint()) {
15595       // If BUILD_VECTOR are from built from integer, they may have different
15596       // operand types. Get the smallest type and truncate all operands to it.
15597       bool FoundMinVT = false;
15598       for (const SDValue &Op : N->ops())
15599         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15600           EVT OpSVT = Op.getOperand(0).getValueType();
15601           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
15602           FoundMinVT = true;
15603         }
15604       assert(FoundMinVT && "Concat vector type mismatch");
15605     }
15606 
15607     for (const SDValue &Op : N->ops()) {
15608       EVT OpVT = Op.getValueType();
15609       unsigned NumElts = OpVT.getVectorNumElements();
15610 
15611       if (ISD::UNDEF == Op.getOpcode())
15612         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
15613 
15614       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
15615         if (SVT.isFloatingPoint()) {
15616           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
15617           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
15618         } else {
15619           for (unsigned i = 0; i != NumElts; ++i)
15620             Opnds.push_back(
15621                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
15622         }
15623       }
15624     }
15625 
15626     assert(VT.getVectorNumElements() == Opnds.size() &&
15627            "Concat vector type mismatch");
15628     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
15629   }
15630 
15631   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
15632   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
15633     return V;
15634 
15635   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
15636   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15637     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
15638       return V;
15639 
15640   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
15641   // nodes often generate nop CONCAT_VECTOR nodes.
15642   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
15643   // place the incoming vectors at the exact same location.
15644   SDValue SingleSource = SDValue();
15645   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
15646 
15647   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15648     SDValue Op = N->getOperand(i);
15649 
15650     if (Op.isUndef())
15651       continue;
15652 
15653     // Check if this is the identity extract:
15654     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15655       return SDValue();
15656 
15657     // Find the single incoming vector for the extract_subvector.
15658     if (SingleSource.getNode()) {
15659       if (Op.getOperand(0) != SingleSource)
15660         return SDValue();
15661     } else {
15662       SingleSource = Op.getOperand(0);
15663 
15664       // Check the source type is the same as the type of the result.
15665       // If not, this concat may extend the vector, so we can not
15666       // optimize it away.
15667       if (SingleSource.getValueType() != N->getValueType(0))
15668         return SDValue();
15669     }
15670 
15671     unsigned IdentityIndex = i * PartNumElem;
15672     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15673     // The extract index must be constant.
15674     if (!CS)
15675       return SDValue();
15676 
15677     // Check that we are reading from the identity index.
15678     if (CS->getZExtValue() != IdentityIndex)
15679       return SDValue();
15680   }
15681 
15682   if (SingleSource.getNode())
15683     return SingleSource;
15684 
15685   return SDValue();
15686 }
15687 
15688 /// If we are extracting a subvector produced by a wide binary operator with at
15689 /// at least one operand that was the result of a vector concatenation, then try
15690 /// to use the narrow vector operands directly to avoid the concatenation and
15691 /// extraction.
15692 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
15693   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
15694   // some of these bailouts with other transforms.
15695 
15696   // The extract index must be a constant, so we can map it to a concat operand.
15697   auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15698   if (!ExtractIndex)
15699     return SDValue();
15700 
15701   // Only handle the case where we are doubling and then halving. A larger ratio
15702   // may require more than two narrow binops to replace the wide binop.
15703   EVT VT = Extract->getValueType(0);
15704   unsigned NumElems = VT.getVectorNumElements();
15705   assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
15706          "Extract index is not a multiple of the vector length.");
15707   if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
15708     return SDValue();
15709 
15710   // We are looking for an optionally bitcasted wide vector binary operator
15711   // feeding an extract subvector.
15712   SDValue BinOp = peekThroughBitcast(Extract->getOperand(0));
15713 
15714   // TODO: The motivating case for this transform is an x86 AVX1 target. That
15715   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
15716   // flavors, but no other 256-bit integer support. This could be extended to
15717   // handle any binop, but that may require fixing/adding other folds to avoid
15718   // codegen regressions.
15719   unsigned BOpcode = BinOp.getOpcode();
15720   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
15721     return SDValue();
15722 
15723   // The binop must be a vector type, so we can chop it in half.
15724   EVT WideBVT = BinOp.getValueType();
15725   if (!WideBVT.isVector())
15726     return SDValue();
15727 
15728   // Bail out if the target does not support a narrower version of the binop.
15729   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
15730                                    WideBVT.getVectorNumElements() / 2);
15731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15732   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
15733     return SDValue();
15734 
15735   // Peek through bitcasts of the binary operator operands if needed.
15736   SDValue LHS = peekThroughBitcast(BinOp.getOperand(0));
15737   SDValue RHS = peekThroughBitcast(BinOp.getOperand(1));
15738 
15739   // We need at least one concatenation operation of a binop operand to make
15740   // this transform worthwhile. The concat must double the input vector sizes.
15741   // TODO: Should we also handle INSERT_SUBVECTOR patterns?
15742   bool ConcatL =
15743       LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
15744   bool ConcatR =
15745       RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
15746   if (!ConcatL && !ConcatR)
15747     return SDValue();
15748 
15749   // If one of the binop operands was not the result of a concat, we must
15750   // extract a half-sized operand for our new narrow binop. We can't just reuse
15751   // the original extract index operand because we may have bitcasted.
15752   unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
15753   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
15754   EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
15755   SDLoc DL(Extract);
15756 
15757   // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
15758   // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
15759   // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
15760   SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
15761                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15762                                     BinOp.getOperand(0),
15763                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15764 
15765   SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
15766                       : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
15767                                     BinOp.getOperand(1),
15768                                     DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
15769 
15770   SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
15771   return DAG.getBitcast(VT, NarrowBinOp);
15772 }
15773 
15774 /// If we are extracting a subvector from a wide vector load, convert to a
15775 /// narrow load to eliminate the extraction:
15776 /// (extract_subvector (load wide vector)) --> (load narrow vector)
15777 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
15778   // TODO: Add support for big-endian. The offset calculation must be adjusted.
15779   if (DAG.getDataLayout().isBigEndian())
15780     return SDValue();
15781 
15782   // TODO: The one-use check is overly conservative. Check the cost of the
15783   // extract instead or remove that condition entirely.
15784   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
15785   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
15786   if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
15787       !ExtIdx)
15788     return SDValue();
15789 
15790   // The narrow load will be offset from the base address of the old load if
15791   // we are extracting from something besides index 0 (little-endian).
15792   EVT VT = Extract->getValueType(0);
15793   SDLoc DL(Extract);
15794   SDValue BaseAddr = Ld->getOperand(1);
15795   unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
15796 
15797   // TODO: Use "BaseIndexOffset" to make this more effective.
15798   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
15799   MachineFunction &MF = DAG.getMachineFunction();
15800   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
15801                                                    VT.getStoreSize());
15802   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
15803   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
15804   return NewLd;
15805 }
15806 
15807 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
15808   EVT NVT = N->getValueType(0);
15809   SDValue V = N->getOperand(0);
15810 
15811   // Extract from UNDEF is UNDEF.
15812   if (V.isUndef())
15813     return DAG.getUNDEF(NVT);
15814 
15815   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
15816     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
15817       return NarrowLoad;
15818 
15819   // Combine:
15820   //    (extract_subvec (concat V1, V2, ...), i)
15821   // Into:
15822   //    Vi if possible
15823   // Only operand 0 is checked as 'concat' assumes all inputs of the same
15824   // type.
15825   if (V->getOpcode() == ISD::CONCAT_VECTORS &&
15826       isa<ConstantSDNode>(N->getOperand(1)) &&
15827       V->getOperand(0).getValueType() == NVT) {
15828     unsigned Idx = N->getConstantOperandVal(1);
15829     unsigned NumElems = NVT.getVectorNumElements();
15830     assert((Idx % NumElems) == 0 &&
15831            "IDX in concat is not a multiple of the result vector length.");
15832     return V->getOperand(Idx / NumElems);
15833   }
15834 
15835   // Skip bitcasting
15836   V = peekThroughBitcast(V);
15837 
15838   // If the input is a build vector. Try to make a smaller build vector.
15839   if (V->getOpcode() == ISD::BUILD_VECTOR) {
15840     if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
15841       EVT InVT = V->getValueType(0);
15842       unsigned ExtractSize = NVT.getSizeInBits();
15843       unsigned EltSize = InVT.getScalarSizeInBits();
15844       // Only do this if we won't split any elements.
15845       if (ExtractSize % EltSize == 0) {
15846         unsigned NumElems = ExtractSize / EltSize;
15847         EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
15848                                          InVT.getVectorElementType(), NumElems);
15849         if ((Level < AfterLegalizeDAG ||
15850              TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT)) &&
15851             (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
15852           unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) /
15853                             EltSize;
15854 
15855           // Extract the pieces from the original build_vector.
15856           SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
15857                                             makeArrayRef(V->op_begin() + IdxVal,
15858                                                          NumElems));
15859           return DAG.getBitcast(NVT, BuildVec);
15860         }
15861       }
15862     }
15863   }
15864 
15865   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
15866     // Handle only simple case where vector being inserted and vector
15867     // being extracted are of same size.
15868     EVT SmallVT = V->getOperand(1).getValueType();
15869     if (!NVT.bitsEq(SmallVT))
15870       return SDValue();
15871 
15872     // Only handle cases where both indexes are constants.
15873     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
15874     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
15875 
15876     if (InsIdx && ExtIdx) {
15877       // Combine:
15878       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
15879       // Into:
15880       //    indices are equal or bit offsets are equal => V1
15881       //    otherwise => (extract_subvec V1, ExtIdx)
15882       if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
15883           ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
15884         return DAG.getBitcast(NVT, V->getOperand(1));
15885       return DAG.getNode(
15886           ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
15887           DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
15888           N->getOperand(1));
15889     }
15890   }
15891 
15892   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
15893     return NarrowBOp;
15894 
15895   return SDValue();
15896 }
15897 
15898 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
15899 // or turn a shuffle of a single concat into simpler shuffle then concat.
15900 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
15901   EVT VT = N->getValueType(0);
15902   unsigned NumElts = VT.getVectorNumElements();
15903 
15904   SDValue N0 = N->getOperand(0);
15905   SDValue N1 = N->getOperand(1);
15906   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15907 
15908   SmallVector<SDValue, 4> Ops;
15909   EVT ConcatVT = N0.getOperand(0).getValueType();
15910   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15911   unsigned NumConcats = NumElts / NumElemsPerConcat;
15912 
15913   // Special case: shuffle(concat(A,B)) can be more efficiently represented
15914   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15915   // half vector elements.
15916   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15917       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15918                   SVN->getMask().end(), [](int i) { return i == -1; })) {
15919     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15920                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15921     N1 = DAG.getUNDEF(ConcatVT);
15922     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15923   }
15924 
15925   // Look at every vector that's inserted. We're looking for exact
15926   // subvector-sized copies from a concatenated vector
15927   for (unsigned I = 0; I != NumConcats; ++I) {
15928     // Make sure we're dealing with a copy.
15929     unsigned Begin = I * NumElemsPerConcat;
15930     bool AllUndef = true, NoUndef = true;
15931     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15932       if (SVN->getMaskElt(J) >= 0)
15933         AllUndef = false;
15934       else
15935         NoUndef = false;
15936     }
15937 
15938     if (NoUndef) {
15939       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15940         return SDValue();
15941 
15942       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15943         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15944           return SDValue();
15945 
15946       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15947       if (FirstElt < N0.getNumOperands())
15948         Ops.push_back(N0.getOperand(FirstElt));
15949       else
15950         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15951 
15952     } else if (AllUndef) {
15953       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15954     } else { // Mixed with general masks and undefs, can't do optimization.
15955       return SDValue();
15956     }
15957   }
15958 
15959   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15960 }
15961 
15962 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15963 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15964 //
15965 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15966 // a simplification in some sense, but it isn't appropriate in general: some
15967 // BUILD_VECTORs are substantially cheaper than others. The general case
15968 // of a BUILD_VECTOR requires inserting each element individually (or
15969 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15970 // all constants is a single constant pool load.  A BUILD_VECTOR where each
15971 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
15972 // are undef lowers to a small number of element insertions.
15973 //
15974 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15975 // We don't fold shuffles where one side is a non-zero constant, and we don't
15976 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
15977 // non-constant operands. This seems to work out reasonably well in practice.
15978 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15979                                        SelectionDAG &DAG,
15980                                        const TargetLowering &TLI) {
15981   EVT VT = SVN->getValueType(0);
15982   unsigned NumElts = VT.getVectorNumElements();
15983   SDValue N0 = SVN->getOperand(0);
15984   SDValue N1 = SVN->getOperand(1);
15985 
15986   if (!N0->hasOneUse() || !N1->hasOneUse())
15987     return SDValue();
15988 
15989   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15990   // discussed above.
15991   if (!N1.isUndef()) {
15992     bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15993     bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15994     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15995       return SDValue();
15996     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15997       return SDValue();
15998   }
15999 
16000   // If both inputs are splats of the same value then we can safely merge this
16001   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
16002   bool IsSplat = false;
16003   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
16004   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
16005   if (BV0 && BV1)
16006     if (SDValue Splat0 = BV0->getSplatValue())
16007       IsSplat = (Splat0 == BV1->getSplatValue());
16008 
16009   SmallVector<SDValue, 8> Ops;
16010   SmallSet<SDValue, 16> DuplicateOps;
16011   for (int M : SVN->getMask()) {
16012     SDValue Op = DAG.getUNDEF(VT.getScalarType());
16013     if (M >= 0) {
16014       int Idx = M < (int)NumElts ? M : M - NumElts;
16015       SDValue &S = (M < (int)NumElts ? N0 : N1);
16016       if (S.getOpcode() == ISD::BUILD_VECTOR) {
16017         Op = S.getOperand(Idx);
16018       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
16019         assert(Idx == 0 && "Unexpected SCALAR_TO_VECTOR operand index.");
16020         Op = S.getOperand(0);
16021       } else {
16022         // Operand can't be combined - bail out.
16023         return SDValue();
16024       }
16025     }
16026 
16027     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
16028     // generating a splat; semantically, this is fine, but it's likely to
16029     // generate low-quality code if the target can't reconstruct an appropriate
16030     // shuffle.
16031     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
16032       if (!IsSplat && !DuplicateOps.insert(Op).second)
16033         return SDValue();
16034 
16035     Ops.push_back(Op);
16036   }
16037 
16038   // BUILD_VECTOR requires all inputs to be of the same type, find the
16039   // maximum type and extend them all.
16040   EVT SVT = VT.getScalarType();
16041   if (SVT.isInteger())
16042     for (SDValue &Op : Ops)
16043       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
16044   if (SVT != VT.getScalarType())
16045     for (SDValue &Op : Ops)
16046       Op = TLI.isZExtFree(Op.getValueType(), SVT)
16047                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
16048                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
16049   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
16050 }
16051 
16052 // Match shuffles that can be converted to any_vector_extend_in_reg.
16053 // This is often generated during legalization.
16054 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
16055 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
16056 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
16057                                             SelectionDAG &DAG,
16058                                             const TargetLowering &TLI,
16059                                             bool LegalOperations,
16060                                             bool LegalTypes) {
16061   EVT VT = SVN->getValueType(0);
16062   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
16063 
16064   // TODO Add support for big-endian when we have a test case.
16065   if (!VT.isInteger() || IsBigEndian)
16066     return SDValue();
16067 
16068   unsigned NumElts = VT.getVectorNumElements();
16069   unsigned EltSizeInBits = VT.getScalarSizeInBits();
16070   ArrayRef<int> Mask = SVN->getMask();
16071   SDValue N0 = SVN->getOperand(0);
16072 
16073   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
16074   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
16075     for (unsigned i = 0; i != NumElts; ++i) {
16076       if (Mask[i] < 0)
16077         continue;
16078       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
16079         continue;
16080       return false;
16081     }
16082     return true;
16083   };
16084 
16085   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
16086   // power-of-2 extensions as they are the most likely.
16087   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
16088     // Check for non power of 2 vector sizes
16089     if (NumElts % Scale != 0)
16090       continue;
16091     if (!isAnyExtend(Scale))
16092       continue;
16093 
16094     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
16095     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
16096     if (!LegalTypes || TLI.isTypeLegal(OutVT))
16097       if (!LegalOperations ||
16098           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
16099         return DAG.getBitcast(VT,
16100                             DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
16101   }
16102 
16103   return SDValue();
16104 }
16105 
16106 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
16107 // each source element of a large type into the lowest elements of a smaller
16108 // destination type. This is often generated during legalization.
16109 // If the source node itself was a '*_extend_vector_inreg' node then we should
16110 // then be able to remove it.
16111 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
16112                                         SelectionDAG &DAG) {
16113   EVT VT = SVN->getValueType(0);
16114   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
16115 
16116   // TODO Add support for big-endian when we have a test case.
16117   if (!VT.isInteger() || IsBigEndian)
16118     return SDValue();
16119 
16120   SDValue N0 = peekThroughBitcast(SVN->getOperand(0));
16121 
16122   unsigned Opcode = N0.getOpcode();
16123   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
16124       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
16125       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
16126     return SDValue();
16127 
16128   SDValue N00 = N0.getOperand(0);
16129   ArrayRef<int> Mask = SVN->getMask();
16130   unsigned NumElts = VT.getVectorNumElements();
16131   unsigned EltSizeInBits = VT.getScalarSizeInBits();
16132   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
16133   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
16134 
16135   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
16136     return SDValue();
16137   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
16138 
16139   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
16140   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
16141   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
16142   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
16143     for (unsigned i = 0; i != NumElts; ++i) {
16144       if (Mask[i] < 0)
16145         continue;
16146       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
16147         continue;
16148       return false;
16149     }
16150     return true;
16151   };
16152 
16153   // At the moment we just handle the case where we've truncated back to the
16154   // same size as before the extension.
16155   // TODO: handle more extension/truncation cases as cases arise.
16156   if (EltSizeInBits != ExtSrcSizeInBits)
16157     return SDValue();
16158 
16159   // We can remove *extend_vector_inreg only if the truncation happens at
16160   // the same scale as the extension.
16161   if (isTruncate(ExtScale))
16162     return DAG.getBitcast(VT, N00);
16163 
16164   return SDValue();
16165 }
16166 
16167 // Combine shuffles of splat-shuffles of the form:
16168 // shuffle (shuffle V, undef, splat-mask), undef, M
16169 // If splat-mask contains undef elements, we need to be careful about
16170 // introducing undef's in the folded mask which are not the result of composing
16171 // the masks of the shuffles.
16172 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
16173                                      ShuffleVectorSDNode *Splat,
16174                                      SelectionDAG &DAG) {
16175   ArrayRef<int> SplatMask = Splat->getMask();
16176   assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
16177 
16178   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
16179   // every undef mask element in the splat-shuffle has a corresponding undef
16180   // element in the user-shuffle's mask or if the composition of mask elements
16181   // would result in undef.
16182   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
16183   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
16184   //   In this case it is not legal to simplify to the splat-shuffle because we
16185   //   may be exposing the users of the shuffle an undef element at index 1
16186   //   which was not there before the combine.
16187   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
16188   //   In this case the composition of masks yields SplatMask, so it's ok to
16189   //   simplify to the splat-shuffle.
16190   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
16191   //   In this case the composed mask includes all undef elements of SplatMask
16192   //   and in addition sets element zero to undef. It is safe to simplify to
16193   //   the splat-shuffle.
16194   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
16195                                        ArrayRef<int> SplatMask) {
16196     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
16197       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
16198           SplatMask[UserMask[i]] != -1)
16199         return false;
16200     return true;
16201   };
16202   if (CanSimplifyToExistingSplat(UserMask, SplatMask))
16203     return SDValue(Splat, 0);
16204 
16205   // Create a new shuffle with a mask that is composed of the two shuffles'
16206   // masks.
16207   SmallVector<int, 32> NewMask;
16208   for (int Idx : UserMask)
16209     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
16210 
16211   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
16212                               Splat->getOperand(0), Splat->getOperand(1),
16213                               NewMask);
16214 }
16215 
16216 /// If the shuffle mask is taking exactly one element from the first vector
16217 /// operand and passing through all other elements from the second vector
16218 /// operand, return the index of the mask element that is choosing an element
16219 /// from the first operand. Otherwise, return -1.
16220 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
16221   int MaskSize = Mask.size();
16222   int EltFromOp0 = -1;
16223   // TODO: This does not match if there are undef elements in the shuffle mask.
16224   // Should we ignore undefs in the shuffle mask instead? The trade-off is
16225   // removing an instruction (a shuffle), but losing the knowledge that some
16226   // vector lanes are not needed.
16227   for (int i = 0; i != MaskSize; ++i) {
16228     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
16229       // We're looking for a shuffle of exactly one element from operand 0.
16230       if (EltFromOp0 != -1)
16231         return -1;
16232       EltFromOp0 = i;
16233     } else if (Mask[i] != i + MaskSize) {
16234       // Nothing from operand 1 can change lanes.
16235       return -1;
16236     }
16237   }
16238   return EltFromOp0;
16239 }
16240 
16241 /// If a shuffle inserts exactly one element from a source vector operand into
16242 /// another vector operand and we can access the specified element as a scalar,
16243 /// then we can eliminate the shuffle.
16244 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
16245                                       SelectionDAG &DAG) {
16246   // First, check if we are taking one element of a vector and shuffling that
16247   // element into another vector.
16248   ArrayRef<int> Mask = Shuf->getMask();
16249   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
16250   SDValue Op0 = Shuf->getOperand(0);
16251   SDValue Op1 = Shuf->getOperand(1);
16252   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
16253   if (ShufOp0Index == -1) {
16254     // Commute mask and check again.
16255     ShuffleVectorSDNode::commuteMask(CommutedMask);
16256     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
16257     if (ShufOp0Index == -1)
16258       return SDValue();
16259     // Commute operands to match the commuted shuffle mask.
16260     std::swap(Op0, Op1);
16261     Mask = CommutedMask;
16262   }
16263 
16264   // The shuffle inserts exactly one element from operand 0 into operand 1.
16265   // Now see if we can access that element as a scalar via a real insert element
16266   // instruction.
16267   // TODO: We can try harder to locate the element as a scalar. Examples: it
16268   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
16269   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
16270          "Shuffle mask value must be from operand 0");
16271   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
16272     return SDValue();
16273 
16274   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
16275   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
16276     return SDValue();
16277 
16278   // There's an existing insertelement with constant insertion index, so we
16279   // don't need to check the legality/profitability of a replacement operation
16280   // that differs at most in the constant value. The target should be able to
16281   // lower any of those in a similar way. If not, legalization will expand this
16282   // to a scalar-to-vector plus shuffle.
16283   //
16284   // Note that the shuffle may move the scalar from the position that the insert
16285   // element used. Therefore, our new insert element occurs at the shuffle's
16286   // mask index value, not the insert's index value.
16287   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
16288   SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf),
16289                                         Op0.getOperand(2).getValueType());
16290   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
16291                      Op1, Op0.getOperand(1), NewInsIndex);
16292 }
16293 
16294 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
16295   EVT VT = N->getValueType(0);
16296   unsigned NumElts = VT.getVectorNumElements();
16297 
16298   SDValue N0 = N->getOperand(0);
16299   SDValue N1 = N->getOperand(1);
16300 
16301   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
16302 
16303   // Canonicalize shuffle undef, undef -> undef
16304   if (N0.isUndef() && N1.isUndef())
16305     return DAG.getUNDEF(VT);
16306 
16307   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
16308 
16309   // Canonicalize shuffle v, v -> v, undef
16310   if (N0 == N1) {
16311     SmallVector<int, 8> NewMask;
16312     for (unsigned i = 0; i != NumElts; ++i) {
16313       int Idx = SVN->getMaskElt(i);
16314       if (Idx >= (int)NumElts) Idx -= NumElts;
16315       NewMask.push_back(Idx);
16316     }
16317     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
16318   }
16319 
16320   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
16321   if (N0.isUndef())
16322     return DAG.getCommutedVectorShuffle(*SVN);
16323 
16324   // Remove references to rhs if it is undef
16325   if (N1.isUndef()) {
16326     bool Changed = false;
16327     SmallVector<int, 8> NewMask;
16328     for (unsigned i = 0; i != NumElts; ++i) {
16329       int Idx = SVN->getMaskElt(i);
16330       if (Idx >= (int)NumElts) {
16331         Idx = -1;
16332         Changed = true;
16333       }
16334       NewMask.push_back(Idx);
16335     }
16336     if (Changed)
16337       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
16338   }
16339 
16340   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
16341     return InsElt;
16342 
16343   // A shuffle of a single vector that is a splat can always be folded.
16344   if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
16345     if (N1->isUndef() && N0Shuf->isSplat())
16346       return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
16347 
16348   // If it is a splat, check if the argument vector is another splat or a
16349   // build_vector.
16350   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
16351     SDNode *V = N0.getNode();
16352 
16353     // If this is a bit convert that changes the element type of the vector but
16354     // not the number of vector elements, look through it.  Be careful not to
16355     // look though conversions that change things like v4f32 to v2f64.
16356     if (V->getOpcode() == ISD::BITCAST) {
16357       SDValue ConvInput = V->getOperand(0);
16358       if (ConvInput.getValueType().isVector() &&
16359           ConvInput.getValueType().getVectorNumElements() == NumElts)
16360         V = ConvInput.getNode();
16361     }
16362 
16363     if (V->getOpcode() == ISD::BUILD_VECTOR) {
16364       assert(V->getNumOperands() == NumElts &&
16365              "BUILD_VECTOR has wrong number of operands");
16366       SDValue Base;
16367       bool AllSame = true;
16368       for (unsigned i = 0; i != NumElts; ++i) {
16369         if (!V->getOperand(i).isUndef()) {
16370           Base = V->getOperand(i);
16371           break;
16372         }
16373       }
16374       // Splat of <u, u, u, u>, return <u, u, u, u>
16375       if (!Base.getNode())
16376         return N0;
16377       for (unsigned i = 0; i != NumElts; ++i) {
16378         if (V->getOperand(i) != Base) {
16379           AllSame = false;
16380           break;
16381         }
16382       }
16383       // Splat of <x, x, x, x>, return <x, x, x, x>
16384       if (AllSame)
16385         return N0;
16386 
16387       // Canonicalize any other splat as a build_vector.
16388       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
16389       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
16390       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
16391 
16392       // We may have jumped through bitcasts, so the type of the
16393       // BUILD_VECTOR may not match the type of the shuffle.
16394       if (V->getValueType(0) != VT)
16395         NewBV = DAG.getBitcast(VT, NewBV);
16396       return NewBV;
16397     }
16398   }
16399 
16400   // Simplify source operands based on shuffle mask.
16401   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
16402     return SDValue(N, 0);
16403 
16404   // Match shuffles that can be converted to any_vector_extend_in_reg.
16405   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations, LegalTypes))
16406     return V;
16407 
16408   // Combine "truncate_vector_in_reg" style shuffles.
16409   if (SDValue V = combineTruncationShuffle(SVN, DAG))
16410     return V;
16411 
16412   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
16413       Level < AfterLegalizeVectorOps &&
16414       (N1.isUndef() ||
16415       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
16416        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
16417     if (SDValue V = partitionShuffleOfConcats(N, DAG))
16418       return V;
16419   }
16420 
16421   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
16422   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
16423   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
16424     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
16425       return Res;
16426 
16427   // If this shuffle only has a single input that is a bitcasted shuffle,
16428   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
16429   // back to their original types.
16430   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
16431       N1.isUndef() && Level < AfterLegalizeVectorOps &&
16432       TLI.isTypeLegal(VT)) {
16433 
16434     // Peek through the bitcast only if there is one user.
16435     SDValue BC0 = N0;
16436     while (BC0.getOpcode() == ISD::BITCAST) {
16437       if (!BC0.hasOneUse())
16438         break;
16439       BC0 = BC0.getOperand(0);
16440     }
16441 
16442     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
16443       if (Scale == 1)
16444         return SmallVector<int, 8>(Mask.begin(), Mask.end());
16445 
16446       SmallVector<int, 8> NewMask;
16447       for (int M : Mask)
16448         for (int s = 0; s != Scale; ++s)
16449           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
16450       return NewMask;
16451     };
16452 
16453     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
16454       EVT SVT = VT.getScalarType();
16455       EVT InnerVT = BC0->getValueType(0);
16456       EVT InnerSVT = InnerVT.getScalarType();
16457 
16458       // Determine which shuffle works with the smaller scalar type.
16459       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
16460       EVT ScaleSVT = ScaleVT.getScalarType();
16461 
16462       if (TLI.isTypeLegal(ScaleVT) &&
16463           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
16464           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
16465         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16466         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
16467 
16468         // Scale the shuffle masks to the smaller scalar type.
16469         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
16470         SmallVector<int, 8> InnerMask =
16471             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
16472         SmallVector<int, 8> OuterMask =
16473             ScaleShuffleMask(SVN->getMask(), OuterScale);
16474 
16475         // Merge the shuffle masks.
16476         SmallVector<int, 8> NewMask;
16477         for (int M : OuterMask)
16478           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
16479 
16480         // Test for shuffle mask legality over both commutations.
16481         SDValue SV0 = BC0->getOperand(0);
16482         SDValue SV1 = BC0->getOperand(1);
16483         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16484         if (!LegalMask) {
16485           std::swap(SV0, SV1);
16486           ShuffleVectorSDNode::commuteMask(NewMask);
16487           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
16488         }
16489 
16490         if (LegalMask) {
16491           SV0 = DAG.getBitcast(ScaleVT, SV0);
16492           SV1 = DAG.getBitcast(ScaleVT, SV1);
16493           return DAG.getBitcast(
16494               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
16495         }
16496       }
16497     }
16498   }
16499 
16500   // Canonicalize shuffles according to rules:
16501   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
16502   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
16503   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
16504   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
16505       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
16506       TLI.isTypeLegal(VT)) {
16507     // The incoming shuffle must be of the same type as the result of the
16508     // current shuffle.
16509     assert(N1->getOperand(0).getValueType() == VT &&
16510            "Shuffle types don't match");
16511 
16512     SDValue SV0 = N1->getOperand(0);
16513     SDValue SV1 = N1->getOperand(1);
16514     bool HasSameOp0 = N0 == SV0;
16515     bool IsSV1Undef = SV1.isUndef();
16516     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
16517       // Commute the operands of this shuffle so that next rule
16518       // will trigger.
16519       return DAG.getCommutedVectorShuffle(*SVN);
16520   }
16521 
16522   // Try to fold according to rules:
16523   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16524   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16525   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16526   // Don't try to fold shuffles with illegal type.
16527   // Only fold if this shuffle is the only user of the other shuffle.
16528   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
16529       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
16530     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
16531 
16532     // Don't try to fold splats; they're likely to simplify somehow, or they
16533     // might be free.
16534     if (OtherSV->isSplat())
16535       return SDValue();
16536 
16537     // The incoming shuffle must be of the same type as the result of the
16538     // current shuffle.
16539     assert(OtherSV->getOperand(0).getValueType() == VT &&
16540            "Shuffle types don't match");
16541 
16542     SDValue SV0, SV1;
16543     SmallVector<int, 4> Mask;
16544     // Compute the combined shuffle mask for a shuffle with SV0 as the first
16545     // operand, and SV1 as the second operand.
16546     for (unsigned i = 0; i != NumElts; ++i) {
16547       int Idx = SVN->getMaskElt(i);
16548       if (Idx < 0) {
16549         // Propagate Undef.
16550         Mask.push_back(Idx);
16551         continue;
16552       }
16553 
16554       SDValue CurrentVec;
16555       if (Idx < (int)NumElts) {
16556         // This shuffle index refers to the inner shuffle N0. Lookup the inner
16557         // shuffle mask to identify which vector is actually referenced.
16558         Idx = OtherSV->getMaskElt(Idx);
16559         if (Idx < 0) {
16560           // Propagate Undef.
16561           Mask.push_back(Idx);
16562           continue;
16563         }
16564 
16565         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
16566                                            : OtherSV->getOperand(1);
16567       } else {
16568         // This shuffle index references an element within N1.
16569         CurrentVec = N1;
16570       }
16571 
16572       // Simple case where 'CurrentVec' is UNDEF.
16573       if (CurrentVec.isUndef()) {
16574         Mask.push_back(-1);
16575         continue;
16576       }
16577 
16578       // Canonicalize the shuffle index. We don't know yet if CurrentVec
16579       // will be the first or second operand of the combined shuffle.
16580       Idx = Idx % NumElts;
16581       if (!SV0.getNode() || SV0 == CurrentVec) {
16582         // Ok. CurrentVec is the left hand side.
16583         // Update the mask accordingly.
16584         SV0 = CurrentVec;
16585         Mask.push_back(Idx);
16586         continue;
16587       }
16588 
16589       // Bail out if we cannot convert the shuffle pair into a single shuffle.
16590       if (SV1.getNode() && SV1 != CurrentVec)
16591         return SDValue();
16592 
16593       // Ok. CurrentVec is the right hand side.
16594       // Update the mask accordingly.
16595       SV1 = CurrentVec;
16596       Mask.push_back(Idx + NumElts);
16597     }
16598 
16599     // Check if all indices in Mask are Undef. In case, propagate Undef.
16600     bool isUndefMask = true;
16601     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
16602       isUndefMask &= Mask[i] < 0;
16603 
16604     if (isUndefMask)
16605       return DAG.getUNDEF(VT);
16606 
16607     if (!SV0.getNode())
16608       SV0 = DAG.getUNDEF(VT);
16609     if (!SV1.getNode())
16610       SV1 = DAG.getUNDEF(VT);
16611 
16612     // Avoid introducing shuffles with illegal mask.
16613     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
16614       ShuffleVectorSDNode::commuteMask(Mask);
16615 
16616       if (!TLI.isShuffleMaskLegal(Mask, VT))
16617         return SDValue();
16618 
16619       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
16620       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
16621       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
16622       std::swap(SV0, SV1);
16623     }
16624 
16625     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
16626     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
16627     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
16628     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
16629   }
16630 
16631   return SDValue();
16632 }
16633 
16634 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
16635   SDValue InVal = N->getOperand(0);
16636   EVT VT = N->getValueType(0);
16637 
16638   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
16639   // with a VECTOR_SHUFFLE and possible truncate.
16640   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16641     SDValue InVec = InVal->getOperand(0);
16642     SDValue EltNo = InVal->getOperand(1);
16643     auto InVecT = InVec.getValueType();
16644     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
16645       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
16646       int Elt = C0->getZExtValue();
16647       NewMask[0] = Elt;
16648       SDValue Val;
16649       // If we have an implict truncate do truncate here as long as it's legal.
16650       // if it's not legal, this should
16651       if (VT.getScalarType() != InVal.getValueType() &&
16652           InVal.getValueType().isScalarInteger() &&
16653           isTypeLegal(VT.getScalarType())) {
16654         Val =
16655             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
16656         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
16657       }
16658       if (VT.getScalarType() == InVecT.getScalarType() &&
16659           VT.getVectorNumElements() <= InVecT.getVectorNumElements() &&
16660           TLI.isShuffleMaskLegal(NewMask, VT)) {
16661         Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec,
16662                                    DAG.getUNDEF(InVecT), NewMask);
16663         // If the initial vector is the correct size this shuffle is a
16664         // valid result.
16665         if (VT == InVecT)
16666           return Val;
16667         // If not we must truncate the vector.
16668         if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
16669           MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
16670           SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy);
16671           EVT SubVT =
16672               EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(),
16673                                VT.getVectorNumElements());
16674           Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val,
16675                             ZeroIdx);
16676           return Val;
16677         }
16678       }
16679     }
16680   }
16681 
16682   return SDValue();
16683 }
16684 
16685 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
16686   EVT VT = N->getValueType(0);
16687   SDValue N0 = N->getOperand(0);
16688   SDValue N1 = N->getOperand(1);
16689   SDValue N2 = N->getOperand(2);
16690 
16691   // If inserting an UNDEF, just return the original vector.
16692   if (N1.isUndef())
16693     return N0;
16694 
16695   // For nested INSERT_SUBVECTORs, attempt to combine inner node first to allow
16696   // us to pull BITCASTs from input to output.
16697   if (N0.hasOneUse() && N0->getOpcode() == ISD::INSERT_SUBVECTOR)
16698     if (SDValue NN0 = visitINSERT_SUBVECTOR(N0.getNode()))
16699       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, NN0, N1, N2);
16700 
16701   // If this is an insert of an extracted vector into an undef vector, we can
16702   // just use the input to the extract.
16703   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16704       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
16705     return N1.getOperand(0);
16706 
16707   // If we are inserting a bitcast value into an undef, with the same
16708   // number of elements, just use the bitcast input of the extract.
16709   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
16710   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
16711   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
16712       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
16713       N1.getOperand(0).getOperand(1) == N2 &&
16714       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
16715           VT.getVectorNumElements() &&
16716       N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
16717           VT.getSizeInBits()) {
16718     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
16719   }
16720 
16721   // If both N1 and N2 are bitcast values on which insert_subvector
16722   // would makes sense, pull the bitcast through.
16723   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
16724   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
16725   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
16726     SDValue CN0 = N0.getOperand(0);
16727     SDValue CN1 = N1.getOperand(0);
16728     EVT CN0VT = CN0.getValueType();
16729     EVT CN1VT = CN1.getValueType();
16730     if (CN0VT.isVector() && CN1VT.isVector() &&
16731         CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
16732         CN0VT.getVectorNumElements() == VT.getVectorNumElements()) {
16733       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
16734                                       CN0.getValueType(), CN0, CN1, N2);
16735       return DAG.getBitcast(VT, NewINSERT);
16736     }
16737   }
16738 
16739   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
16740   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
16741   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
16742   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
16743       N0.getOperand(1).getValueType() == N1.getValueType() &&
16744       N0.getOperand(2) == N2)
16745     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
16746                        N1, N2);
16747 
16748   if (!isa<ConstantSDNode>(N2))
16749     return SDValue();
16750 
16751   unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
16752 
16753   // Canonicalize insert_subvector dag nodes.
16754   // Example:
16755   // (insert_subvector (insert_subvector A, Idx0), Idx1)
16756   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
16757   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
16758       N1.getValueType() == N0.getOperand(1).getValueType() &&
16759       isa<ConstantSDNode>(N0.getOperand(2))) {
16760     unsigned OtherIdx = N0.getConstantOperandVal(2);
16761     if (InsIdx < OtherIdx) {
16762       // Swap nodes.
16763       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
16764                                   N0.getOperand(0), N1, N2);
16765       AddToWorklist(NewOp.getNode());
16766       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
16767                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
16768     }
16769   }
16770 
16771   // If the input vector is a concatenation, and the insert replaces
16772   // one of the pieces, we can optimize into a single concat_vectors.
16773   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
16774       N0.getOperand(0).getValueType() == N1.getValueType()) {
16775     unsigned Factor = N1.getValueType().getVectorNumElements();
16776 
16777     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
16778     Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
16779 
16780     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
16781   }
16782 
16783   return SDValue();
16784 }
16785 
16786 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
16787   SDValue N0 = N->getOperand(0);
16788 
16789   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
16790   if (N0->getOpcode() == ISD::FP16_TO_FP)
16791     return N0->getOperand(0);
16792 
16793   return SDValue();
16794 }
16795 
16796 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
16797   SDValue N0 = N->getOperand(0);
16798 
16799   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
16800   if (N0->getOpcode() == ISD::AND) {
16801     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
16802     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
16803       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
16804                          N0.getOperand(0));
16805     }
16806   }
16807 
16808   return SDValue();
16809 }
16810 
16811 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
16812 /// with the destination vector and a zero vector.
16813 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
16814 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
16815 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
16816   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
16817 
16818   EVT VT = N->getValueType(0);
16819   SDValue LHS = N->getOperand(0);
16820   SDValue RHS = peekThroughBitcast(N->getOperand(1));
16821   SDLoc DL(N);
16822 
16823   // Make sure we're not running after operation legalization where it
16824   // may have custom lowered the vector shuffles.
16825   if (LegalOperations)
16826     return SDValue();
16827 
16828   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
16829     return SDValue();
16830 
16831   EVT RVT = RHS.getValueType();
16832   unsigned NumElts = RHS.getNumOperands();
16833 
16834   // Attempt to create a valid clear mask, splitting the mask into
16835   // sub elements and checking to see if each is
16836   // all zeros or all ones - suitable for shuffle masking.
16837   auto BuildClearMask = [&](int Split) {
16838     int NumSubElts = NumElts * Split;
16839     int NumSubBits = RVT.getScalarSizeInBits() / Split;
16840 
16841     SmallVector<int, 8> Indices;
16842     for (int i = 0; i != NumSubElts; ++i) {
16843       int EltIdx = i / Split;
16844       int SubIdx = i % Split;
16845       SDValue Elt = RHS.getOperand(EltIdx);
16846       if (Elt.isUndef()) {
16847         Indices.push_back(-1);
16848         continue;
16849       }
16850 
16851       APInt Bits;
16852       if (isa<ConstantSDNode>(Elt))
16853         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
16854       else if (isa<ConstantFPSDNode>(Elt))
16855         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
16856       else
16857         return SDValue();
16858 
16859       // Extract the sub element from the constant bit mask.
16860       if (DAG.getDataLayout().isBigEndian()) {
16861         Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
16862       } else {
16863         Bits.lshrInPlace(SubIdx * NumSubBits);
16864       }
16865 
16866       if (Split > 1)
16867         Bits = Bits.trunc(NumSubBits);
16868 
16869       if (Bits.isAllOnesValue())
16870         Indices.push_back(i);
16871       else if (Bits == 0)
16872         Indices.push_back(i + NumSubElts);
16873       else
16874         return SDValue();
16875     }
16876 
16877     // Let's see if the target supports this vector_shuffle.
16878     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
16879     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
16880     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
16881       return SDValue();
16882 
16883     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
16884     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
16885                                                    DAG.getBitcast(ClearVT, LHS),
16886                                                    Zero, Indices));
16887   };
16888 
16889   // Determine maximum split level (byte level masking).
16890   int MaxSplit = 1;
16891   if (RVT.getScalarSizeInBits() % 8 == 0)
16892     MaxSplit = RVT.getScalarSizeInBits() / 8;
16893 
16894   for (int Split = 1; Split <= MaxSplit; ++Split)
16895     if (RVT.getScalarSizeInBits() % Split == 0)
16896       if (SDValue S = BuildClearMask(Split))
16897         return S;
16898 
16899   return SDValue();
16900 }
16901 
16902 /// Visit a binary vector operation, like ADD.
16903 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
16904   assert(N->getValueType(0).isVector() &&
16905          "SimplifyVBinOp only works on vectors!");
16906 
16907   SDValue LHS = N->getOperand(0);
16908   SDValue RHS = N->getOperand(1);
16909   SDValue Ops[] = {LHS, RHS};
16910 
16911   // See if we can constant fold the vector operation.
16912   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
16913           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
16914     return Fold;
16915 
16916   // Type legalization might introduce new shuffles in the DAG.
16917   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
16918   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
16919   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
16920       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
16921       LHS.getOperand(1).isUndef() &&
16922       RHS.getOperand(1).isUndef()) {
16923     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
16924     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
16925 
16926     if (SVN0->getMask().equals(SVN1->getMask())) {
16927       EVT VT = N->getValueType(0);
16928       SDValue UndefVector = LHS.getOperand(1);
16929       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
16930                                      LHS.getOperand(0), RHS.getOperand(0),
16931                                      N->getFlags());
16932       AddUsersToWorklist(N);
16933       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
16934                                   SVN0->getMask());
16935     }
16936   }
16937 
16938   return SDValue();
16939 }
16940 
16941 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
16942                                     SDValue N2) {
16943   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
16944 
16945   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
16946                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
16947 
16948   // If we got a simplified select_cc node back from SimplifySelectCC, then
16949   // break it down into a new SETCC node, and a new SELECT node, and then return
16950   // the SELECT node, since we were called with a SELECT node.
16951   if (SCC.getNode()) {
16952     // Check to see if we got a select_cc back (to turn into setcc/select).
16953     // Otherwise, just return whatever node we got back, like fabs.
16954     if (SCC.getOpcode() == ISD::SELECT_CC) {
16955       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
16956                                   N0.getValueType(),
16957                                   SCC.getOperand(0), SCC.getOperand(1),
16958                                   SCC.getOperand(4));
16959       AddToWorklist(SETCC.getNode());
16960       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
16961                            SCC.getOperand(2), SCC.getOperand(3));
16962     }
16963 
16964     return SCC;
16965   }
16966   return SDValue();
16967 }
16968 
16969 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
16970 /// being selected between, see if we can simplify the select.  Callers of this
16971 /// should assume that TheSelect is deleted if this returns true.  As such, they
16972 /// should return the appropriate thing (e.g. the node) back to the top-level of
16973 /// the DAG combiner loop to avoid it being looked at.
16974 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
16975                                     SDValue RHS) {
16976   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
16977   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
16978   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
16979     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
16980       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
16981       SDValue Sqrt = RHS;
16982       ISD::CondCode CC;
16983       SDValue CmpLHS;
16984       const ConstantFPSDNode *Zero = nullptr;
16985 
16986       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
16987         CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
16988         CmpLHS = TheSelect->getOperand(0);
16989         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
16990       } else {
16991         // SELECT or VSELECT
16992         SDValue Cmp = TheSelect->getOperand(0);
16993         if (Cmp.getOpcode() == ISD::SETCC) {
16994           CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
16995           CmpLHS = Cmp.getOperand(0);
16996           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
16997         }
16998       }
16999       if (Zero && Zero->isZero() &&
17000           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
17001           CC == ISD::SETULT || CC == ISD::SETLT)) {
17002         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
17003         CombineTo(TheSelect, Sqrt);
17004         return true;
17005       }
17006     }
17007   }
17008   // Cannot simplify select with vector condition
17009   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
17010 
17011   // If this is a select from two identical things, try to pull the operation
17012   // through the select.
17013   if (LHS.getOpcode() != RHS.getOpcode() ||
17014       !LHS.hasOneUse() || !RHS.hasOneUse())
17015     return false;
17016 
17017   // If this is a load and the token chain is identical, replace the select
17018   // of two loads with a load through a select of the address to load from.
17019   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
17020   // constants have been dropped into the constant pool.
17021   if (LHS.getOpcode() == ISD::LOAD) {
17022     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
17023     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
17024 
17025     // Token chains must be identical.
17026     if (LHS.getOperand(0) != RHS.getOperand(0) ||
17027         // Do not let this transformation reduce the number of volatile loads.
17028         LLD->isVolatile() || RLD->isVolatile() ||
17029         // FIXME: If either is a pre/post inc/dec load,
17030         // we'd need to split out the address adjustment.
17031         LLD->isIndexed() || RLD->isIndexed() ||
17032         // If this is an EXTLOAD, the VT's must match.
17033         LLD->getMemoryVT() != RLD->getMemoryVT() ||
17034         // If this is an EXTLOAD, the kind of extension must match.
17035         (LLD->getExtensionType() != RLD->getExtensionType() &&
17036          // The only exception is if one of the extensions is anyext.
17037          LLD->getExtensionType() != ISD::EXTLOAD &&
17038          RLD->getExtensionType() != ISD::EXTLOAD) ||
17039         // FIXME: this discards src value information.  This is
17040         // over-conservative. It would be beneficial to be able to remember
17041         // both potential memory locations.  Since we are discarding
17042         // src value info, don't do the transformation if the memory
17043         // locations are not in the default address space.
17044         LLD->getPointerInfo().getAddrSpace() != 0 ||
17045         RLD->getPointerInfo().getAddrSpace() != 0 ||
17046         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
17047                                       LLD->getBasePtr().getValueType()))
17048       return false;
17049 
17050     // Check that the select condition doesn't reach either load.  If so,
17051     // folding this will induce a cycle into the DAG.  If not, this is safe to
17052     // xform, so create a select of the addresses.
17053     SDValue Addr;
17054     if (TheSelect->getOpcode() == ISD::SELECT) {
17055       SDNode *CondNode = TheSelect->getOperand(0).getNode();
17056       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
17057           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
17058         return false;
17059       // The loads must not depend on one another.
17060       if (LLD->isPredecessorOf(RLD) ||
17061           RLD->isPredecessorOf(LLD))
17062         return false;
17063       Addr = DAG.getSelect(SDLoc(TheSelect),
17064                            LLD->getBasePtr().getValueType(),
17065                            TheSelect->getOperand(0), LLD->getBasePtr(),
17066                            RLD->getBasePtr());
17067     } else {  // Otherwise SELECT_CC
17068       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
17069       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
17070 
17071       if ((LLD->hasAnyUseOfValue(1) &&
17072            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
17073           (RLD->hasAnyUseOfValue(1) &&
17074            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
17075         return false;
17076 
17077       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
17078                          LLD->getBasePtr().getValueType(),
17079                          TheSelect->getOperand(0),
17080                          TheSelect->getOperand(1),
17081                          LLD->getBasePtr(), RLD->getBasePtr(),
17082                          TheSelect->getOperand(4));
17083     }
17084 
17085     SDValue Load;
17086     // It is safe to replace the two loads if they have different alignments,
17087     // but the new load must be the minimum (most restrictive) alignment of the
17088     // inputs.
17089     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
17090     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
17091     if (!RLD->isInvariant())
17092       MMOFlags &= ~MachineMemOperand::MOInvariant;
17093     if (!RLD->isDereferenceable())
17094       MMOFlags &= ~MachineMemOperand::MODereferenceable;
17095     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
17096       // FIXME: Discards pointer and AA info.
17097       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
17098                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
17099                          MMOFlags);
17100     } else {
17101       // FIXME: Discards pointer and AA info.
17102       Load = DAG.getExtLoad(
17103           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
17104                                                   : LLD->getExtensionType(),
17105           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
17106           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
17107     }
17108 
17109     // Users of the select now use the result of the load.
17110     CombineTo(TheSelect, Load);
17111 
17112     // Users of the old loads now use the new load's chain.  We know the
17113     // old-load value is dead now.
17114     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
17115     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
17116     return true;
17117   }
17118 
17119   return false;
17120 }
17121 
17122 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
17123 /// bitwise 'and'.
17124 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
17125                                             SDValue N1, SDValue N2, SDValue N3,
17126                                             ISD::CondCode CC) {
17127   // If this is a select where the false operand is zero and the compare is a
17128   // check of the sign bit, see if we can perform the "gzip trick":
17129   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
17130   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
17131   EVT XType = N0.getValueType();
17132   EVT AType = N2.getValueType();
17133   if (!isNullConstant(N3) || !XType.bitsGE(AType))
17134     return SDValue();
17135 
17136   // If the comparison is testing for a positive value, we have to invert
17137   // the sign bit mask, so only do that transform if the target has a bitwise
17138   // 'and not' instruction (the invert is free).
17139   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
17140     // (X > -1) ? A : 0
17141     // (X >  0) ? X : 0 <-- This is canonical signed max.
17142     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
17143       return SDValue();
17144   } else if (CC == ISD::SETLT) {
17145     // (X <  0) ? A : 0
17146     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
17147     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
17148       return SDValue();
17149   } else {
17150     return SDValue();
17151   }
17152 
17153   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
17154   // constant.
17155   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
17156   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
17157   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
17158     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
17159     SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
17160     SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
17161     AddToWorklist(Shift.getNode());
17162 
17163     if (XType.bitsGT(AType)) {
17164       Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17165       AddToWorklist(Shift.getNode());
17166     }
17167 
17168     if (CC == ISD::SETGT)
17169       Shift = DAG.getNOT(DL, Shift, AType);
17170 
17171     return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17172   }
17173 
17174   SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
17175   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
17176   AddToWorklist(Shift.getNode());
17177 
17178   if (XType.bitsGT(AType)) {
17179     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
17180     AddToWorklist(Shift.getNode());
17181   }
17182 
17183   if (CC == ISD::SETGT)
17184     Shift = DAG.getNOT(DL, Shift, AType);
17185 
17186   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
17187 }
17188 
17189 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
17190 /// where 'cond' is the comparison specified by CC.
17191 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
17192                                       SDValue N2, SDValue N3, ISD::CondCode CC,
17193                                       bool NotExtCompare) {
17194   // (x ? y : y) -> y.
17195   if (N2 == N3) return N2;
17196 
17197   EVT VT = N2.getValueType();
17198   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
17199   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
17200 
17201   // Determine if the condition we're dealing with is constant
17202   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
17203                               N0, N1, CC, DL, false);
17204   if (SCC.getNode()) AddToWorklist(SCC.getNode());
17205 
17206   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
17207     // fold select_cc true, x, y -> x
17208     // fold select_cc false, x, y -> y
17209     return !SCCC->isNullValue() ? N2 : N3;
17210   }
17211 
17212   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
17213   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
17214   // in it.  This is a win when the constant is not otherwise available because
17215   // it replaces two constant pool loads with one.  We only do this if the FP
17216   // type is known to be legal, because if it isn't, then we are before legalize
17217   // types an we want the other legalization to happen first (e.g. to avoid
17218   // messing with soft float) and if the ConstantFP is not legal, because if
17219   // it is legal, we may not need to store the FP constant in a constant pool.
17220   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
17221     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
17222       if (TLI.isTypeLegal(N2.getValueType()) &&
17223           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
17224                TargetLowering::Legal &&
17225            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
17226            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
17227           // If both constants have multiple uses, then we won't need to do an
17228           // extra load, they are likely around in registers for other users.
17229           (TV->hasOneUse() || FV->hasOneUse())) {
17230         Constant *Elts[] = {
17231           const_cast<ConstantFP*>(FV->getConstantFPValue()),
17232           const_cast<ConstantFP*>(TV->getConstantFPValue())
17233         };
17234         Type *FPTy = Elts[0]->getType();
17235         const DataLayout &TD = DAG.getDataLayout();
17236 
17237         // Create a ConstantArray of the two constants.
17238         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
17239         SDValue CPIdx =
17240             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
17241                                 TD.getPrefTypeAlignment(FPTy));
17242         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
17243 
17244         // Get the offsets to the 0 and 1 element of the array so that we can
17245         // select between them.
17246         SDValue Zero = DAG.getIntPtrConstant(0, DL);
17247         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
17248         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
17249 
17250         SDValue Cond = DAG.getSetCC(DL,
17251                                     getSetCCResultType(N0.getValueType()),
17252                                     N0, N1, CC);
17253         AddToWorklist(Cond.getNode());
17254         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
17255                                           Cond, One, Zero);
17256         AddToWorklist(CstOffset.getNode());
17257         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
17258                             CstOffset);
17259         AddToWorklist(CPIdx.getNode());
17260         return DAG.getLoad(
17261             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
17262             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
17263             Alignment);
17264       }
17265     }
17266 
17267   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
17268     return V;
17269 
17270   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
17271   // where y is has a single bit set.
17272   // A plaintext description would be, we can turn the SELECT_CC into an AND
17273   // when the condition can be materialized as an all-ones register.  Any
17274   // single bit-test can be materialized as an all-ones register with
17275   // shift-left and shift-right-arith.
17276   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
17277       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
17278     SDValue AndLHS = N0->getOperand(0);
17279     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17280     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
17281       // Shift the tested bit over the sign bit.
17282       const APInt &AndMask = ConstAndRHS->getAPIntValue();
17283       SDValue ShlAmt =
17284         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
17285                         getShiftAmountTy(AndLHS.getValueType()));
17286       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
17287 
17288       // Now arithmetic right shift it all the way over, so the result is either
17289       // all-ones, or zero.
17290       SDValue ShrAmt =
17291         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
17292                         getShiftAmountTy(Shl.getValueType()));
17293       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
17294 
17295       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
17296     }
17297   }
17298 
17299   // fold select C, 16, 0 -> shl C, 4
17300   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
17301       TLI.getBooleanContents(N0.getValueType()) ==
17302           TargetLowering::ZeroOrOneBooleanContent) {
17303 
17304     // If the caller doesn't want us to simplify this into a zext of a compare,
17305     // don't do it.
17306     if (NotExtCompare && N2C->isOne())
17307       return SDValue();
17308 
17309     // Get a SetCC of the condition
17310     // NOTE: Don't create a SETCC if it's not legal on this target.
17311     if (!LegalOperations ||
17312         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
17313       SDValue Temp, SCC;
17314       // cast from setcc result type to select result type
17315       if (LegalTypes) {
17316         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
17317                             N0, N1, CC);
17318         if (N2.getValueType().bitsLT(SCC.getValueType()))
17319           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
17320                                         N2.getValueType());
17321         else
17322           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17323                              N2.getValueType(), SCC);
17324       } else {
17325         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
17326         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
17327                            N2.getValueType(), SCC);
17328       }
17329 
17330       AddToWorklist(SCC.getNode());
17331       AddToWorklist(Temp.getNode());
17332 
17333       if (N2C->isOne())
17334         return Temp;
17335 
17336       // shl setcc result by log2 n2c
17337       return DAG.getNode(
17338           ISD::SHL, DL, N2.getValueType(), Temp,
17339           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
17340                           getShiftAmountTy(Temp.getValueType())));
17341     }
17342   }
17343 
17344   // Check to see if this is an integer abs.
17345   // select_cc setg[te] X,  0,  X, -X ->
17346   // select_cc setgt    X, -1,  X, -X ->
17347   // select_cc setl[te] X,  0, -X,  X ->
17348   // select_cc setlt    X,  1, -X,  X ->
17349   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
17350   if (N1C) {
17351     ConstantSDNode *SubC = nullptr;
17352     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
17353          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
17354         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
17355       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
17356     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
17357               (N1C->isOne() && CC == ISD::SETLT)) &&
17358              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
17359       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
17360 
17361     EVT XType = N0.getValueType();
17362     if (SubC && SubC->isNullValue() && XType.isInteger()) {
17363       SDLoc DL(N0);
17364       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
17365                                   N0,
17366                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
17367                                          getShiftAmountTy(N0.getValueType())));
17368       SDValue Add = DAG.getNode(ISD::ADD, DL,
17369                                 XType, N0, Shift);
17370       AddToWorklist(Shift.getNode());
17371       AddToWorklist(Add.getNode());
17372       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
17373     }
17374   }
17375 
17376   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
17377   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
17378   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
17379   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
17380   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
17381   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
17382   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
17383   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
17384   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
17385     SDValue ValueOnZero = N2;
17386     SDValue Count = N3;
17387     // If the condition is NE instead of E, swap the operands.
17388     if (CC == ISD::SETNE)
17389       std::swap(ValueOnZero, Count);
17390     // Check if the value on zero is a constant equal to the bits in the type.
17391     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
17392       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
17393         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
17394         // legal, combine to just cttz.
17395         if ((Count.getOpcode() == ISD::CTTZ ||
17396              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
17397             N0 == Count.getOperand(0) &&
17398             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
17399           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
17400         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
17401         // legal, combine to just ctlz.
17402         if ((Count.getOpcode() == ISD::CTLZ ||
17403              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
17404             N0 == Count.getOperand(0) &&
17405             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
17406           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
17407       }
17408     }
17409   }
17410 
17411   return SDValue();
17412 }
17413 
17414 /// This is a stub for TargetLowering::SimplifySetCC.
17415 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
17416                                    ISD::CondCode Cond, const SDLoc &DL,
17417                                    bool foldBooleans) {
17418   TargetLowering::DAGCombinerInfo
17419     DagCombineInfo(DAG, Level, false, this);
17420   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
17421 }
17422 
17423 /// Given an ISD::SDIV node expressing a divide by constant, return
17424 /// a DAG expression to select that will generate the same value by multiplying
17425 /// by a magic number.
17426 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17427 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
17428   // when optimising for minimum size, we don't want to expand a div to a mul
17429   // and a shift.
17430   if (DAG.getMachineFunction().getFunction().optForMinSize())
17431     return SDValue();
17432 
17433   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17434   if (!C)
17435     return SDValue();
17436 
17437   // Avoid division by zero.
17438   if (C->isNullValue())
17439     return SDValue();
17440 
17441   std::vector<SDNode *> Built;
17442   SDValue S =
17443       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17444 
17445   for (SDNode *N : Built)
17446     AddToWorklist(N);
17447   return S;
17448 }
17449 
17450 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
17451 /// DAG expression that will generate the same value by right shifting.
17452 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
17453   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17454   if (!C)
17455     return SDValue();
17456 
17457   // Avoid division by zero.
17458   if (C->isNullValue())
17459     return SDValue();
17460 
17461   std::vector<SDNode *> Built;
17462   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
17463 
17464   for (SDNode *N : Built)
17465     AddToWorklist(N);
17466   return S;
17467 }
17468 
17469 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
17470 /// expression that will generate the same value by multiplying by a magic
17471 /// number.
17472 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
17473 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
17474   // when optimising for minimum size, we don't want to expand a div to a mul
17475   // and a shift.
17476   if (DAG.getMachineFunction().getFunction().optForMinSize())
17477     return SDValue();
17478 
17479   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
17480   if (!C)
17481     return SDValue();
17482 
17483   // Avoid division by zero.
17484   if (C->isNullValue())
17485     return SDValue();
17486 
17487   std::vector<SDNode *> Built;
17488   SDValue S =
17489       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
17490 
17491   for (SDNode *N : Built)
17492     AddToWorklist(N);
17493   return S;
17494 }
17495 
17496 /// Determines the LogBase2 value for a non-null input value using the
17497 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
17498 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
17499   EVT VT = V.getValueType();
17500   unsigned EltBits = VT.getScalarSizeInBits();
17501   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
17502   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
17503   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
17504   return LogBase2;
17505 }
17506 
17507 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17508 /// For the reciprocal, we need to find the zero of the function:
17509 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
17510 ///     =>
17511 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
17512 ///     does not require additional intermediate precision]
17513 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
17514   if (Level >= AfterLegalizeDAG)
17515     return SDValue();
17516 
17517   // TODO: Handle half and/or extended types?
17518   EVT VT = Op.getValueType();
17519   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17520     return SDValue();
17521 
17522   // If estimates are explicitly disabled for this function, we're done.
17523   MachineFunction &MF = DAG.getMachineFunction();
17524   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
17525   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17526     return SDValue();
17527 
17528   // Estimates may be explicitly enabled for this type with a custom number of
17529   // refinement steps.
17530   int Iterations = TLI.getDivRefinementSteps(VT, MF);
17531   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
17532     AddToWorklist(Est.getNode());
17533 
17534     if (Iterations) {
17535       EVT VT = Op.getValueType();
17536       SDLoc DL(Op);
17537       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
17538 
17539       // Newton iterations: Est = Est + Est (1 - Arg * Est)
17540       for (int i = 0; i < Iterations; ++i) {
17541         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
17542         AddToWorklist(NewEst.getNode());
17543 
17544         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
17545         AddToWorklist(NewEst.getNode());
17546 
17547         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17548         AddToWorklist(NewEst.getNode());
17549 
17550         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
17551         AddToWorklist(Est.getNode());
17552       }
17553     }
17554     return Est;
17555   }
17556 
17557   return SDValue();
17558 }
17559 
17560 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17561 /// For the reciprocal sqrt, we need to find the zero of the function:
17562 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17563 ///     =>
17564 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
17565 /// As a result, we precompute A/2 prior to the iteration loop.
17566 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
17567                                          unsigned Iterations,
17568                                          SDNodeFlags Flags, bool Reciprocal) {
17569   EVT VT = Arg.getValueType();
17570   SDLoc DL(Arg);
17571   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
17572 
17573   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
17574   // this entire sequence requires only one FP constant.
17575   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
17576   AddToWorklist(HalfArg.getNode());
17577 
17578   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
17579   AddToWorklist(HalfArg.getNode());
17580 
17581   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
17582   for (unsigned i = 0; i < Iterations; ++i) {
17583     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
17584     AddToWorklist(NewEst.getNode());
17585 
17586     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
17587     AddToWorklist(NewEst.getNode());
17588 
17589     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
17590     AddToWorklist(NewEst.getNode());
17591 
17592     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
17593     AddToWorklist(Est.getNode());
17594   }
17595 
17596   // If non-reciprocal square root is requested, multiply the result by Arg.
17597   if (!Reciprocal) {
17598     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
17599     AddToWorklist(Est.getNode());
17600   }
17601 
17602   return Est;
17603 }
17604 
17605 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
17606 /// For the reciprocal sqrt, we need to find the zero of the function:
17607 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
17608 ///     =>
17609 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
17610 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
17611                                          unsigned Iterations,
17612                                          SDNodeFlags Flags, bool Reciprocal) {
17613   EVT VT = Arg.getValueType();
17614   SDLoc DL(Arg);
17615   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
17616   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
17617 
17618   // This routine must enter the loop below to work correctly
17619   // when (Reciprocal == false).
17620   assert(Iterations > 0);
17621 
17622   // Newton iterations for reciprocal square root:
17623   // E = (E * -0.5) * ((A * E) * E + -3.0)
17624   for (unsigned i = 0; i < Iterations; ++i) {
17625     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
17626     AddToWorklist(AE.getNode());
17627 
17628     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
17629     AddToWorklist(AEE.getNode());
17630 
17631     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
17632     AddToWorklist(RHS.getNode());
17633 
17634     // When calculating a square root at the last iteration build:
17635     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
17636     // (notice a common subexpression)
17637     SDValue LHS;
17638     if (Reciprocal || (i + 1) < Iterations) {
17639       // RSQRT: LHS = (E * -0.5)
17640       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
17641     } else {
17642       // SQRT: LHS = (A * E) * -0.5
17643       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
17644     }
17645     AddToWorklist(LHS.getNode());
17646 
17647     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
17648     AddToWorklist(Est.getNode());
17649   }
17650 
17651   return Est;
17652 }
17653 
17654 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
17655 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
17656 /// Op can be zero.
17657 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
17658                                            bool Reciprocal) {
17659   if (Level >= AfterLegalizeDAG)
17660     return SDValue();
17661 
17662   // TODO: Handle half and/or extended types?
17663   EVT VT = Op.getValueType();
17664   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
17665     return SDValue();
17666 
17667   // If estimates are explicitly disabled for this function, we're done.
17668   MachineFunction &MF = DAG.getMachineFunction();
17669   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
17670   if (Enabled == TLI.ReciprocalEstimate::Disabled)
17671     return SDValue();
17672 
17673   // Estimates may be explicitly enabled for this type with a custom number of
17674   // refinement steps.
17675   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
17676 
17677   bool UseOneConstNR = false;
17678   if (SDValue Est =
17679       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
17680                           Reciprocal)) {
17681     AddToWorklist(Est.getNode());
17682 
17683     if (Iterations) {
17684       Est = UseOneConstNR
17685             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
17686             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
17687 
17688       if (!Reciprocal) {
17689         // The estimate is now completely wrong if the input was exactly 0.0 or
17690         // possibly a denormal. Force the answer to 0.0 for those cases.
17691         EVT VT = Op.getValueType();
17692         SDLoc DL(Op);
17693         EVT CCVT = getSetCCResultType(VT);
17694         ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
17695         const Function &F = DAG.getMachineFunction().getFunction();
17696         Attribute Denorms = F.getFnAttribute("denormal-fp-math");
17697         if (Denorms.getValueAsString().equals("ieee")) {
17698           // fabs(X) < SmallestNormal ? 0.0 : Est
17699           const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
17700           APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
17701           SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
17702           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17703           SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
17704           SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
17705           Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
17706           AddToWorklist(Fabs.getNode());
17707           AddToWorklist(IsDenorm.getNode());
17708           AddToWorklist(Est.getNode());
17709         } else {
17710           // X == 0.0 ? 0.0 : Est
17711           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
17712           SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
17713           Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
17714           AddToWorklist(IsZero.getNode());
17715           AddToWorklist(Est.getNode());
17716         }
17717       }
17718     }
17719     return Est;
17720   }
17721 
17722   return SDValue();
17723 }
17724 
17725 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17726   return buildSqrtEstimateImpl(Op, Flags, true);
17727 }
17728 
17729 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
17730   return buildSqrtEstimateImpl(Op, Flags, false);
17731 }
17732 
17733 /// Return true if there is any possibility that the two addresses overlap.
17734 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
17735   // If they are the same then they must be aliases.
17736   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
17737 
17738   // If they are both volatile then they cannot be reordered.
17739   if (Op0->isVolatile() && Op1->isVolatile()) return true;
17740 
17741   // If one operation reads from invariant memory, and the other may store, they
17742   // cannot alias. These should really be checking the equivalent of mayWrite,
17743   // but it only matters for memory nodes other than load /store.
17744   if (Op0->isInvariant() && Op1->writeMem())
17745     return false;
17746 
17747   if (Op1->isInvariant() && Op0->writeMem())
17748     return false;
17749 
17750   unsigned NumBytes0 = Op0->getMemoryVT().getStoreSize();
17751   unsigned NumBytes1 = Op1->getMemoryVT().getStoreSize();
17752 
17753   // Check for BaseIndexOffset matching.
17754   BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0, DAG);
17755   BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1, DAG);
17756   int64_t PtrDiff;
17757   if (BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()) {
17758     if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
17759       return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
17760 
17761     // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
17762     // able to calculate their relative offset if at least one arises
17763     // from an alloca. However, these allocas cannot overlap and we
17764     // can infer there is no alias.
17765     if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
17766       if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
17767         MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17768         // If the base are the same frame index but the we couldn't find a
17769         // constant offset, (indices are different) be conservative.
17770         if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
17771                        !MFI.isFixedObjectIndex(B->getIndex())))
17772           return false;
17773       }
17774 
17775     bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
17776     bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
17777     bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
17778     bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
17779     bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
17780     bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
17781 
17782     // If of mismatched base types or checkable indices we can check
17783     // they do not alias.
17784     if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
17785          (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
17786         (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1))
17787       return false;
17788   }
17789 
17790   // If we know required SrcValue1 and SrcValue2 have relatively large
17791   // alignment compared to the size and offset of the access, we may be able
17792   // to prove they do not alias. This check is conservative for now to catch
17793   // cases created by splitting vector types.
17794   int64_t SrcValOffset0 = Op0->getSrcValueOffset();
17795   int64_t SrcValOffset1 = Op1->getSrcValueOffset();
17796   unsigned OrigAlignment0 = Op0->getOriginalAlignment();
17797   unsigned OrigAlignment1 = Op1->getOriginalAlignment();
17798   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
17799       NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
17800     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
17801     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
17802 
17803     // There is no overlap between these relatively aligned accesses of
17804     // similar size. Return no alias.
17805     if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
17806         (OffAlign1 + NumBytes1) <= OffAlign0)
17807       return false;
17808   }
17809 
17810   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
17811                    ? CombinerGlobalAA
17812                    : DAG.getSubtarget().useAA();
17813 #ifndef NDEBUG
17814   if (CombinerAAOnlyFunc.getNumOccurrences() &&
17815       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
17816     UseAA = false;
17817 #endif
17818 
17819   if (UseAA && AA &&
17820       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
17821     // Use alias analysis information.
17822     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
17823     int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
17824     int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
17825     AliasResult AAResult =
17826         AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
17827                                  UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
17828                   MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
17829                                  UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
17830     if (AAResult == NoAlias)
17831       return false;
17832   }
17833 
17834   // Otherwise we have to assume they alias.
17835   return true;
17836 }
17837 
17838 /// Walk up chain skipping non-aliasing memory nodes,
17839 /// looking for aliasing nodes and adding them to the Aliases vector.
17840 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
17841                                    SmallVectorImpl<SDValue> &Aliases) {
17842   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
17843   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
17844 
17845   // Get alias information for node.
17846   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
17847 
17848   // Starting off.
17849   Chains.push_back(OriginalChain);
17850   unsigned Depth = 0;
17851 
17852   // Look at each chain and determine if it is an alias.  If so, add it to the
17853   // aliases list.  If not, then continue up the chain looking for the next
17854   // candidate.
17855   while (!Chains.empty()) {
17856     SDValue Chain = Chains.pop_back_val();
17857 
17858     // For TokenFactor nodes, look at each operand and only continue up the
17859     // chain until we reach the depth limit.
17860     //
17861     // FIXME: The depth check could be made to return the last non-aliasing
17862     // chain we found before we hit a tokenfactor rather than the original
17863     // chain.
17864     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
17865       Aliases.clear();
17866       Aliases.push_back(OriginalChain);
17867       return;
17868     }
17869 
17870     // Don't bother if we've been before.
17871     if (!Visited.insert(Chain.getNode()).second)
17872       continue;
17873 
17874     switch (Chain.getOpcode()) {
17875     case ISD::EntryToken:
17876       // Entry token is ideal chain operand, but handled in FindBetterChain.
17877       break;
17878 
17879     case ISD::LOAD:
17880     case ISD::STORE: {
17881       // Get alias information for Chain.
17882       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
17883           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
17884 
17885       // If chain is alias then stop here.
17886       if (!(IsLoad && IsOpLoad) &&
17887           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
17888         Aliases.push_back(Chain);
17889       } else {
17890         // Look further up the chain.
17891         Chains.push_back(Chain.getOperand(0));
17892         ++Depth;
17893       }
17894       break;
17895     }
17896 
17897     case ISD::TokenFactor:
17898       // We have to check each of the operands of the token factor for "small"
17899       // token factors, so we queue them up.  Adding the operands to the queue
17900       // (stack) in reverse order maintains the original order and increases the
17901       // likelihood that getNode will find a matching token factor (CSE.)
17902       if (Chain.getNumOperands() > 16) {
17903         Aliases.push_back(Chain);
17904         break;
17905       }
17906       for (unsigned n = Chain.getNumOperands(); n;)
17907         Chains.push_back(Chain.getOperand(--n));
17908       ++Depth;
17909       break;
17910 
17911     case ISD::CopyFromReg:
17912       // Forward past CopyFromReg.
17913       Chains.push_back(Chain.getOperand(0));
17914       ++Depth;
17915       break;
17916 
17917     default:
17918       // For all other instructions we will just have to take what we can get.
17919       Aliases.push_back(Chain);
17920       break;
17921     }
17922   }
17923 }
17924 
17925 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
17926 /// (aliasing node.)
17927 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
17928   if (OptLevel == CodeGenOpt::None)
17929     return OldChain;
17930 
17931   // Ops for replacing token factor.
17932   SmallVector<SDValue, 8> Aliases;
17933 
17934   // Accumulate all the aliases to this node.
17935   GatherAllAliases(N, OldChain, Aliases);
17936 
17937   // If no operands then chain to entry token.
17938   if (Aliases.size() == 0)
17939     return DAG.getEntryNode();
17940 
17941   // If a single operand then chain to it.  We don't need to revisit it.
17942   if (Aliases.size() == 1)
17943     return Aliases[0];
17944 
17945   // Construct a custom tailored token factor.
17946   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
17947 }
17948 
17949 // This function tries to collect a bunch of potentially interesting
17950 // nodes to improve the chains of, all at once. This might seem
17951 // redundant, as this function gets called when visiting every store
17952 // node, so why not let the work be done on each store as it's visited?
17953 //
17954 // I believe this is mainly important because MergeConsecutiveStores
17955 // is unable to deal with merging stores of different sizes, so unless
17956 // we improve the chains of all the potential candidates up-front
17957 // before running MergeConsecutiveStores, it might only see some of
17958 // the nodes that will eventually be candidates, and then not be able
17959 // to go from a partially-merged state to the desired final
17960 // fully-merged state.
17961 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
17962   if (OptLevel == CodeGenOpt::None)
17963     return false;
17964 
17965   // This holds the base pointer, index, and the offset in bytes from the base
17966   // pointer.
17967   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
17968 
17969   // We must have a base and an offset.
17970   if (!BasePtr.getBase().getNode())
17971     return false;
17972 
17973   // Do not handle stores to undef base pointers.
17974   if (BasePtr.getBase().isUndef())
17975     return false;
17976 
17977   SmallVector<StoreSDNode *, 8> ChainedStores;
17978   ChainedStores.push_back(St);
17979 
17980   // Walk up the chain and look for nodes with offsets from the same
17981   // base pointer. Stop when reaching an instruction with a different kind
17982   // or instruction which has a different base pointer.
17983   StoreSDNode *Index = St;
17984   while (Index) {
17985     // If the chain has more than one use, then we can't reorder the mem ops.
17986     if (Index != St && !SDValue(Index, 0)->hasOneUse())
17987       break;
17988 
17989     if (Index->isVolatile() || Index->isIndexed())
17990       break;
17991 
17992     // Find the base pointer and offset for this memory node.
17993     BaseIndexOffset Ptr = BaseIndexOffset::match(Index, DAG);
17994 
17995     // Check that the base pointer is the same as the original one.
17996     if (!BasePtr.equalBaseIndex(Ptr, DAG))
17997       break;
17998 
17999     // Walk up the chain to find the next store node, ignoring any
18000     // intermediate loads. Any other kind of node will halt the loop.
18001     SDNode *NextInChain = Index->getChain().getNode();
18002     while (true) {
18003       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
18004         // We found a store node. Use it for the next iteration.
18005         if (STn->isVolatile() || STn->isIndexed()) {
18006           Index = nullptr;
18007           break;
18008         }
18009         ChainedStores.push_back(STn);
18010         Index = STn;
18011         break;
18012       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
18013         NextInChain = Ldn->getChain().getNode();
18014         continue;
18015       } else {
18016         Index = nullptr;
18017         break;
18018       }
18019     } // end while
18020   }
18021 
18022   // At this point, ChainedStores lists all of the Store nodes
18023   // reachable by iterating up through chain nodes matching the above
18024   // conditions.  For each such store identified, try to find an
18025   // earlier chain to attach the store to which won't violate the
18026   // required ordering.
18027   bool MadeChangeToSt = false;
18028   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
18029 
18030   for (StoreSDNode *ChainedStore : ChainedStores) {
18031     SDValue Chain = ChainedStore->getChain();
18032     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
18033 
18034     if (Chain != BetterChain) {
18035       if (ChainedStore == St)
18036         MadeChangeToSt = true;
18037       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
18038     }
18039   }
18040 
18041   // Do all replacements after finding the replacements to make to avoid making
18042   // the chains more complicated by introducing new TokenFactors.
18043   for (auto Replacement : BetterChains)
18044     replaceStoreChain(Replacement.first, Replacement.second);
18045 
18046   return MadeChangeToSt;
18047 }
18048 
18049 /// This is the entry point for the file.
18050 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
18051                            CodeGenOpt::Level OptLevel) {
18052   /// This is the main entry point to this class.
18053   DAGCombiner(*this, AA, OptLevel).Run(Level);
18054 }
18055