1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
10 // both before and after the DAG is legalized.
11 //
12 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
13 // primarily intended to handle simplification opportunities that are implicit
14 // in the LLVM IR and exposed by the various codegen lowering phases.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntervalMap.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/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/VectorUtils.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 
76 using namespace llvm;
77 
78 #define DEBUG_TYPE "dagcombine"
79 
80 STATISTIC(NodesCombined   , "Number of dag nodes combined");
81 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
82 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
83 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
84 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
85 STATISTIC(SlicedLoads, "Number of load sliced");
86 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
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 static cl::opt<bool>
115     EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
116                        cl::desc("DAG combiner enable merging multiple stores "
117                                 "into a wider store"));
118 
119 static cl::opt<unsigned> TokenFactorInlineLimit(
120     "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
121     cl::desc("Limit the number of operands to inline for Token Factors"));
122 
123 static cl::opt<unsigned> StoreMergeDependenceLimit(
124     "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
125     cl::desc("Limit the number of times for the same StoreNode and RootNode "
126              "to bail out in store merging dependence check"));
127 
128 namespace {
129 
130   class DAGCombiner {
131     SelectionDAG &DAG;
132     const TargetLowering &TLI;
133     CombineLevel Level;
134     CodeGenOpt::Level OptLevel;
135     bool LegalDAG = false;
136     bool LegalOperations = false;
137     bool LegalTypes = false;
138     bool ForCodeSize;
139 
140     /// Worklist of all of the nodes that need to be simplified.
141     ///
142     /// This must behave as a stack -- new nodes to process are pushed onto the
143     /// back and when processing we pop off of the back.
144     ///
145     /// The worklist will not contain duplicates but may contain null entries
146     /// due to nodes being deleted from the underlying DAG.
147     SmallVector<SDNode *, 64> Worklist;
148 
149     /// Mapping from an SDNode to its position on the worklist.
150     ///
151     /// This is used to find and remove nodes from the worklist (by nulling
152     /// them) when they are deleted from the underlying DAG. It relies on
153     /// stable indices of nodes within the worklist.
154     DenseMap<SDNode *, unsigned> WorklistMap;
155     /// This records all nodes attempted to add to the worklist since we
156     /// considered a new worklist entry. As we keep do not add duplicate nodes
157     /// in the worklist, this is different from the tail of the worklist.
158     SmallSetVector<SDNode *, 32> PruningList;
159 
160     /// Set of nodes which have been combined (at least once).
161     ///
162     /// This is used to allow us to reliably add any operands of a DAG node
163     /// which have not yet been combined to the worklist.
164     SmallPtrSet<SDNode *, 32> CombinedNodes;
165 
166     /// Map from candidate StoreNode to the pair of RootNode and count.
167     /// The count is used to track how many times we have seen the StoreNode
168     /// with the same RootNode bail out in dependence check. If we have seen
169     /// the bail out for the same pair many times over a limit, we won't
170     /// consider the StoreNode with the same RootNode as store merging
171     /// candidate again.
172     DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap;
173 
174     // AA - Used for DAG load/store alias analysis.
175     AliasAnalysis *AA;
176 
177     /// When an instruction is simplified, add all users of the instruction to
178     /// the work lists because they might get more simplified now.
179     void AddUsersToWorklist(SDNode *N) {
180       for (SDNode *Node : N->uses())
181         AddToWorklist(Node);
182     }
183 
184     /// Convenient shorthand to add a node and all of its user to the worklist.
185     void AddToWorklistWithUsers(SDNode *N) {
186       AddUsersToWorklist(N);
187       AddToWorklist(N);
188     }
189 
190     // Prune potentially dangling nodes. This is called after
191     // any visit to a node, but should also be called during a visit after any
192     // failed combine which may have created a DAG node.
193     void clearAddedDanglingWorklistEntries() {
194       // Check any nodes added to the worklist to see if they are prunable.
195       while (!PruningList.empty()) {
196         auto *N = PruningList.pop_back_val();
197         if (N->use_empty())
198           recursivelyDeleteUnusedNodes(N);
199       }
200     }
201 
202     SDNode *getNextWorklistEntry() {
203       // Before we do any work, remove nodes that are not in use.
204       clearAddedDanglingWorklistEntries();
205       SDNode *N = nullptr;
206       // The Worklist holds the SDNodes in order, but it may contain null
207       // entries.
208       while (!N && !Worklist.empty()) {
209         N = Worklist.pop_back_val();
210       }
211 
212       if (N) {
213         bool GoodWorklistEntry = WorklistMap.erase(N);
214         (void)GoodWorklistEntry;
215         assert(GoodWorklistEntry &&
216                "Found a worklist entry without a corresponding map entry!");
217       }
218       return N;
219     }
220 
221     /// Call the node-specific routine that folds each particular type of node.
222     SDValue visit(SDNode *N);
223 
224   public:
225     DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
226         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
227           OptLevel(OL), AA(AA) {
228       ForCodeSize = DAG.shouldOptForSize();
229 
230       MaximumLegalStoreInBits = 0;
231       // We use the minimum store size here, since that's all we can guarantee
232       // for the scalable vector types.
233       for (MVT VT : MVT::all_valuetypes())
234         if (EVT(VT).isSimple() && VT != MVT::Other &&
235             TLI.isTypeLegal(EVT(VT)) &&
236             VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits)
237           MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize();
238     }
239 
240     void ConsiderForPruning(SDNode *N) {
241       // Mark this for potential pruning.
242       PruningList.insert(N);
243     }
244 
245     /// Add to the worklist making sure its instance is at the back (next to be
246     /// processed.)
247     void AddToWorklist(SDNode *N) {
248       assert(N->getOpcode() != ISD::DELETED_NODE &&
249              "Deleted Node added to Worklist");
250 
251       // Skip handle nodes as they can't usefully be combined and confuse the
252       // zero-use deletion strategy.
253       if (N->getOpcode() == ISD::HANDLENODE)
254         return;
255 
256       ConsiderForPruning(N);
257 
258       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
259         Worklist.push_back(N);
260     }
261 
262     /// Remove all instances of N from the worklist.
263     void removeFromWorklist(SDNode *N) {
264       CombinedNodes.erase(N);
265       PruningList.remove(N);
266       StoreRootCountMap.erase(N);
267 
268       auto It = WorklistMap.find(N);
269       if (It == WorklistMap.end())
270         return; // Not in the worklist.
271 
272       // Null out the entry rather than erasing it to avoid a linear operation.
273       Worklist[It->second] = nullptr;
274       WorklistMap.erase(It);
275     }
276 
277     void deleteAndRecombine(SDNode *N);
278     bool recursivelyDeleteUnusedNodes(SDNode *N);
279 
280     /// Replaces all uses of the results of one DAG node with new values.
281     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
282                       bool AddTo = true);
283 
284     /// Replaces all uses of the results of one DAG node with new values.
285     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
286       return CombineTo(N, &Res, 1, AddTo);
287     }
288 
289     /// Replaces all uses of the results of one DAG node with new values.
290     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
291                       bool AddTo = true) {
292       SDValue To[] = { Res0, Res1 };
293       return CombineTo(N, To, 2, AddTo);
294     }
295 
296     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
297 
298   private:
299     unsigned MaximumLegalStoreInBits;
300 
301     /// Check the specified integer node value to see if it can be simplified or
302     /// if things it uses can be simplified by bit propagation.
303     /// If so, return true.
304     bool SimplifyDemandedBits(SDValue Op) {
305       unsigned BitWidth = Op.getScalarValueSizeInBits();
306       APInt DemandedBits = APInt::getAllOnesValue(BitWidth);
307       return SimplifyDemandedBits(Op, DemandedBits);
308     }
309 
310     bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
311       EVT VT = Op.getValueType();
312       unsigned NumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
313       APInt DemandedElts = APInt::getAllOnesValue(NumElts);
314       return SimplifyDemandedBits(Op, DemandedBits, DemandedElts);
315     }
316 
317     /// Check the specified vector node value to see if it can be simplified or
318     /// if things it uses can be simplified as it only uses some of the
319     /// elements. If so, return true.
320     bool SimplifyDemandedVectorElts(SDValue Op) {
321       unsigned NumElts = Op.getValueType().getVectorNumElements();
322       APInt DemandedElts = APInt::getAllOnesValue(NumElts);
323       return SimplifyDemandedVectorElts(Op, DemandedElts);
324     }
325 
326     bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
327                               const APInt &DemandedElts,
328                               bool AssumeSingleUse = false);
329     bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
330                                     bool AssumeSingleUse = false);
331 
332     bool CombineToPreIndexedLoadStore(SDNode *N);
333     bool CombineToPostIndexedLoadStore(SDNode *N);
334     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
335     bool SliceUpLoad(SDNode *N);
336 
337     // Scalars have size 0 to distinguish from singleton vectors.
338     SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
339     bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
340     bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
341 
342     /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
343     ///   load.
344     ///
345     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
346     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
347     /// \param EltNo index of the vector element to load.
348     /// \param OriginalLoad load that EVE came from to be replaced.
349     /// \returns EVE on success SDValue() on failure.
350     SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
351                                          SDValue EltNo,
352                                          LoadSDNode *OriginalLoad);
353     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
354     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
355     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
356     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
357     SDValue PromoteIntBinOp(SDValue Op);
358     SDValue PromoteIntShiftOp(SDValue Op);
359     SDValue PromoteExtend(SDValue Op);
360     bool PromoteLoad(SDValue Op);
361 
362     /// Call the node-specific routine that knows how to fold each
363     /// particular type of node. If that doesn't do anything, try the
364     /// target-specific DAG combines.
365     SDValue combine(SDNode *N);
366 
367     // Visitation implementation - Implement dag node combining for different
368     // node types.  The semantics are as follows:
369     // Return Value:
370     //   SDValue.getNode() == 0 - No change was made
371     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
372     //   otherwise              - N should be replaced by the returned Operand.
373     //
374     SDValue visitTokenFactor(SDNode *N);
375     SDValue visitMERGE_VALUES(SDNode *N);
376     SDValue visitADD(SDNode *N);
377     SDValue visitADDLike(SDNode *N);
378     SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference);
379     SDValue visitSUB(SDNode *N);
380     SDValue visitADDSAT(SDNode *N);
381     SDValue visitSUBSAT(SDNode *N);
382     SDValue visitADDC(SDNode *N);
383     SDValue visitADDO(SDNode *N);
384     SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
385     SDValue visitSUBC(SDNode *N);
386     SDValue visitSUBO(SDNode *N);
387     SDValue visitADDE(SDNode *N);
388     SDValue visitADDCARRY(SDNode *N);
389     SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
390     SDValue visitSUBE(SDNode *N);
391     SDValue visitSUBCARRY(SDNode *N);
392     SDValue visitMUL(SDNode *N);
393     SDValue visitMULFIX(SDNode *N);
394     SDValue useDivRem(SDNode *N);
395     SDValue visitSDIV(SDNode *N);
396     SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
397     SDValue visitUDIV(SDNode *N);
398     SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
399     SDValue visitREM(SDNode *N);
400     SDValue visitMULHU(SDNode *N);
401     SDValue visitMULHS(SDNode *N);
402     SDValue visitSMUL_LOHI(SDNode *N);
403     SDValue visitUMUL_LOHI(SDNode *N);
404     SDValue visitMULO(SDNode *N);
405     SDValue visitIMINMAX(SDNode *N);
406     SDValue visitAND(SDNode *N);
407     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
408     SDValue visitOR(SDNode *N);
409     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
410     SDValue visitXOR(SDNode *N);
411     SDValue SimplifyVBinOp(SDNode *N);
412     SDValue visitSHL(SDNode *N);
413     SDValue visitSRA(SDNode *N);
414     SDValue visitSRL(SDNode *N);
415     SDValue visitFunnelShift(SDNode *N);
416     SDValue visitRotate(SDNode *N);
417     SDValue visitABS(SDNode *N);
418     SDValue visitBSWAP(SDNode *N);
419     SDValue visitBITREVERSE(SDNode *N);
420     SDValue visitCTLZ(SDNode *N);
421     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
422     SDValue visitCTTZ(SDNode *N);
423     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
424     SDValue visitCTPOP(SDNode *N);
425     SDValue visitSELECT(SDNode *N);
426     SDValue visitVSELECT(SDNode *N);
427     SDValue visitSELECT_CC(SDNode *N);
428     SDValue visitSETCC(SDNode *N);
429     SDValue visitSETCCCARRY(SDNode *N);
430     SDValue visitSIGN_EXTEND(SDNode *N);
431     SDValue visitZERO_EXTEND(SDNode *N);
432     SDValue visitANY_EXTEND(SDNode *N);
433     SDValue visitAssertExt(SDNode *N);
434     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
435     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
436     SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
437     SDValue visitTRUNCATE(SDNode *N);
438     SDValue visitBITCAST(SDNode *N);
439     SDValue visitFREEZE(SDNode *N);
440     SDValue visitBUILD_PAIR(SDNode *N);
441     SDValue visitFADD(SDNode *N);
442     SDValue visitFSUB(SDNode *N);
443     SDValue visitFMUL(SDNode *N);
444     SDValue visitFMA(SDNode *N);
445     SDValue visitFDIV(SDNode *N);
446     SDValue visitFREM(SDNode *N);
447     SDValue visitFSQRT(SDNode *N);
448     SDValue visitFCOPYSIGN(SDNode *N);
449     SDValue visitFPOW(SDNode *N);
450     SDValue visitSINT_TO_FP(SDNode *N);
451     SDValue visitUINT_TO_FP(SDNode *N);
452     SDValue visitFP_TO_SINT(SDNode *N);
453     SDValue visitFP_TO_UINT(SDNode *N);
454     SDValue visitFP_ROUND(SDNode *N);
455     SDValue visitFP_EXTEND(SDNode *N);
456     SDValue visitFNEG(SDNode *N);
457     SDValue visitFABS(SDNode *N);
458     SDValue visitFCEIL(SDNode *N);
459     SDValue visitFTRUNC(SDNode *N);
460     SDValue visitFFLOOR(SDNode *N);
461     SDValue visitFMINNUM(SDNode *N);
462     SDValue visitFMAXNUM(SDNode *N);
463     SDValue visitFMINIMUM(SDNode *N);
464     SDValue visitFMAXIMUM(SDNode *N);
465     SDValue visitBRCOND(SDNode *N);
466     SDValue visitBR_CC(SDNode *N);
467     SDValue visitLOAD(SDNode *N);
468 
469     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
470     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
471 
472     SDValue visitSTORE(SDNode *N);
473     SDValue visitLIFETIME_END(SDNode *N);
474     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
475     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
476     SDValue visitBUILD_VECTOR(SDNode *N);
477     SDValue visitCONCAT_VECTORS(SDNode *N);
478     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
479     SDValue visitVECTOR_SHUFFLE(SDNode *N);
480     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
481     SDValue visitINSERT_SUBVECTOR(SDNode *N);
482     SDValue visitMLOAD(SDNode *N);
483     SDValue visitMSTORE(SDNode *N);
484     SDValue visitMGATHER(SDNode *N);
485     SDValue visitMSCATTER(SDNode *N);
486     SDValue visitFP_TO_FP16(SDNode *N);
487     SDValue visitFP16_TO_FP(SDNode *N);
488     SDValue visitVECREDUCE(SDNode *N);
489 
490     SDValue visitFADDForFMACombine(SDNode *N);
491     SDValue visitFSUBForFMACombine(SDNode *N);
492     SDValue visitFMULForFMADistributiveCombine(SDNode *N);
493 
494     SDValue XformToShuffleWithZero(SDNode *N);
495     bool reassociationCanBreakAddressingModePattern(unsigned Opc,
496                                                     const SDLoc &DL, SDValue N0,
497                                                     SDValue N1);
498     SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
499                                       SDValue N1);
500     SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
501                            SDValue N1, SDNodeFlags Flags);
502 
503     SDValue visitShiftByConstant(SDNode *N);
504 
505     SDValue foldSelectOfConstants(SDNode *N);
506     SDValue foldVSelectOfConstants(SDNode *N);
507     SDValue foldBinOpIntoSelect(SDNode *BO);
508     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
509     SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
510     SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
511     SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
512                              SDValue N2, SDValue N3, ISD::CondCode CC,
513                              bool NotExtCompare = false);
514     SDValue convertSelectOfFPConstantsToLoadOffset(
515         const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
516         ISD::CondCode CC);
517     SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
518                                    SDValue N2, SDValue N3, ISD::CondCode CC);
519     SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
520                               const SDLoc &DL);
521     SDValue unfoldMaskedMerge(SDNode *N);
522     SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
523     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
524                           const SDLoc &DL, bool foldBooleans);
525     SDValue rebuildSetCC(SDValue N);
526 
527     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
528                            SDValue &CC, bool MatchStrict = false) const;
529     bool isOneUseSetCC(SDValue N) const;
530 
531     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
532                                          unsigned HiOp);
533     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
534     SDValue CombineExtLoad(SDNode *N);
535     SDValue CombineZExtLogicopShiftLoad(SDNode *N);
536     SDValue combineRepeatedFPDivisors(SDNode *N);
537     SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
538     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
539     SDValue BuildSDIV(SDNode *N);
540     SDValue BuildSDIVPow2(SDNode *N);
541     SDValue BuildUDIV(SDNode *N);
542     SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
543     SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
544     SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
545     SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
546     SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
547     SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
548                                 SDNodeFlags Flags, bool Reciprocal);
549     SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
550                                 SDNodeFlags Flags, bool Reciprocal);
551     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
552                                bool DemandHighBits = true);
553     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
554     SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
555                               SDValue InnerPos, SDValue InnerNeg,
556                               unsigned PosOpcode, unsigned NegOpcode,
557                               const SDLoc &DL);
558     SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
559                               SDValue InnerPos, SDValue InnerNeg,
560                               unsigned PosOpcode, unsigned NegOpcode,
561                               const SDLoc &DL);
562     SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
563     SDValue MatchLoadCombine(SDNode *N);
564     SDValue MatchStoreCombine(StoreSDNode *N);
565     SDValue ReduceLoadWidth(SDNode *N);
566     SDValue ReduceLoadOpStoreWidth(SDNode *N);
567     SDValue splitMergedValStore(StoreSDNode *ST);
568     SDValue TransformFPLoadStorePair(SDNode *N);
569     SDValue convertBuildVecZextToZext(SDNode *N);
570     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
571     SDValue reduceBuildVecTruncToBitCast(SDNode *N);
572     SDValue reduceBuildVecToShuffle(SDNode *N);
573     SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
574                                   ArrayRef<int> VectorMask, SDValue VecIn1,
575                                   SDValue VecIn2, unsigned LeftIdx,
576                                   bool DidSplitVec);
577     SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
578 
579     /// Walk up chain skipping non-aliasing memory nodes,
580     /// looking for aliasing nodes and adding them to the Aliases vector.
581     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
582                           SmallVectorImpl<SDValue> &Aliases);
583 
584     /// Return true if there is any possibility that the two addresses overlap.
585     bool isAlias(SDNode *Op0, SDNode *Op1) const;
586 
587     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
588     /// chain (aliasing node.)
589     SDValue FindBetterChain(SDNode *N, SDValue Chain);
590 
591     /// Try to replace a store and any possibly adjacent stores on
592     /// consecutive chains with better chains. Return true only if St is
593     /// replaced.
594     ///
595     /// Notice that other chains may still be replaced even if the function
596     /// returns false.
597     bool findBetterNeighborChains(StoreSDNode *St);
598 
599     // Helper for findBetterNeighborChains. Walk up store chain add additional
600     // chained stores that do not overlap and can be parallelized.
601     bool parallelizeChainedStores(StoreSDNode *St);
602 
603     /// Holds a pointer to an LSBaseSDNode as well as information on where it
604     /// is located in a sequence of memory operations connected by a chain.
605     struct MemOpLink {
606       // Ptr to the mem node.
607       LSBaseSDNode *MemNode;
608 
609       // Offset from the base ptr.
610       int64_t OffsetFromBase;
611 
612       MemOpLink(LSBaseSDNode *N, int64_t Offset)
613           : MemNode(N), OffsetFromBase(Offset) {}
614     };
615 
616     /// This is a helper function for visitMUL to check the profitability
617     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
618     /// MulNode is the original multiply, AddNode is (add x, c1),
619     /// and ConstNode is c2.
620     bool isMulAddWithConstProfitable(SDNode *MulNode,
621                                      SDValue &AddNode,
622                                      SDValue &ConstNode);
623 
624     /// This is a helper function for visitAND and visitZERO_EXTEND.  Returns
625     /// true if the (and (load x) c) pattern matches an extload.  ExtVT returns
626     /// the type of the loaded value to be extended.
627     bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
628                           EVT LoadResultTy, EVT &ExtVT);
629 
630     /// Helper function to calculate whether the given Load/Store can have its
631     /// width reduced to ExtVT.
632     bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
633                            EVT &MemVT, unsigned ShAmt = 0);
634 
635     /// Used by BackwardsPropagateMask to find suitable loads.
636     bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
637                            SmallPtrSetImpl<SDNode*> &NodesWithConsts,
638                            ConstantSDNode *Mask, SDNode *&NodeToMask);
639     /// Attempt to propagate a given AND node back to load leaves so that they
640     /// can be combined into narrow loads.
641     bool BackwardsPropagateMask(SDNode *N);
642 
643     /// Helper function for MergeConsecutiveStores which merges the
644     /// component store chains.
645     SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
646                                 unsigned NumStores);
647 
648     /// This is a helper function for MergeConsecutiveStores. When the
649     /// source elements of the consecutive stores are all constants or
650     /// all extracted vector elements, try to merge them into one
651     /// larger store introducing bitcasts if necessary.  \return True
652     /// if a merged store was created.
653     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
654                                          EVT MemVT, unsigned NumStores,
655                                          bool IsConstantSrc, bool UseVector,
656                                          bool UseTrunc);
657 
658     /// This is a helper function for MergeConsecutiveStores. Stores
659     /// that potentially may be merged with St are placed in
660     /// StoreNodes. RootNode is a chain predecessor to all store
661     /// candidates.
662     void getStoreMergeCandidates(StoreSDNode *St,
663                                  SmallVectorImpl<MemOpLink> &StoreNodes,
664                                  SDNode *&Root);
665 
666     /// Helper function for MergeConsecutiveStores. Checks if
667     /// candidate stores have indirect dependency through their
668     /// operands. RootNode is the predecessor to all stores calculated
669     /// by getStoreMergeCandidates and is used to prune the dependency check.
670     /// \return True if safe to merge.
671     bool checkMergeStoreCandidatesForDependencies(
672         SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
673         SDNode *RootNode);
674 
675     /// Merge consecutive store operations into a wide store.
676     /// This optimization uses wide integers or vectors when possible.
677     /// \return number of stores that were merged into a merged store (the
678     /// affected nodes are stored as a prefix in \p StoreNodes).
679     bool MergeConsecutiveStores(StoreSDNode *St);
680 
681     /// Try to transform a truncation where C is a constant:
682     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
683     ///
684     /// \p N needs to be a truncation and its first operand an AND. Other
685     /// requirements are checked by the function (e.g. that trunc is
686     /// single-use) and if missed an empty SDValue is returned.
687     SDValue distributeTruncateThroughAnd(SDNode *N);
688 
689     /// Helper function to determine whether the target supports operation
690     /// given by \p Opcode for type \p VT, that is, whether the operation
691     /// is legal or custom before legalizing operations, and whether is
692     /// legal (but not custom) after legalization.
693     bool hasOperation(unsigned Opcode, EVT VT) {
694       if (LegalOperations)
695         return TLI.isOperationLegal(Opcode, VT);
696       return TLI.isOperationLegalOrCustom(Opcode, VT);
697     }
698 
699   public:
700     /// Runs the dag combiner on all nodes in the work list
701     void Run(CombineLevel AtLevel);
702 
703     SelectionDAG &getDAG() const { return DAG; }
704 
705     /// Returns a type large enough to hold any valid shift amount - before type
706     /// legalization these can be huge.
707     EVT getShiftAmountTy(EVT LHSTy) {
708       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
709       return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
710     }
711 
712     /// This method returns true if we are running before type legalization or
713     /// if the specified VT is legal.
714     bool isTypeLegal(const EVT &VT) {
715       if (!LegalTypes) return true;
716       return TLI.isTypeLegal(VT);
717     }
718 
719     /// Convenience wrapper around TargetLowering::getSetCCResultType
720     EVT getSetCCResultType(EVT VT) const {
721       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
722     }
723 
724     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
725                          SDValue OrigLoad, SDValue ExtLoad,
726                          ISD::NodeType ExtType);
727   };
728 
729 /// This class is a DAGUpdateListener that removes any deleted
730 /// nodes from the worklist.
731 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
732   DAGCombiner &DC;
733 
734 public:
735   explicit WorklistRemover(DAGCombiner &dc)
736     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
737 
738   void NodeDeleted(SDNode *N, SDNode *E) override {
739     DC.removeFromWorklist(N);
740   }
741 };
742 
743 class WorklistInserter : public SelectionDAG::DAGUpdateListener {
744   DAGCombiner &DC;
745 
746 public:
747   explicit WorklistInserter(DAGCombiner &dc)
748       : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
749 
750   // FIXME: Ideally we could add N to the worklist, but this causes exponential
751   //        compile time costs in large DAGs, e.g. Halide.
752   void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
753 };
754 
755 } // end anonymous namespace
756 
757 //===----------------------------------------------------------------------===//
758 //  TargetLowering::DAGCombinerInfo implementation
759 //===----------------------------------------------------------------------===//
760 
761 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
762   ((DAGCombiner*)DC)->AddToWorklist(N);
763 }
764 
765 SDValue TargetLowering::DAGCombinerInfo::
766 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
767   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
768 }
769 
770 SDValue TargetLowering::DAGCombinerInfo::
771 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
772   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
773 }
774 
775 SDValue TargetLowering::DAGCombinerInfo::
776 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
777   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
778 }
779 
780 bool TargetLowering::DAGCombinerInfo::
781 recursivelyDeleteUnusedNodes(SDNode *N) {
782   return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
783 }
784 
785 void TargetLowering::DAGCombinerInfo::
786 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
787   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
788 }
789 
790 //===----------------------------------------------------------------------===//
791 // Helper Functions
792 //===----------------------------------------------------------------------===//
793 
794 void DAGCombiner::deleteAndRecombine(SDNode *N) {
795   removeFromWorklist(N);
796 
797   // If the operands of this node are only used by the node, they will now be
798   // dead. Make sure to re-visit them and recursively delete dead nodes.
799   for (const SDValue &Op : N->ops())
800     // For an operand generating multiple values, one of the values may
801     // become dead allowing further simplification (e.g. split index
802     // arithmetic from an indexed load).
803     if (Op->hasOneUse() || Op->getNumValues() > 1)
804       AddToWorklist(Op.getNode());
805 
806   DAG.DeleteNode(N);
807 }
808 
809 // APInts must be the same size for most operations, this helper
810 // function zero extends the shorter of the pair so that they match.
811 // We provide an Offset so that we can create bitwidths that won't overflow.
812 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
813   unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
814   LHS = LHS.zextOrSelf(Bits);
815   RHS = RHS.zextOrSelf(Bits);
816 }
817 
818 // Return true if this node is a setcc, or is a select_cc
819 // that selects between the target values used for true and false, making it
820 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
821 // the appropriate nodes based on the type of node we are checking. This
822 // simplifies life a bit for the callers.
823 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
824                                     SDValue &CC, bool MatchStrict) const {
825   if (N.getOpcode() == ISD::SETCC) {
826     LHS = N.getOperand(0);
827     RHS = N.getOperand(1);
828     CC  = N.getOperand(2);
829     return true;
830   }
831 
832   if (MatchStrict &&
833       (N.getOpcode() == ISD::STRICT_FSETCC ||
834        N.getOpcode() == ISD::STRICT_FSETCCS)) {
835     LHS = N.getOperand(1);
836     RHS = N.getOperand(2);
837     CC  = N.getOperand(3);
838     return true;
839   }
840 
841   if (N.getOpcode() != ISD::SELECT_CC ||
842       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
843       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
844     return false;
845 
846   if (TLI.getBooleanContents(N.getValueType()) ==
847       TargetLowering::UndefinedBooleanContent)
848     return false;
849 
850   LHS = N.getOperand(0);
851   RHS = N.getOperand(1);
852   CC  = N.getOperand(4);
853   return true;
854 }
855 
856 /// Return true if this is a SetCC-equivalent operation with only one use.
857 /// If this is true, it allows the users to invert the operation for free when
858 /// it is profitable to do so.
859 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
860   SDValue N0, N1, N2;
861   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
862     return true;
863   return false;
864 }
865 
866 // Returns the SDNode if it is a constant float BuildVector
867 // or constant float.
868 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
869   if (isa<ConstantFPSDNode>(N))
870     return N.getNode();
871   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
872     return N.getNode();
873   return nullptr;
874 }
875 
876 // Determines if it is a constant integer or a build vector of constant
877 // integers (and undefs).
878 // Do not permit build vector implicit truncation.
879 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
880   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
881     return !(Const->isOpaque() && NoOpaques);
882   if (N.getOpcode() != ISD::BUILD_VECTOR)
883     return false;
884   unsigned BitWidth = N.getScalarValueSizeInBits();
885   for (const SDValue &Op : N->op_values()) {
886     if (Op.isUndef())
887       continue;
888     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
889     if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
890         (Const->isOpaque() && NoOpaques))
891       return false;
892   }
893   return true;
894 }
895 
896 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
897 // undef's.
898 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
899   if (V.getOpcode() != ISD::BUILD_VECTOR)
900     return false;
901   return isConstantOrConstantVector(V, NoOpaques) ||
902          ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
903 }
904 
905 // Determine if this an indexed load with an opaque target constant index.
906 static bool canSplitIdx(LoadSDNode *LD) {
907   return MaySplitLoadIndex &&
908          (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
909           !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
910 }
911 
912 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
913                                                              const SDLoc &DL,
914                                                              SDValue N0,
915                                                              SDValue N1) {
916   // Currently this only tries to ensure we don't undo the GEP splits done by
917   // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
918   // we check if the following transformation would be problematic:
919   // (load/store (add, (add, x, offset1), offset2)) ->
920   // (load/store (add, x, offset1+offset2)).
921 
922   if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
923     return false;
924 
925   if (N0.hasOneUse())
926     return false;
927 
928   auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
929   auto *C2 = dyn_cast<ConstantSDNode>(N1);
930   if (!C1 || !C2)
931     return false;
932 
933   const APInt &C1APIntVal = C1->getAPIntValue();
934   const APInt &C2APIntVal = C2->getAPIntValue();
935   if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64)
936     return false;
937 
938   const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
939   if (CombinedValueIntVal.getBitWidth() > 64)
940     return false;
941   const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
942 
943   for (SDNode *Node : N0->uses()) {
944     auto LoadStore = dyn_cast<MemSDNode>(Node);
945     if (LoadStore) {
946       // Is x[offset2] already not a legal addressing mode? If so then
947       // reassociating the constants breaks nothing (we test offset2 because
948       // that's the one we hope to fold into the load or store).
949       TargetLoweringBase::AddrMode AM;
950       AM.HasBaseReg = true;
951       AM.BaseOffs = C2APIntVal.getSExtValue();
952       EVT VT = LoadStore->getMemoryVT();
953       unsigned AS = LoadStore->getAddressSpace();
954       Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
955       if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
956         continue;
957 
958       // Would x[offset1+offset2] still be a legal addressing mode?
959       AM.BaseOffs = CombinedValue;
960       if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
961         return true;
962     }
963   }
964 
965   return false;
966 }
967 
968 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
969 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
970 SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
971                                                SDValue N0, SDValue N1) {
972   EVT VT = N0.getValueType();
973 
974   if (N0.getOpcode() != Opc)
975     return SDValue();
976 
977   if (DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
978     if (DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
979       // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
980       if (SDValue OpNode =
981               DAG.FoldConstantArithmetic(Opc, DL, VT, {N0.getOperand(1), N1}))
982         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
983       return SDValue();
984     }
985     if (N0.hasOneUse()) {
986       // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
987       //              iff (op x, c1) has one use
988       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
989       if (!OpNode.getNode())
990         return SDValue();
991       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
992     }
993   }
994   return SDValue();
995 }
996 
997 // Try to reassociate commutative binops.
998 SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
999                                     SDValue N1, SDNodeFlags Flags) {
1000   assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
1001 
1002   // Floating-point reassociation is not allowed without loose FP math.
1003   if (N0.getValueType().isFloatingPoint() ||
1004       N1.getValueType().isFloatingPoint())
1005     if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1006       return SDValue();
1007 
1008   if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
1009     return Combined;
1010   if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
1011     return Combined;
1012   return SDValue();
1013 }
1014 
1015 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1016                                bool AddTo) {
1017   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1018   ++NodesCombined;
1019   LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1020              To[0].getNode()->dump(&DAG);
1021              dbgs() << " and " << NumTo - 1 << " other values\n");
1022   for (unsigned i = 0, e = NumTo; i != e; ++i)
1023     assert((!To[i].getNode() ||
1024             N->getValueType(i) == To[i].getValueType()) &&
1025            "Cannot combine value to value of different type!");
1026 
1027   WorklistRemover DeadNodes(*this);
1028   DAG.ReplaceAllUsesWith(N, To);
1029   if (AddTo) {
1030     // Push the new nodes and any users onto the worklist
1031     for (unsigned i = 0, e = NumTo; i != e; ++i) {
1032       if (To[i].getNode()) {
1033         AddToWorklist(To[i].getNode());
1034         AddUsersToWorklist(To[i].getNode());
1035       }
1036     }
1037   }
1038 
1039   // Finally, if the node is now dead, remove it from the graph.  The node
1040   // may not be dead if the replacement process recursively simplified to
1041   // something else needing this node.
1042   if (N->use_empty())
1043     deleteAndRecombine(N);
1044   return SDValue(N, 0);
1045 }
1046 
1047 void DAGCombiner::
1048 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1049   // Replace all uses.  If any nodes become isomorphic to other nodes and
1050   // are deleted, make sure to remove them from our worklist.
1051   WorklistRemover DeadNodes(*this);
1052   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1053 
1054   // Push the new node and any (possibly new) users onto the worklist.
1055   AddToWorklistWithUsers(TLO.New.getNode());
1056 
1057   // Finally, if the node is now dead, remove it from the graph.  The node
1058   // may not be dead if the replacement process recursively simplified to
1059   // something else needing this node.
1060   if (TLO.Old.getNode()->use_empty())
1061     deleteAndRecombine(TLO.Old.getNode());
1062 }
1063 
1064 /// Check the specified integer node value to see if it can be simplified or if
1065 /// things it uses can be simplified by bit propagation. If so, return true.
1066 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1067                                        const APInt &DemandedElts,
1068                                        bool AssumeSingleUse) {
1069   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1070   KnownBits Known;
1071   if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1072                                 AssumeSingleUse))
1073     return false;
1074 
1075   // Revisit the node.
1076   AddToWorklist(Op.getNode());
1077 
1078   // Replace the old value with the new one.
1079   ++NodesCombined;
1080   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1081              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1082              dbgs() << '\n');
1083 
1084   CommitTargetLoweringOpt(TLO);
1085   return true;
1086 }
1087 
1088 /// Check the specified vector node value to see if it can be simplified or
1089 /// if things it uses can be simplified as it only uses some of the elements.
1090 /// If so, return true.
1091 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1092                                              const APInt &DemandedElts,
1093                                              bool AssumeSingleUse) {
1094   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1095   APInt KnownUndef, KnownZero;
1096   if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1097                                       TLO, 0, AssumeSingleUse))
1098     return false;
1099 
1100   // Revisit the node.
1101   AddToWorklist(Op.getNode());
1102 
1103   // Replace the old value with the new one.
1104   ++NodesCombined;
1105   LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
1106              dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
1107              dbgs() << '\n');
1108 
1109   CommitTargetLoweringOpt(TLO);
1110   return true;
1111 }
1112 
1113 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1114   SDLoc DL(Load);
1115   EVT VT = Load->getValueType(0);
1116   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1117 
1118   LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1119              Trunc.getNode()->dump(&DAG); dbgs() << '\n');
1120   WorklistRemover DeadNodes(*this);
1121   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1122   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1123   deleteAndRecombine(Load);
1124   AddToWorklist(Trunc.getNode());
1125 }
1126 
1127 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1128   Replace = false;
1129   SDLoc DL(Op);
1130   if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1131     LoadSDNode *LD = cast<LoadSDNode>(Op);
1132     EVT MemVT = LD->getMemoryVT();
1133     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1134                                                       : LD->getExtensionType();
1135     Replace = true;
1136     return DAG.getExtLoad(ExtType, DL, PVT,
1137                           LD->getChain(), LD->getBasePtr(),
1138                           MemVT, LD->getMemOperand());
1139   }
1140 
1141   unsigned Opc = Op.getOpcode();
1142   switch (Opc) {
1143   default: break;
1144   case ISD::AssertSext:
1145     if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1146       return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1147     break;
1148   case ISD::AssertZext:
1149     if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1150       return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1151     break;
1152   case ISD::Constant: {
1153     unsigned ExtOpc =
1154       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1155     return DAG.getNode(ExtOpc, DL, PVT, Op);
1156   }
1157   }
1158 
1159   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1160     return SDValue();
1161   return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1162 }
1163 
1164 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1165   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1166     return SDValue();
1167   EVT OldVT = Op.getValueType();
1168   SDLoc DL(Op);
1169   bool Replace = false;
1170   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1171   if (!NewOp.getNode())
1172     return SDValue();
1173   AddToWorklist(NewOp.getNode());
1174 
1175   if (Replace)
1176     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1177   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1178                      DAG.getValueType(OldVT));
1179 }
1180 
1181 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1182   EVT OldVT = Op.getValueType();
1183   SDLoc DL(Op);
1184   bool Replace = false;
1185   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1186   if (!NewOp.getNode())
1187     return SDValue();
1188   AddToWorklist(NewOp.getNode());
1189 
1190   if (Replace)
1191     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1192   return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1193 }
1194 
1195 /// Promote the specified integer binary operation if the target indicates it is
1196 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1197 /// i32 since i16 instructions are longer.
1198 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1199   if (!LegalOperations)
1200     return SDValue();
1201 
1202   EVT VT = Op.getValueType();
1203   if (VT.isVector() || !VT.isInteger())
1204     return SDValue();
1205 
1206   // If operation type is 'undesirable', e.g. i16 on x86, consider
1207   // promoting it.
1208   unsigned Opc = Op.getOpcode();
1209   if (TLI.isTypeDesirableForOp(Opc, VT))
1210     return SDValue();
1211 
1212   EVT PVT = VT;
1213   // Consult target whether it is a good idea to promote this operation and
1214   // what's the right type to promote it to.
1215   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1216     assert(PVT != VT && "Don't know what type to promote to!");
1217 
1218     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1219 
1220     bool Replace0 = false;
1221     SDValue N0 = Op.getOperand(0);
1222     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1223 
1224     bool Replace1 = false;
1225     SDValue N1 = Op.getOperand(1);
1226     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1227     SDLoc DL(Op);
1228 
1229     SDValue RV =
1230         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1231 
1232     // We are always replacing N0/N1's use in N and only need
1233     // additional replacements if there are additional uses.
1234     Replace0 &= !N0->hasOneUse();
1235     Replace1 &= (N0 != N1) && !N1->hasOneUse();
1236 
1237     // Combine Op here so it is preserved past replacements.
1238     CombineTo(Op.getNode(), RV);
1239 
1240     // If operands have a use ordering, make sure we deal with
1241     // predecessor first.
1242     if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
1243       std::swap(N0, N1);
1244       std::swap(NN0, NN1);
1245     }
1246 
1247     if (Replace0) {
1248       AddToWorklist(NN0.getNode());
1249       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1250     }
1251     if (Replace1) {
1252       AddToWorklist(NN1.getNode());
1253       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1254     }
1255     return Op;
1256   }
1257   return SDValue();
1258 }
1259 
1260 /// Promote the specified integer shift operation if the target indicates it is
1261 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1262 /// i32 since i16 instructions are longer.
1263 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1264   if (!LegalOperations)
1265     return SDValue();
1266 
1267   EVT VT = Op.getValueType();
1268   if (VT.isVector() || !VT.isInteger())
1269     return SDValue();
1270 
1271   // If operation type is 'undesirable', e.g. i16 on x86, consider
1272   // promoting it.
1273   unsigned Opc = Op.getOpcode();
1274   if (TLI.isTypeDesirableForOp(Opc, VT))
1275     return SDValue();
1276 
1277   EVT PVT = VT;
1278   // Consult target whether it is a good idea to promote this operation and
1279   // what's the right type to promote it to.
1280   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1281     assert(PVT != VT && "Don't know what type to promote to!");
1282 
1283     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1284 
1285     bool Replace = false;
1286     SDValue N0 = Op.getOperand(0);
1287     SDValue N1 = Op.getOperand(1);
1288     if (Opc == ISD::SRA)
1289       N0 = SExtPromoteOperand(N0, PVT);
1290     else if (Opc == ISD::SRL)
1291       N0 = ZExtPromoteOperand(N0, PVT);
1292     else
1293       N0 = PromoteOperand(N0, PVT, Replace);
1294 
1295     if (!N0.getNode())
1296       return SDValue();
1297 
1298     SDLoc DL(Op);
1299     SDValue RV =
1300         DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1301 
1302     if (Replace)
1303       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1304 
1305     // Deal with Op being deleted.
1306     if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1307       return RV;
1308   }
1309   return SDValue();
1310 }
1311 
1312 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1313   if (!LegalOperations)
1314     return SDValue();
1315 
1316   EVT VT = Op.getValueType();
1317   if (VT.isVector() || !VT.isInteger())
1318     return SDValue();
1319 
1320   // If operation type is 'undesirable', e.g. i16 on x86, consider
1321   // promoting it.
1322   unsigned Opc = Op.getOpcode();
1323   if (TLI.isTypeDesirableForOp(Opc, VT))
1324     return SDValue();
1325 
1326   EVT PVT = VT;
1327   // Consult target whether it is a good idea to promote this operation and
1328   // what's the right type to promote it to.
1329   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1330     assert(PVT != VT && "Don't know what type to promote to!");
1331     // fold (aext (aext x)) -> (aext x)
1332     // fold (aext (zext x)) -> (zext x)
1333     // fold (aext (sext x)) -> (sext x)
1334     LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1335     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1336   }
1337   return SDValue();
1338 }
1339 
1340 bool DAGCombiner::PromoteLoad(SDValue Op) {
1341   if (!LegalOperations)
1342     return false;
1343 
1344   if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1345     return false;
1346 
1347   EVT VT = Op.getValueType();
1348   if (VT.isVector() || !VT.isInteger())
1349     return false;
1350 
1351   // If operation type is 'undesirable', e.g. i16 on x86, consider
1352   // promoting it.
1353   unsigned Opc = Op.getOpcode();
1354   if (TLI.isTypeDesirableForOp(Opc, VT))
1355     return false;
1356 
1357   EVT PVT = VT;
1358   // Consult target whether it is a good idea to promote this operation and
1359   // what's the right type to promote it to.
1360   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1361     assert(PVT != VT && "Don't know what type to promote to!");
1362 
1363     SDLoc DL(Op);
1364     SDNode *N = Op.getNode();
1365     LoadSDNode *LD = cast<LoadSDNode>(N);
1366     EVT MemVT = LD->getMemoryVT();
1367     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
1368                                                       : LD->getExtensionType();
1369     SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1370                                    LD->getChain(), LD->getBasePtr(),
1371                                    MemVT, LD->getMemOperand());
1372     SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1373 
1374     LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1375                Result.getNode()->dump(&DAG); dbgs() << '\n');
1376     WorklistRemover DeadNodes(*this);
1377     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1378     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1379     deleteAndRecombine(N);
1380     AddToWorklist(Result.getNode());
1381     return true;
1382   }
1383   return false;
1384 }
1385 
1386 /// Recursively delete a node which has no uses and any operands for
1387 /// which it is the only use.
1388 ///
1389 /// Note that this both deletes the nodes and removes them from the worklist.
1390 /// It also adds any nodes who have had a user deleted to the worklist as they
1391 /// may now have only one use and subject to other combines.
1392 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1393   if (!N->use_empty())
1394     return false;
1395 
1396   SmallSetVector<SDNode *, 16> Nodes;
1397   Nodes.insert(N);
1398   do {
1399     N = Nodes.pop_back_val();
1400     if (!N)
1401       continue;
1402 
1403     if (N->use_empty()) {
1404       for (const SDValue &ChildN : N->op_values())
1405         Nodes.insert(ChildN.getNode());
1406 
1407       removeFromWorklist(N);
1408       DAG.DeleteNode(N);
1409     } else {
1410       AddToWorklist(N);
1411     }
1412   } while (!Nodes.empty());
1413   return true;
1414 }
1415 
1416 //===----------------------------------------------------------------------===//
1417 //  Main DAG Combiner implementation
1418 //===----------------------------------------------------------------------===//
1419 
1420 void DAGCombiner::Run(CombineLevel AtLevel) {
1421   // set the instance variables, so that the various visit routines may use it.
1422   Level = AtLevel;
1423   LegalDAG = Level >= AfterLegalizeDAG;
1424   LegalOperations = Level >= AfterLegalizeVectorOps;
1425   LegalTypes = Level >= AfterLegalizeTypes;
1426 
1427   WorklistInserter AddNodes(*this);
1428 
1429   // Add all the dag nodes to the worklist.
1430   for (SDNode &Node : DAG.allnodes())
1431     AddToWorklist(&Node);
1432 
1433   // Create a dummy node (which is not added to allnodes), that adds a reference
1434   // to the root node, preventing it from being deleted, and tracking any
1435   // changes of the root.
1436   HandleSDNode Dummy(DAG.getRoot());
1437 
1438   // While we have a valid worklist entry node, try to combine it.
1439   while (SDNode *N = getNextWorklistEntry()) {
1440     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1441     // N is deleted from the DAG, since they too may now be dead or may have a
1442     // reduced number of uses, allowing other xforms.
1443     if (recursivelyDeleteUnusedNodes(N))
1444       continue;
1445 
1446     WorklistRemover DeadNodes(*this);
1447 
1448     // If this combine is running after legalizing the DAG, re-legalize any
1449     // nodes pulled off the worklist.
1450     if (LegalDAG) {
1451       SmallSetVector<SDNode *, 16> UpdatedNodes;
1452       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1453 
1454       for (SDNode *LN : UpdatedNodes)
1455         AddToWorklistWithUsers(LN);
1456 
1457       if (!NIsValid)
1458         continue;
1459     }
1460 
1461     LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1462 
1463     // Add any operands of the new node which have not yet been combined to the
1464     // worklist as well. Because the worklist uniques things already, this
1465     // won't repeatedly process the same operand.
1466     CombinedNodes.insert(N);
1467     for (const SDValue &ChildN : N->op_values())
1468       if (!CombinedNodes.count(ChildN.getNode()))
1469         AddToWorklist(ChildN.getNode());
1470 
1471     SDValue RV = combine(N);
1472 
1473     if (!RV.getNode())
1474       continue;
1475 
1476     ++NodesCombined;
1477 
1478     // If we get back the same node we passed in, rather than a new node or
1479     // zero, we know that the node must have defined multiple values and
1480     // CombineTo was used.  Since CombineTo takes care of the worklist
1481     // mechanics for us, we have no work to do in this case.
1482     if (RV.getNode() == N)
1483       continue;
1484 
1485     assert(N->getOpcode() != ISD::DELETED_NODE &&
1486            RV.getOpcode() != ISD::DELETED_NODE &&
1487            "Node was deleted but visit returned new node!");
1488 
1489     LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
1490 
1491     if (N->getNumValues() == RV.getNode()->getNumValues())
1492       DAG.ReplaceAllUsesWith(N, RV.getNode());
1493     else {
1494       assert(N->getValueType(0) == RV.getValueType() &&
1495              N->getNumValues() == 1 && "Type mismatch");
1496       DAG.ReplaceAllUsesWith(N, &RV);
1497     }
1498 
1499     // Push the new node and any users onto the worklist
1500     AddToWorklist(RV.getNode());
1501     AddUsersToWorklist(RV.getNode());
1502 
1503     // Finally, if the node is now dead, remove it from the graph.  The node
1504     // may not be dead if the replacement process recursively simplified to
1505     // something else needing this node. This will also take care of adding any
1506     // operands which have lost a user to the worklist.
1507     recursivelyDeleteUnusedNodes(N);
1508   }
1509 
1510   // If the root changed (e.g. it was a dead load, update the root).
1511   DAG.setRoot(Dummy.getValue());
1512   DAG.RemoveDeadNodes();
1513 }
1514 
1515 SDValue DAGCombiner::visit(SDNode *N) {
1516   switch (N->getOpcode()) {
1517   default: break;
1518   case ISD::TokenFactor:        return visitTokenFactor(N);
1519   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1520   case ISD::ADD:                return visitADD(N);
1521   case ISD::SUB:                return visitSUB(N);
1522   case ISD::SADDSAT:
1523   case ISD::UADDSAT:            return visitADDSAT(N);
1524   case ISD::SSUBSAT:
1525   case ISD::USUBSAT:            return visitSUBSAT(N);
1526   case ISD::ADDC:               return visitADDC(N);
1527   case ISD::SADDO:
1528   case ISD::UADDO:              return visitADDO(N);
1529   case ISD::SUBC:               return visitSUBC(N);
1530   case ISD::SSUBO:
1531   case ISD::USUBO:              return visitSUBO(N);
1532   case ISD::ADDE:               return visitADDE(N);
1533   case ISD::ADDCARRY:           return visitADDCARRY(N);
1534   case ISD::SUBE:               return visitSUBE(N);
1535   case ISD::SUBCARRY:           return visitSUBCARRY(N);
1536   case ISD::SMULFIX:
1537   case ISD::SMULFIXSAT:
1538   case ISD::UMULFIX:
1539   case ISD::UMULFIXSAT:         return visitMULFIX(N);
1540   case ISD::MUL:                return visitMUL(N);
1541   case ISD::SDIV:               return visitSDIV(N);
1542   case ISD::UDIV:               return visitUDIV(N);
1543   case ISD::SREM:
1544   case ISD::UREM:               return visitREM(N);
1545   case ISD::MULHU:              return visitMULHU(N);
1546   case ISD::MULHS:              return visitMULHS(N);
1547   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1548   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1549   case ISD::SMULO:
1550   case ISD::UMULO:              return visitMULO(N);
1551   case ISD::SMIN:
1552   case ISD::SMAX:
1553   case ISD::UMIN:
1554   case ISD::UMAX:               return visitIMINMAX(N);
1555   case ISD::AND:                return visitAND(N);
1556   case ISD::OR:                 return visitOR(N);
1557   case ISD::XOR:                return visitXOR(N);
1558   case ISD::SHL:                return visitSHL(N);
1559   case ISD::SRA:                return visitSRA(N);
1560   case ISD::SRL:                return visitSRL(N);
1561   case ISD::ROTR:
1562   case ISD::ROTL:               return visitRotate(N);
1563   case ISD::FSHL:
1564   case ISD::FSHR:               return visitFunnelShift(N);
1565   case ISD::ABS:                return visitABS(N);
1566   case ISD::BSWAP:              return visitBSWAP(N);
1567   case ISD::BITREVERSE:         return visitBITREVERSE(N);
1568   case ISD::CTLZ:               return visitCTLZ(N);
1569   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1570   case ISD::CTTZ:               return visitCTTZ(N);
1571   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1572   case ISD::CTPOP:              return visitCTPOP(N);
1573   case ISD::SELECT:             return visitSELECT(N);
1574   case ISD::VSELECT:            return visitVSELECT(N);
1575   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1576   case ISD::SETCC:              return visitSETCC(N);
1577   case ISD::SETCCCARRY:         return visitSETCCCARRY(N);
1578   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1579   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1580   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1581   case ISD::AssertSext:
1582   case ISD::AssertZext:         return visitAssertExt(N);
1583   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1584   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1585   case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1586   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1587   case ISD::BITCAST:            return visitBITCAST(N);
1588   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1589   case ISD::FADD:               return visitFADD(N);
1590   case ISD::FSUB:               return visitFSUB(N);
1591   case ISD::FMUL:               return visitFMUL(N);
1592   case ISD::FMA:                return visitFMA(N);
1593   case ISD::FDIV:               return visitFDIV(N);
1594   case ISD::FREM:               return visitFREM(N);
1595   case ISD::FSQRT:              return visitFSQRT(N);
1596   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1597   case ISD::FPOW:               return visitFPOW(N);
1598   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1599   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1600   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1601   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1602   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1603   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1604   case ISD::FNEG:               return visitFNEG(N);
1605   case ISD::FABS:               return visitFABS(N);
1606   case ISD::FFLOOR:             return visitFFLOOR(N);
1607   case ISD::FMINNUM:            return visitFMINNUM(N);
1608   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1609   case ISD::FMINIMUM:           return visitFMINIMUM(N);
1610   case ISD::FMAXIMUM:           return visitFMAXIMUM(N);
1611   case ISD::FCEIL:              return visitFCEIL(N);
1612   case ISD::FTRUNC:             return visitFTRUNC(N);
1613   case ISD::BRCOND:             return visitBRCOND(N);
1614   case ISD::BR_CC:              return visitBR_CC(N);
1615   case ISD::LOAD:               return visitLOAD(N);
1616   case ISD::STORE:              return visitSTORE(N);
1617   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1618   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1619   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1620   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1621   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1622   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1623   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1624   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1625   case ISD::MGATHER:            return visitMGATHER(N);
1626   case ISD::MLOAD:              return visitMLOAD(N);
1627   case ISD::MSCATTER:           return visitMSCATTER(N);
1628   case ISD::MSTORE:             return visitMSTORE(N);
1629   case ISD::LIFETIME_END:       return visitLIFETIME_END(N);
1630   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1631   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1632   case ISD::FREEZE:             return visitFREEZE(N);
1633   case ISD::VECREDUCE_FADD:
1634   case ISD::VECREDUCE_FMUL:
1635   case ISD::VECREDUCE_ADD:
1636   case ISD::VECREDUCE_MUL:
1637   case ISD::VECREDUCE_AND:
1638   case ISD::VECREDUCE_OR:
1639   case ISD::VECREDUCE_XOR:
1640   case ISD::VECREDUCE_SMAX:
1641   case ISD::VECREDUCE_SMIN:
1642   case ISD::VECREDUCE_UMAX:
1643   case ISD::VECREDUCE_UMIN:
1644   case ISD::VECREDUCE_FMAX:
1645   case ISD::VECREDUCE_FMIN:     return visitVECREDUCE(N);
1646   }
1647   return SDValue();
1648 }
1649 
1650 SDValue DAGCombiner::combine(SDNode *N) {
1651   SDValue RV = visit(N);
1652 
1653   // If nothing happened, try a target-specific DAG combine.
1654   if (!RV.getNode()) {
1655     assert(N->getOpcode() != ISD::DELETED_NODE &&
1656            "Node was deleted but visit returned NULL!");
1657 
1658     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1659         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1660 
1661       // Expose the DAG combiner to the target combiner impls.
1662       TargetLowering::DAGCombinerInfo
1663         DagCombineInfo(DAG, Level, false, this);
1664 
1665       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1666     }
1667   }
1668 
1669   // If nothing happened still, try promoting the operation.
1670   if (!RV.getNode()) {
1671     switch (N->getOpcode()) {
1672     default: break;
1673     case ISD::ADD:
1674     case ISD::SUB:
1675     case ISD::MUL:
1676     case ISD::AND:
1677     case ISD::OR:
1678     case ISD::XOR:
1679       RV = PromoteIntBinOp(SDValue(N, 0));
1680       break;
1681     case ISD::SHL:
1682     case ISD::SRA:
1683     case ISD::SRL:
1684       RV = PromoteIntShiftOp(SDValue(N, 0));
1685       break;
1686     case ISD::SIGN_EXTEND:
1687     case ISD::ZERO_EXTEND:
1688     case ISD::ANY_EXTEND:
1689       RV = PromoteExtend(SDValue(N, 0));
1690       break;
1691     case ISD::LOAD:
1692       if (PromoteLoad(SDValue(N, 0)))
1693         RV = SDValue(N, 0);
1694       break;
1695     }
1696   }
1697 
1698   // If N is a commutative binary node, try to eliminate it if the commuted
1699   // version is already present in the DAG.
1700   if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1701       N->getNumValues() == 1) {
1702     SDValue N0 = N->getOperand(0);
1703     SDValue N1 = N->getOperand(1);
1704 
1705     // Constant operands are canonicalized to RHS.
1706     if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
1707       SDValue Ops[] = {N1, N0};
1708       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1709                                             N->getFlags());
1710       if (CSENode)
1711         return SDValue(CSENode, 0);
1712     }
1713   }
1714 
1715   return RV;
1716 }
1717 
1718 /// Given a node, return its input chain if it has one, otherwise return a null
1719 /// sd operand.
1720 static SDValue getInputChainForNode(SDNode *N) {
1721   if (unsigned NumOps = N->getNumOperands()) {
1722     if (N->getOperand(0).getValueType() == MVT::Other)
1723       return N->getOperand(0);
1724     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1725       return N->getOperand(NumOps-1);
1726     for (unsigned i = 1; i < NumOps-1; ++i)
1727       if (N->getOperand(i).getValueType() == MVT::Other)
1728         return N->getOperand(i);
1729   }
1730   return SDValue();
1731 }
1732 
1733 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1734   // If N has two operands, where one has an input chain equal to the other,
1735   // the 'other' chain is redundant.
1736   if (N->getNumOperands() == 2) {
1737     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1738       return N->getOperand(0);
1739     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1740       return N->getOperand(1);
1741   }
1742 
1743   // Don't simplify token factors if optnone.
1744   if (OptLevel == CodeGenOpt::None)
1745     return SDValue();
1746 
1747   // If the sole user is a token factor, we should make sure we have a
1748   // chance to merge them together. This prevents TF chains from inhibiting
1749   // optimizations.
1750   if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
1751     AddToWorklist(*(N->use_begin()));
1752 
1753   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1754   SmallVector<SDValue, 8> Ops;      // Ops for replacing token factor.
1755   SmallPtrSet<SDNode*, 16> SeenOps;
1756   bool Changed = false;             // If we should replace this token factor.
1757 
1758   // Start out with this token factor.
1759   TFs.push_back(N);
1760 
1761   // Iterate through token factors.  The TFs grows when new token factors are
1762   // encountered.
1763   for (unsigned i = 0; i < TFs.size(); ++i) {
1764     // Limit number of nodes to inline, to avoid quadratic compile times.
1765     // We have to add the outstanding Token Factors to Ops, otherwise we might
1766     // drop Ops from the resulting Token Factors.
1767     if (Ops.size() > TokenFactorInlineLimit) {
1768       for (unsigned j = i; j < TFs.size(); j++)
1769         Ops.emplace_back(TFs[j], 0);
1770       // Drop unprocessed Token Factors from TFs, so we do not add them to the
1771       // combiner worklist later.
1772       TFs.resize(i);
1773       break;
1774     }
1775 
1776     SDNode *TF = TFs[i];
1777     // Check each of the operands.
1778     for (const SDValue &Op : TF->op_values()) {
1779       switch (Op.getOpcode()) {
1780       case ISD::EntryToken:
1781         // Entry tokens don't need to be added to the list. They are
1782         // redundant.
1783         Changed = true;
1784         break;
1785 
1786       case ISD::TokenFactor:
1787         if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1788           // Queue up for processing.
1789           TFs.push_back(Op.getNode());
1790           Changed = true;
1791           break;
1792         }
1793         LLVM_FALLTHROUGH;
1794 
1795       default:
1796         // Only add if it isn't already in the list.
1797         if (SeenOps.insert(Op.getNode()).second)
1798           Ops.push_back(Op);
1799         else
1800           Changed = true;
1801         break;
1802       }
1803     }
1804   }
1805 
1806   // Re-visit inlined Token Factors, to clean them up in case they have been
1807   // removed. Skip the first Token Factor, as this is the current node.
1808   for (unsigned i = 1, e = TFs.size(); i < e; i++)
1809     AddToWorklist(TFs[i]);
1810 
1811   // Remove Nodes that are chained to another node in the list. Do so
1812   // by walking up chains breath-first stopping when we've seen
1813   // another operand. In general we must climb to the EntryNode, but we can exit
1814   // early if we find all remaining work is associated with just one operand as
1815   // no further pruning is possible.
1816 
1817   // List of nodes to search through and original Ops from which they originate.
1818   SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1819   SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1820   SmallPtrSet<SDNode *, 16> SeenChains;
1821   bool DidPruneOps = false;
1822 
1823   unsigned NumLeftToConsider = 0;
1824   for (const SDValue &Op : Ops) {
1825     Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1826     OpWorkCount.push_back(1);
1827   }
1828 
1829   auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1830     // If this is an Op, we can remove the op from the list. Remark any
1831     // search associated with it as from the current OpNumber.
1832     if (SeenOps.count(Op) != 0) {
1833       Changed = true;
1834       DidPruneOps = true;
1835       unsigned OrigOpNumber = 0;
1836       while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1837         OrigOpNumber++;
1838       assert((OrigOpNumber != Ops.size()) &&
1839              "expected to find TokenFactor Operand");
1840       // Re-mark worklist from OrigOpNumber to OpNumber
1841       for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1842         if (Worklist[i].second == OrigOpNumber) {
1843           Worklist[i].second = OpNumber;
1844         }
1845       }
1846       OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1847       OpWorkCount[OrigOpNumber] = 0;
1848       NumLeftToConsider--;
1849     }
1850     // Add if it's a new chain
1851     if (SeenChains.insert(Op).second) {
1852       OpWorkCount[OpNumber]++;
1853       Worklist.push_back(std::make_pair(Op, OpNumber));
1854     }
1855   };
1856 
1857   for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1858     // We need at least be consider at least 2 Ops to prune.
1859     if (NumLeftToConsider <= 1)
1860       break;
1861     auto CurNode = Worklist[i].first;
1862     auto CurOpNumber = Worklist[i].second;
1863     assert((OpWorkCount[CurOpNumber] > 0) &&
1864            "Node should not appear in worklist");
1865     switch (CurNode->getOpcode()) {
1866     case ISD::EntryToken:
1867       // Hitting EntryToken is the only way for the search to terminate without
1868       // hitting
1869       // another operand's search. Prevent us from marking this operand
1870       // considered.
1871       NumLeftToConsider++;
1872       break;
1873     case ISD::TokenFactor:
1874       for (const SDValue &Op : CurNode->op_values())
1875         AddToWorklist(i, Op.getNode(), CurOpNumber);
1876       break;
1877     case ISD::LIFETIME_START:
1878     case ISD::LIFETIME_END:
1879     case ISD::CopyFromReg:
1880     case ISD::CopyToReg:
1881       AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1882       break;
1883     default:
1884       if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1885         AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1886       break;
1887     }
1888     OpWorkCount[CurOpNumber]--;
1889     if (OpWorkCount[CurOpNumber] == 0)
1890       NumLeftToConsider--;
1891   }
1892 
1893   // If we've changed things around then replace token factor.
1894   if (Changed) {
1895     SDValue Result;
1896     if (Ops.empty()) {
1897       // The entry token is the only possible outcome.
1898       Result = DAG.getEntryNode();
1899     } else {
1900       if (DidPruneOps) {
1901         SmallVector<SDValue, 8> PrunedOps;
1902         //
1903         for (const SDValue &Op : Ops) {
1904           if (SeenChains.count(Op.getNode()) == 0)
1905             PrunedOps.push_back(Op);
1906         }
1907         Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
1908       } else {
1909         Result = DAG.getTokenFactor(SDLoc(N), Ops);
1910       }
1911     }
1912     return Result;
1913   }
1914   return SDValue();
1915 }
1916 
1917 /// MERGE_VALUES can always be eliminated.
1918 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1919   WorklistRemover DeadNodes(*this);
1920   // Replacing results may cause a different MERGE_VALUES to suddenly
1921   // be CSE'd with N, and carry its uses with it. Iterate until no
1922   // uses remain, to ensure that the node can be safely deleted.
1923   // First add the users of this node to the work list so that they
1924   // can be tried again once they have new operands.
1925   AddUsersToWorklist(N);
1926   do {
1927     // Do as a single replacement to avoid rewalking use lists.
1928     SmallVector<SDValue, 8> Ops;
1929     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1930       Ops.push_back(N->getOperand(i));
1931     DAG.ReplaceAllUsesWith(N, Ops.data());
1932   } while (!N->use_empty());
1933   deleteAndRecombine(N);
1934   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1935 }
1936 
1937 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1938 /// ConstantSDNode pointer else nullptr.
1939 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1940   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1941   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1942 }
1943 
1944 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1945   assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
1946          "Unexpected binary operator");
1947 
1948   // Don't do this unless the old select is going away. We want to eliminate the
1949   // binary operator, not replace a binop with a select.
1950   // TODO: Handle ISD::SELECT_CC.
1951   unsigned SelOpNo = 0;
1952   SDValue Sel = BO->getOperand(0);
1953   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
1954     SelOpNo = 1;
1955     Sel = BO->getOperand(1);
1956   }
1957 
1958   if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1959     return SDValue();
1960 
1961   SDValue CT = Sel.getOperand(1);
1962   if (!isConstantOrConstantVector(CT, true) &&
1963       !isConstantFPBuildVectorOrConstantFP(CT))
1964     return SDValue();
1965 
1966   SDValue CF = Sel.getOperand(2);
1967   if (!isConstantOrConstantVector(CF, true) &&
1968       !isConstantFPBuildVectorOrConstantFP(CF))
1969     return SDValue();
1970 
1971   // Bail out if any constants are opaque because we can't constant fold those.
1972   // The exception is "and" and "or" with either 0 or -1 in which case we can
1973   // propagate non constant operands into select. I.e.:
1974   // and (select Cond, 0, -1), X --> select Cond, 0, X
1975   // or X, (select Cond, -1, 0) --> select Cond, -1, X
1976   auto BinOpcode = BO->getOpcode();
1977   bool CanFoldNonConst =
1978       (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
1979       (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) &&
1980       (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF));
1981 
1982   SDValue CBO = BO->getOperand(SelOpNo ^ 1);
1983   if (!CanFoldNonConst &&
1984       !isConstantOrConstantVector(CBO, true) &&
1985       !isConstantFPBuildVectorOrConstantFP(CBO))
1986     return SDValue();
1987 
1988   EVT VT = Sel.getValueType();
1989 
1990   // In case of shift value and shift amount may have different VT. For instance
1991   // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
1992   // swapped operands and value types do not match. NB: x86 is fine if operands
1993   // are not swapped with shift amount VT being not bigger than shifted value.
1994   // TODO: that is possible to check for a shift operation, correct VTs and
1995   // still perform optimization on x86 if needed.
1996   if (SelOpNo && VT != CBO.getValueType())
1997     return SDValue();
1998 
1999   // We have a select-of-constants followed by a binary operator with a
2000   // constant. Eliminate the binop by pulling the constant math into the select.
2001   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2002   SDLoc DL(Sel);
2003   SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
2004                           : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
2005   if (!CanFoldNonConst && !NewCT.isUndef() &&
2006       !isConstantOrConstantVector(NewCT, true) &&
2007       !isConstantFPBuildVectorOrConstantFP(NewCT))
2008     return SDValue();
2009 
2010   SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
2011                           : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
2012   if (!CanFoldNonConst && !NewCF.isUndef() &&
2013       !isConstantOrConstantVector(NewCF, true) &&
2014       !isConstantFPBuildVectorOrConstantFP(NewCF))
2015     return SDValue();
2016 
2017   SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
2018   SelectOp->setFlags(BO->getFlags());
2019   return SelectOp;
2020 }
2021 
2022 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
2023   assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2024          "Expecting add or sub");
2025 
2026   // Match a constant operand and a zext operand for the math instruction:
2027   // add Z, C
2028   // sub C, Z
2029   bool IsAdd = N->getOpcode() == ISD::ADD;
2030   SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2031   SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2032   auto *CN = dyn_cast<ConstantSDNode>(C);
2033   if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2034     return SDValue();
2035 
2036   // Match the zext operand as a setcc of a boolean.
2037   if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
2038       Z.getOperand(0).getValueType() != MVT::i1)
2039     return SDValue();
2040 
2041   // Match the compare as: setcc (X & 1), 0, eq.
2042   SDValue SetCC = Z.getOperand(0);
2043   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
2044   if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
2045       SetCC.getOperand(0).getOpcode() != ISD::AND ||
2046       !isOneConstant(SetCC.getOperand(0).getOperand(1)))
2047     return SDValue();
2048 
2049   // We are adding/subtracting a constant and an inverted low bit. Turn that
2050   // into a subtract/add of the low bit with incremented/decremented constant:
2051   // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2052   // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2053   EVT VT = C.getValueType();
2054   SDLoc DL(N);
2055   SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
2056   SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
2057                        DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2058   return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2059 }
2060 
2061 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2062 /// a shift and add with a different constant.
2063 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
2064   assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2065          "Expecting add or sub");
2066 
2067   // We need a constant operand for the add/sub, and the other operand is a
2068   // logical shift right: add (srl), C or sub C, (srl).
2069   // TODO - support non-uniform vector amounts.
2070   bool IsAdd = N->getOpcode() == ISD::ADD;
2071   SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2072   SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2073   ConstantSDNode *C = isConstOrConstSplat(ConstantOp);
2074   if (!C || ShiftOp.getOpcode() != ISD::SRL)
2075     return SDValue();
2076 
2077   // The shift must be of a 'not' value.
2078   SDValue Not = ShiftOp.getOperand(0);
2079   if (!Not.hasOneUse() || !isBitwiseNot(Not))
2080     return SDValue();
2081 
2082   // The shift must be moving the sign bit to the least-significant-bit.
2083   EVT VT = ShiftOp.getValueType();
2084   SDValue ShAmt = ShiftOp.getOperand(1);
2085   ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2086   if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2087     return SDValue();
2088 
2089   // Eliminate the 'not' by adjusting the shift and add/sub constant:
2090   // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2091   // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2092   SDLoc DL(N);
2093   auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
2094   SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
2095   APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1;
2096   return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT));
2097 }
2098 
2099 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2100 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2101 /// are no common bits set in the operands).
2102 SDValue DAGCombiner::visitADDLike(SDNode *N) {
2103   SDValue N0 = N->getOperand(0);
2104   SDValue N1 = N->getOperand(1);
2105   EVT VT = N0.getValueType();
2106   SDLoc DL(N);
2107 
2108   // fold vector ops
2109   if (VT.isVector()) {
2110     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2111       return FoldedVOp;
2112 
2113     // fold (add x, 0) -> x, vector edition
2114     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2115       return N0;
2116     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2117       return N1;
2118   }
2119 
2120   // fold (add x, undef) -> undef
2121   if (N0.isUndef())
2122     return N0;
2123 
2124   if (N1.isUndef())
2125     return N1;
2126 
2127   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2128     // canonicalize constant to RHS
2129     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2130       return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2131     // fold (add c1, c2) -> c1+c2
2132     return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1});
2133   }
2134 
2135   // fold (add x, 0) -> x
2136   if (isNullConstant(N1))
2137     return N0;
2138 
2139   if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
2140     // fold ((A-c1)+c2) -> (A+(c2-c1))
2141     if (N0.getOpcode() == ISD::SUB &&
2142         isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
2143       SDValue Sub =
2144           DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)});
2145       assert(Sub && "Constant folding failed");
2146       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2147     }
2148 
2149     // fold ((c1-A)+c2) -> (c1+c2)-A
2150     if (N0.getOpcode() == ISD::SUB &&
2151         isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
2152       SDValue Add =
2153           DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)});
2154       assert(Add && "Constant folding failed");
2155       return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2156     }
2157 
2158     // add (sext i1 X), 1 -> zext (not i1 X)
2159     // We don't transform this pattern:
2160     //   add (zext i1 X), -1 -> sext (not i1 X)
2161     // because most (?) targets generate better code for the zext form.
2162     if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2163         isOneOrOneSplat(N1)) {
2164       SDValue X = N0.getOperand(0);
2165       if ((!LegalOperations ||
2166            (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2167             TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
2168           X.getScalarValueSizeInBits() == 1) {
2169         SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2170         return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2171       }
2172     }
2173 
2174     // Undo the add -> or combine to merge constant offsets from a frame index.
2175     if (N0.getOpcode() == ISD::OR &&
2176         isa<FrameIndexSDNode>(N0.getOperand(0)) &&
2177         isa<ConstantSDNode>(N0.getOperand(1)) &&
2178         DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
2179       SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1));
2180       return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
2181     }
2182   }
2183 
2184   if (SDValue NewSel = foldBinOpIntoSelect(N))
2185     return NewSel;
2186 
2187   // reassociate add
2188   if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) {
2189     if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
2190       return RADD;
2191   }
2192   // fold ((0-A) + B) -> B-A
2193   if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
2194     return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2195 
2196   // fold (A + (0-B)) -> A-B
2197   if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
2198     return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
2199 
2200   // fold (A+(B-A)) -> B
2201   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
2202     return N1.getOperand(0);
2203 
2204   // fold ((B-A)+A) -> B
2205   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
2206     return N0.getOperand(0);
2207 
2208   // fold ((A-B)+(C-A)) -> (C-B)
2209   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2210       N0.getOperand(0) == N1.getOperand(1))
2211     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2212                        N0.getOperand(1));
2213 
2214   // fold ((A-B)+(B-C)) -> (A-C)
2215   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
2216       N0.getOperand(1) == N1.getOperand(0))
2217     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2218                        N1.getOperand(1));
2219 
2220   // fold (A+(B-(A+C))) to (B-C)
2221   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2222       N0 == N1.getOperand(1).getOperand(0))
2223     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2224                        N1.getOperand(1).getOperand(1));
2225 
2226   // fold (A+(B-(C+A))) to (B-C)
2227   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
2228       N0 == N1.getOperand(1).getOperand(1))
2229     return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
2230                        N1.getOperand(1).getOperand(0));
2231 
2232   // fold (A+((B-A)+or-C)) to (B+or-C)
2233   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
2234       N1.getOperand(0).getOpcode() == ISD::SUB &&
2235       N0 == N1.getOperand(0).getOperand(1))
2236     return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
2237                        N1.getOperand(1));
2238 
2239   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2240   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
2241     SDValue N00 = N0.getOperand(0);
2242     SDValue N01 = N0.getOperand(1);
2243     SDValue N10 = N1.getOperand(0);
2244     SDValue N11 = N1.getOperand(1);
2245 
2246     if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
2247       return DAG.getNode(ISD::SUB, DL, VT,
2248                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
2249                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
2250   }
2251 
2252   // fold (add (umax X, C), -C) --> (usubsat X, C)
2253   if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
2254     auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
2255       return (!Max && !Op) ||
2256              (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
2257     };
2258     if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
2259                                   /*AllowUndefs*/ true))
2260       return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
2261                          N0.getOperand(1));
2262   }
2263 
2264   if (SimplifyDemandedBits(SDValue(N, 0)))
2265     return SDValue(N, 0);
2266 
2267   if (isOneOrOneSplat(N1)) {
2268     // fold (add (xor a, -1), 1) -> (sub 0, a)
2269     if (isBitwiseNot(N0))
2270       return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
2271                          N0.getOperand(0));
2272 
2273     // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2274     if (N0.getOpcode() == ISD::ADD ||
2275         N0.getOpcode() == ISD::UADDO ||
2276         N0.getOpcode() == ISD::SADDO) {
2277       SDValue A, Xor;
2278 
2279       if (isBitwiseNot(N0.getOperand(0))) {
2280         A = N0.getOperand(1);
2281         Xor = N0.getOperand(0);
2282       } else if (isBitwiseNot(N0.getOperand(1))) {
2283         A = N0.getOperand(0);
2284         Xor = N0.getOperand(1);
2285       }
2286 
2287       if (Xor)
2288         return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
2289     }
2290 
2291     // Look for:
2292     //   add (add x, y), 1
2293     // And if the target does not like this form then turn into:
2294     //   sub y, (xor x, -1)
2295     if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2296         N0.getOpcode() == ISD::ADD) {
2297       SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2298                                 DAG.getAllOnesConstant(DL, VT));
2299       return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
2300     }
2301   }
2302 
2303   // (x - y) + -1  ->  add (xor y, -1), x
2304   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2305       isAllOnesOrAllOnesSplat(N1)) {
2306     SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
2307     return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
2308   }
2309 
2310   if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
2311     return Combined;
2312 
2313   if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
2314     return Combined;
2315 
2316   return SDValue();
2317 }
2318 
2319 SDValue DAGCombiner::visitADD(SDNode *N) {
2320   SDValue N0 = N->getOperand(0);
2321   SDValue N1 = N->getOperand(1);
2322   EVT VT = N0.getValueType();
2323   SDLoc DL(N);
2324 
2325   if (SDValue Combined = visitADDLike(N))
2326     return Combined;
2327 
2328   if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
2329     return V;
2330 
2331   if (SDValue V = foldAddSubOfSignBit(N, DAG))
2332     return V;
2333 
2334   // fold (a+b) -> (a|b) iff a and b share no bits.
2335   if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
2336       DAG.haveNoCommonBitsSet(N0, N1))
2337     return DAG.getNode(ISD::OR, DL, VT, N0, N1);
2338 
2339   // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
2340   if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
2341     APInt C0 = N0->getConstantOperandAPInt(0);
2342     APInt C1 = N1->getConstantOperandAPInt(0);
2343     return DAG.getVScale(DL, VT, C0 + C1);
2344   }
2345 
2346   return SDValue();
2347 }
2348 
2349 SDValue DAGCombiner::visitADDSAT(SDNode *N) {
2350   unsigned Opcode = N->getOpcode();
2351   SDValue N0 = N->getOperand(0);
2352   SDValue N1 = N->getOperand(1);
2353   EVT VT = N0.getValueType();
2354   SDLoc DL(N);
2355 
2356   // fold vector ops
2357   if (VT.isVector()) {
2358     // TODO SimplifyVBinOp
2359 
2360     // fold (add_sat x, 0) -> x, vector edition
2361     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2362       return N0;
2363     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2364       return N1;
2365   }
2366 
2367   // fold (add_sat x, undef) -> -1
2368   if (N0.isUndef() || N1.isUndef())
2369     return DAG.getAllOnesConstant(DL, VT);
2370 
2371   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
2372     // canonicalize constant to RHS
2373     if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
2374       return DAG.getNode(Opcode, DL, VT, N1, N0);
2375     // fold (add_sat c1, c2) -> c3
2376     return DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1});
2377   }
2378 
2379   // fold (add_sat x, 0) -> x
2380   if (isNullConstant(N1))
2381     return N0;
2382 
2383   // If it cannot overflow, transform into an add.
2384   if (Opcode == ISD::UADDSAT)
2385     if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2386       return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
2387 
2388   return SDValue();
2389 }
2390 
2391 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
2392   bool Masked = false;
2393 
2394   // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2395   while (true) {
2396     if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
2397       V = V.getOperand(0);
2398       continue;
2399     }
2400 
2401     if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
2402       Masked = true;
2403       V = V.getOperand(0);
2404       continue;
2405     }
2406 
2407     break;
2408   }
2409 
2410   // If this is not a carry, return.
2411   if (V.getResNo() != 1)
2412     return SDValue();
2413 
2414   if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2415       V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2416     return SDValue();
2417 
2418   EVT VT = V.getNode()->getValueType(0);
2419   if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
2420     return SDValue();
2421 
2422   // If the result is masked, then no matter what kind of bool it is we can
2423   // return. If it isn't, then we need to make sure the bool type is either 0 or
2424   // 1 and not other values.
2425   if (Masked ||
2426       TLI.getBooleanContents(V.getValueType()) ==
2427           TargetLoweringBase::ZeroOrOneBooleanContent)
2428     return V;
2429 
2430   return SDValue();
2431 }
2432 
2433 /// Given the operands of an add/sub operation, see if the 2nd operand is a
2434 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2435 /// the opcode and bypass the mask operation.
2436 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
2437                                  SelectionDAG &DAG, const SDLoc &DL) {
2438   if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
2439     return SDValue();
2440 
2441   EVT VT = N0.getValueType();
2442   if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
2443     return SDValue();
2444 
2445   // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2446   // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2447   return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
2448 }
2449 
2450 /// Helper for doing combines based on N0 and N1 being added to each other.
2451 SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
2452                                           SDNode *LocReference) {
2453   EVT VT = N0.getValueType();
2454   SDLoc DL(LocReference);
2455 
2456   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2457   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2458       isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
2459     return DAG.getNode(ISD::SUB, DL, VT, N0,
2460                        DAG.getNode(ISD::SHL, DL, VT,
2461                                    N1.getOperand(0).getOperand(1),
2462                                    N1.getOperand(1)));
2463 
2464   if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
2465     return V;
2466 
2467   // Look for:
2468   //   add (add x, 1), y
2469   // And if the target does not like this form then turn into:
2470   //   sub y, (xor x, -1)
2471   if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
2472       N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) {
2473     SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
2474                               DAG.getAllOnesConstant(DL, VT));
2475     return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
2476   }
2477 
2478   // Hoist one-use subtraction by non-opaque constant:
2479   //   (x - C) + y  ->  (x + y) - C
2480   // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2481   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2482       isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
2483     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
2484     return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2485   }
2486   // Hoist one-use subtraction from non-opaque constant:
2487   //   (C - x) + y  ->  (y - x) + C
2488   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
2489       isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
2490     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
2491     return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
2492   }
2493 
2494   // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2495   // rather than 'add 0/-1' (the zext should get folded).
2496   // add (sext i1 Y), X --> sub X, (zext i1 Y)
2497   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2498       N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
2499       TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
2500     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2501     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2502   }
2503 
2504   // add X, (sextinreg Y i1) -> sub 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::SUB, DL, VT, N0, ZExt);
2511     }
2512   }
2513 
2514   // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2515   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
2516       N1.getResNo() == 0)
2517     return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2518                        N0, N1.getOperand(0), N1.getOperand(2));
2519 
2520   // (add X, Carry) -> (addcarry X, 0, Carry)
2521   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2522     if (SDValue Carry = getAsCarry(TLI, N1))
2523       return DAG.getNode(ISD::ADDCARRY, DL,
2524                          DAG.getVTList(VT, Carry.getValueType()), N0,
2525                          DAG.getConstant(0, DL, VT), Carry);
2526 
2527   return SDValue();
2528 }
2529 
2530 SDValue DAGCombiner::visitADDC(SDNode *N) {
2531   SDValue N0 = N->getOperand(0);
2532   SDValue N1 = N->getOperand(1);
2533   EVT VT = N0.getValueType();
2534   SDLoc DL(N);
2535 
2536   // If the flag result is dead, turn this into an ADD.
2537   if (!N->hasAnyUseOfValue(1))
2538     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2539                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2540 
2541   // canonicalize constant to RHS.
2542   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2543   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2544   if (N0C && !N1C)
2545     return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2546 
2547   // fold (addc x, 0) -> x + no carry out
2548   if (isNullConstant(N1))
2549     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2550                                         DL, MVT::Glue));
2551 
2552   // If it cannot overflow, transform into an add.
2553   if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2554     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2555                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2556 
2557   return SDValue();
2558 }
2559 
2560 static SDValue flipBoolean(SDValue V, const SDLoc &DL,
2561                            SelectionDAG &DAG, const TargetLowering &TLI) {
2562   EVT VT = V.getValueType();
2563 
2564   SDValue Cst;
2565   switch (TLI.getBooleanContents(VT)) {
2566   case TargetLowering::ZeroOrOneBooleanContent:
2567   case TargetLowering::UndefinedBooleanContent:
2568     Cst = DAG.getConstant(1, DL, VT);
2569     break;
2570   case TargetLowering::ZeroOrNegativeOneBooleanContent:
2571     Cst = DAG.getAllOnesConstant(DL, VT);
2572     break;
2573   }
2574 
2575   return DAG.getNode(ISD::XOR, DL, VT, V, Cst);
2576 }
2577 
2578 /**
2579  * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2580  * then the flip also occurs if computing the inverse is the same cost.
2581  * This function returns an empty SDValue in case it cannot flip the boolean
2582  * without increasing the cost of the computation. If you want to flip a boolean
2583  * no matter what, use flipBoolean.
2584  */
2585 static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
2586                                   const TargetLowering &TLI,
2587                                   bool Force) {
2588   if (Force && isa<ConstantSDNode>(V))
2589     return flipBoolean(V, SDLoc(V), DAG, TLI);
2590 
2591   if (V.getOpcode() != ISD::XOR)
2592     return SDValue();
2593 
2594   ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
2595   if (!Const)
2596     return SDValue();
2597 
2598   EVT VT = V.getValueType();
2599 
2600   bool IsFlip = false;
2601   switch(TLI.getBooleanContents(VT)) {
2602     case TargetLowering::ZeroOrOneBooleanContent:
2603       IsFlip = Const->isOne();
2604       break;
2605     case TargetLowering::ZeroOrNegativeOneBooleanContent:
2606       IsFlip = Const->isAllOnesValue();
2607       break;
2608     case TargetLowering::UndefinedBooleanContent:
2609       IsFlip = (Const->getAPIntValue() & 0x01) == 1;
2610       break;
2611   }
2612 
2613   if (IsFlip)
2614     return V.getOperand(0);
2615   if (Force)
2616     return flipBoolean(V, SDLoc(V), DAG, TLI);
2617   return SDValue();
2618 }
2619 
2620 SDValue DAGCombiner::visitADDO(SDNode *N) {
2621   SDValue N0 = N->getOperand(0);
2622   SDValue N1 = N->getOperand(1);
2623   EVT VT = N0.getValueType();
2624   bool IsSigned = (ISD::SADDO == N->getOpcode());
2625 
2626   EVT CarryVT = N->getValueType(1);
2627   SDLoc DL(N);
2628 
2629   // If the flag result is dead, turn this into an ADD.
2630   if (!N->hasAnyUseOfValue(1))
2631     return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2632                      DAG.getUNDEF(CarryVT));
2633 
2634   // canonicalize constant to RHS.
2635   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2636       !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2637     return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
2638 
2639   // fold (addo x, 0) -> x + no carry out
2640   if (isNullOrNullSplat(N1))
2641     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2642 
2643   if (!IsSigned) {
2644     // If it cannot overflow, transform into an add.
2645     if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2646       return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2647                        DAG.getConstant(0, DL, CarryVT));
2648 
2649     // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2650     if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
2651       SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
2652                                 DAG.getConstant(0, DL, VT), N0.getOperand(0));
2653       return CombineTo(N, Sub,
2654                        flipBoolean(Sub.getValue(1), DL, DAG, TLI));
2655     }
2656 
2657     if (SDValue Combined = visitUADDOLike(N0, N1, N))
2658       return Combined;
2659 
2660     if (SDValue Combined = visitUADDOLike(N1, N0, N))
2661       return Combined;
2662   }
2663 
2664   return SDValue();
2665 }
2666 
2667 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2668   EVT VT = N0.getValueType();
2669   if (VT.isVector())
2670     return SDValue();
2671 
2672   // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2673   // If Y + 1 cannot overflow.
2674   if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2675     SDValue Y = N1.getOperand(0);
2676     SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2677     if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2678       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2679                          N1.getOperand(2));
2680   }
2681 
2682   // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2683   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2684     if (SDValue Carry = getAsCarry(TLI, N1))
2685       return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2686                          DAG.getConstant(0, SDLoc(N), VT), Carry);
2687 
2688   return SDValue();
2689 }
2690 
2691 SDValue DAGCombiner::visitADDE(SDNode *N) {
2692   SDValue N0 = N->getOperand(0);
2693   SDValue N1 = N->getOperand(1);
2694   SDValue CarryIn = N->getOperand(2);
2695 
2696   // canonicalize constant to RHS
2697   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2698   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2699   if (N0C && !N1C)
2700     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2701                        N1, N0, CarryIn);
2702 
2703   // fold (adde x, y, false) -> (addc x, y)
2704   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2705     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2706 
2707   return SDValue();
2708 }
2709 
2710 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2711   SDValue N0 = N->getOperand(0);
2712   SDValue N1 = N->getOperand(1);
2713   SDValue CarryIn = N->getOperand(2);
2714   SDLoc DL(N);
2715 
2716   // canonicalize constant to RHS
2717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2719   if (N0C && !N1C)
2720     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2721 
2722   // fold (addcarry x, y, false) -> (uaddo x, y)
2723   if (isNullConstant(CarryIn)) {
2724     if (!LegalOperations ||
2725         TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
2726       return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2727   }
2728 
2729   // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2730   if (isNullConstant(N0) && isNullConstant(N1)) {
2731     EVT VT = N0.getValueType();
2732     EVT CarryVT = CarryIn.getValueType();
2733     SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2734     AddToWorklist(CarryExt.getNode());
2735     return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2736                                     DAG.getConstant(1, DL, VT)),
2737                      DAG.getConstant(0, DL, CarryVT));
2738   }
2739 
2740   if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2741     return Combined;
2742 
2743   if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2744     return Combined;
2745 
2746   return SDValue();
2747 }
2748 
2749 /**
2750  * If we are facing some sort of diamond carry propapagtion pattern try to
2751  * break it up to generate something like:
2752  *   (addcarry X, 0, (addcarry A, B, Z):Carry)
2753  *
2754  * The end result is usually an increase in operation required, but because the
2755  * carry is now linearized, other tranforms can kick in and optimize the DAG.
2756  *
2757  * Patterns typically look something like
2758  *            (uaddo A, B)
2759  *             /       \
2760  *          Carry      Sum
2761  *            |          \
2762  *            | (addcarry *, 0, Z)
2763  *            |       /
2764  *             \   Carry
2765  *              |   /
2766  * (addcarry X, *, *)
2767  *
2768  * But numerous variation exist. Our goal is to identify A, B, X and Z and
2769  * produce a combine with a single path for carry propagation.
2770  */
2771 static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
2772                                       SDValue X, SDValue Carry0, SDValue Carry1,
2773                                       SDNode *N) {
2774   if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
2775     return SDValue();
2776   if (Carry1.getOpcode() != ISD::UADDO)
2777     return SDValue();
2778 
2779   SDValue Z;
2780 
2781   /**
2782    * First look for a suitable Z. It will present itself in the form of
2783    * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2784    */
2785   if (Carry0.getOpcode() == ISD::ADDCARRY &&
2786       isNullConstant(Carry0.getOperand(1))) {
2787     Z = Carry0.getOperand(2);
2788   } else if (Carry0.getOpcode() == ISD::UADDO &&
2789              isOneConstant(Carry0.getOperand(1))) {
2790     EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
2791     Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
2792   } else {
2793     // We couldn't find a suitable Z.
2794     return SDValue();
2795   }
2796 
2797 
2798   auto cancelDiamond = [&](SDValue A,SDValue B) {
2799     SDLoc DL(N);
2800     SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
2801     Combiner.AddToWorklist(NewY.getNode());
2802     return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
2803                        DAG.getConstant(0, DL, X.getValueType()),
2804                        NewY.getValue(1));
2805   };
2806 
2807   /**
2808    *      (uaddo A, B)
2809    *           |
2810    *          Sum
2811    *           |
2812    * (addcarry *, 0, Z)
2813    */
2814   if (Carry0.getOperand(0) == Carry1.getValue(0)) {
2815     return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
2816   }
2817 
2818   /**
2819    * (addcarry A, 0, Z)
2820    *         |
2821    *        Sum
2822    *         |
2823    *  (uaddo *, B)
2824    */
2825   if (Carry1.getOperand(0) == Carry0.getValue(0)) {
2826     return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
2827   }
2828 
2829   if (Carry1.getOperand(1) == Carry0.getValue(0)) {
2830     return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
2831   }
2832 
2833   return SDValue();
2834 }
2835 
2836 // If we are facing some sort of diamond carry/borrow in/out pattern try to
2837 // match patterns like:
2838 //
2839 //          (uaddo A, B)            CarryIn
2840 //            |  \                     |
2841 //            |   \                    |
2842 //    PartialSum   PartialCarryOutX   /
2843 //            |        |             /
2844 //            |    ____|____________/
2845 //            |   /    |
2846 //     (uaddo *, *)    \________
2847 //       |  \                   \
2848 //       |   \                   |
2849 //       |    PartialCarryOutY   |
2850 //       |        \              |
2851 //       |         \            /
2852 //   AddCarrySum    |    ______/
2853 //                  |   /
2854 //   CarryOut = (or *, *)
2855 //
2856 // And generate ADDCARRY (or SUBCARRY) with two result values:
2857 //
2858 //    {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn)
2859 //
2860 // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with
2861 // a single path for carry/borrow out propagation:
2862 static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
2863                                    const TargetLowering &TLI, SDValue Carry0,
2864                                    SDValue Carry1, SDNode *N) {
2865   if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1)
2866     return SDValue();
2867   unsigned Opcode = Carry0.getOpcode();
2868   if (Opcode != Carry1.getOpcode())
2869     return SDValue();
2870   if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
2871     return SDValue();
2872 
2873   // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the
2874   // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in
2875   // the above ASCII art.)
2876   if (Carry1.getOperand(0) != Carry0.getValue(0) &&
2877       Carry1.getOperand(1) != Carry0.getValue(0))
2878     std::swap(Carry0, Carry1);
2879   if (Carry1.getOperand(0) != Carry0.getValue(0) &&
2880       Carry1.getOperand(1) != Carry0.getValue(0))
2881     return SDValue();
2882 
2883   // The carry in value must be on the righthand side for subtraction.
2884   unsigned CarryInOperandNum =
2885       Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
2886   if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
2887     return SDValue();
2888   SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
2889 
2890   unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY;
2891   if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
2892     return SDValue();
2893 
2894   // Verify that the carry/borrow in is plausibly a carry/borrow bit.
2895   // TODO: make getAsCarry() aware of how partial carries are merged.
2896   if (CarryIn.getOpcode() != ISD::ZERO_EXTEND)
2897     return SDValue();
2898   CarryIn = CarryIn.getOperand(0);
2899   if (CarryIn.getValueType() != MVT::i1)
2900     return SDValue();
2901 
2902   SDLoc DL(N);
2903   SDValue Merged =
2904       DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
2905                   Carry0.getOperand(1), CarryIn);
2906 
2907   // Please note that because we have proven that the result of the UADDO/USUBO
2908   // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
2909   // therefore prove that if the first UADDO/USUBO overflows, the second
2910   // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
2911   // maximum value.
2912   //
2913   //   0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
2914   //   0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
2915   //
2916   // This is important because it means that OR and XOR can be used to merge
2917   // carry flags; and that AND can return a constant zero.
2918   //
2919   // TODO: match other operations that can merge flags (ADD, etc)
2920   DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
2921   if (N->getOpcode() == ISD::AND)
2922     return DAG.getConstant(0, DL, MVT::i1);
2923   return Merged.getValue(1);
2924 }
2925 
2926 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2927                                        SDNode *N) {
2928   // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
2929   if (isBitwiseNot(N0))
2930     if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
2931       SDLoc DL(N);
2932       SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
2933                                 N0.getOperand(0), NotC);
2934       return CombineTo(N, Sub,
2935                        flipBoolean(Sub.getValue(1), DL, DAG, TLI));
2936     }
2937 
2938   // Iff the flag result is dead:
2939   // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2940   // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
2941   // or the dependency between the instructions.
2942   if ((N0.getOpcode() == ISD::ADD ||
2943        (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
2944         N0.getValue(1) != CarryIn)) &&
2945       isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2946     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2947                        N0.getOperand(0), N0.getOperand(1), CarryIn);
2948 
2949   /**
2950    * When one of the addcarry argument is itself a carry, we may be facing
2951    * a diamond carry propagation. In which case we try to transform the DAG
2952    * to ensure linear carry propagation if that is possible.
2953    */
2954   if (auto Y = getAsCarry(TLI, N1)) {
2955     // Because both are carries, Y and Z can be swapped.
2956     if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
2957       return R;
2958     if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
2959       return R;
2960   }
2961 
2962   return SDValue();
2963 }
2964 
2965 // Since it may not be valid to emit a fold to zero for vector initializers
2966 // check if we can before folding.
2967 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2968                              SelectionDAG &DAG, bool LegalOperations) {
2969   if (!VT.isVector())
2970     return DAG.getConstant(0, DL, VT);
2971   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2972     return DAG.getConstant(0, DL, VT);
2973   return SDValue();
2974 }
2975 
2976 SDValue DAGCombiner::visitSUB(SDNode *N) {
2977   SDValue N0 = N->getOperand(0);
2978   SDValue N1 = N->getOperand(1);
2979   EVT VT = N0.getValueType();
2980   SDLoc DL(N);
2981 
2982   // fold vector ops
2983   if (VT.isVector()) {
2984     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2985       return FoldedVOp;
2986 
2987     // fold (sub x, 0) -> x, vector edition
2988     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2989       return N0;
2990   }
2991 
2992   // fold (sub x, x) -> 0
2993   // FIXME: Refactor this and xor and other similar operations together.
2994   if (N0 == N1)
2995     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
2996 
2997   // fold (sub c1, c2) -> c3
2998   if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
2999     return C;
3000 
3001   if (SDValue NewSel = foldBinOpIntoSelect(N))
3002     return NewSel;
3003 
3004   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3005 
3006   // fold (sub x, c) -> (add x, -c)
3007   if (N1C) {
3008     return DAG.getNode(ISD::ADD, DL, VT, N0,
3009                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3010   }
3011 
3012   if (isNullOrNullSplat(N0)) {
3013     unsigned BitWidth = VT.getScalarSizeInBits();
3014     // Right-shifting everything out but the sign bit followed by negation is
3015     // the same as flipping arithmetic/logical shift type without the negation:
3016     // -(X >>u 31) -> (X >>s 31)
3017     // -(X >>s 31) -> (X >>u 31)
3018     if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
3019       ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
3020       if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
3021         auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
3022         if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
3023           return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
3024       }
3025     }
3026 
3027     // 0 - X --> 0 if the sub is NUW.
3028     if (N->getFlags().hasNoUnsignedWrap())
3029       return N0;
3030 
3031     if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
3032       // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3033       // N1 must be 0 because negating the minimum signed value is undefined.
3034       if (N->getFlags().hasNoSignedWrap())
3035         return N0;
3036 
3037       // 0 - X --> X if X is 0 or the minimum signed value.
3038       return N1;
3039     }
3040   }
3041 
3042   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3043   if (isAllOnesOrAllOnesSplat(N0))
3044     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
3045 
3046   // fold (A - (0-B)) -> A+B
3047   if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
3048     return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
3049 
3050   // fold A-(A-B) -> B
3051   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
3052     return N1.getOperand(1);
3053 
3054   // fold (A+B)-A -> B
3055   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
3056     return N0.getOperand(1);
3057 
3058   // fold (A+B)-B -> A
3059   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
3060     return N0.getOperand(0);
3061 
3062   // fold (A+C1)-C2 -> A+(C1-C2)
3063   if (N0.getOpcode() == ISD::ADD &&
3064       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3065       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3066     SDValue NewC =
3067         DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1});
3068     assert(NewC && "Constant folding failed");
3069     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
3070   }
3071 
3072   // fold C2-(A+C1) -> (C2-C1)-A
3073   if (N1.getOpcode() == ISD::ADD) {
3074     SDValue N11 = N1.getOperand(1);
3075     if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
3076         isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
3077       SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11});
3078       assert(NewC && "Constant folding failed");
3079       return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
3080     }
3081   }
3082 
3083   // fold (A-C1)-C2 -> A-(C1+C2)
3084   if (N0.getOpcode() == ISD::SUB &&
3085       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3086       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3087     SDValue NewC =
3088         DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1});
3089     assert(NewC && "Constant folding failed");
3090     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
3091   }
3092 
3093   // fold (c1-A)-c2 -> (c1-c2)-A
3094   if (N0.getOpcode() == ISD::SUB &&
3095       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3096       isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) {
3097     SDValue NewC =
3098         DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1});
3099     assert(NewC && "Constant folding failed");
3100     return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
3101   }
3102 
3103   // fold ((A+(B+or-C))-B) -> A+or-C
3104   if (N0.getOpcode() == ISD::ADD &&
3105       (N0.getOperand(1).getOpcode() == ISD::SUB ||
3106        N0.getOperand(1).getOpcode() == ISD::ADD) &&
3107       N0.getOperand(1).getOperand(0) == N1)
3108     return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
3109                        N0.getOperand(1).getOperand(1));
3110 
3111   // fold ((A+(C+B))-B) -> A+C
3112   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
3113       N0.getOperand(1).getOperand(1) == N1)
3114     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
3115                        N0.getOperand(1).getOperand(0));
3116 
3117   // fold ((A-(B-C))-C) -> A-B
3118   if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
3119       N0.getOperand(1).getOperand(1) == N1)
3120     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
3121                        N0.getOperand(1).getOperand(0));
3122 
3123   // fold (A-(B-C)) -> A+(C-B)
3124   if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
3125     return DAG.getNode(ISD::ADD, DL, VT, N0,
3126                        DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
3127                                    N1.getOperand(0)));
3128 
3129   // A - (A & B)  ->  A & (~B)
3130   if (N1.getOpcode() == ISD::AND) {
3131     SDValue A = N1.getOperand(0);
3132     SDValue B = N1.getOperand(1);
3133     if (A != N0)
3134       std::swap(A, B);
3135     if (A == N0 &&
3136         (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) {
3137       SDValue InvB =
3138           DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT));
3139       return DAG.getNode(ISD::AND, DL, VT, A, InvB);
3140     }
3141   }
3142 
3143   // fold (X - (-Y * Z)) -> (X + (Y * Z))
3144   if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
3145     if (N1.getOperand(0).getOpcode() == ISD::SUB &&
3146         isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
3147       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3148                                 N1.getOperand(0).getOperand(1),
3149                                 N1.getOperand(1));
3150       return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3151     }
3152     if (N1.getOperand(1).getOpcode() == ISD::SUB &&
3153         isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
3154       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
3155                                 N1.getOperand(0),
3156                                 N1.getOperand(1).getOperand(1));
3157       return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
3158     }
3159   }
3160 
3161   // If either operand of a sub is undef, the result is undef
3162   if (N0.isUndef())
3163     return N0;
3164   if (N1.isUndef())
3165     return N1;
3166 
3167   if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
3168     return V;
3169 
3170   if (SDValue V = foldAddSubOfSignBit(N, DAG))
3171     return V;
3172 
3173   if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
3174     return V;
3175 
3176   // (x - y) - 1  ->  add (xor y, -1), x
3177   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) {
3178     SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
3179                               DAG.getAllOnesConstant(DL, VT));
3180     return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
3181   }
3182 
3183   // Look for:
3184   //   sub y, (xor x, -1)
3185   // And if the target does not like this form then turn into:
3186   //   add (add x, y), 1
3187   if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
3188     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
3189     return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
3190   }
3191 
3192   // Hoist one-use addition by non-opaque constant:
3193   //   (x + C) - y  ->  (x - y) + C
3194   if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
3195       isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3196     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3197     return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
3198   }
3199   // y - (x + C)  ->  (y - x) - C
3200   if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD &&
3201       isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
3202     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
3203     return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
3204   }
3205   // (x - C) - y  ->  (x - y) - C
3206   // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3207   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3208       isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3209     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
3210     return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
3211   }
3212   // (C - x) - y  ->  C - (x + y)
3213   if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
3214       isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3215     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
3216     return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
3217   }
3218 
3219   // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3220   // rather than 'sub 0/1' (the sext should get folded).
3221   // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3222   if (N1.getOpcode() == ISD::ZERO_EXTEND &&
3223       N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
3224       TLI.getBooleanContents(VT) ==
3225           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3226     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
3227     return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
3228   }
3229 
3230   // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3231   if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
3232     if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
3233       SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
3234       SDValue S0 = N1.getOperand(0);
3235       if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) {
3236         unsigned OpSizeInBits = VT.getScalarSizeInBits();
3237         if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
3238           if (C->getAPIntValue() == (OpSizeInBits - 1))
3239             return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
3240       }
3241     }
3242   }
3243 
3244   // If the relocation model supports it, consider symbol offsets.
3245   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
3246     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
3247       // fold (sub Sym, c) -> Sym-c
3248       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
3249         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
3250                                     GA->getOffset() -
3251                                         (uint64_t)N1C->getSExtValue());
3252       // fold (sub Sym+c1, Sym+c2) -> c1-c2
3253       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
3254         if (GA->getGlobal() == GB->getGlobal())
3255           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
3256                                  DL, VT);
3257     }
3258 
3259   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3260   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3261     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3262     if (TN->getVT() == MVT::i1) {
3263       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3264                                  DAG.getConstant(1, DL, VT));
3265       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
3266     }
3267   }
3268 
3269   // canonicalize (sub X, (vscale * C)) to (add X,  (vscale * -C))
3270   if (N1.getOpcode() == ISD::VSCALE) {
3271     APInt IntVal = N1.getConstantOperandAPInt(0);
3272     return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
3273   }
3274 
3275   // Prefer an add for more folding potential and possibly better codegen:
3276   // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3277   if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
3278     SDValue ShAmt = N1.getOperand(1);
3279     ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
3280     if (ShAmtC &&
3281         ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
3282       SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
3283       return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
3284     }
3285   }
3286 
3287   if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) {
3288     // (sub Carry, X)  ->  (addcarry (sub 0, X), 0, Carry)
3289     if (SDValue Carry = getAsCarry(TLI, N0)) {
3290       SDValue X = N1;
3291       SDValue Zero = DAG.getConstant(0, DL, VT);
3292       SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
3293       return DAG.getNode(ISD::ADDCARRY, DL,
3294                          DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
3295                          Carry);
3296     }
3297   }
3298 
3299   return SDValue();
3300 }
3301 
3302 SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
3303   SDValue N0 = N->getOperand(0);
3304   SDValue N1 = N->getOperand(1);
3305   EVT VT = N0.getValueType();
3306   SDLoc DL(N);
3307 
3308   // fold vector ops
3309   if (VT.isVector()) {
3310     // TODO SimplifyVBinOp
3311 
3312     // fold (sub_sat x, 0) -> x, vector edition
3313     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3314       return N0;
3315   }
3316 
3317   // fold (sub_sat x, undef) -> 0
3318   if (N0.isUndef() || N1.isUndef())
3319     return DAG.getConstant(0, DL, VT);
3320 
3321   // fold (sub_sat x, x) -> 0
3322   if (N0 == N1)
3323     return DAG.getConstant(0, DL, VT);
3324 
3325   // fold (sub_sat c1, c2) -> c3
3326   if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
3327     return C;
3328 
3329   // fold (sub_sat x, 0) -> x
3330   if (isNullConstant(N1))
3331     return N0;
3332 
3333   return SDValue();
3334 }
3335 
3336 SDValue DAGCombiner::visitSUBC(SDNode *N) {
3337   SDValue N0 = N->getOperand(0);
3338   SDValue N1 = N->getOperand(1);
3339   EVT VT = N0.getValueType();
3340   SDLoc DL(N);
3341 
3342   // If the flag result is dead, turn this into an SUB.
3343   if (!N->hasAnyUseOfValue(1))
3344     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3345                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3346 
3347   // fold (subc x, x) -> 0 + no borrow
3348   if (N0 == N1)
3349     return CombineTo(N, DAG.getConstant(0, DL, VT),
3350                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3351 
3352   // fold (subc x, 0) -> x + no borrow
3353   if (isNullConstant(N1))
3354     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3355 
3356   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3357   if (isAllOnesConstant(N0))
3358     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3359                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3360 
3361   return SDValue();
3362 }
3363 
3364 SDValue DAGCombiner::visitSUBO(SDNode *N) {
3365   SDValue N0 = N->getOperand(0);
3366   SDValue N1 = N->getOperand(1);
3367   EVT VT = N0.getValueType();
3368   bool IsSigned = (ISD::SSUBO == N->getOpcode());
3369 
3370   EVT CarryVT = N->getValueType(1);
3371   SDLoc DL(N);
3372 
3373   // If the flag result is dead, turn this into an SUB.
3374   if (!N->hasAnyUseOfValue(1))
3375     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
3376                      DAG.getUNDEF(CarryVT));
3377 
3378   // fold (subo x, x) -> 0 + no borrow
3379   if (N0 == N1)
3380     return CombineTo(N, DAG.getConstant(0, DL, VT),
3381                      DAG.getConstant(0, DL, CarryVT));
3382 
3383   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3384 
3385   // fold (subox, c) -> (addo x, -c)
3386   if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
3387     return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
3388                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
3389   }
3390 
3391   // fold (subo x, 0) -> x + no borrow
3392   if (isNullOrNullSplat(N1))
3393     return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3394 
3395   // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3396   if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
3397     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
3398                      DAG.getConstant(0, DL, CarryVT));
3399 
3400   return SDValue();
3401 }
3402 
3403 SDValue DAGCombiner::visitSUBE(SDNode *N) {
3404   SDValue N0 = N->getOperand(0);
3405   SDValue N1 = N->getOperand(1);
3406   SDValue CarryIn = N->getOperand(2);
3407 
3408   // fold (sube x, y, false) -> (subc x, y)
3409   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3410     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
3411 
3412   return SDValue();
3413 }
3414 
3415 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
3416   SDValue N0 = N->getOperand(0);
3417   SDValue N1 = N->getOperand(1);
3418   SDValue CarryIn = N->getOperand(2);
3419 
3420   // fold (subcarry x, y, false) -> (usubo x, y)
3421   if (isNullConstant(CarryIn)) {
3422     if (!LegalOperations ||
3423         TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
3424       return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
3425   }
3426 
3427   return SDValue();
3428 }
3429 
3430 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
3431 // UMULFIXSAT here.
3432 SDValue DAGCombiner::visitMULFIX(SDNode *N) {
3433   SDValue N0 = N->getOperand(0);
3434   SDValue N1 = N->getOperand(1);
3435   SDValue Scale = N->getOperand(2);
3436   EVT VT = N0.getValueType();
3437 
3438   // fold (mulfix x, undef, scale) -> 0
3439   if (N0.isUndef() || N1.isUndef())
3440     return DAG.getConstant(0, SDLoc(N), VT);
3441 
3442   // Canonicalize constant to RHS (vector doesn't have to splat)
3443   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3444      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3445     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
3446 
3447   // fold (mulfix x, 0, scale) -> 0
3448   if (isNullConstant(N1))
3449     return DAG.getConstant(0, SDLoc(N), VT);
3450 
3451   return SDValue();
3452 }
3453 
3454 SDValue DAGCombiner::visitMUL(SDNode *N) {
3455   SDValue N0 = N->getOperand(0);
3456   SDValue N1 = N->getOperand(1);
3457   EVT VT = N0.getValueType();
3458 
3459   // fold (mul x, undef) -> 0
3460   if (N0.isUndef() || N1.isUndef())
3461     return DAG.getConstant(0, SDLoc(N), VT);
3462 
3463   bool N1IsConst = false;
3464   bool N1IsOpaqueConst = false;
3465   APInt ConstValue1;
3466 
3467   // fold vector ops
3468   if (VT.isVector()) {
3469     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3470       return FoldedVOp;
3471 
3472     N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
3473     assert((!N1IsConst ||
3474             ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
3475            "Splat APInt should be element width");
3476   } else {
3477     N1IsConst = isa<ConstantSDNode>(N1);
3478     if (N1IsConst) {
3479       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
3480       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
3481     }
3482   }
3483 
3484   // fold (mul c1, c2) -> c1*c2
3485   if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1}))
3486     return C;
3487 
3488   // canonicalize constant to RHS (vector doesn't have to splat)
3489   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3490      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3491     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
3492 
3493   // fold (mul x, 0) -> 0
3494   if (N1IsConst && ConstValue1.isNullValue())
3495     return N1;
3496 
3497   // fold (mul x, 1) -> x
3498   if (N1IsConst && ConstValue1.isOneValue())
3499     return N0;
3500 
3501   if (SDValue NewSel = foldBinOpIntoSelect(N))
3502     return NewSel;
3503 
3504   // fold (mul x, -1) -> 0-x
3505   if (N1IsConst && ConstValue1.isAllOnesValue()) {
3506     SDLoc DL(N);
3507     return DAG.getNode(ISD::SUB, DL, VT,
3508                        DAG.getConstant(0, DL, VT), N0);
3509   }
3510 
3511   // fold (mul x, (1 << c)) -> x << c
3512   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3513       DAG.isKnownToBeAPowerOfTwo(N1) &&
3514       (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
3515     SDLoc DL(N);
3516     SDValue LogBase2 = BuildLogBase2(N1, DL);
3517     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3518     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3519     return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
3520   }
3521 
3522   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3523   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) {
3524     unsigned Log2Val = (-ConstValue1).logBase2();
3525     SDLoc DL(N);
3526     // FIXME: If the input is something that is easily negated (e.g. a
3527     // single-use add), we should put the negate there.
3528     return DAG.getNode(ISD::SUB, DL, VT,
3529                        DAG.getConstant(0, DL, VT),
3530                        DAG.getNode(ISD::SHL, DL, VT, N0,
3531                             DAG.getConstant(Log2Val, DL,
3532                                       getShiftAmountTy(N0.getValueType()))));
3533   }
3534 
3535   // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3536   // mul x, (2^N + 1) --> add (shl x, N), x
3537   // mul x, (2^N - 1) --> sub (shl x, N), x
3538   // Examples: x * 33 --> (x << 5) + x
3539   //           x * 15 --> (x << 4) - x
3540   //           x * -33 --> -((x << 5) + x)
3541   //           x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3542   if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
3543     // TODO: We could handle more general decomposition of any constant by
3544     //       having the target set a limit on number of ops and making a
3545     //       callback to determine that sequence (similar to sqrt expansion).
3546     unsigned MathOp = ISD::DELETED_NODE;
3547     APInt MulC = ConstValue1.abs();
3548     if ((MulC - 1).isPowerOf2())
3549       MathOp = ISD::ADD;
3550     else if ((MulC + 1).isPowerOf2())
3551       MathOp = ISD::SUB;
3552 
3553     if (MathOp != ISD::DELETED_NODE) {
3554       unsigned ShAmt =
3555           MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
3556       assert(ShAmt < VT.getScalarSizeInBits() &&
3557              "multiply-by-constant generated out of bounds shift");
3558       SDLoc DL(N);
3559       SDValue Shl =
3560           DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
3561       SDValue R = DAG.getNode(MathOp, DL, VT, Shl, N0);
3562       if (ConstValue1.isNegative())
3563         R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
3564       return R;
3565     }
3566   }
3567 
3568   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3569   if (N0.getOpcode() == ISD::SHL &&
3570       isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
3571       isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
3572     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
3573     if (isConstantOrConstantVector(C3))
3574       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
3575   }
3576 
3577   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3578   // use.
3579   {
3580     SDValue Sh(nullptr, 0), Y(nullptr, 0);
3581 
3582     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
3583     if (N0.getOpcode() == ISD::SHL &&
3584         isConstantOrConstantVector(N0.getOperand(1)) &&
3585         N0.getNode()->hasOneUse()) {
3586       Sh = N0; Y = N1;
3587     } else if (N1.getOpcode() == ISD::SHL &&
3588                isConstantOrConstantVector(N1.getOperand(1)) &&
3589                N1.getNode()->hasOneUse()) {
3590       Sh = N1; Y = N0;
3591     }
3592 
3593     if (Sh.getNode()) {
3594       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
3595       return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
3596     }
3597   }
3598 
3599   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3600   if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
3601       N0.getOpcode() == ISD::ADD &&
3602       DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
3603       isMulAddWithConstProfitable(N, N0, N1))
3604       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
3605                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
3606                                      N0.getOperand(0), N1),
3607                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
3608                                      N0.getOperand(1), N1));
3609 
3610   // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
3611   if (N0.getOpcode() == ISD::VSCALE)
3612     if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) {
3613       APInt C0 = N0.getConstantOperandAPInt(0);
3614       APInt C1 = NC1->getAPIntValue();
3615       return DAG.getVScale(SDLoc(N), VT, C0 * C1);
3616     }
3617 
3618   // reassociate mul
3619   if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
3620     return RMUL;
3621 
3622   return SDValue();
3623 }
3624 
3625 /// Return true if divmod libcall is available.
3626 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
3627                                      const TargetLowering &TLI) {
3628   RTLIB::Libcall LC;
3629   EVT NodeType = Node->getValueType(0);
3630   if (!NodeType.isSimple())
3631     return false;
3632   switch (NodeType.getSimpleVT().SimpleTy) {
3633   default: return false; // No libcall for vector types.
3634   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
3635   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
3636   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
3637   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
3638   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
3639   }
3640 
3641   return TLI.getLibcallName(LC) != nullptr;
3642 }
3643 
3644 /// Issue divrem if both quotient and remainder are needed.
3645 SDValue DAGCombiner::useDivRem(SDNode *Node) {
3646   if (Node->use_empty())
3647     return SDValue(); // This is a dead node, leave it alone.
3648 
3649   unsigned Opcode = Node->getOpcode();
3650   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
3651   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3652 
3653   // DivMod lib calls can still work on non-legal types if using lib-calls.
3654   EVT VT = Node->getValueType(0);
3655   if (VT.isVector() || !VT.isInteger())
3656     return SDValue();
3657 
3658   if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
3659     return SDValue();
3660 
3661   // If DIVREM is going to get expanded into a libcall,
3662   // but there is no libcall available, then don't combine.
3663   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
3664       !isDivRemLibcallAvailable(Node, isSigned, TLI))
3665     return SDValue();
3666 
3667   // If div is legal, it's better to do the normal expansion
3668   unsigned OtherOpcode = 0;
3669   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
3670     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
3671     if (TLI.isOperationLegalOrCustom(Opcode, VT))
3672       return SDValue();
3673   } else {
3674     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
3675     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
3676       return SDValue();
3677   }
3678 
3679   SDValue Op0 = Node->getOperand(0);
3680   SDValue Op1 = Node->getOperand(1);
3681   SDValue combined;
3682   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
3683          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
3684     SDNode *User = *UI;
3685     if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
3686         User->use_empty())
3687       continue;
3688     // Convert the other matching node(s), too;
3689     // otherwise, the DIVREM may get target-legalized into something
3690     // target-specific that we won't be able to recognize.
3691     unsigned UserOpc = User->getOpcode();
3692     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
3693         User->getOperand(0) == Op0 &&
3694         User->getOperand(1) == Op1) {
3695       if (!combined) {
3696         if (UserOpc == OtherOpcode) {
3697           SDVTList VTs = DAG.getVTList(VT, VT);
3698           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
3699         } else if (UserOpc == DivRemOpc) {
3700           combined = SDValue(User, 0);
3701         } else {
3702           assert(UserOpc == Opcode);
3703           continue;
3704         }
3705       }
3706       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
3707         CombineTo(User, combined);
3708       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
3709         CombineTo(User, combined.getValue(1));
3710     }
3711   }
3712   return combined;
3713 }
3714 
3715 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
3716   SDValue N0 = N->getOperand(0);
3717   SDValue N1 = N->getOperand(1);
3718   EVT VT = N->getValueType(0);
3719   SDLoc DL(N);
3720 
3721   unsigned Opc = N->getOpcode();
3722   bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
3723   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3724 
3725   // X / undef -> undef
3726   // X % undef -> undef
3727   // X / 0 -> undef
3728   // X % 0 -> undef
3729   // NOTE: This includes vectors where any divisor element is zero/undef.
3730   if (DAG.isUndef(Opc, {N0, N1}))
3731     return DAG.getUNDEF(VT);
3732 
3733   // undef / X -> 0
3734   // undef % X -> 0
3735   if (N0.isUndef())
3736     return DAG.getConstant(0, DL, VT);
3737 
3738   // 0 / X -> 0
3739   // 0 % X -> 0
3740   ConstantSDNode *N0C = isConstOrConstSplat(N0);
3741   if (N0C && N0C->isNullValue())
3742     return N0;
3743 
3744   // X / X -> 1
3745   // X % X -> 0
3746   if (N0 == N1)
3747     return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
3748 
3749   // X / 1 -> X
3750   // X % 1 -> 0
3751   // If this is a boolean op (single-bit element type), we can't have
3752   // division-by-zero or remainder-by-zero, so assume the divisor is 1.
3753   // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
3754   // it's a 1.
3755   if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
3756     return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
3757 
3758   return SDValue();
3759 }
3760 
3761 SDValue DAGCombiner::visitSDIV(SDNode *N) {
3762   SDValue N0 = N->getOperand(0);
3763   SDValue N1 = N->getOperand(1);
3764   EVT VT = N->getValueType(0);
3765   EVT CCVT = getSetCCResultType(VT);
3766 
3767   // fold vector ops
3768   if (VT.isVector())
3769     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3770       return FoldedVOp;
3771 
3772   SDLoc DL(N);
3773 
3774   // fold (sdiv c1, c2) -> c1/c2
3775   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3776   if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
3777     return C;
3778 
3779   // fold (sdiv X, -1) -> 0-X
3780   if (N1C && N1C->isAllOnesValue())
3781     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
3782 
3783   // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3784   if (N1C && N1C->getAPIntValue().isMinSignedValue())
3785     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3786                          DAG.getConstant(1, DL, VT),
3787                          DAG.getConstant(0, DL, VT));
3788 
3789   if (SDValue V = simplifyDivRem(N, DAG))
3790     return V;
3791 
3792   if (SDValue NewSel = foldBinOpIntoSelect(N))
3793     return NewSel;
3794 
3795   // If we know the sign bits of both operands are zero, strength reduce to a
3796   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
3797   if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
3798     return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
3799 
3800   if (SDValue V = visitSDIVLike(N0, N1, N)) {
3801     // If the corresponding remainder node exists, update its users with
3802     // (Dividend - (Quotient * Divisor).
3803     if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
3804                                               { N0, N1 })) {
3805       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3806       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3807       AddToWorklist(Mul.getNode());
3808       AddToWorklist(Sub.getNode());
3809       CombineTo(RemNode, Sub);
3810     }
3811     return V;
3812   }
3813 
3814   // sdiv, srem -> sdivrem
3815   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3816   // true.  Otherwise, we break the simplification logic in visitREM().
3817   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3818   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3819     if (SDValue DivRem = useDivRem(N))
3820         return DivRem;
3821 
3822   return SDValue();
3823 }
3824 
3825 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3826   SDLoc DL(N);
3827   EVT VT = N->getValueType(0);
3828   EVT CCVT = getSetCCResultType(VT);
3829   unsigned BitWidth = VT.getScalarSizeInBits();
3830 
3831   // Helper for determining whether a value is a power-2 constant scalar or a
3832   // vector of such elements.
3833   auto IsPowerOfTwo = [](ConstantSDNode *C) {
3834     if (C->isNullValue() || C->isOpaque())
3835       return false;
3836     if (C->getAPIntValue().isPowerOf2())
3837       return true;
3838     if ((-C->getAPIntValue()).isPowerOf2())
3839       return true;
3840     return false;
3841   };
3842 
3843   // fold (sdiv X, pow2) -> simple ops after legalize
3844   // FIXME: We check for the exact bit here because the generic lowering gives
3845   // better results in that case. The target-specific lowering should learn how
3846   // to handle exact sdivs efficiently.
3847   if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
3848     // Target-specific implementation of sdiv x, pow2.
3849     if (SDValue Res = BuildSDIVPow2(N))
3850       return Res;
3851 
3852     // Create constants that are functions of the shift amount value.
3853     EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
3854     SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
3855     SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
3856     C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
3857     SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
3858     if (!isConstantOrConstantVector(Inexact))
3859       return SDValue();
3860 
3861     // Splat the sign bit into the register
3862     SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
3863                                DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
3864     AddToWorklist(Sign.getNode());
3865 
3866     // Add (N0 < 0) ? abs2 - 1 : 0;
3867     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
3868     AddToWorklist(Srl.getNode());
3869     SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
3870     AddToWorklist(Add.getNode());
3871     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
3872     AddToWorklist(Sra.getNode());
3873 
3874     // Special case: (sdiv X, 1) -> X
3875     // Special Case: (sdiv X, -1) -> 0-X
3876     SDValue One = DAG.getConstant(1, DL, VT);
3877     SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
3878     SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
3879     SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
3880     SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
3881     Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
3882 
3883     // If dividing by a positive value, we're done. Otherwise, the result must
3884     // be negated.
3885     SDValue Zero = DAG.getConstant(0, DL, VT);
3886     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
3887 
3888     // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3889     SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
3890     SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
3891     return Res;
3892   }
3893 
3894   // If integer divide is expensive and we satisfy the requirements, emit an
3895   // alternate sequence.  Targets may check function attributes for size/speed
3896   // trade-offs.
3897   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3898   if (isConstantOrConstantVector(N1) &&
3899       !TLI.isIntDivCheap(N->getValueType(0), Attr))
3900     if (SDValue Op = BuildSDIV(N))
3901       return Op;
3902 
3903   return SDValue();
3904 }
3905 
3906 SDValue DAGCombiner::visitUDIV(SDNode *N) {
3907   SDValue N0 = N->getOperand(0);
3908   SDValue N1 = N->getOperand(1);
3909   EVT VT = N->getValueType(0);
3910   EVT CCVT = getSetCCResultType(VT);
3911 
3912   // fold vector ops
3913   if (VT.isVector())
3914     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3915       return FoldedVOp;
3916 
3917   SDLoc DL(N);
3918 
3919   // fold (udiv c1, c2) -> c1/c2
3920   ConstantSDNode *N1C = isConstOrConstSplat(N1);
3921   if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
3922     return C;
3923 
3924   // fold (udiv X, -1) -> select(X == -1, 1, 0)
3925   if (N1C && N1C->getAPIntValue().isAllOnesValue())
3926     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
3927                          DAG.getConstant(1, DL, VT),
3928                          DAG.getConstant(0, DL, VT));
3929 
3930   if (SDValue V = simplifyDivRem(N, DAG))
3931     return V;
3932 
3933   if (SDValue NewSel = foldBinOpIntoSelect(N))
3934     return NewSel;
3935 
3936   if (SDValue V = visitUDIVLike(N0, N1, N)) {
3937     // If the corresponding remainder node exists, update its users with
3938     // (Dividend - (Quotient * Divisor).
3939     if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
3940                                               { N0, N1 })) {
3941       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
3942       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
3943       AddToWorklist(Mul.getNode());
3944       AddToWorklist(Sub.getNode());
3945       CombineTo(RemNode, Sub);
3946     }
3947     return V;
3948   }
3949 
3950   // sdiv, srem -> sdivrem
3951   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3952   // true.  Otherwise, we break the simplification logic in visitREM().
3953   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3954   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
3955     if (SDValue DivRem = useDivRem(N))
3956         return DivRem;
3957 
3958   return SDValue();
3959 }
3960 
3961 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
3962   SDLoc DL(N);
3963   EVT VT = N->getValueType(0);
3964 
3965   // fold (udiv x, (1 << c)) -> x >>u c
3966   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
3967       DAG.isKnownToBeAPowerOfTwo(N1)) {
3968     SDValue LogBase2 = BuildLogBase2(N1, DL);
3969     AddToWorklist(LogBase2.getNode());
3970 
3971     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
3972     SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
3973     AddToWorklist(Trunc.getNode());
3974     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
3975   }
3976 
3977   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
3978   if (N1.getOpcode() == ISD::SHL) {
3979     SDValue N10 = N1.getOperand(0);
3980     if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
3981         DAG.isKnownToBeAPowerOfTwo(N10)) {
3982       SDValue LogBase2 = BuildLogBase2(N10, DL);
3983       AddToWorklist(LogBase2.getNode());
3984 
3985       EVT ADDVT = N1.getOperand(1).getValueType();
3986       SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
3987       AddToWorklist(Trunc.getNode());
3988       SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
3989       AddToWorklist(Add.getNode());
3990       return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
3991     }
3992   }
3993 
3994   // fold (udiv x, c) -> alternate
3995   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3996   if (isConstantOrConstantVector(N1) &&
3997       !TLI.isIntDivCheap(N->getValueType(0), Attr))
3998     if (SDValue Op = BuildUDIV(N))
3999       return Op;
4000 
4001   return SDValue();
4002 }
4003 
4004 // handles ISD::SREM and ISD::UREM
4005 SDValue DAGCombiner::visitREM(SDNode *N) {
4006   unsigned Opcode = N->getOpcode();
4007   SDValue N0 = N->getOperand(0);
4008   SDValue N1 = N->getOperand(1);
4009   EVT VT = N->getValueType(0);
4010   EVT CCVT = getSetCCResultType(VT);
4011 
4012   bool isSigned = (Opcode == ISD::SREM);
4013   SDLoc DL(N);
4014 
4015   // fold (rem c1, c2) -> c1%c2
4016   ConstantSDNode *N1C = isConstOrConstSplat(N1);
4017   if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4018     return C;
4019 
4020   // fold (urem X, -1) -> select(X == -1, 0, x)
4021   if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue())
4022     return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
4023                          DAG.getConstant(0, DL, VT), N0);
4024 
4025   if (SDValue V = simplifyDivRem(N, DAG))
4026     return V;
4027 
4028   if (SDValue NewSel = foldBinOpIntoSelect(N))
4029     return NewSel;
4030 
4031   if (isSigned) {
4032     // If we know the sign bits of both operands are zero, strength reduce to a
4033     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4034     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
4035       return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
4036   } else {
4037     SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
4038     if (DAG.isKnownToBeAPowerOfTwo(N1)) {
4039       // fold (urem x, pow2) -> (and x, pow2-1)
4040       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4041       AddToWorklist(Add.getNode());
4042       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4043     }
4044     if (N1.getOpcode() == ISD::SHL &&
4045         DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
4046       // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4047       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
4048       AddToWorklist(Add.getNode());
4049       return DAG.getNode(ISD::AND, DL, VT, N0, Add);
4050     }
4051   }
4052 
4053   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4054 
4055   // If X/C can be simplified by the division-by-constant logic, lower
4056   // X%C to the equivalent of X-X/C*C.
4057   // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4058   // speculative DIV must not cause a DIVREM conversion.  We guard against this
4059   // by skipping the simplification if isIntDivCheap().  When div is not cheap,
4060   // combine will not return a DIVREM.  Regardless, checking cheapness here
4061   // makes sense since the simplification results in fatter code.
4062   if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
4063     SDValue OptimizedDiv =
4064         isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
4065     if (OptimizedDiv.getNode()) {
4066       // If the equivalent Div node also exists, update its users.
4067       unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
4068       if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
4069                                                 { N0, N1 }))
4070         CombineTo(DivNode, OptimizedDiv);
4071       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
4072       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
4073       AddToWorklist(OptimizedDiv.getNode());
4074       AddToWorklist(Mul.getNode());
4075       return Sub;
4076     }
4077   }
4078 
4079   // sdiv, srem -> sdivrem
4080   if (SDValue DivRem = useDivRem(N))
4081     return DivRem.getValue(1);
4082 
4083   return SDValue();
4084 }
4085 
4086 SDValue DAGCombiner::visitMULHS(SDNode *N) {
4087   SDValue N0 = N->getOperand(0);
4088   SDValue N1 = N->getOperand(1);
4089   EVT VT = N->getValueType(0);
4090   SDLoc DL(N);
4091 
4092   if (VT.isVector()) {
4093     // fold (mulhs x, 0) -> 0
4094     // do not return N0/N1, because undef node may exist.
4095     if (ISD::isBuildVectorAllZeros(N0.getNode()) ||
4096         ISD::isBuildVectorAllZeros(N1.getNode()))
4097       return DAG.getConstant(0, DL, VT);
4098   }
4099 
4100   // fold (mulhs x, 0) -> 0
4101   if (isNullConstant(N1))
4102     return N1;
4103   // fold (mulhs x, 1) -> (sra x, size(x)-1)
4104   if (isOneConstant(N1))
4105     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
4106                        DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL,
4107                                        getShiftAmountTy(N0.getValueType())));
4108 
4109   // fold (mulhs x, undef) -> 0
4110   if (N0.isUndef() || N1.isUndef())
4111     return DAG.getConstant(0, DL, VT);
4112 
4113   // If the type twice as wide is legal, transform the mulhs to a wider multiply
4114   // plus a shift.
4115   if (VT.isSimple() && !VT.isVector()) {
4116     MVT Simple = VT.getSimpleVT();
4117     unsigned SimpleSize = Simple.getSizeInBits();
4118     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4119     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4120       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
4121       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
4122       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4123       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4124             DAG.getConstant(SimpleSize, DL,
4125                             getShiftAmountTy(N1.getValueType())));
4126       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4127     }
4128   }
4129 
4130   return SDValue();
4131 }
4132 
4133 SDValue DAGCombiner::visitMULHU(SDNode *N) {
4134   SDValue N0 = N->getOperand(0);
4135   SDValue N1 = N->getOperand(1);
4136   EVT VT = N->getValueType(0);
4137   SDLoc DL(N);
4138 
4139   if (VT.isVector()) {
4140     // fold (mulhu x, 0) -> 0
4141     // do not return N0/N1, because undef node may exist.
4142     if (ISD::isBuildVectorAllZeros(N0.getNode()) ||
4143         ISD::isBuildVectorAllZeros(N1.getNode()))
4144       return DAG.getConstant(0, DL, VT);
4145   }
4146 
4147   // fold (mulhu x, 0) -> 0
4148   if (isNullConstant(N1))
4149     return N1;
4150   // fold (mulhu x, 1) -> 0
4151   if (isOneConstant(N1))
4152     return DAG.getConstant(0, DL, N0.getValueType());
4153   // fold (mulhu x, undef) -> 0
4154   if (N0.isUndef() || N1.isUndef())
4155     return DAG.getConstant(0, DL, VT);
4156 
4157   // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4158   if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4159       DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
4160     unsigned NumEltBits = VT.getScalarSizeInBits();
4161     SDValue LogBase2 = BuildLogBase2(N1, DL);
4162     SDValue SRLAmt = DAG.getNode(
4163         ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
4164     EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4165     SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
4166     return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
4167   }
4168 
4169   // If the type twice as wide is legal, transform the mulhu to a wider multiply
4170   // plus a shift.
4171   if (VT.isSimple() && !VT.isVector()) {
4172     MVT Simple = VT.getSimpleVT();
4173     unsigned SimpleSize = Simple.getSizeInBits();
4174     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4175     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4176       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
4177       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
4178       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
4179       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
4180             DAG.getConstant(SimpleSize, DL,
4181                             getShiftAmountTy(N1.getValueType())));
4182       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
4183     }
4184   }
4185 
4186   return SDValue();
4187 }
4188 
4189 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4190 /// give the opcodes for the two computations that are being performed. Return
4191 /// true if a simplification was made.
4192 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
4193                                                 unsigned HiOp) {
4194   // If the high half is not needed, just compute the low half.
4195   bool HiExists = N->hasAnyUseOfValue(1);
4196   if (!HiExists && (!LegalOperations ||
4197                     TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
4198     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4199     return CombineTo(N, Res, Res);
4200   }
4201 
4202   // If the low half is not needed, just compute the high half.
4203   bool LoExists = N->hasAnyUseOfValue(0);
4204   if (!LoExists && (!LegalOperations ||
4205                     TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
4206     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4207     return CombineTo(N, Res, Res);
4208   }
4209 
4210   // If both halves are used, return as it is.
4211   if (LoExists && HiExists)
4212     return SDValue();
4213 
4214   // If the two computed results can be simplified separately, separate them.
4215   if (LoExists) {
4216     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
4217     AddToWorklist(Lo.getNode());
4218     SDValue LoOpt = combine(Lo.getNode());
4219     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
4220         (!LegalOperations ||
4221          TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
4222       return CombineTo(N, LoOpt, LoOpt);
4223   }
4224 
4225   if (HiExists) {
4226     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
4227     AddToWorklist(Hi.getNode());
4228     SDValue HiOpt = combine(Hi.getNode());
4229     if (HiOpt.getNode() && HiOpt != Hi &&
4230         (!LegalOperations ||
4231          TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
4232       return CombineTo(N, HiOpt, HiOpt);
4233   }
4234 
4235   return SDValue();
4236 }
4237 
4238 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
4239   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
4240     return Res;
4241 
4242   EVT VT = N->getValueType(0);
4243   SDLoc DL(N);
4244 
4245   // If the type is twice as wide is legal, transform the mulhu to a wider
4246   // multiply plus a shift.
4247   if (VT.isSimple() && !VT.isVector()) {
4248     MVT Simple = VT.getSimpleVT();
4249     unsigned SimpleSize = Simple.getSizeInBits();
4250     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4251     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4252       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
4253       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
4254       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4255       // Compute the high part as N1.
4256       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4257             DAG.getConstant(SimpleSize, DL,
4258                             getShiftAmountTy(Lo.getValueType())));
4259       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4260       // Compute the low part as N0.
4261       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4262       return CombineTo(N, Lo, Hi);
4263     }
4264   }
4265 
4266   return SDValue();
4267 }
4268 
4269 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
4270   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
4271     return Res;
4272 
4273   EVT VT = N->getValueType(0);
4274   SDLoc DL(N);
4275 
4276   // (umul_lohi N0, 0) -> (0, 0)
4277   if (isNullConstant(N->getOperand(1))) {
4278     SDValue Zero = DAG.getConstant(0, DL, VT);
4279     return CombineTo(N, Zero, Zero);
4280   }
4281 
4282   // (umul_lohi N0, 1) -> (N0, 0)
4283   if (isOneConstant(N->getOperand(1))) {
4284     SDValue Zero = DAG.getConstant(0, DL, VT);
4285     return CombineTo(N, N->getOperand(0), Zero);
4286   }
4287 
4288   // If the type is twice as wide is legal, transform the mulhu to a wider
4289   // multiply plus a shift.
4290   if (VT.isSimple() && !VT.isVector()) {
4291     MVT Simple = VT.getSimpleVT();
4292     unsigned SimpleSize = Simple.getSizeInBits();
4293     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
4294     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
4295       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
4296       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
4297       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
4298       // Compute the high part as N1.
4299       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
4300             DAG.getConstant(SimpleSize, DL,
4301                             getShiftAmountTy(Lo.getValueType())));
4302       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
4303       // Compute the low part as N0.
4304       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
4305       return CombineTo(N, Lo, Hi);
4306     }
4307   }
4308 
4309   return SDValue();
4310 }
4311 
4312 SDValue DAGCombiner::visitMULO(SDNode *N) {
4313   SDValue N0 = N->getOperand(0);
4314   SDValue N1 = N->getOperand(1);
4315   EVT VT = N0.getValueType();
4316   bool IsSigned = (ISD::SMULO == N->getOpcode());
4317 
4318   EVT CarryVT = N->getValueType(1);
4319   SDLoc DL(N);
4320 
4321   // canonicalize constant to RHS.
4322   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4323       !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4324     return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
4325 
4326   // fold (mulo x, 0) -> 0 + no carry out
4327   if (isNullOrNullSplat(N1))
4328     return CombineTo(N, DAG.getConstant(0, DL, VT),
4329                      DAG.getConstant(0, DL, CarryVT));
4330 
4331   // (mulo x, 2) -> (addo x, x)
4332   if (ConstantSDNode *C2 = isConstOrConstSplat(N1))
4333     if (C2->getAPIntValue() == 2)
4334       return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
4335                          N->getVTList(), N0, N0);
4336 
4337   return SDValue();
4338 }
4339 
4340 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
4341   SDValue N0 = N->getOperand(0);
4342   SDValue N1 = N->getOperand(1);
4343   EVT VT = N0.getValueType();
4344   unsigned Opcode = N->getOpcode();
4345 
4346   // fold vector ops
4347   if (VT.isVector())
4348     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4349       return FoldedVOp;
4350 
4351   // fold operation with constant operands.
4352   if (SDValue C = DAG.FoldConstantArithmetic(Opcode, SDLoc(N), VT, {N0, N1}))
4353     return C;
4354 
4355   // canonicalize constant to RHS
4356   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4357       !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4358     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
4359 
4360   // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4361   // Only do this if the current op isn't legal and the flipped is.
4362   if (!TLI.isOperationLegal(Opcode, VT) &&
4363       (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
4364       (N1.isUndef() || DAG.SignBitIsZero(N1))) {
4365     unsigned AltOpcode;
4366     switch (Opcode) {
4367     case ISD::SMIN: AltOpcode = ISD::UMIN; break;
4368     case ISD::SMAX: AltOpcode = ISD::UMAX; break;
4369     case ISD::UMIN: AltOpcode = ISD::SMIN; break;
4370     case ISD::UMAX: AltOpcode = ISD::SMAX; break;
4371     default: llvm_unreachable("Unknown MINMAX opcode");
4372     }
4373     if (TLI.isOperationLegal(AltOpcode, VT))
4374       return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1);
4375   }
4376 
4377   return SDValue();
4378 }
4379 
4380 /// If this is a bitwise logic instruction and both operands have the same
4381 /// opcode, try to sink the other opcode after the logic instruction.
4382 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
4383   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
4384   EVT VT = N0.getValueType();
4385   unsigned LogicOpcode = N->getOpcode();
4386   unsigned HandOpcode = N0.getOpcode();
4387   assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
4388           LogicOpcode == ISD::XOR) && "Expected logic opcode");
4389   assert(HandOpcode == N1.getOpcode() && "Bad input!");
4390 
4391   // Bail early if none of these transforms apply.
4392   if (N0.getNumOperands() == 0)
4393     return SDValue();
4394 
4395   // FIXME: We should check number of uses of the operands to not increase
4396   //        the instruction count for all transforms.
4397 
4398   // Handle size-changing casts.
4399   SDValue X = N0.getOperand(0);
4400   SDValue Y = N1.getOperand(0);
4401   EVT XVT = X.getValueType();
4402   SDLoc DL(N);
4403   if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
4404       HandOpcode == ISD::SIGN_EXTEND) {
4405     // If both operands have other uses, this transform would create extra
4406     // instructions without eliminating anything.
4407     if (!N0.hasOneUse() && !N1.hasOneUse())
4408       return SDValue();
4409     // We need matching integer source types.
4410     if (XVT != Y.getValueType())
4411       return SDValue();
4412     // Don't create an illegal op during or after legalization. Don't ever
4413     // create an unsupported vector op.
4414     if ((VT.isVector() || LegalOperations) &&
4415         !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
4416       return SDValue();
4417     // Avoid infinite looping with PromoteIntBinOp.
4418     // TODO: Should we apply desirable/legal constraints to all opcodes?
4419     if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
4420         !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
4421       return SDValue();
4422     // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
4423     SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4424     return DAG.getNode(HandOpcode, DL, VT, Logic);
4425   }
4426 
4427   // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
4428   if (HandOpcode == ISD::TRUNCATE) {
4429     // If both operands have other uses, this transform would create extra
4430     // instructions without eliminating anything.
4431     if (!N0.hasOneUse() && !N1.hasOneUse())
4432       return SDValue();
4433     // We need matching source types.
4434     if (XVT != Y.getValueType())
4435       return SDValue();
4436     // Don't create an illegal op during or after legalization.
4437     if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
4438       return SDValue();
4439     // Be extra careful sinking truncate. If it's free, there's no benefit in
4440     // widening a binop. Also, don't create a logic op on an illegal type.
4441     if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
4442       return SDValue();
4443     if (!TLI.isTypeLegal(XVT))
4444       return SDValue();
4445     SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4446     return DAG.getNode(HandOpcode, DL, VT, Logic);
4447   }
4448 
4449   // For binops SHL/SRL/SRA/AND:
4450   //   logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
4451   if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
4452        HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
4453       N0.getOperand(1) == N1.getOperand(1)) {
4454     // If either operand has other uses, this transform is not an improvement.
4455     if (!N0.hasOneUse() || !N1.hasOneUse())
4456       return SDValue();
4457     SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4458     return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
4459   }
4460 
4461   // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
4462   if (HandOpcode == ISD::BSWAP) {
4463     // If either operand has other uses, this transform is not an improvement.
4464     if (!N0.hasOneUse() || !N1.hasOneUse())
4465       return SDValue();
4466     SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4467     return DAG.getNode(HandOpcode, DL, VT, Logic);
4468   }
4469 
4470   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4471   // Only perform this optimization up until type legalization, before
4472   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4473   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4474   // we don't want to undo this promotion.
4475   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4476   // on scalars.
4477   if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
4478        Level <= AfterLegalizeTypes) {
4479     // Input types must be integer and the same.
4480     if (XVT.isInteger() && XVT == Y.getValueType() &&
4481         !(VT.isVector() && TLI.isTypeLegal(VT) &&
4482           !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
4483       SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
4484       return DAG.getNode(HandOpcode, DL, VT, Logic);
4485     }
4486   }
4487 
4488   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4489   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4490   // If both shuffles use the same mask, and both shuffle within a single
4491   // vector, then it is worthwhile to move the swizzle after the operation.
4492   // The type-legalizer generates this pattern when loading illegal
4493   // vector types from memory. In many cases this allows additional shuffle
4494   // optimizations.
4495   // There are other cases where moving the shuffle after the xor/and/or
4496   // is profitable even if shuffles don't perform a swizzle.
4497   // If both shuffles use the same mask, and both shuffles have the same first
4498   // or second operand, then it might still be profitable to move the shuffle
4499   // after the xor/and/or operation.
4500   if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
4501     auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
4502     auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
4503     assert(X.getValueType() == Y.getValueType() &&
4504            "Inputs to shuffles are not the same type");
4505 
4506     // Check that both shuffles use the same mask. The masks are known to be of
4507     // the same length because the result vector type is the same.
4508     // Check also that shuffles have only one use to avoid introducing extra
4509     // instructions.
4510     if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
4511         !SVN0->getMask().equals(SVN1->getMask()))
4512       return SDValue();
4513 
4514     // Don't try to fold this node if it requires introducing a
4515     // build vector of all zeros that might be illegal at this stage.
4516     SDValue ShOp = N0.getOperand(1);
4517     if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4518       ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4519 
4520     // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4521     if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
4522       SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
4523                                   N0.getOperand(0), N1.getOperand(0));
4524       return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
4525     }
4526 
4527     // Don't try to fold this node if it requires introducing a
4528     // build vector of all zeros that might be illegal at this stage.
4529     ShOp = N0.getOperand(0);
4530     if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
4531       ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4532 
4533     // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4534     if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
4535       SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
4536                                   N1.getOperand(1));
4537       return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
4538     }
4539   }
4540 
4541   return SDValue();
4542 }
4543 
4544 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4545 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
4546                                        const SDLoc &DL) {
4547   SDValue LL, LR, RL, RR, N0CC, N1CC;
4548   if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
4549       !isSetCCEquivalent(N1, RL, RR, N1CC))
4550     return SDValue();
4551 
4552   assert(N0.getValueType() == N1.getValueType() &&
4553          "Unexpected operand types for bitwise logic op");
4554   assert(LL.getValueType() == LR.getValueType() &&
4555          RL.getValueType() == RR.getValueType() &&
4556          "Unexpected operand types for setcc");
4557 
4558   // If we're here post-legalization or the logic op type is not i1, the logic
4559   // op type must match a setcc result type. Also, all folds require new
4560   // operations on the left and right operands, so those types must match.
4561   EVT VT = N0.getValueType();
4562   EVT OpVT = LL.getValueType();
4563   if (LegalOperations || VT.getScalarType() != MVT::i1)
4564     if (VT != getSetCCResultType(OpVT))
4565       return SDValue();
4566   if (OpVT != RL.getValueType())
4567     return SDValue();
4568 
4569   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
4570   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
4571   bool IsInteger = OpVT.isInteger();
4572   if (LR == RR && CC0 == CC1 && IsInteger) {
4573     bool IsZero = isNullOrNullSplat(LR);
4574     bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
4575 
4576     // All bits clear?
4577     bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
4578     // All sign bits clear?
4579     bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
4580     // Any bits set?
4581     bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
4582     // Any sign bits set?
4583     bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
4584 
4585     // (and (seteq X,  0), (seteq Y,  0)) --> (seteq (or X, Y),  0)
4586     // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4587     // (or  (setne X,  0), (setne Y,  0)) --> (setne (or X, Y),  0)
4588     // (or  (setlt X,  0), (setlt Y,  0)) --> (setlt (or X, Y),  0)
4589     if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
4590       SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
4591       AddToWorklist(Or.getNode());
4592       return DAG.getSetCC(DL, VT, Or, LR, CC1);
4593     }
4594 
4595     // All bits set?
4596     bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
4597     // All sign bits set?
4598     bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
4599     // Any bits clear?
4600     bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
4601     // Any sign bits clear?
4602     bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
4603 
4604     // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
4605     // (and (setlt X,  0), (setlt Y,  0)) --> (setlt (and X, Y),  0)
4606     // (or  (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
4607     // (or  (setgt X, -1), (setgt Y  -1)) --> (setgt (and X, Y), -1)
4608     if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
4609       SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
4610       AddToWorklist(And.getNode());
4611       return DAG.getSetCC(DL, VT, And, LR, CC1);
4612     }
4613   }
4614 
4615   // TODO: What is the 'or' equivalent of this fold?
4616   // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
4617   if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
4618       IsInteger && CC0 == ISD::SETNE &&
4619       ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
4620        (isAllOnesConstant(LR) && isNullConstant(RR)))) {
4621     SDValue One = DAG.getConstant(1, DL, OpVT);
4622     SDValue Two = DAG.getConstant(2, DL, OpVT);
4623     SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
4624     AddToWorklist(Add.getNode());
4625     return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
4626   }
4627 
4628   // Try more general transforms if the predicates match and the only user of
4629   // the compares is the 'and' or 'or'.
4630   if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
4631       N0.hasOneUse() && N1.hasOneUse()) {
4632     // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
4633     // or  (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
4634     if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
4635       SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
4636       SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
4637       SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
4638       SDValue Zero = DAG.getConstant(0, DL, OpVT);
4639       return DAG.getSetCC(DL, VT, Or, Zero, CC1);
4640     }
4641 
4642     // Turn compare of constants whose difference is 1 bit into add+and+setcc.
4643     // TODO - support non-uniform vector amounts.
4644     if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
4645       // Match a shared variable operand and 2 non-opaque constant operands.
4646       ConstantSDNode *C0 = isConstOrConstSplat(LR);
4647       ConstantSDNode *C1 = isConstOrConstSplat(RR);
4648       if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
4649         // Canonicalize larger constant as C0.
4650         if (C1->getAPIntValue().ugt(C0->getAPIntValue()))
4651           std::swap(C0, C1);
4652 
4653         // The difference of the constants must be a single bit.
4654         const APInt &C0Val = C0->getAPIntValue();
4655         const APInt &C1Val = C1->getAPIntValue();
4656         if ((C0Val - C1Val).isPowerOf2()) {
4657           // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) -->
4658           // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq
4659           SDValue OffsetC = DAG.getConstant(-C1Val, DL, OpVT);
4660           SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LL, OffsetC);
4661           SDValue MaskC = DAG.getConstant(~(C0Val - C1Val), DL, OpVT);
4662           SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Add, MaskC);
4663           SDValue Zero = DAG.getConstant(0, DL, OpVT);
4664           return DAG.getSetCC(DL, VT, And, Zero, CC0);
4665         }
4666       }
4667     }
4668   }
4669 
4670   // Canonicalize equivalent operands to LL == RL.
4671   if (LL == RR && LR == RL) {
4672     CC1 = ISD::getSetCCSwappedOperands(CC1);
4673     std::swap(RL, RR);
4674   }
4675 
4676   // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4677   // (or  (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4678   if (LL == RL && LR == RR) {
4679     ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
4680                                 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
4681     if (NewCC != ISD::SETCC_INVALID &&
4682         (!LegalOperations ||
4683          (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
4684           TLI.isOperationLegal(ISD::SETCC, OpVT))))
4685       return DAG.getSetCC(DL, VT, LL, LR, NewCC);
4686   }
4687 
4688   return SDValue();
4689 }
4690 
4691 /// This contains all DAGCombine rules which reduce two values combined by
4692 /// an And operation to a single value. This makes them reusable in the context
4693 /// of visitSELECT(). Rules involving constants are not included as
4694 /// visitSELECT() already handles those cases.
4695 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
4696   EVT VT = N1.getValueType();
4697   SDLoc DL(N);
4698 
4699   // fold (and x, undef) -> 0
4700   if (N0.isUndef() || N1.isUndef())
4701     return DAG.getConstant(0, DL, VT);
4702 
4703   if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
4704     return V;
4705 
4706   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
4707       VT.getSizeInBits() <= 64) {
4708     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4709       if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
4710         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
4711         // immediate for an add, but it is legal if its top c2 bits are set,
4712         // transform the ADD so the immediate doesn't need to be materialized
4713         // in a register.
4714         APInt ADDC = ADDI->getAPIntValue();
4715         APInt SRLC = SRLI->getAPIntValue();
4716         if (ADDC.getMinSignedBits() <= 64 &&
4717             SRLC.ult(VT.getSizeInBits()) &&
4718             !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4719           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
4720                                              SRLC.getZExtValue());
4721           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
4722             ADDC |= Mask;
4723             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
4724               SDLoc DL0(N0);
4725               SDValue NewAdd =
4726                 DAG.getNode(ISD::ADD, DL0, VT,
4727                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
4728               CombineTo(N0.getNode(), NewAdd);
4729               // Return N so it doesn't get rechecked!
4730               return SDValue(N, 0);
4731             }
4732           }
4733         }
4734       }
4735     }
4736   }
4737 
4738   // Reduce bit extract of low half of an integer to the narrower type.
4739   // (and (srl i64:x, K), KMask) ->
4740   //   (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
4741   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4742     if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
4743       if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4744         unsigned Size = VT.getSizeInBits();
4745         const APInt &AndMask = CAnd->getAPIntValue();
4746         unsigned ShiftBits = CShift->getZExtValue();
4747 
4748         // Bail out, this node will probably disappear anyway.
4749         if (ShiftBits == 0)
4750           return SDValue();
4751 
4752         unsigned MaskBits = AndMask.countTrailingOnes();
4753         EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
4754 
4755         if (AndMask.isMask() &&
4756             // Required bits must not span the two halves of the integer and
4757             // must fit in the half size type.
4758             (ShiftBits + MaskBits <= Size / 2) &&
4759             TLI.isNarrowingProfitable(VT, HalfVT) &&
4760             TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
4761             TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
4762             TLI.isTruncateFree(VT, HalfVT) &&
4763             TLI.isZExtFree(HalfVT, VT)) {
4764           // The isNarrowingProfitable is to avoid regressions on PPC and
4765           // AArch64 which match a few 64-bit bit insert / bit extract patterns
4766           // on downstream users of this. Those patterns could probably be
4767           // extended to handle extensions mixed in.
4768 
4769           SDValue SL(N0);
4770           assert(MaskBits <= Size);
4771 
4772           // Extracting the highest bit of the low half.
4773           EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
4774           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
4775                                       N0.getOperand(0));
4776 
4777           SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
4778           SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
4779           SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
4780           SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
4781           return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
4782         }
4783       }
4784     }
4785   }
4786 
4787   return SDValue();
4788 }
4789 
4790 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
4791                                    EVT LoadResultTy, EVT &ExtVT) {
4792   if (!AndC->getAPIntValue().isMask())
4793     return false;
4794 
4795   unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
4796 
4797   ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4798   EVT LoadedVT = LoadN->getMemoryVT();
4799 
4800   if (ExtVT == LoadedVT &&
4801       (!LegalOperations ||
4802        TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
4803     // ZEXTLOAD will match without needing to change the size of the value being
4804     // loaded.
4805     return true;
4806   }
4807 
4808   // Do not change the width of a volatile or atomic loads.
4809   if (!LoadN->isSimple())
4810     return false;
4811 
4812   // Do not generate loads of non-round integer types since these can
4813   // be expensive (and would be wrong if the type is not byte sized).
4814   if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
4815     return false;
4816 
4817   if (LegalOperations &&
4818       !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
4819     return false;
4820 
4821   if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
4822     return false;
4823 
4824   return true;
4825 }
4826 
4827 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
4828                                     ISD::LoadExtType ExtType, EVT &MemVT,
4829                                     unsigned ShAmt) {
4830   if (!LDST)
4831     return false;
4832   // Only allow byte offsets.
4833   if (ShAmt % 8)
4834     return false;
4835 
4836   // Do not generate loads of non-round integer types since these can
4837   // be expensive (and would be wrong if the type is not byte sized).
4838   if (!MemVT.isRound())
4839     return false;
4840 
4841   // Don't change the width of a volatile or atomic loads.
4842   if (!LDST->isSimple())
4843     return false;
4844 
4845   // Verify that we are actually reducing a load width here.
4846   if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits())
4847     return false;
4848 
4849   // Ensure that this isn't going to produce an unsupported memory access.
4850   if (ShAmt &&
4851       !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4852                               LDST->getAddressSpace(), ShAmt / 8,
4853                               LDST->getMemOperand()->getFlags()))
4854     return false;
4855 
4856   // It's not possible to generate a constant of extended or untyped type.
4857   EVT PtrType = LDST->getBasePtr().getValueType();
4858   if (PtrType == MVT::Untyped || PtrType.isExtended())
4859     return false;
4860 
4861   if (isa<LoadSDNode>(LDST)) {
4862     LoadSDNode *Load = cast<LoadSDNode>(LDST);
4863     // Don't transform one with multiple uses, this would require adding a new
4864     // load.
4865     if (!SDValue(Load, 0).hasOneUse())
4866       return false;
4867 
4868     if (LegalOperations &&
4869         !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
4870       return false;
4871 
4872     // For the transform to be legal, the load must produce only two values
4873     // (the value loaded and the chain).  Don't transform a pre-increment
4874     // load, for example, which produces an extra value.  Otherwise the
4875     // transformation is not equivalent, and the downstream logic to replace
4876     // uses gets things wrong.
4877     if (Load->getNumValues() > 2)
4878       return false;
4879 
4880     // If the load that we're shrinking is an extload and we're not just
4881     // discarding the extension we can't simply shrink the load. Bail.
4882     // TODO: It would be possible to merge the extensions in some cases.
4883     if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
4884         Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4885       return false;
4886 
4887     if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
4888       return false;
4889   } else {
4890     assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
4891     StoreSDNode *Store = cast<StoreSDNode>(LDST);
4892     // Can't write outside the original store
4893     if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
4894       return false;
4895 
4896     if (LegalOperations &&
4897         !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
4898       return false;
4899   }
4900   return true;
4901 }
4902 
4903 bool DAGCombiner::SearchForAndLoads(SDNode *N,
4904                                     SmallVectorImpl<LoadSDNode*> &Loads,
4905                                     SmallPtrSetImpl<SDNode*> &NodesWithConsts,
4906                                     ConstantSDNode *Mask,
4907                                     SDNode *&NodeToMask) {
4908   // Recursively search for the operands, looking for loads which can be
4909   // narrowed.
4910   for (SDValue Op : N->op_values()) {
4911     if (Op.getValueType().isVector())
4912       return false;
4913 
4914     // Some constants may need fixing up later if they are too large.
4915     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4916       if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
4917           (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
4918         NodesWithConsts.insert(N);
4919       continue;
4920     }
4921 
4922     if (!Op.hasOneUse())
4923       return false;
4924 
4925     switch(Op.getOpcode()) {
4926     case ISD::LOAD: {
4927       auto *Load = cast<LoadSDNode>(Op);
4928       EVT ExtVT;
4929       if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
4930           isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
4931 
4932         // ZEXTLOAD is already small enough.
4933         if (Load->getExtensionType() == ISD::ZEXTLOAD &&
4934             ExtVT.bitsGE(Load->getMemoryVT()))
4935           continue;
4936 
4937         // Use LE to convert equal sized loads to zext.
4938         if (ExtVT.bitsLE(Load->getMemoryVT()))
4939           Loads.push_back(Load);
4940 
4941         continue;
4942       }
4943       return false;
4944     }
4945     case ISD::ZERO_EXTEND:
4946     case ISD::AssertZext: {
4947       unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
4948       EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
4949       EVT VT = Op.getOpcode() == ISD::AssertZext ?
4950         cast<VTSDNode>(Op.getOperand(1))->getVT() :
4951         Op.getOperand(0).getValueType();
4952 
4953       // We can accept extending nodes if the mask is wider or an equal
4954       // width to the original type.
4955       if (ExtVT.bitsGE(VT))
4956         continue;
4957       break;
4958     }
4959     case ISD::OR:
4960     case ISD::XOR:
4961     case ISD::AND:
4962       if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
4963                              NodeToMask))
4964         return false;
4965       continue;
4966     }
4967 
4968     // Allow one node which will masked along with any loads found.
4969     if (NodeToMask)
4970       return false;
4971 
4972     // Also ensure that the node to be masked only produces one data result.
4973     NodeToMask = Op.getNode();
4974     if (NodeToMask->getNumValues() > 1) {
4975       bool HasValue = false;
4976       for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
4977         MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
4978         if (VT != MVT::Glue && VT != MVT::Other) {
4979           if (HasValue) {
4980             NodeToMask = nullptr;
4981             return false;
4982           }
4983           HasValue = true;
4984         }
4985       }
4986       assert(HasValue && "Node to be masked has no data result?");
4987     }
4988   }
4989   return true;
4990 }
4991 
4992 bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
4993   auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
4994   if (!Mask)
4995     return false;
4996 
4997   if (!Mask->getAPIntValue().isMask())
4998     return false;
4999 
5000   // No need to do anything if the and directly uses a load.
5001   if (isa<LoadSDNode>(N->getOperand(0)))
5002     return false;
5003 
5004   SmallVector<LoadSDNode*, 8> Loads;
5005   SmallPtrSet<SDNode*, 2> NodesWithConsts;
5006   SDNode *FixupNode = nullptr;
5007   if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
5008     if (Loads.size() == 0)
5009       return false;
5010 
5011     LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
5012     SDValue MaskOp = N->getOperand(1);
5013 
5014     // If it exists, fixup the single node we allow in the tree that needs
5015     // masking.
5016     if (FixupNode) {
5017       LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
5018       SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
5019                                 FixupNode->getValueType(0),
5020                                 SDValue(FixupNode, 0), MaskOp);
5021       DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
5022       if (And.getOpcode() == ISD ::AND)
5023         DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
5024     }
5025 
5026     // Narrow any constants that need it.
5027     for (auto *LogicN : NodesWithConsts) {
5028       SDValue Op0 = LogicN->getOperand(0);
5029       SDValue Op1 = LogicN->getOperand(1);
5030 
5031       if (isa<ConstantSDNode>(Op0))
5032           std::swap(Op0, Op1);
5033 
5034       SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
5035                                 Op1, MaskOp);
5036 
5037       DAG.UpdateNodeOperands(LogicN, Op0, And);
5038     }
5039 
5040     // Create narrow loads.
5041     for (auto *Load : Loads) {
5042       LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
5043       SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
5044                                 SDValue(Load, 0), MaskOp);
5045       DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
5046       if (And.getOpcode() == ISD ::AND)
5047         And = SDValue(
5048             DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
5049       SDValue NewLoad = ReduceLoadWidth(And.getNode());
5050       assert(NewLoad &&
5051              "Shouldn't be masking the load if it can't be narrowed");
5052       CombineTo(Load, NewLoad, NewLoad.getValue(1));
5053     }
5054     DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
5055     return true;
5056   }
5057   return false;
5058 }
5059 
5060 // Unfold
5061 //    x &  (-1 'logical shift' y)
5062 // To
5063 //    (x 'opposite logical shift' y) 'logical shift' y
5064 // if it is better for performance.
5065 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
5066   assert(N->getOpcode() == ISD::AND);
5067 
5068   SDValue N0 = N->getOperand(0);
5069   SDValue N1 = N->getOperand(1);
5070 
5071   // Do we actually prefer shifts over mask?
5072   if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
5073     return SDValue();
5074 
5075   // Try to match  (-1 '[outer] logical shift' y)
5076   unsigned OuterShift;
5077   unsigned InnerShift; // The opposite direction to the OuterShift.
5078   SDValue Y;           // Shift amount.
5079   auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
5080     if (!M.hasOneUse())
5081       return false;
5082     OuterShift = M->getOpcode();
5083     if (OuterShift == ISD::SHL)
5084       InnerShift = ISD::SRL;
5085     else if (OuterShift == ISD::SRL)
5086       InnerShift = ISD::SHL;
5087     else
5088       return false;
5089     if (!isAllOnesConstant(M->getOperand(0)))
5090       return false;
5091     Y = M->getOperand(1);
5092     return true;
5093   };
5094 
5095   SDValue X;
5096   if (matchMask(N1))
5097     X = N0;
5098   else if (matchMask(N0))
5099     X = N1;
5100   else
5101     return SDValue();
5102 
5103   SDLoc DL(N);
5104   EVT VT = N->getValueType(0);
5105 
5106   //     tmp = x   'opposite logical shift' y
5107   SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
5108   //     ret = tmp 'logical shift' y
5109   SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
5110 
5111   return T1;
5112 }
5113 
5114 /// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
5115 /// For a target with a bit test, this is expected to become test + set and save
5116 /// at least 1 instruction.
5117 static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) {
5118   assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
5119 
5120   // This is probably not worthwhile without a supported type.
5121   EVT VT = And->getValueType(0);
5122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5123   if (!TLI.isTypeLegal(VT))
5124     return SDValue();
5125 
5126   // Look through an optional extension and find a 'not'.
5127   // TODO: Should we favor test+set even without the 'not' op?
5128   SDValue Not = And->getOperand(0), And1 = And->getOperand(1);
5129   if (Not.getOpcode() == ISD::ANY_EXTEND)
5130     Not = Not.getOperand(0);
5131   if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1))
5132     return SDValue();
5133 
5134   // Look though an optional truncation. The source operand may not be the same
5135   // type as the original 'and', but that is ok because we are masking off
5136   // everything but the low bit.
5137   SDValue Srl = Not.getOperand(0);
5138   if (Srl.getOpcode() == ISD::TRUNCATE)
5139     Srl = Srl.getOperand(0);
5140 
5141   // Match a shift-right by constant.
5142   if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() ||
5143       !isa<ConstantSDNode>(Srl.getOperand(1)))
5144     return SDValue();
5145 
5146   // We might have looked through casts that make this transform invalid.
5147   // TODO: If the source type is wider than the result type, do the mask and
5148   //       compare in the source type.
5149   const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1);
5150   unsigned VTBitWidth = VT.getSizeInBits();
5151   if (ShiftAmt.uge(VTBitWidth))
5152     return SDValue();
5153 
5154   // Turn this into a bit-test pattern using mask op + setcc:
5155   // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
5156   SDLoc DL(And);
5157   SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT);
5158   EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5159   SDValue Mask = DAG.getConstant(
5160       APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT);
5161   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask);
5162   SDValue Zero = DAG.getConstant(0, DL, VT);
5163   SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
5164   return DAG.getZExtOrTrunc(Setcc, DL, VT);
5165 }
5166 
5167 SDValue DAGCombiner::visitAND(SDNode *N) {
5168   SDValue N0 = N->getOperand(0);
5169   SDValue N1 = N->getOperand(1);
5170   EVT VT = N1.getValueType();
5171 
5172   // x & x --> x
5173   if (N0 == N1)
5174     return N0;
5175 
5176   // fold vector ops
5177   if (VT.isVector()) {
5178     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5179       return FoldedVOp;
5180 
5181     // fold (and x, 0) -> 0, vector edition
5182     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5183       // do not return N0, because undef node may exist in N0
5184       return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
5185                              SDLoc(N), N0.getValueType());
5186     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5187       // do not return N1, because undef node may exist in N1
5188       return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
5189                              SDLoc(N), N1.getValueType());
5190 
5191     // fold (and x, -1) -> x, vector edition
5192     if (ISD::isBuildVectorAllOnes(N0.getNode()))
5193       return N1;
5194     if (ISD::isBuildVectorAllOnes(N1.getNode()))
5195       return N0;
5196   }
5197 
5198   // fold (and c1, c2) -> c1&c2
5199   ConstantSDNode *N1C = isConstOrConstSplat(N1);
5200   if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1}))
5201     return C;
5202 
5203   // canonicalize constant to RHS
5204   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5205       !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5206     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
5207 
5208   // fold (and x, -1) -> x
5209   if (isAllOnesConstant(N1))
5210     return N0;
5211 
5212   // if (and x, c) is known to be zero, return 0
5213   unsigned BitWidth = VT.getScalarSizeInBits();
5214   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5215                                    APInt::getAllOnesValue(BitWidth)))
5216     return DAG.getConstant(0, SDLoc(N), VT);
5217 
5218   if (SDValue NewSel = foldBinOpIntoSelect(N))
5219     return NewSel;
5220 
5221   // reassociate and
5222   if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
5223     return RAND;
5224 
5225   // Try to convert a constant mask AND into a shuffle clear mask.
5226   if (VT.isVector())
5227     if (SDValue Shuffle = XformToShuffleWithZero(N))
5228       return Shuffle;
5229 
5230   if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N))
5231     return Combined;
5232 
5233   // fold (and (or x, C), D) -> D if (C & D) == D
5234   auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
5235     return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
5236   };
5237   if (N0.getOpcode() == ISD::OR &&
5238       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
5239     return N1;
5240   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5241   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5242     SDValue N0Op0 = N0.getOperand(0);
5243     APInt Mask = ~N1C->getAPIntValue();
5244     Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
5245     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
5246       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
5247                                  N0.getValueType(), N0Op0);
5248 
5249       // Replace uses of the AND with uses of the Zero extend node.
5250       CombineTo(N, Zext);
5251 
5252       // We actually want to replace all uses of the any_extend with the
5253       // zero_extend, to avoid duplicating things.  This will later cause this
5254       // AND to be folded.
5255       CombineTo(N0.getNode(), Zext);
5256       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5257     }
5258   }
5259 
5260   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5261   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5262   // already be zero by virtue of the width of the base type of the load.
5263   //
5264   // the 'X' node here can either be nothing or an extract_vector_elt to catch
5265   // more cases.
5266   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5267        N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
5268        N0.getOperand(0).getOpcode() == ISD::LOAD &&
5269        N0.getOperand(0).getResNo() == 0) ||
5270       (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
5271     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
5272                                          N0 : N0.getOperand(0) );
5273 
5274     // Get the constant (if applicable) the zero'th operand is being ANDed with.
5275     // This can be a pure constant or a vector splat, in which case we treat the
5276     // vector as a scalar and use the splat value.
5277     APInt Constant = APInt::getNullValue(1);
5278     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
5279       Constant = C->getAPIntValue();
5280     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
5281       APInt SplatValue, SplatUndef;
5282       unsigned SplatBitSize;
5283       bool HasAnyUndefs;
5284       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
5285                                              SplatBitSize, HasAnyUndefs);
5286       if (IsSplat) {
5287         // Undef bits can contribute to a possible optimisation if set, so
5288         // set them.
5289         SplatValue |= SplatUndef;
5290 
5291         // The splat value may be something like "0x00FFFFFF", which means 0 for
5292         // the first vector value and FF for the rest, repeating. We need a mask
5293         // that will apply equally to all members of the vector, so AND all the
5294         // lanes of the constant together.
5295         unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
5296 
5297         // If the splat value has been compressed to a bitlength lower
5298         // than the size of the vector lane, we need to re-expand it to
5299         // the lane size.
5300         if (EltBitWidth > SplatBitSize)
5301           for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
5302                SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
5303             SplatValue |= SplatValue.shl(SplatBitSize);
5304 
5305         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5306         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5307         if ((SplatBitSize % EltBitWidth) == 0) {
5308           Constant = APInt::getAllOnesValue(EltBitWidth);
5309           for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
5310             Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
5311         }
5312       }
5313     }
5314 
5315     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
5316     // actually legal and isn't going to get expanded, else this is a false
5317     // optimisation.
5318     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
5319                                                     Load->getValueType(0),
5320                                                     Load->getMemoryVT());
5321 
5322     // Resize the constant to the same size as the original memory access before
5323     // extension. If it is still the AllOnesValue then this AND is completely
5324     // unneeded.
5325     Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
5326 
5327     bool B;
5328     switch (Load->getExtensionType()) {
5329     default: B = false; break;
5330     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
5331     case ISD::ZEXTLOAD:
5332     case ISD::NON_EXTLOAD: B = true; break;
5333     }
5334 
5335     if (B && Constant.isAllOnesValue()) {
5336       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
5337       // preserve semantics once we get rid of the AND.
5338       SDValue NewLoad(Load, 0);
5339 
5340       // Fold the AND away. NewLoad may get replaced immediately.
5341       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
5342 
5343       if (Load->getExtensionType() == ISD::EXTLOAD) {
5344         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
5345                               Load->getValueType(0), SDLoc(Load),
5346                               Load->getChain(), Load->getBasePtr(),
5347                               Load->getOffset(), Load->getMemoryVT(),
5348                               Load->getMemOperand());
5349         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
5350         if (Load->getNumValues() == 3) {
5351           // PRE/POST_INC loads have 3 values.
5352           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
5353                            NewLoad.getValue(2) };
5354           CombineTo(Load, To, 3, true);
5355         } else {
5356           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
5357         }
5358       }
5359 
5360       return SDValue(N, 0); // Return N so it doesn't get rechecked!
5361     }
5362   }
5363 
5364   // fold (and (load x), 255) -> (zextload x, i8)
5365   // fold (and (extload x, i16), 255) -> (zextload x, i8)
5366   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
5367   if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
5368                                 (N0.getOpcode() == ISD::ANY_EXTEND &&
5369                                  N0.getOperand(0).getOpcode() == ISD::LOAD))) {
5370     if (SDValue Res = ReduceLoadWidth(N)) {
5371       LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
5372         ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
5373       AddToWorklist(N);
5374       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res);
5375       return SDValue(N, 0);
5376     }
5377   }
5378 
5379   if (LegalTypes) {
5380     // Attempt to propagate the AND back up to the leaves which, if they're
5381     // loads, can be combined to narrow loads and the AND node can be removed.
5382     // Perform after legalization so that extend nodes will already be
5383     // combined into the loads.
5384     if (BackwardsPropagateMask(N))
5385       return SDValue(N, 0);
5386   }
5387 
5388   if (SDValue Combined = visitANDLike(N0, N1, N))
5389     return Combined;
5390 
5391   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
5392   if (N0.getOpcode() == N1.getOpcode())
5393     if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
5394       return V;
5395 
5396   // Masking the negated extension of a boolean is just the zero-extended
5397   // boolean:
5398   // and (sub 0, zext(bool X)), 1 --> zext(bool X)
5399   // and (sub 0, sext(bool X)), 1 --> zext(bool X)
5400   //
5401   // Note: the SimplifyDemandedBits fold below can make an information-losing
5402   // transform, and then we have no way to find this better fold.
5403   if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
5404     if (isNullOrNullSplat(N0.getOperand(0))) {
5405       SDValue SubRHS = N0.getOperand(1);
5406       if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
5407           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5408         return SubRHS;
5409       if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
5410           SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
5411         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
5412     }
5413   }
5414 
5415   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
5416   // fold (and (sra)) -> (and (srl)) when possible.
5417   if (SimplifyDemandedBits(SDValue(N, 0)))
5418     return SDValue(N, 0);
5419 
5420   // fold (zext_inreg (extload x)) -> (zextload x)
5421   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
5422   if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
5423       (ISD::isEXTLoad(N0.getNode()) ||
5424        (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
5425     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5426     EVT MemVT = LN0->getMemoryVT();
5427     // If we zero all the possible extended bits, then we can turn this into
5428     // a zextload if we are running before legalize or the operation is legal.
5429     unsigned ExtBitSize = N1.getScalarValueSizeInBits();
5430     unsigned MemBitSize = MemVT.getScalarSizeInBits();
5431     APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
5432     if (DAG.MaskedValueIsZero(N1, ExtBits) &&
5433         ((!LegalOperations && LN0->isSimple()) ||
5434          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
5435       SDValue ExtLoad =
5436           DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
5437                          LN0->getBasePtr(), MemVT, LN0->getMemOperand());
5438       AddToWorklist(N);
5439       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5440       return SDValue(N, 0); // Return N so it doesn't get rechecked!
5441     }
5442   }
5443 
5444   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
5445   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
5446     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5447                                            N0.getOperand(1), false))
5448       return BSwap;
5449   }
5450 
5451   if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
5452     return Shifts;
5453 
5454   if (TLI.hasBitTest(N0, N1))
5455     if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
5456       return V;
5457 
5458   return SDValue();
5459 }
5460 
5461 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
5462 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
5463                                         bool DemandHighBits) {
5464   if (!LegalOperations)
5465     return SDValue();
5466 
5467   EVT VT = N->getValueType(0);
5468   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
5469     return SDValue();
5470   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
5471     return SDValue();
5472 
5473   // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
5474   bool LookPassAnd0 = false;
5475   bool LookPassAnd1 = false;
5476   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
5477       std::swap(N0, N1);
5478   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
5479       std::swap(N0, N1);
5480   if (N0.getOpcode() == ISD::AND) {
5481     if (!N0.getNode()->hasOneUse())
5482       return SDValue();
5483     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5484     // Also handle 0xffff since the LHS is guaranteed to have zeros there.
5485     // This is needed for X86.
5486     if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
5487                   N01C->getZExtValue() != 0xFFFF))
5488       return SDValue();
5489     N0 = N0.getOperand(0);
5490     LookPassAnd0 = true;
5491   }
5492 
5493   if (N1.getOpcode() == ISD::AND) {
5494     if (!N1.getNode()->hasOneUse())
5495       return SDValue();
5496     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5497     if (!N11C || N11C->getZExtValue() != 0xFF)
5498       return SDValue();
5499     N1 = N1.getOperand(0);
5500     LookPassAnd1 = true;
5501   }
5502 
5503   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
5504     std::swap(N0, N1);
5505   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
5506     return SDValue();
5507   if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
5508     return SDValue();
5509 
5510   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5511   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5512   if (!N01C || !N11C)
5513     return SDValue();
5514   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
5515     return SDValue();
5516 
5517   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
5518   SDValue N00 = N0->getOperand(0);
5519   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
5520     if (!N00.getNode()->hasOneUse())
5521       return SDValue();
5522     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
5523     if (!N001C || N001C->getZExtValue() != 0xFF)
5524       return SDValue();
5525     N00 = N00.getOperand(0);
5526     LookPassAnd0 = true;
5527   }
5528 
5529   SDValue N10 = N1->getOperand(0);
5530   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
5531     if (!N10.getNode()->hasOneUse())
5532       return SDValue();
5533     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
5534     // Also allow 0xFFFF since the bits will be shifted out. This is needed
5535     // for X86.
5536     if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
5537                    N101C->getZExtValue() != 0xFFFF))
5538       return SDValue();
5539     N10 = N10.getOperand(0);
5540     LookPassAnd1 = true;
5541   }
5542 
5543   if (N00 != N10)
5544     return SDValue();
5545 
5546   // Make sure everything beyond the low halfword gets set to zero since the SRL
5547   // 16 will clear the top bits.
5548   unsigned OpSizeInBits = VT.getSizeInBits();
5549   if (DemandHighBits && OpSizeInBits > 16) {
5550     // If the left-shift isn't masked out then the only way this is a bswap is
5551     // if all bits beyond the low 8 are 0. In that case the entire pattern
5552     // reduces to a left shift anyway: leave it for other parts of the combiner.
5553     if (!LookPassAnd0)
5554       return SDValue();
5555 
5556     // However, if the right shift isn't masked out then it might be because
5557     // it's not needed. See if we can spot that too.
5558     if (!LookPassAnd1 &&
5559         !DAG.MaskedValueIsZero(
5560             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
5561       return SDValue();
5562   }
5563 
5564   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
5565   if (OpSizeInBits > 16) {
5566     SDLoc DL(N);
5567     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
5568                       DAG.getConstant(OpSizeInBits - 16, DL,
5569                                       getShiftAmountTy(VT)));
5570   }
5571   return Res;
5572 }
5573 
5574 /// Return true if the specified node is an element that makes up a 32-bit
5575 /// packed halfword byteswap.
5576 /// ((x & 0x000000ff) << 8) |
5577 /// ((x & 0x0000ff00) >> 8) |
5578 /// ((x & 0x00ff0000) << 8) |
5579 /// ((x & 0xff000000) >> 8)
5580 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
5581   if (!N.getNode()->hasOneUse())
5582     return false;
5583 
5584   unsigned Opc = N.getOpcode();
5585   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
5586     return false;
5587 
5588   SDValue N0 = N.getOperand(0);
5589   unsigned Opc0 = N0.getOpcode();
5590   if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
5591     return false;
5592 
5593   ConstantSDNode *N1C = nullptr;
5594   // SHL or SRL: look upstream for AND mask operand
5595   if (Opc == ISD::AND)
5596     N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5597   else if (Opc0 == ISD::AND)
5598     N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5599   if (!N1C)
5600     return false;
5601 
5602   unsigned MaskByteOffset;
5603   switch (N1C->getZExtValue()) {
5604   default:
5605     return false;
5606   case 0xFF:       MaskByteOffset = 0; break;
5607   case 0xFF00:     MaskByteOffset = 1; break;
5608   case 0xFFFF:
5609     // In case demanded bits didn't clear the bits that will be shifted out.
5610     // This is needed for X86.
5611     if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
5612       MaskByteOffset = 1;
5613       break;
5614     }
5615     return false;
5616   case 0xFF0000:   MaskByteOffset = 2; break;
5617   case 0xFF000000: MaskByteOffset = 3; break;
5618   }
5619 
5620   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
5621   if (Opc == ISD::AND) {
5622     if (MaskByteOffset == 0 || MaskByteOffset == 2) {
5623       // (x >> 8) & 0xff
5624       // (x >> 8) & 0xff0000
5625       if (Opc0 != ISD::SRL)
5626         return false;
5627       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5628       if (!C || C->getZExtValue() != 8)
5629         return false;
5630     } else {
5631       // (x << 8) & 0xff00
5632       // (x << 8) & 0xff000000
5633       if (Opc0 != ISD::SHL)
5634         return false;
5635       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5636       if (!C || C->getZExtValue() != 8)
5637         return false;
5638     }
5639   } else if (Opc == ISD::SHL) {
5640     // (x & 0xff) << 8
5641     // (x & 0xff0000) << 8
5642     if (MaskByteOffset != 0 && MaskByteOffset != 2)
5643       return false;
5644     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5645     if (!C || C->getZExtValue() != 8)
5646       return false;
5647   } else { // Opc == ISD::SRL
5648     // (x & 0xff00) >> 8
5649     // (x & 0xff000000) >> 8
5650     if (MaskByteOffset != 1 && MaskByteOffset != 3)
5651       return false;
5652     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
5653     if (!C || C->getZExtValue() != 8)
5654       return false;
5655   }
5656 
5657   if (Parts[MaskByteOffset])
5658     return false;
5659 
5660   Parts[MaskByteOffset] = N0.getOperand(0).getNode();
5661   return true;
5662 }
5663 
5664 // Match 2 elements of a packed halfword bswap.
5665 static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) {
5666   if (N.getOpcode() == ISD::OR)
5667     return isBSwapHWordElement(N.getOperand(0), Parts) &&
5668            isBSwapHWordElement(N.getOperand(1), Parts);
5669 
5670   if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
5671     ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
5672     if (!C || C->getAPIntValue() != 16)
5673       return false;
5674     Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
5675     return true;
5676   }
5677 
5678   return false;
5679 }
5680 
5681 // Match this pattern:
5682 //   (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
5683 // And rewrite this to:
5684 //   (rotr (bswap A), 16)
5685 static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI,
5686                                        SelectionDAG &DAG, SDNode *N, SDValue N0,
5687                                        SDValue N1, EVT VT, EVT ShiftAmountTy) {
5688   assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
5689          "MatchBSwapHWordOrAndAnd: expecting i32");
5690   if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
5691     return SDValue();
5692   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
5693     return SDValue();
5694   // TODO: this is too restrictive; lifting this restriction requires more tests
5695   if (!N0->hasOneUse() || !N1->hasOneUse())
5696     return SDValue();
5697   ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1));
5698   ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1));
5699   if (!Mask0 || !Mask1)
5700     return SDValue();
5701   if (Mask0->getAPIntValue() != 0xff00ff00 ||
5702       Mask1->getAPIntValue() != 0x00ff00ff)
5703     return SDValue();
5704   SDValue Shift0 = N0.getOperand(0);
5705   SDValue Shift1 = N1.getOperand(0);
5706   if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
5707     return SDValue();
5708   ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
5709   ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
5710   if (!ShiftAmt0 || !ShiftAmt1)
5711     return SDValue();
5712   if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
5713     return SDValue();
5714   if (Shift0.getOperand(0) != Shift1.getOperand(0))
5715     return SDValue();
5716 
5717   SDLoc DL(N);
5718   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
5719   SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy);
5720   return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
5721 }
5722 
5723 /// Match a 32-bit packed halfword bswap. That is
5724 /// ((x & 0x000000ff) << 8) |
5725 /// ((x & 0x0000ff00) >> 8) |
5726 /// ((x & 0x00ff0000) << 8) |
5727 /// ((x & 0xff000000) >> 8)
5728 /// => (rotl (bswap x), 16)
5729 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
5730   if (!LegalOperations)
5731     return SDValue();
5732 
5733   EVT VT = N->getValueType(0);
5734   if (VT != MVT::i32)
5735     return SDValue();
5736   if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
5737     return SDValue();
5738 
5739   if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT,
5740                                               getShiftAmountTy(VT)))
5741   return BSwap;
5742 
5743   // Try again with commuted operands.
5744   if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT,
5745                                               getShiftAmountTy(VT)))
5746   return BSwap;
5747 
5748 
5749   // Look for either
5750   // (or (bswaphpair), (bswaphpair))
5751   // (or (or (bswaphpair), (and)), (and))
5752   // (or (or (and), (bswaphpair)), (and))
5753   SDNode *Parts[4] = {};
5754 
5755   if (isBSwapHWordPair(N0, Parts)) {
5756     // (or (or (and), (and)), (or (and), (and)))
5757     if (!isBSwapHWordPair(N1, Parts))
5758       return SDValue();
5759   } else if (N0.getOpcode() == ISD::OR) {
5760     // (or (or (or (and), (and)), (and)), (and))
5761     if (!isBSwapHWordElement(N1, Parts))
5762       return SDValue();
5763     SDValue N00 = N0.getOperand(0);
5764     SDValue N01 = N0.getOperand(1);
5765     if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
5766         !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
5767       return SDValue();
5768   } else
5769     return SDValue();
5770 
5771   // Make sure the parts are all coming from the same node.
5772   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
5773     return SDValue();
5774 
5775   SDLoc DL(N);
5776   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
5777                               SDValue(Parts[0], 0));
5778 
5779   // Result of the bswap should be rotated by 16. If it's not legal, then
5780   // do  (x << 16) | (x >> 16).
5781   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
5782   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
5783     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
5784   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
5785     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
5786   return DAG.getNode(ISD::OR, DL, VT,
5787                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
5788                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
5789 }
5790 
5791 /// This contains all DAGCombine rules which reduce two values combined by
5792 /// an Or operation to a single value \see visitANDLike().
5793 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
5794   EVT VT = N1.getValueType();
5795   SDLoc DL(N);
5796 
5797   // fold (or x, undef) -> -1
5798   if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
5799     return DAG.getAllOnesConstant(DL, VT);
5800 
5801   if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
5802     return V;
5803 
5804   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
5805   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
5806       // Don't increase # computations.
5807       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
5808     // We can only do this xform if we know that bits from X that are set in C2
5809     // but not in C1 are already zero.  Likewise for Y.
5810     if (const ConstantSDNode *N0O1C =
5811         getAsNonOpaqueConstant(N0.getOperand(1))) {
5812       if (const ConstantSDNode *N1O1C =
5813           getAsNonOpaqueConstant(N1.getOperand(1))) {
5814         // We can only do this xform if we know that bits from X that are set in
5815         // C2 but not in C1 are already zero.  Likewise for Y.
5816         const APInt &LHSMask = N0O1C->getAPIntValue();
5817         const APInt &RHSMask = N1O1C->getAPIntValue();
5818 
5819         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
5820             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
5821           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
5822                                   N0.getOperand(0), N1.getOperand(0));
5823           return DAG.getNode(ISD::AND, DL, VT, X,
5824                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
5825         }
5826       }
5827     }
5828   }
5829 
5830   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
5831   if (N0.getOpcode() == ISD::AND &&
5832       N1.getOpcode() == ISD::AND &&
5833       N0.getOperand(0) == N1.getOperand(0) &&
5834       // Don't increase # computations.
5835       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
5836     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
5837                             N0.getOperand(1), N1.getOperand(1));
5838     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
5839   }
5840 
5841   return SDValue();
5842 }
5843 
5844 /// OR combines for which the commuted variant will be tried as well.
5845 static SDValue visitORCommutative(
5846     SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) {
5847   EVT VT = N0.getValueType();
5848   if (N0.getOpcode() == ISD::AND) {
5849     // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
5850     if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1)
5851       return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1);
5852 
5853     // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
5854     if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1)
5855       return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1);
5856   }
5857 
5858   return SDValue();
5859 }
5860 
5861 SDValue DAGCombiner::visitOR(SDNode *N) {
5862   SDValue N0 = N->getOperand(0);
5863   SDValue N1 = N->getOperand(1);
5864   EVT VT = N1.getValueType();
5865 
5866   // x | x --> x
5867   if (N0 == N1)
5868     return N0;
5869 
5870   // fold vector ops
5871   if (VT.isVector()) {
5872     if (SDValue FoldedVOp = SimplifyVBinOp(N))
5873       return FoldedVOp;
5874 
5875     // fold (or x, 0) -> x, vector edition
5876     if (ISD::isBuildVectorAllZeros(N0.getNode()))
5877       return N1;
5878     if (ISD::isBuildVectorAllZeros(N1.getNode()))
5879       return N0;
5880 
5881     // fold (or x, -1) -> -1, vector edition
5882     if (ISD::isBuildVectorAllOnes(N0.getNode()))
5883       // do not return N0, because undef node may exist in N0
5884       return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
5885     if (ISD::isBuildVectorAllOnes(N1.getNode()))
5886       // do not return N1, because undef node may exist in N1
5887       return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
5888 
5889     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
5890     // Do this only if the resulting shuffle is legal.
5891     if (isa<ShuffleVectorSDNode>(N0) &&
5892         isa<ShuffleVectorSDNode>(N1) &&
5893         // Avoid folding a node with illegal type.
5894         TLI.isTypeLegal(VT)) {
5895       bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
5896       bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
5897       bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5898       bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
5899       // Ensure both shuffles have a zero input.
5900       if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
5901         assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
5902         assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
5903         const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
5904         const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
5905         bool CanFold = true;
5906         int NumElts = VT.getVectorNumElements();
5907         SmallVector<int, 4> Mask(NumElts);
5908 
5909         for (int i = 0; i != NumElts; ++i) {
5910           int M0 = SV0->getMaskElt(i);
5911           int M1 = SV1->getMaskElt(i);
5912 
5913           // Determine if either index is pointing to a zero vector.
5914           bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
5915           bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
5916 
5917           // If one element is zero and the otherside is undef, keep undef.
5918           // This also handles the case that both are undef.
5919           if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
5920             Mask[i] = -1;
5921             continue;
5922           }
5923 
5924           // Make sure only one of the elements is zero.
5925           if (M0Zero == M1Zero) {
5926             CanFold = false;
5927             break;
5928           }
5929 
5930           assert((M0 >= 0 || M1 >= 0) && "Undef index!");
5931 
5932           // We have a zero and non-zero element. If the non-zero came from
5933           // SV0 make the index a LHS index. If it came from SV1, make it
5934           // a RHS index. We need to mod by NumElts because we don't care
5935           // which operand it came from in the original shuffles.
5936           Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
5937         }
5938 
5939         if (CanFold) {
5940           SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
5941           SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
5942 
5943           SDValue LegalShuffle =
5944               TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS,
5945                                           Mask, DAG);
5946           if (LegalShuffle)
5947             return LegalShuffle;
5948         }
5949       }
5950     }
5951   }
5952 
5953   // fold (or c1, c2) -> c1|c2
5954   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5955   if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1}))
5956     return C;
5957 
5958   // canonicalize constant to RHS
5959   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5960      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5961     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
5962 
5963   // fold (or x, 0) -> x
5964   if (isNullConstant(N1))
5965     return N0;
5966 
5967   // fold (or x, -1) -> -1
5968   if (isAllOnesConstant(N1))
5969     return N1;
5970 
5971   if (SDValue NewSel = foldBinOpIntoSelect(N))
5972     return NewSel;
5973 
5974   // fold (or x, c) -> c iff (x & ~c) == 0
5975   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
5976     return N1;
5977 
5978   if (SDValue Combined = visitORLike(N0, N1, N))
5979     return Combined;
5980 
5981   if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N))
5982     return Combined;
5983 
5984   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
5985   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
5986     return BSwap;
5987   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
5988     return BSwap;
5989 
5990   // reassociate or
5991   if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags()))
5992     return ROR;
5993 
5994   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
5995   // iff (c1 & c2) != 0 or c1/c2 are undef.
5996   auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
5997     return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
5998   };
5999   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
6000       ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
6001     if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
6002                                                  {N1, N0.getOperand(1)})) {
6003       SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
6004       AddToWorklist(IOR.getNode());
6005       return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
6006     }
6007   }
6008 
6009   if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
6010     return Combined;
6011   if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
6012     return Combined;
6013 
6014   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
6015   if (N0.getOpcode() == N1.getOpcode())
6016     if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
6017       return V;
6018 
6019   // See if this is some rotate idiom.
6020   if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N)))
6021     return Rot;
6022 
6023   if (SDValue Load = MatchLoadCombine(N))
6024     return Load;
6025 
6026   // Simplify the operands using demanded-bits information.
6027   if (SimplifyDemandedBits(SDValue(N, 0)))
6028     return SDValue(N, 0);
6029 
6030   // If OR can be rewritten into ADD, try combines based on ADD.
6031   if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
6032       DAG.haveNoCommonBitsSet(N0, N1))
6033     if (SDValue Combined = visitADDLike(N))
6034       return Combined;
6035 
6036   return SDValue();
6037 }
6038 
6039 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) {
6040   if (Op.getOpcode() == ISD::AND &&
6041       DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
6042     Mask = Op.getOperand(1);
6043     return Op.getOperand(0);
6044   }
6045   return Op;
6046 }
6047 
6048 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
6049 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift,
6050                             SDValue &Mask) {
6051   Op = stripConstantMask(DAG, Op, Mask);
6052   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
6053     Shift = Op;
6054     return true;
6055   }
6056   return false;
6057 }
6058 
6059 /// Helper function for visitOR to extract the needed side of a rotate idiom
6060 /// from a shl/srl/mul/udiv.  This is meant to handle cases where
6061 /// InstCombine merged some outside op with one of the shifts from
6062 /// the rotate pattern.
6063 /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
6064 /// Otherwise, returns an expansion of \p ExtractFrom based on the following
6065 /// patterns:
6066 ///
6067 ///   (or (add v v) (shrl v bitwidth-1)):
6068 ///     expands (add v v) -> (shl v 1)
6069 ///
6070 ///   (or (mul v c0) (shrl (mul v c1) c2)):
6071 ///     expands (mul v c0) -> (shl (mul v c1) c3)
6072 ///
6073 ///   (or (udiv v c0) (shl (udiv v c1) c2)):
6074 ///     expands (udiv v c0) -> (shrl (udiv v c1) c3)
6075 ///
6076 ///   (or (shl v c0) (shrl (shl v c1) c2)):
6077 ///     expands (shl v c0) -> (shl (shl v c1) c3)
6078 ///
6079 ///   (or (shrl v c0) (shl (shrl v c1) c2)):
6080 ///     expands (shrl v c0) -> (shrl (shrl v c1) c3)
6081 ///
6082 /// Such that in all cases, c3+c2==bitwidth(op v c1).
6083 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift,
6084                                      SDValue ExtractFrom, SDValue &Mask,
6085                                      const SDLoc &DL) {
6086   assert(OppShift && ExtractFrom && "Empty SDValue");
6087   assert(
6088       (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) &&
6089       "Existing shift must be valid as a rotate half");
6090 
6091   ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
6092 
6093   // Value and Type of the shift.
6094   SDValue OppShiftLHS = OppShift.getOperand(0);
6095   EVT ShiftedVT = OppShiftLHS.getValueType();
6096 
6097   // Amount of the existing shift.
6098   ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
6099 
6100   // (add v v) -> (shl v 1)
6101   // TODO: Should this be a general DAG canonicalization?
6102   if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
6103       ExtractFrom.getOpcode() == ISD::ADD &&
6104       ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
6105       ExtractFrom.getOperand(0) == OppShiftLHS &&
6106       OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
6107     return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
6108                        DAG.getShiftAmountConstant(1, ShiftedVT, DL));
6109 
6110   // Preconditions:
6111   //    (or (op0 v c0) (shiftl/r (op0 v c1) c2))
6112   //
6113   // Find opcode of the needed shift to be extracted from (op0 v c0).
6114   unsigned Opcode = ISD::DELETED_NODE;
6115   bool IsMulOrDiv = false;
6116   // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
6117   // opcode or its arithmetic (mul or udiv) variant.
6118   auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
6119     IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
6120     if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
6121       return false;
6122     Opcode = NeededShift;
6123     return true;
6124   };
6125   // op0 must be either the needed shift opcode or the mul/udiv equivalent
6126   // that the needed shift can be extracted from.
6127   if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
6128       (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
6129     return SDValue();
6130 
6131   // op0 must be the same opcode on both sides, have the same LHS argument,
6132   // and produce the same value type.
6133   if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
6134       OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
6135       ShiftedVT != ExtractFrom.getValueType())
6136     return SDValue();
6137 
6138   // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
6139   ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
6140   // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
6141   ConstantSDNode *ExtractFromCst =
6142       isConstOrConstSplat(ExtractFrom.getOperand(1));
6143   // TODO: We should be able to handle non-uniform constant vectors for these values
6144   // Check that we have constant values.
6145   if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
6146       !OppLHSCst || !OppLHSCst->getAPIntValue() ||
6147       !ExtractFromCst || !ExtractFromCst->getAPIntValue())
6148     return SDValue();
6149 
6150   // Compute the shift amount we need to extract to complete the rotate.
6151   const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
6152   if (OppShiftCst->getAPIntValue().ugt(VTWidth))
6153     return SDValue();
6154   APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
6155   // Normalize the bitwidth of the two mul/udiv/shift constant operands.
6156   APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
6157   APInt OppLHSAmt = OppLHSCst->getAPIntValue();
6158   zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
6159 
6160   // Now try extract the needed shift from the ExtractFrom op and see if the
6161   // result matches up with the existing shift's LHS op.
6162   if (IsMulOrDiv) {
6163     // Op to extract from is a mul or udiv by a constant.
6164     // Check:
6165     //     c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
6166     //     c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
6167     const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
6168                                                  NeededShiftAmt.getZExtValue());
6169     APInt ResultAmt;
6170     APInt Rem;
6171     APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
6172     if (Rem != 0 || ResultAmt != OppLHSAmt)
6173       return SDValue();
6174   } else {
6175     // Op to extract from is a shift by a constant.
6176     // Check:
6177     //      c2 - (bitwidth(op0 v c0) - c1) == c0
6178     if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
6179                                           ExtractFromAmt.getBitWidth()))
6180       return SDValue();
6181   }
6182 
6183   // Return the expanded shift op that should allow a rotate to be formed.
6184   EVT ShiftVT = OppShift.getOperand(1).getValueType();
6185   EVT ResVT = ExtractFrom.getValueType();
6186   SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
6187   return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
6188 }
6189 
6190 // Return true if we can prove that, whenever Neg and Pos are both in the
6191 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
6192 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
6193 //
6194 //     (or (shift1 X, Neg), (shift2 X, Pos))
6195 //
6196 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
6197 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
6198 // to consider shift amounts with defined behavior.
6199 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
6200                            SelectionDAG &DAG) {
6201   // If EltSize is a power of 2 then:
6202   //
6203   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
6204   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
6205   //
6206   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
6207   // for the stronger condition:
6208   //
6209   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
6210   //
6211   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
6212   // we can just replace Neg with Neg' for the rest of the function.
6213   //
6214   // In other cases we check for the even stronger condition:
6215   //
6216   //     Neg == EltSize - Pos                                    [B]
6217   //
6218   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
6219   // behavior if Pos == 0 (and consequently Neg == EltSize).
6220   //
6221   // We could actually use [A] whenever EltSize is a power of 2, but the
6222   // only extra cases that it would match are those uninteresting ones
6223   // where Neg and Pos are never in range at the same time.  E.g. for
6224   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
6225   // as well as (sub 32, Pos), but:
6226   //
6227   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
6228   //
6229   // always invokes undefined behavior for 32-bit X.
6230   //
6231   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
6232   unsigned MaskLoBits = 0;
6233   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
6234     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
6235       KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0));
6236       unsigned Bits = Log2_64(EltSize);
6237       if (NegC->getAPIntValue().getActiveBits() <= Bits &&
6238           ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) {
6239         Neg = Neg.getOperand(0);
6240         MaskLoBits = Bits;
6241       }
6242     }
6243   }
6244 
6245   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
6246   if (Neg.getOpcode() != ISD::SUB)
6247     return false;
6248   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
6249   if (!NegC)
6250     return false;
6251   SDValue NegOp1 = Neg.getOperand(1);
6252 
6253   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
6254   // Pos'.  The truncation is redundant for the purpose of the equality.
6255   if (MaskLoBits && Pos.getOpcode() == ISD::AND) {
6256     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) {
6257       KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0));
6258       if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
6259           ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >=
6260            MaskLoBits))
6261         Pos = Pos.getOperand(0);
6262     }
6263   }
6264 
6265   // The condition we need is now:
6266   //
6267   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
6268   //
6269   // If NegOp1 == Pos then we need:
6270   //
6271   //              EltSize & Mask == NegC & Mask
6272   //
6273   // (because "x & Mask" is a truncation and distributes through subtraction).
6274   //
6275   // We also need to account for a potential truncation of NegOp1 if the amount
6276   // has already been legalized to a shift amount type.
6277   APInt Width;
6278   if ((Pos == NegOp1) ||
6279       (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
6280     Width = NegC->getAPIntValue();
6281 
6282   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
6283   // Then the condition we want to prove becomes:
6284   //
6285   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
6286   //
6287   // which, again because "x & Mask" is a truncation, becomes:
6288   //
6289   //                NegC & Mask == (EltSize - PosC) & Mask
6290   //             EltSize & Mask == (NegC + PosC) & Mask
6291   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
6292     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
6293       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
6294     else
6295       return false;
6296   } else
6297     return false;
6298 
6299   // Now we just need to check that EltSize & Mask == Width & Mask.
6300   if (MaskLoBits)
6301     // EltSize & Mask is 0 since Mask is EltSize - 1.
6302     return Width.getLoBits(MaskLoBits) == 0;
6303   return Width == EltSize;
6304 }
6305 
6306 // A subroutine of MatchRotate used once we have found an OR of two opposite
6307 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
6308 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
6309 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
6310 // Neg with outer conversions stripped away.
6311 SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
6312                                        SDValue Neg, SDValue InnerPos,
6313                                        SDValue InnerNeg, unsigned PosOpcode,
6314                                        unsigned NegOpcode, const SDLoc &DL) {
6315   // fold (or (shl x, (*ext y)),
6316   //          (srl x, (*ext (sub 32, y)))) ->
6317   //   (rotl x, y) or (rotr x, (sub 32, y))
6318   //
6319   // fold (or (shl x, (*ext (sub 32, y))),
6320   //          (srl x, (*ext y))) ->
6321   //   (rotr x, y) or (rotl x, (sub 32, y))
6322   EVT VT = Shifted.getValueType();
6323   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) {
6324     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
6325     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
6326                        HasPos ? Pos : Neg);
6327   }
6328 
6329   return SDValue();
6330 }
6331 
6332 // A subroutine of MatchRotate used once we have found an OR of two opposite
6333 // shifts of N0 + N1.  If Neg == <operand size> - Pos then the OR reduces
6334 // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
6335 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
6336 // Neg with outer conversions stripped away.
6337 // TODO: Merge with MatchRotatePosNeg.
6338 SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
6339                                        SDValue Neg, SDValue InnerPos,
6340                                        SDValue InnerNeg, unsigned PosOpcode,
6341                                        unsigned NegOpcode, const SDLoc &DL) {
6342   EVT VT = N0.getValueType();
6343   unsigned EltBits = VT.getScalarSizeInBits();
6344 
6345   // fold (or (shl x0, (*ext y)),
6346   //          (srl x1, (*ext (sub 32, y)))) ->
6347   //   (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
6348   //
6349   // fold (or (shl x0, (*ext (sub 32, y))),
6350   //          (srl x1, (*ext y))) ->
6351   //   (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
6352   if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG)) {
6353     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
6354     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
6355                        HasPos ? Pos : Neg);
6356   }
6357 
6358   // Matching the shift+xor cases, we can't easily use the xor'd shift amount
6359   // so for now just use the PosOpcode case if its legal.
6360   // TODO: When can we use the NegOpcode case?
6361   if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
6362     auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) {
6363       if (Op.getOpcode() != BinOpc)
6364         return false;
6365       ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1));
6366       return Cst && (Cst->getAPIntValue() == Imm);
6367     };
6368 
6369     // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
6370     //   -> (fshl x0, x1, y)
6371     if (IsBinOpImm(N1, ISD::SRL, 1) &&
6372         IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) &&
6373         InnerPos == InnerNeg.getOperand(0) &&
6374         TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) {
6375       return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos);
6376     }
6377 
6378     // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
6379     //   -> (fshr x0, x1, y)
6380     if (IsBinOpImm(N0, ISD::SHL, 1) &&
6381         IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
6382         InnerNeg == InnerPos.getOperand(0) &&
6383         TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
6384       return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
6385     }
6386 
6387     // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y))
6388     //   -> (fshr x0, x1, y)
6389     // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
6390     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) &&
6391         IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
6392         InnerNeg == InnerPos.getOperand(0) &&
6393         TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
6394       return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
6395     }
6396   }
6397 
6398   return SDValue();
6399 }
6400 
6401 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
6402 // idioms for rotate, and if the target supports rotation instructions, generate
6403 // a rot[lr]. This also matches funnel shift patterns, similar to rotation but
6404 // with different shifted sources.
6405 SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
6406   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
6407   EVT VT = LHS.getValueType();
6408   if (!TLI.isTypeLegal(VT))
6409     return SDValue();
6410 
6411   // The target must have at least one rotate/funnel flavor.
6412   bool HasROTL = hasOperation(ISD::ROTL, VT);
6413   bool HasROTR = hasOperation(ISD::ROTR, VT);
6414   bool HasFSHL = hasOperation(ISD::FSHL, VT);
6415   bool HasFSHR = hasOperation(ISD::FSHR, VT);
6416   if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
6417     return SDValue();
6418 
6419   // Check for truncated rotate.
6420   if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
6421       LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
6422     assert(LHS.getValueType() == RHS.getValueType());
6423     if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
6424       return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
6425     }
6426   }
6427 
6428   // Match "(X shl/srl V1) & V2" where V2 may not be present.
6429   SDValue LHSShift;   // The shift.
6430   SDValue LHSMask;    // AND value if any.
6431   matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
6432 
6433   SDValue RHSShift;   // The shift.
6434   SDValue RHSMask;    // AND value if any.
6435   matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
6436 
6437   // If neither side matched a rotate half, bail
6438   if (!LHSShift && !RHSShift)
6439     return SDValue();
6440 
6441   // InstCombine may have combined a constant shl, srl, mul, or udiv with one
6442   // side of the rotate, so try to handle that here. In all cases we need to
6443   // pass the matched shift from the opposite side to compute the opcode and
6444   // needed shift amount to extract.  We still want to do this if both sides
6445   // matched a rotate half because one half may be a potential overshift that
6446   // can be broken down (ie if InstCombine merged two shl or srl ops into a
6447   // single one).
6448 
6449   // Have LHS side of the rotate, try to extract the needed shift from the RHS.
6450   if (LHSShift)
6451     if (SDValue NewRHSShift =
6452             extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
6453       RHSShift = NewRHSShift;
6454   // Have RHS side of the rotate, try to extract the needed shift from the LHS.
6455   if (RHSShift)
6456     if (SDValue NewLHSShift =
6457             extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
6458       LHSShift = NewLHSShift;
6459 
6460   // If a side is still missing, nothing else we can do.
6461   if (!RHSShift || !LHSShift)
6462     return SDValue();
6463 
6464   // At this point we've matched or extracted a shift op on each side.
6465 
6466   if (LHSShift.getOpcode() == RHSShift.getOpcode())
6467     return SDValue(); // Shifts must disagree.
6468 
6469   bool IsRotate = LHSShift.getOperand(0) == RHSShift.getOperand(0);
6470   if (!IsRotate && !(HasFSHL || HasFSHR))
6471     return SDValue(); // Requires funnel shift support.
6472 
6473   // Canonicalize shl to left side in a shl/srl pair.
6474   if (RHSShift.getOpcode() == ISD::SHL) {
6475     std::swap(LHS, RHS);
6476     std::swap(LHSShift, RHSShift);
6477     std::swap(LHSMask, RHSMask);
6478   }
6479 
6480   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6481   SDValue LHSShiftArg = LHSShift.getOperand(0);
6482   SDValue LHSShiftAmt = LHSShift.getOperand(1);
6483   SDValue RHSShiftArg = RHSShift.getOperand(0);
6484   SDValue RHSShiftAmt = RHSShift.getOperand(1);
6485 
6486   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
6487   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
6488   // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
6489   // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
6490   // iff C1+C2 == EltSizeInBits
6491   auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
6492                                         ConstantSDNode *RHS) {
6493     return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
6494   };
6495   if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
6496     SDValue Res;
6497     if (IsRotate && (HasROTL || HasROTR))
6498       Res = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
6499                         HasROTL ? LHSShiftAmt : RHSShiftAmt);
6500     else
6501       Res = DAG.getNode(HasFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
6502                         RHSShiftArg, HasFSHL ? LHSShiftAmt : RHSShiftAmt);
6503 
6504     // If there is an AND of either shifted operand, apply it to the result.
6505     if (LHSMask.getNode() || RHSMask.getNode()) {
6506       SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
6507       SDValue Mask = AllOnes;
6508 
6509       if (LHSMask.getNode()) {
6510         SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
6511         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
6512                            DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
6513       }
6514       if (RHSMask.getNode()) {
6515         SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
6516         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
6517                            DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
6518       }
6519 
6520       Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
6521     }
6522 
6523     return Res;
6524   }
6525 
6526   // If there is a mask here, and we have a variable shift, we can't be sure
6527   // that we're masking out the right stuff.
6528   if (LHSMask.getNode() || RHSMask.getNode())
6529     return SDValue();
6530 
6531   // If the shift amount is sign/zext/any-extended just peel it off.
6532   SDValue LExtOp0 = LHSShiftAmt;
6533   SDValue RExtOp0 = RHSShiftAmt;
6534   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
6535        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
6536        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
6537        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
6538       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
6539        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
6540        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
6541        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
6542     LExtOp0 = LHSShiftAmt.getOperand(0);
6543     RExtOp0 = RHSShiftAmt.getOperand(0);
6544   }
6545 
6546   if (IsRotate && (HasROTL || HasROTR)) {
6547     SDValue TryL =
6548         MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0,
6549                           RExtOp0, ISD::ROTL, ISD::ROTR, DL);
6550     if (TryL)
6551       return TryL;
6552 
6553     SDValue TryR =
6554         MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0,
6555                           LExtOp0, ISD::ROTR, ISD::ROTL, DL);
6556     if (TryR)
6557       return TryR;
6558   }
6559 
6560   SDValue TryL =
6561       MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt,
6562                         LExtOp0, RExtOp0, ISD::FSHL, ISD::FSHR, DL);
6563   if (TryL)
6564     return TryL;
6565 
6566   SDValue TryR =
6567       MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
6568                         RExtOp0, LExtOp0, ISD::FSHR, ISD::FSHL, DL);
6569   if (TryR)
6570     return TryR;
6571 
6572   return SDValue();
6573 }
6574 
6575 namespace {
6576 
6577 /// Represents known origin of an individual byte in load combine pattern. The
6578 /// value of the byte is either constant zero or comes from memory.
6579 struct ByteProvider {
6580   // For constant zero providers Load is set to nullptr. For memory providers
6581   // Load represents the node which loads the byte from memory.
6582   // ByteOffset is the offset of the byte in the value produced by the load.
6583   LoadSDNode *Load = nullptr;
6584   unsigned ByteOffset = 0;
6585 
6586   ByteProvider() = default;
6587 
6588   static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
6589     return ByteProvider(Load, ByteOffset);
6590   }
6591 
6592   static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
6593 
6594   bool isConstantZero() const { return !Load; }
6595   bool isMemory() const { return Load; }
6596 
6597   bool operator==(const ByteProvider &Other) const {
6598     return Other.Load == Load && Other.ByteOffset == ByteOffset;
6599   }
6600 
6601 private:
6602   ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
6603       : Load(Load), ByteOffset(ByteOffset) {}
6604 };
6605 
6606 } // end anonymous namespace
6607 
6608 /// Recursively traverses the expression calculating the origin of the requested
6609 /// byte of the given value. Returns None if the provider can't be calculated.
6610 ///
6611 /// For all the values except the root of the expression verifies that the value
6612 /// has exactly one use and if it's not true return None. This way if the origin
6613 /// of the byte is returned it's guaranteed that the values which contribute to
6614 /// the byte are not used outside of this expression.
6615 ///
6616 /// Because the parts of the expression are not allowed to have more than one
6617 /// use this function iterates over trees, not DAGs. So it never visits the same
6618 /// node more than once.
6619 static const Optional<ByteProvider>
6620 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
6621                       bool Root = false) {
6622   // Typical i64 by i8 pattern requires recursion up to 8 calls depth
6623   if (Depth == 10)
6624     return None;
6625 
6626   if (!Root && !Op.hasOneUse())
6627     return None;
6628 
6629   assert(Op.getValueType().isScalarInteger() && "can't handle other types");
6630   unsigned BitWidth = Op.getValueSizeInBits();
6631   if (BitWidth % 8 != 0)
6632     return None;
6633   unsigned ByteWidth = BitWidth / 8;
6634   assert(Index < ByteWidth && "invalid index requested");
6635   (void) ByteWidth;
6636 
6637   switch (Op.getOpcode()) {
6638   case ISD::OR: {
6639     auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
6640     if (!LHS)
6641       return None;
6642     auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
6643     if (!RHS)
6644       return None;
6645 
6646     if (LHS->isConstantZero())
6647       return RHS;
6648     if (RHS->isConstantZero())
6649       return LHS;
6650     return None;
6651   }
6652   case ISD::SHL: {
6653     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
6654     if (!ShiftOp)
6655       return None;
6656 
6657     uint64_t BitShift = ShiftOp->getZExtValue();
6658     if (BitShift % 8 != 0)
6659       return None;
6660     uint64_t ByteShift = BitShift / 8;
6661 
6662     return Index < ByteShift
6663                ? ByteProvider::getConstantZero()
6664                : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
6665                                        Depth + 1);
6666   }
6667   case ISD::ANY_EXTEND:
6668   case ISD::SIGN_EXTEND:
6669   case ISD::ZERO_EXTEND: {
6670     SDValue NarrowOp = Op->getOperand(0);
6671     unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
6672     if (NarrowBitWidth % 8 != 0)
6673       return None;
6674     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6675 
6676     if (Index >= NarrowByteWidth)
6677       return Op.getOpcode() == ISD::ZERO_EXTEND
6678                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
6679                  : None;
6680     return calculateByteProvider(NarrowOp, Index, Depth + 1);
6681   }
6682   case ISD::BSWAP:
6683     return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
6684                                  Depth + 1);
6685   case ISD::LOAD: {
6686     auto L = cast<LoadSDNode>(Op.getNode());
6687     if (!L->isSimple() || L->isIndexed())
6688       return None;
6689 
6690     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
6691     if (NarrowBitWidth % 8 != 0)
6692       return None;
6693     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
6694 
6695     if (Index >= NarrowByteWidth)
6696       return L->getExtensionType() == ISD::ZEXTLOAD
6697                  ? Optional<ByteProvider>(ByteProvider::getConstantZero())
6698                  : None;
6699     return ByteProvider::getMemory(L, Index);
6700   }
6701   }
6702 
6703   return None;
6704 }
6705 
6706 static unsigned LittleEndianByteAt(unsigned BW, unsigned i) {
6707   return i;
6708 }
6709 
6710 static unsigned BigEndianByteAt(unsigned BW, unsigned i) {
6711   return BW - i - 1;
6712 }
6713 
6714 // Check if the bytes offsets we are looking at match with either big or
6715 // little endian value loaded. Return true for big endian, false for little
6716 // endian, and None if match failed.
6717 static Optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets,
6718                                   int64_t FirstOffset) {
6719   // The endian can be decided only when it is 2 bytes at least.
6720   unsigned Width = ByteOffsets.size();
6721   if (Width < 2)
6722     return None;
6723 
6724   bool BigEndian = true, LittleEndian = true;
6725   for (unsigned i = 0; i < Width; i++) {
6726     int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
6727     LittleEndian &= CurrentByteOffset == LittleEndianByteAt(Width, i);
6728     BigEndian &= CurrentByteOffset == BigEndianByteAt(Width, i);
6729     if (!BigEndian && !LittleEndian)
6730       return None;
6731   }
6732 
6733   assert((BigEndian != LittleEndian) && "It should be either big endian or"
6734                                         "little endian");
6735   return BigEndian;
6736 }
6737 
6738 static SDValue stripTruncAndExt(SDValue Value) {
6739   switch (Value.getOpcode()) {
6740   case ISD::TRUNCATE:
6741   case ISD::ZERO_EXTEND:
6742   case ISD::SIGN_EXTEND:
6743   case ISD::ANY_EXTEND:
6744     return stripTruncAndExt(Value.getOperand(0));
6745   }
6746   return Value;
6747 }
6748 
6749 /// Match a pattern where a wide type scalar value is stored by several narrow
6750 /// stores. Fold it into a single store or a BSWAP and a store if the targets
6751 /// supports it.
6752 ///
6753 /// Assuming little endian target:
6754 ///  i8 *p = ...
6755 ///  i32 val = ...
6756 ///  p[0] = (val >> 0) & 0xFF;
6757 ///  p[1] = (val >> 8) & 0xFF;
6758 ///  p[2] = (val >> 16) & 0xFF;
6759 ///  p[3] = (val >> 24) & 0xFF;
6760 /// =>
6761 ///  *((i32)p) = val;
6762 ///
6763 ///  i8 *p = ...
6764 ///  i32 val = ...
6765 ///  p[0] = (val >> 24) & 0xFF;
6766 ///  p[1] = (val >> 16) & 0xFF;
6767 ///  p[2] = (val >> 8) & 0xFF;
6768 ///  p[3] = (val >> 0) & 0xFF;
6769 /// =>
6770 ///  *((i32)p) = BSWAP(val);
6771 SDValue DAGCombiner::MatchStoreCombine(StoreSDNode *N) {
6772   // Collect all the stores in the chain.
6773   SDValue Chain;
6774   SmallVector<StoreSDNode *, 8> Stores;
6775   for (StoreSDNode *Store = N; Store; Store = dyn_cast<StoreSDNode>(Chain)) {
6776     // TODO: Allow unordered atomics when wider type is legal (see D66309)
6777     if (Store->getMemoryVT() != MVT::i8 ||
6778         !Store->isSimple() || Store->isIndexed())
6779       return SDValue();
6780     Stores.push_back(Store);
6781     Chain = Store->getChain();
6782   }
6783   // Handle the simple type only.
6784   unsigned Width = Stores.size();
6785   EVT VT = EVT::getIntegerVT(
6786     *DAG.getContext(), Width * N->getMemoryVT().getSizeInBits());
6787   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6788     return SDValue();
6789 
6790   if (LegalOperations && !TLI.isOperationLegal(ISD::STORE, VT))
6791     return SDValue();
6792 
6793   // Check if all the bytes of the combined value we are looking at are stored
6794   // to the same base address. Collect bytes offsets from Base address into
6795   // ByteOffsets.
6796   SDValue CombinedValue;
6797   SmallVector<int64_t, 8> ByteOffsets(Width, INT64_MAX);
6798   int64_t FirstOffset = INT64_MAX;
6799   StoreSDNode *FirstStore = nullptr;
6800   Optional<BaseIndexOffset> Base;
6801   for (auto Store : Stores) {
6802     // All the stores store different byte of the CombinedValue. A truncate is
6803     // required to get that byte value.
6804     SDValue Trunc = Store->getValue();
6805     if (Trunc.getOpcode() != ISD::TRUNCATE)
6806       return SDValue();
6807     // A shift operation is required to get the right byte offset, except the
6808     // first byte.
6809     int64_t Offset = 0;
6810     SDValue Value = Trunc.getOperand(0);
6811     if (Value.getOpcode() == ISD::SRL ||
6812         Value.getOpcode() == ISD::SRA) {
6813       auto *ShiftOffset = dyn_cast<ConstantSDNode>(Value.getOperand(1));
6814       // Trying to match the following pattern. The shift offset must be
6815       // a constant and a multiple of 8. It is the byte offset in "y".
6816       //
6817       // x = srl y, offset
6818       // i8 z = trunc x
6819       // store z, ...
6820       if (!ShiftOffset || (ShiftOffset->getSExtValue() % 8))
6821         return SDValue();
6822 
6823      Offset = ShiftOffset->getSExtValue()/8;
6824      Value = Value.getOperand(0);
6825     }
6826 
6827     // Stores must share the same combined value with different offsets.
6828     if (!CombinedValue)
6829       CombinedValue = Value;
6830     else if (stripTruncAndExt(CombinedValue) != stripTruncAndExt(Value))
6831       return SDValue();
6832 
6833     // The trunc and all the extend operation should be stripped to get the
6834     // real value we are stored.
6835     else if (CombinedValue.getValueType() != VT) {
6836       if (Value.getValueType() == VT ||
6837           Value.getValueSizeInBits() > CombinedValue.getValueSizeInBits())
6838         CombinedValue = Value;
6839       // Give up if the combined value type is smaller than the store size.
6840       if (CombinedValue.getValueSizeInBits() < VT.getSizeInBits())
6841         return SDValue();
6842     }
6843 
6844     // Stores must share the same base address
6845     BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
6846     int64_t ByteOffsetFromBase = 0;
6847     if (!Base)
6848       Base = Ptr;
6849     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
6850       return SDValue();
6851 
6852     // Remember the first byte store
6853     if (ByteOffsetFromBase < FirstOffset) {
6854       FirstStore = Store;
6855       FirstOffset = ByteOffsetFromBase;
6856     }
6857     // Map the offset in the store and the offset in the combined value, and
6858     // early return if it has been set before.
6859     if (Offset < 0 || Offset >= Width || ByteOffsets[Offset] != INT64_MAX)
6860       return SDValue();
6861     ByteOffsets[Offset] = ByteOffsetFromBase;
6862   }
6863 
6864   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
6865   assert(FirstStore && "First store must be set");
6866 
6867   // Check if the bytes of the combined value we are looking at match with
6868   // either big or little endian value store.
6869   Optional<bool> IsBigEndian = isBigEndian(ByteOffsets, FirstOffset);
6870   if (!IsBigEndian.hasValue())
6871     return SDValue();
6872 
6873   // The node we are looking at matches with the pattern, check if we can
6874   // replace it with a single bswap if needed and store.
6875 
6876   // If the store needs byte swap check if the target supports it
6877   bool NeedsBswap = DAG.getDataLayout().isBigEndian() != *IsBigEndian;
6878 
6879   // Before legalize we can introduce illegal bswaps which will be later
6880   // converted to an explicit bswap sequence. This way we end up with a single
6881   // store and byte shuffling instead of several stores and byte shuffling.
6882   if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
6883     return SDValue();
6884 
6885   // Check that a store of the wide type is both allowed and fast on the target
6886   bool Fast = false;
6887   bool Allowed =
6888       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
6889                              *FirstStore->getMemOperand(), &Fast);
6890   if (!Allowed || !Fast)
6891     return SDValue();
6892 
6893   if (VT != CombinedValue.getValueType()) {
6894     assert(CombinedValue.getValueType().getSizeInBits() > VT.getSizeInBits() &&
6895            "Get unexpected store value to combine");
6896     CombinedValue = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
6897                              CombinedValue);
6898   }
6899 
6900   if (NeedsBswap)
6901     CombinedValue = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, CombinedValue);
6902 
6903   SDValue NewStore =
6904     DAG.getStore(Chain, SDLoc(N),  CombinedValue, FirstStore->getBasePtr(),
6905                  FirstStore->getPointerInfo(), FirstStore->getAlignment());
6906 
6907   // Rely on other DAG combine rules to remove the other individual stores.
6908   DAG.ReplaceAllUsesWith(N, NewStore.getNode());
6909   return NewStore;
6910 }
6911 
6912 /// Match a pattern where a wide type scalar value is loaded by several narrow
6913 /// loads and combined by shifts and ors. Fold it into a single load or a load
6914 /// and a BSWAP if the targets supports it.
6915 ///
6916 /// Assuming little endian target:
6917 ///  i8 *a = ...
6918 ///  i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
6919 /// =>
6920 ///  i32 val = *((i32)a)
6921 ///
6922 ///  i8 *a = ...
6923 ///  i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
6924 /// =>
6925 ///  i32 val = BSWAP(*((i32)a))
6926 ///
6927 /// TODO: This rule matches complex patterns with OR node roots and doesn't
6928 /// interact well with the worklist mechanism. When a part of the pattern is
6929 /// updated (e.g. one of the loads) its direct users are put into the worklist,
6930 /// but the root node of the pattern which triggers the load combine is not
6931 /// necessarily a direct user of the changed node. For example, once the address
6932 /// of t28 load is reassociated load combine won't be triggered:
6933 ///             t25: i32 = add t4, Constant:i32<2>
6934 ///           t26: i64 = sign_extend t25
6935 ///        t27: i64 = add t2, t26
6936 ///       t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
6937 ///     t29: i32 = zero_extend t28
6938 ///   t32: i32 = shl t29, Constant:i8<8>
6939 /// t33: i32 = or t23, t32
6940 /// As a possible fix visitLoad can check if the load can be a part of a load
6941 /// combine pattern and add corresponding OR roots to the worklist.
6942 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
6943   assert(N->getOpcode() == ISD::OR &&
6944          "Can only match load combining against OR nodes");
6945 
6946   // Handles simple types only
6947   EVT VT = N->getValueType(0);
6948   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
6949     return SDValue();
6950   unsigned ByteWidth = VT.getSizeInBits() / 8;
6951 
6952   bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
6953   auto MemoryByteOffset = [&] (ByteProvider P) {
6954     assert(P.isMemory() && "Must be a memory byte provider");
6955     unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
6956     assert(LoadBitWidth % 8 == 0 &&
6957            "can only analyze providers for individual bytes not bit");
6958     unsigned LoadByteWidth = LoadBitWidth / 8;
6959     return IsBigEndianTarget
6960             ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
6961             : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
6962   };
6963 
6964   Optional<BaseIndexOffset> Base;
6965   SDValue Chain;
6966 
6967   SmallPtrSet<LoadSDNode *, 8> Loads;
6968   Optional<ByteProvider> FirstByteProvider;
6969   int64_t FirstOffset = INT64_MAX;
6970 
6971   // Check if all the bytes of the OR we are looking at are loaded from the same
6972   // base address. Collect bytes offsets from Base address in ByteOffsets.
6973   SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
6974   unsigned ZeroExtendedBytes = 0;
6975   for (int i = ByteWidth - 1; i >= 0; --i) {
6976     auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
6977     if (!P)
6978       return SDValue();
6979 
6980     if (P->isConstantZero()) {
6981       // It's OK for the N most significant bytes to be 0, we can just
6982       // zero-extend the load.
6983       if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
6984         return SDValue();
6985       continue;
6986     }
6987     assert(P->isMemory() && "provenance should either be memory or zero");
6988 
6989     LoadSDNode *L = P->Load;
6990     assert(L->hasNUsesOfValue(1, 0) && L->isSimple() &&
6991            !L->isIndexed() &&
6992            "Must be enforced by calculateByteProvider");
6993     assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
6994 
6995     // All loads must share the same chain
6996     SDValue LChain = L->getChain();
6997     if (!Chain)
6998       Chain = LChain;
6999     else if (Chain != LChain)
7000       return SDValue();
7001 
7002     // Loads must share the same base address
7003     BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
7004     int64_t ByteOffsetFromBase = 0;
7005     if (!Base)
7006       Base = Ptr;
7007     else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
7008       return SDValue();
7009 
7010     // Calculate the offset of the current byte from the base address
7011     ByteOffsetFromBase += MemoryByteOffset(*P);
7012     ByteOffsets[i] = ByteOffsetFromBase;
7013 
7014     // Remember the first byte load
7015     if (ByteOffsetFromBase < FirstOffset) {
7016       FirstByteProvider = P;
7017       FirstOffset = ByteOffsetFromBase;
7018     }
7019 
7020     Loads.insert(L);
7021   }
7022   assert(!Loads.empty() && "All the bytes of the value must be loaded from "
7023          "memory, so there must be at least one load which produces the value");
7024   assert(Base && "Base address of the accessed memory location must be set");
7025   assert(FirstOffset != INT64_MAX && "First byte offset must be set");
7026 
7027   bool NeedsZext = ZeroExtendedBytes > 0;
7028 
7029   EVT MemVT =
7030       EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
7031 
7032   if (!MemVT.isSimple())
7033     return SDValue();
7034 
7035   // Before legalize we can introduce too wide illegal loads which will be later
7036   // split into legal sized loads. This enables us to combine i64 load by i8
7037   // patterns to a couple of i32 loads on 32 bit targets.
7038   if (LegalOperations &&
7039       !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD,
7040                             MemVT))
7041     return SDValue();
7042 
7043   // Check if the bytes of the OR we are looking at match with either big or
7044   // little endian value load
7045   Optional<bool> IsBigEndian = isBigEndian(
7046       makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
7047   if (!IsBigEndian.hasValue())
7048     return SDValue();
7049 
7050   assert(FirstByteProvider && "must be set");
7051 
7052   // Ensure that the first byte is loaded from zero offset of the first load.
7053   // So the combined value can be loaded from the first load address.
7054   if (MemoryByteOffset(*FirstByteProvider) != 0)
7055     return SDValue();
7056   LoadSDNode *FirstLoad = FirstByteProvider->Load;
7057 
7058   // The node we are looking at matches with the pattern, check if we can
7059   // replace it with a single (possibly zero-extended) load and bswap + shift if
7060   // needed.
7061 
7062   // If the load needs byte swap check if the target supports it
7063   bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
7064 
7065   // Before legalize we can introduce illegal bswaps which will be later
7066   // converted to an explicit bswap sequence. This way we end up with a single
7067   // load and byte shuffling instead of several loads and byte shuffling.
7068   // We do not introduce illegal bswaps when zero-extending as this tends to
7069   // introduce too many arithmetic instructions.
7070   if (NeedsBswap && (LegalOperations || NeedsZext) &&
7071       !TLI.isOperationLegal(ISD::BSWAP, VT))
7072     return SDValue();
7073 
7074   // If we need to bswap and zero extend, we have to insert a shift. Check that
7075   // it is legal.
7076   if (NeedsBswap && NeedsZext && LegalOperations &&
7077       !TLI.isOperationLegal(ISD::SHL, VT))
7078     return SDValue();
7079 
7080   // Check that a load of the wide type is both allowed and fast on the target
7081   bool Fast = false;
7082   bool Allowed =
7083       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7084                              *FirstLoad->getMemOperand(), &Fast);
7085   if (!Allowed || !Fast)
7086     return SDValue();
7087 
7088   SDValue NewLoad = DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD,
7089                                    SDLoc(N), VT, Chain, FirstLoad->getBasePtr(),
7090                                    FirstLoad->getPointerInfo(), MemVT,
7091                                    FirstLoad->getAlignment());
7092 
7093   // Transfer chain users from old loads to the new load.
7094   for (LoadSDNode *L : Loads)
7095     DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
7096 
7097   if (!NeedsBswap)
7098     return NewLoad;
7099 
7100   SDValue ShiftedLoad =
7101       NeedsZext
7102           ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
7103                         DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT,
7104                                                    SDLoc(N), LegalOperations))
7105           : NewLoad;
7106   return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
7107 }
7108 
7109 // If the target has andn, bsl, or a similar bit-select instruction,
7110 // we want to unfold masked merge, with canonical pattern of:
7111 //   |        A  |  |B|
7112 //   ((x ^ y) & m) ^ y
7113 //    |  D  |
7114 // Into:
7115 //   (x & m) | (y & ~m)
7116 // If y is a constant, and the 'andn' does not work with immediates,
7117 // we unfold into a different pattern:
7118 //   ~(~x & m) & (m | y)
7119 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
7120 //       the very least that breaks andnpd / andnps patterns, and because those
7121 //       patterns are simplified in IR and shouldn't be created in the DAG
7122 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
7123   assert(N->getOpcode() == ISD::XOR);
7124 
7125   // Don't touch 'not' (i.e. where y = -1).
7126   if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
7127     return SDValue();
7128 
7129   EVT VT = N->getValueType(0);
7130 
7131   // There are 3 commutable operators in the pattern,
7132   // so we have to deal with 8 possible variants of the basic pattern.
7133   SDValue X, Y, M;
7134   auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
7135     if (And.getOpcode() != ISD::AND || !And.hasOneUse())
7136       return false;
7137     SDValue Xor = And.getOperand(XorIdx);
7138     if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
7139       return false;
7140     SDValue Xor0 = Xor.getOperand(0);
7141     SDValue Xor1 = Xor.getOperand(1);
7142     // Don't touch 'not' (i.e. where y = -1).
7143     if (isAllOnesOrAllOnesSplat(Xor1))
7144       return false;
7145     if (Other == Xor0)
7146       std::swap(Xor0, Xor1);
7147     if (Other != Xor1)
7148       return false;
7149     X = Xor0;
7150     Y = Xor1;
7151     M = And.getOperand(XorIdx ? 0 : 1);
7152     return true;
7153   };
7154 
7155   SDValue N0 = N->getOperand(0);
7156   SDValue N1 = N->getOperand(1);
7157   if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
7158       !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
7159     return SDValue();
7160 
7161   // Don't do anything if the mask is constant. This should not be reachable.
7162   // InstCombine should have already unfolded this pattern, and DAGCombiner
7163   // probably shouldn't produce it, too.
7164   if (isa<ConstantSDNode>(M.getNode()))
7165     return SDValue();
7166 
7167   // We can transform if the target has AndNot
7168   if (!TLI.hasAndNot(M))
7169     return SDValue();
7170 
7171   SDLoc DL(N);
7172 
7173   // If Y is a constant, check that 'andn' works with immediates.
7174   if (!TLI.hasAndNot(Y)) {
7175     assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
7176     // If not, we need to do a bit more work to make sure andn is still used.
7177     SDValue NotX = DAG.getNOT(DL, X, VT);
7178     SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
7179     SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
7180     SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
7181     return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
7182   }
7183 
7184   SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
7185   SDValue NotM = DAG.getNOT(DL, M, VT);
7186   SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
7187 
7188   return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
7189 }
7190 
7191 SDValue DAGCombiner::visitXOR(SDNode *N) {
7192   SDValue N0 = N->getOperand(0);
7193   SDValue N1 = N->getOperand(1);
7194   EVT VT = N0.getValueType();
7195 
7196   // fold vector ops
7197   if (VT.isVector()) {
7198     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7199       return FoldedVOp;
7200 
7201     // fold (xor x, 0) -> x, vector edition
7202     if (ISD::isBuildVectorAllZeros(N0.getNode()))
7203       return N1;
7204     if (ISD::isBuildVectorAllZeros(N1.getNode()))
7205       return N0;
7206   }
7207 
7208   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
7209   SDLoc DL(N);
7210   if (N0.isUndef() && N1.isUndef())
7211     return DAG.getConstant(0, DL, VT);
7212 
7213   // fold (xor x, undef) -> undef
7214   if (N0.isUndef())
7215     return N0;
7216   if (N1.isUndef())
7217     return N1;
7218 
7219   // fold (xor c1, c2) -> c1^c2
7220   if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
7221     return C;
7222 
7223   // canonicalize constant to RHS
7224   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
7225      !DAG.isConstantIntBuildVectorOrConstantInt(N1))
7226     return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
7227 
7228   // fold (xor x, 0) -> x
7229   if (isNullConstant(N1))
7230     return N0;
7231 
7232   if (SDValue NewSel = foldBinOpIntoSelect(N))
7233     return NewSel;
7234 
7235   // reassociate xor
7236   if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
7237     return RXOR;
7238 
7239   // fold !(x cc y) -> (x !cc y)
7240   unsigned N0Opcode = N0.getOpcode();
7241   SDValue LHS, RHS, CC;
7242   if (TLI.isConstTrueVal(N1.getNode()) &&
7243       isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/true)) {
7244     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
7245                                                LHS.getValueType());
7246     if (!LegalOperations ||
7247         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
7248       switch (N0Opcode) {
7249       default:
7250         llvm_unreachable("Unhandled SetCC Equivalent!");
7251       case ISD::SETCC:
7252         return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
7253       case ISD::SELECT_CC:
7254         return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
7255                                N0.getOperand(3), NotCC);
7256       case ISD::STRICT_FSETCC:
7257       case ISD::STRICT_FSETCCS: {
7258         if (N0.hasOneUse()) {
7259           // FIXME Can we handle multiple uses? Could we token factor the chain
7260           // results from the new/old setcc?
7261           SDValue SetCC = DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC,
7262                                        N0.getOperand(0),
7263                                        N0Opcode == ISD::STRICT_FSETCCS);
7264           CombineTo(N, SetCC);
7265           DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
7266           recursivelyDeleteUnusedNodes(N0.getNode());
7267           return SDValue(N, 0); // Return N so it doesn't get rechecked!
7268         }
7269         break;
7270       }
7271       }
7272     }
7273   }
7274 
7275   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
7276   if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
7277       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
7278     SDValue V = N0.getOperand(0);
7279     SDLoc DL0(N0);
7280     V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
7281                     DAG.getConstant(1, DL0, V.getValueType()));
7282     AddToWorklist(V.getNode());
7283     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
7284   }
7285 
7286   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
7287   if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
7288       (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
7289     SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
7290     if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
7291       unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
7292       N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
7293       N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
7294       AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
7295       return DAG.getNode(NewOpcode, DL, VT, N00, N01);
7296     }
7297   }
7298   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
7299   if (isAllOnesConstant(N1) && N0.hasOneUse() &&
7300       (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
7301     SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
7302     if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
7303       unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
7304       N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
7305       N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
7306       AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
7307       return DAG.getNode(NewOpcode, DL, VT, N00, N01);
7308     }
7309   }
7310 
7311   // fold (not (neg x)) -> (add X, -1)
7312   // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
7313   // Y is a constant or the subtract has a single use.
7314   if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB &&
7315       isNullConstant(N0.getOperand(0))) {
7316     return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
7317                        DAG.getAllOnesConstant(DL, VT));
7318   }
7319 
7320   // fold (not (add X, -1)) -> (neg X)
7321   if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD &&
7322       isAllOnesOrAllOnesSplat(N0.getOperand(1))) {
7323     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7324                        N0.getOperand(0));
7325   }
7326 
7327   // fold (xor (and x, y), y) -> (and (not x), y)
7328   if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
7329     SDValue X = N0.getOperand(0);
7330     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
7331     AddToWorklist(NotX.getNode());
7332     return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
7333   }
7334 
7335   if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) {
7336     ConstantSDNode *XorC = isConstOrConstSplat(N1);
7337     ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1));
7338     unsigned BitWidth = VT.getScalarSizeInBits();
7339     if (XorC && ShiftC) {
7340       // Don't crash on an oversized shift. We can not guarantee that a bogus
7341       // shift has been simplified to undef.
7342       uint64_t ShiftAmt = ShiftC->getLimitedValue();
7343       if (ShiftAmt < BitWidth) {
7344         APInt Ones = APInt::getAllOnesValue(BitWidth);
7345         Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt);
7346         if (XorC->getAPIntValue() == Ones) {
7347           // If the xor constant is a shifted -1, do a 'not' before the shift:
7348           // xor (X << ShiftC), XorC --> (not X) << ShiftC
7349           // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
7350           SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
7351           return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1));
7352         }
7353       }
7354     }
7355   }
7356 
7357   // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
7358   if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
7359     SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
7360     SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
7361     if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
7362       SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
7363       SDValue S0 = S.getOperand(0);
7364       if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) {
7365         unsigned OpSizeInBits = VT.getScalarSizeInBits();
7366         if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
7367           if (C->getAPIntValue() == (OpSizeInBits - 1))
7368             return DAG.getNode(ISD::ABS, DL, VT, S0);
7369       }
7370     }
7371   }
7372 
7373   // fold (xor x, x) -> 0
7374   if (N0 == N1)
7375     return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
7376 
7377   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
7378   // Here is a concrete example of this equivalence:
7379   // i16   x ==  14
7380   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
7381   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
7382   //
7383   // =>
7384   //
7385   // i16     ~1      == 0b1111111111111110
7386   // i16 rol(~1, 14) == 0b1011111111111111
7387   //
7388   // Some additional tips to help conceptualize this transform:
7389   // - Try to see the operation as placing a single zero in a value of all ones.
7390   // - There exists no value for x which would allow the result to contain zero.
7391   // - Values of x larger than the bitwidth are undefined and do not require a
7392   //   consistent result.
7393   // - Pushing the zero left requires shifting one bits in from the right.
7394   // A rotate left of ~1 is a nice way of achieving the desired result.
7395   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
7396       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
7397     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
7398                        N0.getOperand(1));
7399   }
7400 
7401   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
7402   if (N0Opcode == N1.getOpcode())
7403     if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
7404       return V;
7405 
7406   // Unfold  ((x ^ y) & m) ^ y  into  (x & m) | (y & ~m)  if profitable
7407   if (SDValue MM = unfoldMaskedMerge(N))
7408     return MM;
7409 
7410   // Simplify the expression using non-local knowledge.
7411   if (SimplifyDemandedBits(SDValue(N, 0)))
7412     return SDValue(N, 0);
7413 
7414   if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N))
7415     return Combined;
7416 
7417   return SDValue();
7418 }
7419 
7420 /// If we have a shift-by-constant of a bitwise logic op that itself has a
7421 /// shift-by-constant operand with identical opcode, we may be able to convert
7422 /// that into 2 independent shifts followed by the logic op. This is a
7423 /// throughput improvement.
7424 static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) {
7425   // Match a one-use bitwise logic op.
7426   SDValue LogicOp = Shift->getOperand(0);
7427   if (!LogicOp.hasOneUse())
7428     return SDValue();
7429 
7430   unsigned LogicOpcode = LogicOp.getOpcode();
7431   if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
7432       LogicOpcode != ISD::XOR)
7433     return SDValue();
7434 
7435   // Find a matching one-use shift by constant.
7436   unsigned ShiftOpcode = Shift->getOpcode();
7437   SDValue C1 = Shift->getOperand(1);
7438   ConstantSDNode *C1Node = isConstOrConstSplat(C1);
7439   assert(C1Node && "Expected a shift with constant operand");
7440   const APInt &C1Val = C1Node->getAPIntValue();
7441   auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
7442                              const APInt *&ShiftAmtVal) {
7443     if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
7444       return false;
7445 
7446     ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
7447     if (!ShiftCNode)
7448       return false;
7449 
7450     // Capture the shifted operand and shift amount value.
7451     ShiftOp = V.getOperand(0);
7452     ShiftAmtVal = &ShiftCNode->getAPIntValue();
7453 
7454     // Shift amount types do not have to match their operand type, so check that
7455     // the constants are the same width.
7456     if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
7457       return false;
7458 
7459     // The fold is not valid if the sum of the shift values exceeds bitwidth.
7460     if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits()))
7461       return false;
7462 
7463     return true;
7464   };
7465 
7466   // Logic ops are commutative, so check each operand for a match.
7467   SDValue X, Y;
7468   const APInt *C0Val;
7469   if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
7470     Y = LogicOp.getOperand(1);
7471   else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
7472     Y = LogicOp.getOperand(0);
7473   else
7474     return SDValue();
7475 
7476   // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
7477   SDLoc DL(Shift);
7478   EVT VT = Shift->getValueType(0);
7479   EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
7480   SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
7481   SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
7482   SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
7483   return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2);
7484 }
7485 
7486 /// Handle transforms common to the three shifts, when the shift amount is a
7487 /// constant.
7488 /// We are looking for: (shift being one of shl/sra/srl)
7489 ///   shift (binop X, C0), C1
7490 /// And want to transform into:
7491 ///   binop (shift X, C1), (shift C0, C1)
7492 SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
7493   assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
7494 
7495   // Do not turn a 'not' into a regular xor.
7496   if (isBitwiseNot(N->getOperand(0)))
7497     return SDValue();
7498 
7499   // The inner binop must be one-use, since we want to replace it.
7500   SDValue LHS = N->getOperand(0);
7501   if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
7502     return SDValue();
7503 
7504   // TODO: This is limited to early combining because it may reveal regressions
7505   //       otherwise. But since we just checked a target hook to see if this is
7506   //       desirable, that should have filtered out cases where this interferes
7507   //       with some other pattern matching.
7508   if (!LegalTypes)
7509     if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
7510       return R;
7511 
7512   // We want to pull some binops through shifts, so that we have (and (shift))
7513   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
7514   // thing happens with address calculations, so it's important to canonicalize
7515   // it.
7516   switch (LHS.getOpcode()) {
7517   default:
7518     return SDValue();
7519   case ISD::OR:
7520   case ISD::XOR:
7521   case ISD::AND:
7522     break;
7523   case ISD::ADD:
7524     if (N->getOpcode() != ISD::SHL)
7525       return SDValue(); // only shl(add) not sr[al](add).
7526     break;
7527   }
7528 
7529   // We require the RHS of the binop to be a constant and not opaque as well.
7530   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS.getOperand(1));
7531   if (!BinOpCst)
7532     return SDValue();
7533 
7534   // FIXME: disable this unless the input to the binop is a shift by a constant
7535   // or is copy/select. Enable this in other cases when figure out it's exactly
7536   // profitable.
7537   SDValue BinOpLHSVal = LHS.getOperand(0);
7538   bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
7539                             BinOpLHSVal.getOpcode() == ISD::SRA ||
7540                             BinOpLHSVal.getOpcode() == ISD::SRL) &&
7541                            isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
7542   bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
7543                         BinOpLHSVal.getOpcode() == ISD::SELECT;
7544 
7545   if (!IsShiftByConstant && !IsCopyOrSelect)
7546     return SDValue();
7547 
7548   if (IsCopyOrSelect && N->hasOneUse())
7549     return SDValue();
7550 
7551   // Fold the constants, shifting the binop RHS by the shift amount.
7552   SDLoc DL(N);
7553   EVT VT = N->getValueType(0);
7554   SDValue NewRHS = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(1),
7555                                N->getOperand(1));
7556   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
7557 
7558   SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
7559                                  N->getOperand(1));
7560   return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
7561 }
7562 
7563 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
7564   assert(N->getOpcode() == ISD::TRUNCATE);
7565   assert(N->getOperand(0).getOpcode() == ISD::AND);
7566 
7567   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
7568   EVT TruncVT = N->getValueType(0);
7569   if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
7570       TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
7571     SDValue N01 = N->getOperand(0).getOperand(1);
7572     if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
7573       SDLoc DL(N);
7574       SDValue N00 = N->getOperand(0).getOperand(0);
7575       SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
7576       SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
7577       AddToWorklist(Trunc00.getNode());
7578       AddToWorklist(Trunc01.getNode());
7579       return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
7580     }
7581   }
7582 
7583   return SDValue();
7584 }
7585 
7586 SDValue DAGCombiner::visitRotate(SDNode *N) {
7587   SDLoc dl(N);
7588   SDValue N0 = N->getOperand(0);
7589   SDValue N1 = N->getOperand(1);
7590   EVT VT = N->getValueType(0);
7591   unsigned Bitsize = VT.getScalarSizeInBits();
7592 
7593   // fold (rot x, 0) -> x
7594   if (isNullOrNullSplat(N1))
7595     return N0;
7596 
7597   // fold (rot x, c) -> x iff (c % BitSize) == 0
7598   if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
7599     APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
7600     if (DAG.MaskedValueIsZero(N1, ModuloMask))
7601       return N0;
7602   }
7603 
7604   // fold (rot x, c) -> (rot x, c % BitSize)
7605   bool OutOfRange = false;
7606   auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
7607     OutOfRange |= C->getAPIntValue().uge(Bitsize);
7608     return true;
7609   };
7610   if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
7611     EVT AmtVT = N1.getValueType();
7612     SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
7613     if (SDValue Amt =
7614             DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
7615       return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
7616   }
7617 
7618   // Simplify the operands using demanded-bits information.
7619   if (SimplifyDemandedBits(SDValue(N, 0)))
7620     return SDValue(N, 0);
7621 
7622   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
7623   if (N1.getOpcode() == ISD::TRUNCATE &&
7624       N1.getOperand(0).getOpcode() == ISD::AND) {
7625     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7626       return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
7627   }
7628 
7629   unsigned NextOp = N0.getOpcode();
7630   // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
7631   if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
7632     SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
7633     SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
7634     if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
7635       EVT ShiftVT = C1->getValueType(0);
7636       bool SameSide = (N->getOpcode() == NextOp);
7637       unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
7638       if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
7639               CombineOp, dl, ShiftVT, {N1, N0.getOperand(1)})) {
7640         SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
7641         SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
7642             ISD::SREM, dl, ShiftVT, {CombinedShift, BitsizeC});
7643         return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
7644                            CombinedShiftNorm);
7645       }
7646     }
7647   }
7648   return SDValue();
7649 }
7650 
7651 SDValue DAGCombiner::visitSHL(SDNode *N) {
7652   SDValue N0 = N->getOperand(0);
7653   SDValue N1 = N->getOperand(1);
7654   if (SDValue V = DAG.simplifyShift(N0, N1))
7655     return V;
7656 
7657   EVT VT = N0.getValueType();
7658   EVT ShiftVT = N1.getValueType();
7659   unsigned OpSizeInBits = VT.getScalarSizeInBits();
7660 
7661   // fold vector ops
7662   if (VT.isVector()) {
7663     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7664       return FoldedVOp;
7665 
7666     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
7667     // If setcc produces all-one true value then:
7668     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
7669     if (N1CV && N1CV->isConstant()) {
7670       if (N0.getOpcode() == ISD::AND) {
7671         SDValue N00 = N0->getOperand(0);
7672         SDValue N01 = N0->getOperand(1);
7673         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
7674 
7675         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
7676             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
7677                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7678           if (SDValue C =
7679                   DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1}))
7680             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
7681         }
7682       }
7683     }
7684   }
7685 
7686   ConstantSDNode *N1C = isConstOrConstSplat(N1);
7687 
7688   // fold (shl c1, c2) -> c1<<c2
7689   if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1}))
7690     return C;
7691 
7692   if (SDValue NewSel = foldBinOpIntoSelect(N))
7693     return NewSel;
7694 
7695   // if (shl x, c) is known to be zero, return 0
7696   if (DAG.MaskedValueIsZero(SDValue(N, 0),
7697                             APInt::getAllOnesValue(OpSizeInBits)))
7698     return DAG.getConstant(0, SDLoc(N), VT);
7699 
7700   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
7701   if (N1.getOpcode() == ISD::TRUNCATE &&
7702       N1.getOperand(0).getOpcode() == ISD::AND) {
7703     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
7704       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
7705   }
7706 
7707   if (SimplifyDemandedBits(SDValue(N, 0)))
7708     return SDValue(N, 0);
7709 
7710   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
7711   if (N0.getOpcode() == ISD::SHL) {
7712     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
7713                                           ConstantSDNode *RHS) {
7714       APInt c1 = LHS->getAPIntValue();
7715       APInt c2 = RHS->getAPIntValue();
7716       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7717       return (c1 + c2).uge(OpSizeInBits);
7718     };
7719     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
7720       return DAG.getConstant(0, SDLoc(N), VT);
7721 
7722     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
7723                                        ConstantSDNode *RHS) {
7724       APInt c1 = LHS->getAPIntValue();
7725       APInt c2 = RHS->getAPIntValue();
7726       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7727       return (c1 + c2).ult(OpSizeInBits);
7728     };
7729     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
7730       SDLoc DL(N);
7731       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
7732       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
7733     }
7734   }
7735 
7736   // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
7737   // For this to be valid, the second form must not preserve any of the bits
7738   // that are shifted out by the inner shift in the first form.  This means
7739   // the outer shift size must be >= the number of bits added by the ext.
7740   // As a corollary, we don't care what kind of ext it is.
7741   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
7742        N0.getOpcode() == ISD::ANY_EXTEND ||
7743        N0.getOpcode() == ISD::SIGN_EXTEND) &&
7744       N0.getOperand(0).getOpcode() == ISD::SHL) {
7745     SDValue N0Op0 = N0.getOperand(0);
7746     SDValue InnerShiftAmt = N0Op0.getOperand(1);
7747     EVT InnerVT = N0Op0.getValueType();
7748     uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
7749 
7750     auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
7751                                                          ConstantSDNode *RHS) {
7752       APInt c1 = LHS->getAPIntValue();
7753       APInt c2 = RHS->getAPIntValue();
7754       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7755       return c2.uge(OpSizeInBits - InnerBitwidth) &&
7756              (c1 + c2).uge(OpSizeInBits);
7757     };
7758     if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
7759                                   /*AllowUndefs*/ false,
7760                                   /*AllowTypeMismatch*/ true))
7761       return DAG.getConstant(0, SDLoc(N), VT);
7762 
7763     auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
7764                                                       ConstantSDNode *RHS) {
7765       APInt c1 = LHS->getAPIntValue();
7766       APInt c2 = RHS->getAPIntValue();
7767       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7768       return c2.uge(OpSizeInBits - InnerBitwidth) &&
7769              (c1 + c2).ult(OpSizeInBits);
7770     };
7771     if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
7772                                   /*AllowUndefs*/ false,
7773                                   /*AllowTypeMismatch*/ true)) {
7774       SDLoc DL(N);
7775       SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
7776       SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
7777       Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
7778       return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
7779     }
7780   }
7781 
7782   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
7783   // Only fold this if the inner zext has no other uses to avoid increasing
7784   // the total number of instructions.
7785   if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
7786       N0.getOperand(0).getOpcode() == ISD::SRL) {
7787     SDValue N0Op0 = N0.getOperand(0);
7788     SDValue InnerShiftAmt = N0Op0.getOperand(1);
7789 
7790     auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7791       APInt c1 = LHS->getAPIntValue();
7792       APInt c2 = RHS->getAPIntValue();
7793       zeroExtendToMatch(c1, c2);
7794       return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
7795     };
7796     if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
7797                                   /*AllowUndefs*/ false,
7798                                   /*AllowTypeMismatch*/ true)) {
7799       SDLoc DL(N);
7800       EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
7801       SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
7802       NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
7803       AddToWorklist(NewSHL.getNode());
7804       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
7805     }
7806   }
7807 
7808   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
7809   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
7810   // TODO - support non-uniform vector shift amounts.
7811   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
7812       N0->getFlags().hasExact()) {
7813     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
7814       uint64_t C1 = N0C1->getZExtValue();
7815       uint64_t C2 = N1C->getZExtValue();
7816       SDLoc DL(N);
7817       if (C1 <= C2)
7818         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
7819                            DAG.getConstant(C2 - C1, DL, ShiftVT));
7820       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
7821                          DAG.getConstant(C1 - C2, DL, ShiftVT));
7822     }
7823   }
7824 
7825   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
7826   //                               (and (srl x, (sub c1, c2), MASK)
7827   // Only fold this if the inner shift has no other uses -- if it does, folding
7828   // this will increase the total number of instructions.
7829   // TODO - drop hasOneUse requirement if c1 == c2?
7830   // TODO - support non-uniform vector shift amounts.
7831   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
7832       TLI.shouldFoldConstantShiftPairToMask(N, Level)) {
7833     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
7834       if (N0C1->getAPIntValue().ult(OpSizeInBits)) {
7835         uint64_t c1 = N0C1->getZExtValue();
7836         uint64_t c2 = N1C->getZExtValue();
7837         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
7838         SDValue Shift;
7839         if (c2 > c1) {
7840           Mask <<= c2 - c1;
7841           SDLoc DL(N);
7842           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
7843                               DAG.getConstant(c2 - c1, DL, ShiftVT));
7844         } else {
7845           Mask.lshrInPlace(c1 - c2);
7846           SDLoc DL(N);
7847           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
7848                               DAG.getConstant(c1 - c2, DL, ShiftVT));
7849         }
7850         SDLoc DL(N0);
7851         return DAG.getNode(ISD::AND, DL, VT, Shift,
7852                            DAG.getConstant(Mask, DL, VT));
7853       }
7854     }
7855   }
7856 
7857   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
7858   if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
7859       isConstantOrConstantVector(N1, /* No Opaques */ true)) {
7860     SDLoc DL(N);
7861     SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
7862     SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
7863     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
7864   }
7865 
7866   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7867   // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7868   // Variant of version done on multiply, except mul by a power of 2 is turned
7869   // into a shift.
7870   if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
7871       N0.getNode()->hasOneUse() &&
7872       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
7873       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) &&
7874       TLI.isDesirableToCommuteWithShift(N, Level)) {
7875     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
7876     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
7877     AddToWorklist(Shl0.getNode());
7878     AddToWorklist(Shl1.getNode());
7879     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
7880   }
7881 
7882   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
7883   if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
7884       isConstantOrConstantVector(N1, /* No Opaques */ true) &&
7885       isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
7886     SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
7887     if (isConstantOrConstantVector(Shl))
7888       return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
7889   }
7890 
7891   if (N1C && !N1C->isOpaque())
7892     if (SDValue NewSHL = visitShiftByConstant(N))
7893       return NewSHL;
7894 
7895   // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
7896   if (N0.getOpcode() == ISD::VSCALE)
7897     if (ConstantSDNode *NC1 = isConstOrConstSplat(N->getOperand(1))) {
7898       auto DL = SDLoc(N);
7899       APInt C0 = N0.getConstantOperandAPInt(0);
7900       APInt C1 = NC1->getAPIntValue();
7901       return DAG.getVScale(DL, VT, C0 << C1);
7902     }
7903 
7904   return SDValue();
7905 }
7906 
7907 SDValue DAGCombiner::visitSRA(SDNode *N) {
7908   SDValue N0 = N->getOperand(0);
7909   SDValue N1 = N->getOperand(1);
7910   if (SDValue V = DAG.simplifyShift(N0, N1))
7911     return V;
7912 
7913   EVT VT = N0.getValueType();
7914   unsigned OpSizeInBits = VT.getScalarSizeInBits();
7915 
7916   // Arithmetic shifting an all-sign-bit value is a no-op.
7917   // fold (sra 0, x) -> 0
7918   // fold (sra -1, x) -> -1
7919   if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
7920     return N0;
7921 
7922   // fold vector ops
7923   if (VT.isVector())
7924     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7925       return FoldedVOp;
7926 
7927   ConstantSDNode *N1C = isConstOrConstSplat(N1);
7928 
7929   // fold (sra c1, c2) -> (sra c1, c2)
7930   if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1}))
7931     return C;
7932 
7933   if (SDValue NewSel = foldBinOpIntoSelect(N))
7934     return NewSel;
7935 
7936   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
7937   // sext_inreg.
7938   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
7939     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
7940     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
7941     if (VT.isVector())
7942       ExtVT = EVT::getVectorVT(*DAG.getContext(),
7943                                ExtVT, VT.getVectorNumElements());
7944     if (!LegalOperations ||
7945         TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) ==
7946         TargetLowering::Legal)
7947       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7948                          N0.getOperand(0), DAG.getValueType(ExtVT));
7949   }
7950 
7951   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
7952   // clamp (add c1, c2) to max shift.
7953   if (N0.getOpcode() == ISD::SRA) {
7954     SDLoc DL(N);
7955     EVT ShiftVT = N1.getValueType();
7956     EVT ShiftSVT = ShiftVT.getScalarType();
7957     SmallVector<SDValue, 16> ShiftValues;
7958 
7959     auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7960       APInt c1 = LHS->getAPIntValue();
7961       APInt c2 = RHS->getAPIntValue();
7962       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
7963       APInt Sum = c1 + c2;
7964       unsigned ShiftSum =
7965           Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
7966       ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
7967       return true;
7968     };
7969     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
7970       SDValue ShiftValue;
7971       if (VT.isVector())
7972         ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
7973       else
7974         ShiftValue = ShiftValues[0];
7975       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
7976     }
7977   }
7978 
7979   // fold (sra (shl X, m), (sub result_size, n))
7980   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
7981   // result_size - n != m.
7982   // If truncate is free for the target sext(shl) is likely to result in better
7983   // code.
7984   if (N0.getOpcode() == ISD::SHL && N1C) {
7985     // Get the two constanst of the shifts, CN0 = m, CN = n.
7986     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
7987     if (N01C) {
7988       LLVMContext &Ctx = *DAG.getContext();
7989       // Determine what the truncate's result bitsize and type would be.
7990       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
7991 
7992       if (VT.isVector())
7993         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
7994 
7995       // Determine the residual right-shift amount.
7996       int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
7997 
7998       // If the shift is not a no-op (in which case this should be just a sign
7999       // extend already), the truncated to type is legal, sign_extend is legal
8000       // on that type, and the truncate to that type is both legal and free,
8001       // perform the transform.
8002       if ((ShiftAmt > 0) &&
8003           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
8004           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
8005           TLI.isTruncateFree(VT, TruncVT)) {
8006         SDLoc DL(N);
8007         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
8008             getShiftAmountTy(N0.getOperand(0).getValueType()));
8009         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
8010                                     N0.getOperand(0), Amt);
8011         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
8012                                     Shift);
8013         return DAG.getNode(ISD::SIGN_EXTEND, DL,
8014                            N->getValueType(0), Trunc);
8015       }
8016     }
8017   }
8018 
8019   // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
8020   //   sra (add (shl X, N1C), AddC), N1C -->
8021   //   sext (add (trunc X to (width - N1C)), AddC')
8022   if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C &&
8023       N0.getOperand(0).getOpcode() == ISD::SHL &&
8024       N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) {
8025     if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
8026       SDValue Shl = N0.getOperand(0);
8027       // Determine what the truncate's type would be and ask the target if that
8028       // is a free operation.
8029       LLVMContext &Ctx = *DAG.getContext();
8030       unsigned ShiftAmt = N1C->getZExtValue();
8031       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt);
8032       if (VT.isVector())
8033         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
8034 
8035       // TODO: The simple type check probably belongs in the default hook
8036       //       implementation and/or target-specific overrides (because
8037       //       non-simple types likely require masking when legalized), but that
8038       //       restriction may conflict with other transforms.
8039       if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
8040           TLI.isTruncateFree(VT, TruncVT)) {
8041         SDLoc DL(N);
8042         SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
8043         SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).
8044                              trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT);
8045         SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
8046         return DAG.getSExtOrTrunc(Add, DL, VT);
8047       }
8048     }
8049   }
8050 
8051   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
8052   if (N1.getOpcode() == ISD::TRUNCATE &&
8053       N1.getOperand(0).getOpcode() == ISD::AND) {
8054     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
8055       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
8056   }
8057 
8058   // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
8059   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
8060   //      if c1 is equal to the number of bits the trunc removes
8061   // TODO - support non-uniform vector shift amounts.
8062   if (N0.getOpcode() == ISD::TRUNCATE &&
8063       (N0.getOperand(0).getOpcode() == ISD::SRL ||
8064        N0.getOperand(0).getOpcode() == ISD::SRA) &&
8065       N0.getOperand(0).hasOneUse() &&
8066       N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
8067     SDValue N0Op0 = N0.getOperand(0);
8068     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
8069       EVT LargeVT = N0Op0.getValueType();
8070       unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
8071       if (LargeShift->getAPIntValue() == TruncBits) {
8072         SDLoc DL(N);
8073         SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL,
8074                                       getShiftAmountTy(LargeVT));
8075         SDValue SRA =
8076             DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
8077         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
8078       }
8079     }
8080   }
8081 
8082   // Simplify, based on bits shifted out of the LHS.
8083   if (SimplifyDemandedBits(SDValue(N, 0)))
8084     return SDValue(N, 0);
8085 
8086   // If the sign bit is known to be zero, switch this to a SRL.
8087   if (DAG.SignBitIsZero(N0))
8088     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
8089 
8090   if (N1C && !N1C->isOpaque())
8091     if (SDValue NewSRA = visitShiftByConstant(N))
8092       return NewSRA;
8093 
8094   return SDValue();
8095 }
8096 
8097 SDValue DAGCombiner::visitSRL(SDNode *N) {
8098   SDValue N0 = N->getOperand(0);
8099   SDValue N1 = N->getOperand(1);
8100   if (SDValue V = DAG.simplifyShift(N0, N1))
8101     return V;
8102 
8103   EVT VT = N0.getValueType();
8104   unsigned OpSizeInBits = VT.getScalarSizeInBits();
8105 
8106   // fold vector ops
8107   if (VT.isVector())
8108     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8109       return FoldedVOp;
8110 
8111   ConstantSDNode *N1C = isConstOrConstSplat(N1);
8112 
8113   // fold (srl c1, c2) -> c1 >>u c2
8114   if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1}))
8115     return C;
8116 
8117   if (SDValue NewSel = foldBinOpIntoSelect(N))
8118     return NewSel;
8119 
8120   // if (srl x, c) is known to be zero, return 0
8121   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
8122                                    APInt::getAllOnesValue(OpSizeInBits)))
8123     return DAG.getConstant(0, SDLoc(N), VT);
8124 
8125   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
8126   if (N0.getOpcode() == ISD::SRL) {
8127     auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
8128                                           ConstantSDNode *RHS) {
8129       APInt c1 = LHS->getAPIntValue();
8130       APInt c2 = RHS->getAPIntValue();
8131       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
8132       return (c1 + c2).uge(OpSizeInBits);
8133     };
8134     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
8135       return DAG.getConstant(0, SDLoc(N), VT);
8136 
8137     auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
8138                                        ConstantSDNode *RHS) {
8139       APInt c1 = LHS->getAPIntValue();
8140       APInt c2 = RHS->getAPIntValue();
8141       zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
8142       return (c1 + c2).ult(OpSizeInBits);
8143     };
8144     if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
8145       SDLoc DL(N);
8146       EVT ShiftVT = N1.getValueType();
8147       SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
8148       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
8149     }
8150   }
8151 
8152   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
8153       N0.getOperand(0).getOpcode() == ISD::SRL) {
8154     SDValue InnerShift = N0.getOperand(0);
8155     // TODO - support non-uniform vector shift amounts.
8156     if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
8157       uint64_t c1 = N001C->getZExtValue();
8158       uint64_t c2 = N1C->getZExtValue();
8159       EVT InnerShiftVT = InnerShift.getValueType();
8160       EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
8161       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
8162       // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
8163       // This is only valid if the OpSizeInBits + c1 = size of inner shift.
8164       if (c1 + OpSizeInBits == InnerShiftSize) {
8165         SDLoc DL(N);
8166         if (c1 + c2 >= InnerShiftSize)
8167           return DAG.getConstant(0, DL, VT);
8168         SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
8169         SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
8170                                        InnerShift.getOperand(0), NewShiftAmt);
8171         return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
8172       }
8173       // In the more general case, we can clear the high bits after the shift:
8174       // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
8175       if (N0.hasOneUse() && InnerShift.hasOneUse() &&
8176           c1 + c2 < InnerShiftSize) {
8177         SDLoc DL(N);
8178         SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
8179         SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
8180                                        InnerShift.getOperand(0), NewShiftAmt);
8181         SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
8182                                                             OpSizeInBits - c2),
8183                                        DL, InnerShiftVT);
8184         SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
8185         return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
8186       }
8187     }
8188   }
8189 
8190   // fold (srl (shl x, c), c) -> (and x, cst2)
8191   // TODO - (srl (shl x, c1), c2).
8192   if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
8193       isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
8194     SDLoc DL(N);
8195     SDValue Mask =
8196         DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
8197     AddToWorklist(Mask.getNode());
8198     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
8199   }
8200 
8201   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
8202   // TODO - support non-uniform vector shift amounts.
8203   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
8204     // Shifting in all undef bits?
8205     EVT SmallVT = N0.getOperand(0).getValueType();
8206     unsigned BitSize = SmallVT.getScalarSizeInBits();
8207     if (N1C->getAPIntValue().uge(BitSize))
8208       return DAG.getUNDEF(VT);
8209 
8210     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
8211       uint64_t ShiftAmt = N1C->getZExtValue();
8212       SDLoc DL0(N0);
8213       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
8214                                        N0.getOperand(0),
8215                           DAG.getConstant(ShiftAmt, DL0,
8216                                           getShiftAmountTy(SmallVT)));
8217       AddToWorklist(SmallShift.getNode());
8218       APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
8219       SDLoc DL(N);
8220       return DAG.getNode(ISD::AND, DL, VT,
8221                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
8222                          DAG.getConstant(Mask, DL, VT));
8223     }
8224   }
8225 
8226   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
8227   // bit, which is unmodified by sra.
8228   if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
8229     if (N0.getOpcode() == ISD::SRA)
8230       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
8231   }
8232 
8233   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
8234   if (N1C && N0.getOpcode() == ISD::CTLZ &&
8235       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
8236     KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
8237 
8238     // If any of the input bits are KnownOne, then the input couldn't be all
8239     // zeros, thus the result of the srl will always be zero.
8240     if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
8241 
8242     // If all of the bits input the to ctlz node are known to be zero, then
8243     // the result of the ctlz is "32" and the result of the shift is one.
8244     APInt UnknownBits = ~Known.Zero;
8245     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
8246 
8247     // Otherwise, check to see if there is exactly one bit input to the ctlz.
8248     if (UnknownBits.isPowerOf2()) {
8249       // Okay, we know that only that the single bit specified by UnknownBits
8250       // could be set on input to the CTLZ node. If this bit is set, the SRL
8251       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
8252       // to an SRL/XOR pair, which is likely to simplify more.
8253       unsigned ShAmt = UnknownBits.countTrailingZeros();
8254       SDValue Op = N0.getOperand(0);
8255 
8256       if (ShAmt) {
8257         SDLoc DL(N0);
8258         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
8259                   DAG.getConstant(ShAmt, DL,
8260                                   getShiftAmountTy(Op.getValueType())));
8261         AddToWorklist(Op.getNode());
8262       }
8263 
8264       SDLoc DL(N);
8265       return DAG.getNode(ISD::XOR, DL, VT,
8266                          Op, DAG.getConstant(1, DL, VT));
8267     }
8268   }
8269 
8270   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
8271   if (N1.getOpcode() == ISD::TRUNCATE &&
8272       N1.getOperand(0).getOpcode() == ISD::AND) {
8273     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
8274       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
8275   }
8276 
8277   // fold operands of srl based on knowledge that the low bits are not
8278   // demanded.
8279   if (SimplifyDemandedBits(SDValue(N, 0)))
8280     return SDValue(N, 0);
8281 
8282   if (N1C && !N1C->isOpaque())
8283     if (SDValue NewSRL = visitShiftByConstant(N))
8284       return NewSRL;
8285 
8286   // Attempt to convert a srl of a load into a narrower zero-extending load.
8287   if (SDValue NarrowLoad = ReduceLoadWidth(N))
8288     return NarrowLoad;
8289 
8290   // Here is a common situation. We want to optimize:
8291   //
8292   //   %a = ...
8293   //   %b = and i32 %a, 2
8294   //   %c = srl i32 %b, 1
8295   //   brcond i32 %c ...
8296   //
8297   // into
8298   //
8299   //   %a = ...
8300   //   %b = and %a, 2
8301   //   %c = setcc eq %b, 0
8302   //   brcond %c ...
8303   //
8304   // However when after the source operand of SRL is optimized into AND, the SRL
8305   // itself may not be optimized further. Look for it and add the BRCOND into
8306   // the worklist.
8307   if (N->hasOneUse()) {
8308     SDNode *Use = *N->use_begin();
8309     if (Use->getOpcode() == ISD::BRCOND)
8310       AddToWorklist(Use);
8311     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
8312       // Also look pass the truncate.
8313       Use = *Use->use_begin();
8314       if (Use->getOpcode() == ISD::BRCOND)
8315         AddToWorklist(Use);
8316     }
8317   }
8318 
8319   return SDValue();
8320 }
8321 
8322 SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
8323   EVT VT = N->getValueType(0);
8324   SDValue N0 = N->getOperand(0);
8325   SDValue N1 = N->getOperand(1);
8326   SDValue N2 = N->getOperand(2);
8327   bool IsFSHL = N->getOpcode() == ISD::FSHL;
8328   unsigned BitWidth = VT.getScalarSizeInBits();
8329 
8330   // fold (fshl N0, N1, 0) -> N0
8331   // fold (fshr N0, N1, 0) -> N1
8332   if (isPowerOf2_32(BitWidth))
8333     if (DAG.MaskedValueIsZero(
8334             N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
8335       return IsFSHL ? N0 : N1;
8336 
8337   auto IsUndefOrZero = [](SDValue V) {
8338     return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
8339   };
8340 
8341   // TODO - support non-uniform vector shift amounts.
8342   if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
8343     EVT ShAmtTy = N2.getValueType();
8344 
8345     // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
8346     if (Cst->getAPIntValue().uge(BitWidth)) {
8347       uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
8348       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1,
8349                          DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy));
8350     }
8351 
8352     unsigned ShAmt = Cst->getZExtValue();
8353     if (ShAmt == 0)
8354       return IsFSHL ? N0 : N1;
8355 
8356     // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
8357     // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
8358     // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
8359     // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
8360     if (IsUndefOrZero(N0))
8361       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1,
8362                          DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt,
8363                                          SDLoc(N), ShAmtTy));
8364     if (IsUndefOrZero(N1))
8365       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
8366                          DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt,
8367                                          SDLoc(N), ShAmtTy));
8368 
8369     // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
8370     // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
8371     // TODO - bigendian support once we have test coverage.
8372     // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
8373     // TODO - permit LHS EXTLOAD if extensions are shifted out.
8374     if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
8375         !DAG.getDataLayout().isBigEndian()) {
8376       auto *LHS = dyn_cast<LoadSDNode>(N0);
8377       auto *RHS = dyn_cast<LoadSDNode>(N1);
8378       if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
8379           LHS->getAddressSpace() == RHS->getAddressSpace() &&
8380           (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) &&
8381           ISD::isNON_EXTLoad(LHS)) {
8382         if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
8383           SDLoc DL(RHS);
8384           uint64_t PtrOff =
8385               IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
8386           unsigned NewAlign = MinAlign(RHS->getAlignment(), PtrOff);
8387           bool Fast = false;
8388           if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8389                                      RHS->getAddressSpace(), NewAlign,
8390                                      RHS->getMemOperand()->getFlags(), &Fast) &&
8391               Fast) {
8392             SDValue NewPtr =
8393                 DAG.getMemBasePlusOffset(RHS->getBasePtr(), PtrOff, DL);
8394             AddToWorklist(NewPtr.getNode());
8395             SDValue Load = DAG.getLoad(
8396                 VT, DL, RHS->getChain(), NewPtr,
8397                 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8398                 RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
8399             // Replace the old load's chain with the new load's chain.
8400             WorklistRemover DeadNodes(*this);
8401             DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1));
8402             return Load;
8403           }
8404         }
8405       }
8406     }
8407   }
8408 
8409   // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
8410   // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
8411   // iff We know the shift amount is in range.
8412   // TODO: when is it worth doing SUB(BW, N2) as well?
8413   if (isPowerOf2_32(BitWidth)) {
8414     APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
8415     if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
8416       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2);
8417     if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
8418       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2);
8419   }
8420 
8421   // fold (fshl N0, N0, N2) -> (rotl N0, N2)
8422   // fold (fshr N0, N0, N2) -> (rotr N0, N2)
8423   // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
8424   // is legal as well we might be better off avoiding non-constant (BW - N2).
8425   unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
8426   if (N0 == N1 && hasOperation(RotOpc, VT))
8427     return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2);
8428 
8429   // Simplify, based on bits shifted out of N0/N1.
8430   if (SimplifyDemandedBits(SDValue(N, 0)))
8431     return SDValue(N, 0);
8432 
8433   return SDValue();
8434 }
8435 
8436 SDValue DAGCombiner::visitABS(SDNode *N) {
8437   SDValue N0 = N->getOperand(0);
8438   EVT VT = N->getValueType(0);
8439 
8440   // fold (abs c1) -> c2
8441   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8442     return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
8443   // fold (abs (abs x)) -> (abs x)
8444   if (N0.getOpcode() == ISD::ABS)
8445     return N0;
8446   // fold (abs x) -> x iff not-negative
8447   if (DAG.SignBitIsZero(N0))
8448     return N0;
8449   return SDValue();
8450 }
8451 
8452 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
8453   SDValue N0 = N->getOperand(0);
8454   EVT VT = N->getValueType(0);
8455 
8456   // fold (bswap c1) -> c2
8457   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8458     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
8459   // fold (bswap (bswap x)) -> x
8460   if (N0.getOpcode() == ISD::BSWAP)
8461     return N0->getOperand(0);
8462   return SDValue();
8463 }
8464 
8465 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
8466   SDValue N0 = N->getOperand(0);
8467   EVT VT = N->getValueType(0);
8468 
8469   // fold (bitreverse c1) -> c2
8470   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8471     return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
8472   // fold (bitreverse (bitreverse x)) -> x
8473   if (N0.getOpcode() == ISD::BITREVERSE)
8474     return N0.getOperand(0);
8475   return SDValue();
8476 }
8477 
8478 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
8479   SDValue N0 = N->getOperand(0);
8480   EVT VT = N->getValueType(0);
8481 
8482   // fold (ctlz c1) -> c2
8483   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8484     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
8485 
8486   // If the value is known never to be zero, switch to the undef version.
8487   if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
8488     if (DAG.isKnownNeverZero(N0))
8489       return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8490   }
8491 
8492   return SDValue();
8493 }
8494 
8495 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
8496   SDValue N0 = N->getOperand(0);
8497   EVT VT = N->getValueType(0);
8498 
8499   // fold (ctlz_zero_undef c1) -> c2
8500   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8501     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8502   return SDValue();
8503 }
8504 
8505 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
8506   SDValue N0 = N->getOperand(0);
8507   EVT VT = N->getValueType(0);
8508 
8509   // fold (cttz c1) -> c2
8510   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8511     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
8512 
8513   // If the value is known never to be zero, switch to the undef version.
8514   if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
8515     if (DAG.isKnownNeverZero(N0))
8516       return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8517   }
8518 
8519   return SDValue();
8520 }
8521 
8522 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
8523   SDValue N0 = N->getOperand(0);
8524   EVT VT = N->getValueType(0);
8525 
8526   // fold (cttz_zero_undef c1) -> c2
8527   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8528     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
8529   return SDValue();
8530 }
8531 
8532 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
8533   SDValue N0 = N->getOperand(0);
8534   EVT VT = N->getValueType(0);
8535 
8536   // fold (ctpop c1) -> c2
8537   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8538     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
8539   return SDValue();
8540 }
8541 
8542 // FIXME: This should be checking for no signed zeros on individual operands, as
8543 // well as no nans.
8544 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS,
8545                                          SDValue RHS,
8546                                          const TargetLowering &TLI) {
8547   const TargetOptions &Options = DAG.getTarget().Options;
8548   EVT VT = LHS.getValueType();
8549 
8550   return Options.NoSignedZerosFPMath && VT.isFloatingPoint() &&
8551          TLI.isProfitableToCombineMinNumMaxNum(VT) &&
8552          DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS);
8553 }
8554 
8555 /// Generate Min/Max node
8556 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
8557                                    SDValue RHS, SDValue True, SDValue False,
8558                                    ISD::CondCode CC, const TargetLowering &TLI,
8559                                    SelectionDAG &DAG) {
8560   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
8561     return SDValue();
8562 
8563   EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
8564   switch (CC) {
8565   case ISD::SETOLT:
8566   case ISD::SETOLE:
8567   case ISD::SETLT:
8568   case ISD::SETLE:
8569   case ISD::SETULT:
8570   case ISD::SETULE: {
8571     // Since it's known never nan to get here already, either fminnum or
8572     // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
8573     // expanded in terms of it.
8574     unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
8575     if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
8576       return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
8577 
8578     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
8579     if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
8580       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8581     return SDValue();
8582   }
8583   case ISD::SETOGT:
8584   case ISD::SETOGE:
8585   case ISD::SETGT:
8586   case ISD::SETGE:
8587   case ISD::SETUGT:
8588   case ISD::SETUGE: {
8589     unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
8590     if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
8591       return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
8592 
8593     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
8594     if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
8595       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8596     return SDValue();
8597   }
8598   default:
8599     return SDValue();
8600   }
8601 }
8602 
8603 /// If a (v)select has a condition value that is a sign-bit test, try to smear
8604 /// the condition operand sign-bit across the value width and use it as a mask.
8605 static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) {
8606   SDValue Cond = N->getOperand(0);
8607   SDValue C1 = N->getOperand(1);
8608   SDValue C2 = N->getOperand(2);
8609   assert(isConstantOrConstantVector(C1) && isConstantOrConstantVector(C2) &&
8610          "Expected select-of-constants");
8611 
8612   EVT VT = N->getValueType(0);
8613   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
8614       VT != Cond.getOperand(0).getValueType())
8615     return SDValue();
8616 
8617   // The inverted-condition + commuted-select variants of these patterns are
8618   // canonicalized to these forms in IR.
8619   SDValue X = Cond.getOperand(0);
8620   SDValue CondC = Cond.getOperand(1);
8621   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8622   if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
8623       isAllOnesOrAllOnesSplat(C2)) {
8624     // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
8625     SDLoc DL(N);
8626     SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
8627     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
8628     return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
8629   }
8630   if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
8631     // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
8632     SDLoc DL(N);
8633     SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
8634     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
8635     return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
8636   }
8637   return SDValue();
8638 }
8639 
8640 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
8641   SDValue Cond = N->getOperand(0);
8642   SDValue N1 = N->getOperand(1);
8643   SDValue N2 = N->getOperand(2);
8644   EVT VT = N->getValueType(0);
8645   EVT CondVT = Cond.getValueType();
8646   SDLoc DL(N);
8647 
8648   if (!VT.isInteger())
8649     return SDValue();
8650 
8651   auto *C1 = dyn_cast<ConstantSDNode>(N1);
8652   auto *C2 = dyn_cast<ConstantSDNode>(N2);
8653   if (!C1 || !C2)
8654     return SDValue();
8655 
8656   // Only do this before legalization to avoid conflicting with target-specific
8657   // transforms in the other direction (create a select from a zext/sext). There
8658   // is also a target-independent combine here in DAGCombiner in the other
8659   // direction for (select Cond, -1, 0) when the condition is not i1.
8660   if (CondVT == MVT::i1 && !LegalOperations) {
8661     if (C1->isNullValue() && C2->isOne()) {
8662       // select Cond, 0, 1 --> zext (!Cond)
8663       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
8664       if (VT != MVT::i1)
8665         NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
8666       return NotCond;
8667     }
8668     if (C1->isNullValue() && C2->isAllOnesValue()) {
8669       // select Cond, 0, -1 --> sext (!Cond)
8670       SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
8671       if (VT != MVT::i1)
8672         NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
8673       return NotCond;
8674     }
8675     if (C1->isOne() && C2->isNullValue()) {
8676       // select Cond, 1, 0 --> zext (Cond)
8677       if (VT != MVT::i1)
8678         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
8679       return Cond;
8680     }
8681     if (C1->isAllOnesValue() && C2->isNullValue()) {
8682       // select Cond, -1, 0 --> sext (Cond)
8683       if (VT != MVT::i1)
8684         Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
8685       return Cond;
8686     }
8687 
8688     // Use a target hook because some targets may prefer to transform in the
8689     // other direction.
8690     if (TLI.convertSelectOfConstantsToMath(VT)) {
8691       // For any constants that differ by 1, we can transform the select into an
8692       // extend and add.
8693       const APInt &C1Val = C1->getAPIntValue();
8694       const APInt &C2Val = C2->getAPIntValue();
8695       if (C1Val - 1 == C2Val) {
8696         // select Cond, C1, C1-1 --> add (zext Cond), C1-1
8697         if (VT != MVT::i1)
8698           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
8699         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
8700       }
8701       if (C1Val + 1 == C2Val) {
8702         // select Cond, C1, C1+1 --> add (sext Cond), C1+1
8703         if (VT != MVT::i1)
8704           Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
8705         return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
8706       }
8707 
8708       // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
8709       if (C1Val.isPowerOf2() && C2Val.isNullValue()) {
8710         if (VT != MVT::i1)
8711           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
8712         SDValue ShAmtC = DAG.getConstant(C1Val.exactLogBase2(), DL, VT);
8713         return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
8714       }
8715 
8716       if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
8717         return V;
8718     }
8719 
8720     return SDValue();
8721   }
8722 
8723   // fold (select Cond, 0, 1) -> (xor Cond, 1)
8724   // We can't do this reliably if integer based booleans have different contents
8725   // to floating point based booleans. This is because we can't tell whether we
8726   // have an integer-based boolean or a floating-point-based boolean unless we
8727   // can find the SETCC that produced it and inspect its operands. This is
8728   // fairly easy if C is the SETCC node, but it can potentially be
8729   // undiscoverable (or not reasonably discoverable). For example, it could be
8730   // in another basic block or it could require searching a complicated
8731   // expression.
8732   if (CondVT.isInteger() &&
8733       TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
8734           TargetLowering::ZeroOrOneBooleanContent &&
8735       TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
8736           TargetLowering::ZeroOrOneBooleanContent &&
8737       C1->isNullValue() && C2->isOne()) {
8738     SDValue NotCond =
8739         DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
8740     if (VT.bitsEq(CondVT))
8741       return NotCond;
8742     return DAG.getZExtOrTrunc(NotCond, DL, VT);
8743   }
8744 
8745   return SDValue();
8746 }
8747 
8748 SDValue DAGCombiner::visitSELECT(SDNode *N) {
8749   SDValue N0 = N->getOperand(0);
8750   SDValue N1 = N->getOperand(1);
8751   SDValue N2 = N->getOperand(2);
8752   EVT VT = N->getValueType(0);
8753   EVT VT0 = N0.getValueType();
8754   SDLoc DL(N);
8755   SDNodeFlags Flags = N->getFlags();
8756 
8757   if (SDValue V = DAG.simplifySelect(N0, N1, N2))
8758     return V;
8759 
8760   // fold (select X, X, Y) -> (or X, Y)
8761   // fold (select X, 1, Y) -> (or C, Y)
8762   if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
8763     return DAG.getNode(ISD::OR, DL, VT, N0, N2);
8764 
8765   if (SDValue V = foldSelectOfConstants(N))
8766     return V;
8767 
8768   // fold (select C, 0, X) -> (and (not C), X)
8769   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
8770     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
8771     AddToWorklist(NOTNode.getNode());
8772     return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
8773   }
8774   // fold (select C, X, 1) -> (or (not C), X)
8775   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
8776     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
8777     AddToWorklist(NOTNode.getNode());
8778     return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
8779   }
8780   // fold (select X, Y, X) -> (and X, Y)
8781   // fold (select X, Y, 0) -> (and X, Y)
8782   if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
8783     return DAG.getNode(ISD::AND, DL, VT, N0, N1);
8784 
8785   // If we can fold this based on the true/false value, do so.
8786   if (SimplifySelectOps(N, N1, N2))
8787     return SDValue(N, 0); // Don't revisit N.
8788 
8789   if (VT0 == MVT::i1) {
8790     // The code in this block deals with the following 2 equivalences:
8791     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
8792     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
8793     // The target can specify its preferred form with the
8794     // shouldNormalizeToSelectSequence() callback. However we always transform
8795     // to the right anyway if we find the inner select exists in the DAG anyway
8796     // and we always transform to the left side if we know that we can further
8797     // optimize the combination of the conditions.
8798     bool normalizeToSequence =
8799         TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
8800     // select (and Cond0, Cond1), X, Y
8801     //   -> select Cond0, (select Cond1, X, Y), Y
8802     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
8803       SDValue Cond0 = N0->getOperand(0);
8804       SDValue Cond1 = N0->getOperand(1);
8805       SDValue InnerSelect =
8806           DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
8807       if (normalizeToSequence || !InnerSelect.use_empty())
8808         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
8809                            InnerSelect, N2, Flags);
8810       // Cleanup on failure.
8811       if (InnerSelect.use_empty())
8812         recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8813     }
8814     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
8815     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
8816       SDValue Cond0 = N0->getOperand(0);
8817       SDValue Cond1 = N0->getOperand(1);
8818       SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
8819                                         Cond1, N1, N2, Flags);
8820       if (normalizeToSequence || !InnerSelect.use_empty())
8821         return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
8822                            InnerSelect, Flags);
8823       // Cleanup on failure.
8824       if (InnerSelect.use_empty())
8825         recursivelyDeleteUnusedNodes(InnerSelect.getNode());
8826     }
8827 
8828     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
8829     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
8830       SDValue N1_0 = N1->getOperand(0);
8831       SDValue N1_1 = N1->getOperand(1);
8832       SDValue N1_2 = N1->getOperand(2);
8833       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
8834         // Create the actual and node if we can generate good code for it.
8835         if (!normalizeToSequence) {
8836           SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
8837           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
8838                              N2, Flags);
8839         }
8840         // Otherwise see if we can optimize the "and" to a better pattern.
8841         if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
8842           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
8843                              N2, Flags);
8844         }
8845       }
8846     }
8847     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
8848     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
8849       SDValue N2_0 = N2->getOperand(0);
8850       SDValue N2_1 = N2->getOperand(1);
8851       SDValue N2_2 = N2->getOperand(2);
8852       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
8853         // Create the actual or node if we can generate good code for it.
8854         if (!normalizeToSequence) {
8855           SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
8856           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
8857                              N2_2, Flags);
8858         }
8859         // Otherwise see if we can optimize to a better pattern.
8860         if (SDValue Combined = visitORLike(N0, N2_0, N))
8861           return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
8862                              N2_2, Flags);
8863       }
8864     }
8865   }
8866 
8867   // select (not Cond), N1, N2 -> select Cond, N2, N1
8868   if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) {
8869     SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1);
8870     SelectOp->setFlags(Flags);
8871     return SelectOp;
8872   }
8873 
8874   // Fold selects based on a setcc into other things, such as min/max/abs.
8875   if (N0.getOpcode() == ISD::SETCC) {
8876     SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
8877     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
8878 
8879     // select (fcmp lt x, y), x, y -> fminnum x, y
8880     // select (fcmp gt x, y), x, y -> fmaxnum x, y
8881     //
8882     // This is OK if we don't care what happens if either operand is a NaN.
8883     if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI))
8884       if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2,
8885                                                 CC, TLI, DAG))
8886         return FMinMax;
8887 
8888     // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
8889     // This is conservatively limited to pre-legal-operations to give targets
8890     // a chance to reverse the transform if they want to do that. Also, it is
8891     // unlikely that the pattern would be formed late, so it's probably not
8892     // worth going through the other checks.
8893     if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
8894         CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
8895         N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
8896       auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
8897       auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
8898       if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
8899         // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
8900         // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
8901         //
8902         // The IR equivalent of this transform would have this form:
8903         //   %a = add %x, C
8904         //   %c = icmp ugt %x, ~C
8905         //   %r = select %c, -1, %a
8906         //   =>
8907         //   %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
8908         //   %u0 = extractvalue %u, 0
8909         //   %u1 = extractvalue %u, 1
8910         //   %r = select %u1, -1, %u0
8911         SDVTList VTs = DAG.getVTList(VT, VT0);
8912         SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
8913         return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
8914       }
8915     }
8916 
8917     if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
8918         (!LegalOperations &&
8919          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) {
8920       // Any flags available in a select/setcc fold will be on the setcc as they
8921       // migrated from fcmp
8922       Flags = N0.getNode()->getFlags();
8923       SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1,
8924                                        N2, N0.getOperand(2));
8925       SelectNode->setFlags(Flags);
8926       return SelectNode;
8927     }
8928 
8929     return SimplifySelect(DL, N0, N1, N2);
8930   }
8931 
8932   return SDValue();
8933 }
8934 
8935 // This function assumes all the vselect's arguments are CONCAT_VECTOR
8936 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
8937 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
8938   SDLoc DL(N);
8939   SDValue Cond = N->getOperand(0);
8940   SDValue LHS = N->getOperand(1);
8941   SDValue RHS = N->getOperand(2);
8942   EVT VT = N->getValueType(0);
8943   int NumElems = VT.getVectorNumElements();
8944   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
8945          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
8946          Cond.getOpcode() == ISD::BUILD_VECTOR);
8947 
8948   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
8949   // binary ones here.
8950   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
8951     return SDValue();
8952 
8953   // We're sure we have an even number of elements due to the
8954   // concat_vectors we have as arguments to vselect.
8955   // Skip BV elements until we find one that's not an UNDEF
8956   // After we find an UNDEF element, keep looping until we get to half the
8957   // length of the BV and see if all the non-undef nodes are the same.
8958   ConstantSDNode *BottomHalf = nullptr;
8959   for (int i = 0; i < NumElems / 2; ++i) {
8960     if (Cond->getOperand(i)->isUndef())
8961       continue;
8962 
8963     if (BottomHalf == nullptr)
8964       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
8965     else if (Cond->getOperand(i).getNode() != BottomHalf)
8966       return SDValue();
8967   }
8968 
8969   // Do the same for the second half of the BuildVector
8970   ConstantSDNode *TopHalf = nullptr;
8971   for (int i = NumElems / 2; i < NumElems; ++i) {
8972     if (Cond->getOperand(i)->isUndef())
8973       continue;
8974 
8975     if (TopHalf == nullptr)
8976       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
8977     else if (Cond->getOperand(i).getNode() != TopHalf)
8978       return SDValue();
8979   }
8980 
8981   assert(TopHalf && BottomHalf &&
8982          "One half of the selector was all UNDEFs and the other was all the "
8983          "same value. This should have been addressed before this function.");
8984   return DAG.getNode(
8985       ISD::CONCAT_VECTORS, DL, VT,
8986       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
8987       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
8988 }
8989 
8990 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
8991   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
8992   SDValue Mask = MSC->getMask();
8993   SDValue Chain = MSC->getChain();
8994   SDLoc DL(N);
8995 
8996   // Zap scatters with a zero mask.
8997   if (ISD::isBuildVectorAllZeros(Mask.getNode()))
8998     return Chain;
8999 
9000   return SDValue();
9001 }
9002 
9003 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
9004   MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
9005   SDValue Mask = MST->getMask();
9006   SDValue Chain = MST->getChain();
9007   SDLoc DL(N);
9008 
9009   // Zap masked stores with a zero mask.
9010   if (ISD::isBuildVectorAllZeros(Mask.getNode()))
9011     return Chain;
9012 
9013   // Try transforming N to an indexed store.
9014   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9015     return SDValue(N, 0);
9016 
9017   return SDValue();
9018 }
9019 
9020 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
9021   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
9022   SDValue Mask = MGT->getMask();
9023   SDLoc DL(N);
9024 
9025   // Zap gathers with a zero mask.
9026   if (ISD::isBuildVectorAllZeros(Mask.getNode()))
9027     return CombineTo(N, MGT->getPassThru(), MGT->getChain());
9028 
9029   return SDValue();
9030 }
9031 
9032 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
9033   MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
9034   SDValue Mask = MLD->getMask();
9035   SDLoc DL(N);
9036 
9037   // Zap masked loads with a zero mask.
9038   if (ISD::isBuildVectorAllZeros(Mask.getNode()))
9039     return CombineTo(N, MLD->getPassThru(), MLD->getChain());
9040 
9041   // Try transforming N to an indexed load.
9042   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9043     return SDValue(N, 0);
9044 
9045   return SDValue();
9046 }
9047 
9048 /// A vector select of 2 constant vectors can be simplified to math/logic to
9049 /// avoid a variable select instruction and possibly avoid constant loads.
9050 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
9051   SDValue Cond = N->getOperand(0);
9052   SDValue N1 = N->getOperand(1);
9053   SDValue N2 = N->getOperand(2);
9054   EVT VT = N->getValueType(0);
9055   if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
9056       !TLI.convertSelectOfConstantsToMath(VT) ||
9057       !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
9058       !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
9059     return SDValue();
9060 
9061   // Check if we can use the condition value to increment/decrement a single
9062   // constant value. This simplifies a select to an add and removes a constant
9063   // load/materialization from the general case.
9064   bool AllAddOne = true;
9065   bool AllSubOne = true;
9066   unsigned Elts = VT.getVectorNumElements();
9067   for (unsigned i = 0; i != Elts; ++i) {
9068     SDValue N1Elt = N1.getOperand(i);
9069     SDValue N2Elt = N2.getOperand(i);
9070     if (N1Elt.isUndef() || N2Elt.isUndef())
9071       continue;
9072     if (N1Elt.getValueType() != N2Elt.getValueType())
9073       continue;
9074 
9075     const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
9076     const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
9077     if (C1 != C2 + 1)
9078       AllAddOne = false;
9079     if (C1 != C2 - 1)
9080       AllSubOne = false;
9081   }
9082 
9083   // Further simplifications for the extra-special cases where the constants are
9084   // all 0 or all -1 should be implemented as folds of these patterns.
9085   SDLoc DL(N);
9086   if (AllAddOne || AllSubOne) {
9087     // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
9088     // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
9089     auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9090     SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
9091     return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
9092   }
9093 
9094   // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
9095   APInt Pow2C;
9096   if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
9097       isNullOrNullSplat(N2)) {
9098     SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
9099     SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
9100     return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
9101   }
9102 
9103   if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
9104     return V;
9105 
9106   // The general case for select-of-constants:
9107   // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
9108   // ...but that only makes sense if a vselect is slower than 2 logic ops, so
9109   // leave that to a machine-specific pass.
9110   return SDValue();
9111 }
9112 
9113 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
9114   SDValue N0 = N->getOperand(0);
9115   SDValue N1 = N->getOperand(1);
9116   SDValue N2 = N->getOperand(2);
9117   EVT VT = N->getValueType(0);
9118   SDLoc DL(N);
9119 
9120   if (SDValue V = DAG.simplifySelect(N0, N1, N2))
9121     return V;
9122 
9123   // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
9124   if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
9125     return DAG.getSelect(DL, VT, F, N2, N1);
9126 
9127   // Canonicalize integer abs.
9128   // vselect (setg[te] X,  0),  X, -X ->
9129   // vselect (setgt    X, -1),  X, -X ->
9130   // vselect (setl[te] X,  0), -X,  X ->
9131   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9132   if (N0.getOpcode() == ISD::SETCC) {
9133     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
9134     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
9135     bool isAbs = false;
9136     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
9137 
9138     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9139          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
9140         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
9141       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
9142     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
9143              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
9144       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
9145 
9146     if (isAbs) {
9147       if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
9148         return DAG.getNode(ISD::ABS, DL, VT, LHS);
9149 
9150       SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS,
9151                                   DAG.getConstant(VT.getScalarSizeInBits() - 1,
9152                                                   DL, getShiftAmountTy(VT)));
9153       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
9154       AddToWorklist(Shift.getNode());
9155       AddToWorklist(Add.getNode());
9156       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
9157     }
9158 
9159     // vselect x, y (fcmp lt x, y) -> fminnum x, y
9160     // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
9161     //
9162     // This is OK if we don't care about what happens if either operand is a
9163     // NaN.
9164     //
9165     if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) {
9166       if (SDValue FMinMax =
9167               combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC, TLI, DAG))
9168         return FMinMax;
9169     }
9170 
9171     // If this select has a condition (setcc) with narrower operands than the
9172     // select, try to widen the compare to match the select width.
9173     // TODO: This should be extended to handle any constant.
9174     // TODO: This could be extended to handle non-loading patterns, but that
9175     //       requires thorough testing to avoid regressions.
9176     if (isNullOrNullSplat(RHS)) {
9177       EVT NarrowVT = LHS.getValueType();
9178       EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger();
9179       EVT SetCCVT = getSetCCResultType(LHS.getValueType());
9180       unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
9181       unsigned WideWidth = WideVT.getScalarSizeInBits();
9182       bool IsSigned = isSignedIntSetCC(CC);
9183       auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
9184       if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() &&
9185           SetCCWidth != 1 && SetCCWidth < WideWidth &&
9186           TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) &&
9187           TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
9188         // Both compare operands can be widened for free. The LHS can use an
9189         // extended load, and the RHS is a constant:
9190         //   vselect (ext (setcc load(X), C)), N1, N2 -->
9191         //   vselect (setcc extload(X), C'), N1, N2
9192         auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9193         SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
9194         SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
9195         EVT WideSetCCVT = getSetCCResultType(WideVT);
9196         SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
9197         return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
9198       }
9199     }
9200   }
9201 
9202   if (SimplifySelectOps(N, N1, N2))
9203     return SDValue(N, 0);  // Don't revisit N.
9204 
9205   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
9206   if (ISD::isBuildVectorAllOnes(N0.getNode()))
9207     return N1;
9208   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
9209   if (ISD::isBuildVectorAllZeros(N0.getNode()))
9210     return N2;
9211 
9212   // The ConvertSelectToConcatVector function is assuming both the above
9213   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
9214   // and addressed.
9215   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9216       N2.getOpcode() == ISD::CONCAT_VECTORS &&
9217       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
9218     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
9219       return CV;
9220   }
9221 
9222   if (SDValue V = foldVSelectOfConstants(N))
9223     return V;
9224 
9225   return SDValue();
9226 }
9227 
9228 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
9229   SDValue N0 = N->getOperand(0);
9230   SDValue N1 = N->getOperand(1);
9231   SDValue N2 = N->getOperand(2);
9232   SDValue N3 = N->getOperand(3);
9233   SDValue N4 = N->getOperand(4);
9234   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
9235 
9236   // fold select_cc lhs, rhs, x, x, cc -> x
9237   if (N2 == N3)
9238     return N2;
9239 
9240   // Determine if the condition we're dealing with is constant
9241   if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
9242                                   CC, SDLoc(N), false)) {
9243     AddToWorklist(SCC.getNode());
9244 
9245     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
9246       if (!SCCC->isNullValue())
9247         return N2;    // cond always true -> true val
9248       else
9249         return N3;    // cond always false -> false val
9250     } else if (SCC->isUndef()) {
9251       // When the condition is UNDEF, just return the first operand. This is
9252       // coherent the DAG creation, no setcc node is created in this case
9253       return N2;
9254     } else if (SCC.getOpcode() == ISD::SETCC) {
9255       // Fold to a simpler select_cc
9256       SDValue SelectOp = DAG.getNode(
9257           ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0),
9258           SCC.getOperand(1), N2, N3, SCC.getOperand(2));
9259       SelectOp->setFlags(SCC->getFlags());
9260       return SelectOp;
9261     }
9262   }
9263 
9264   // If we can fold this based on the true/false value, do so.
9265   if (SimplifySelectOps(N, N2, N3))
9266     return SDValue(N, 0);  // Don't revisit N.
9267 
9268   // fold select_cc into other things, such as min/max/abs
9269   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
9270 }
9271 
9272 SDValue DAGCombiner::visitSETCC(SDNode *N) {
9273   // setcc is very commonly used as an argument to brcond. This pattern
9274   // also lend itself to numerous combines and, as a result, it is desired
9275   // we keep the argument to a brcond as a setcc as much as possible.
9276   bool PreferSetCC =
9277       N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
9278 
9279   SDValue Combined = SimplifySetCC(
9280       N->getValueType(0), N->getOperand(0), N->getOperand(1),
9281       cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC);
9282 
9283   if (!Combined)
9284     return SDValue();
9285 
9286   // If we prefer to have a setcc, and we don't, we'll try our best to
9287   // recreate one using rebuildSetCC.
9288   if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
9289     SDValue NewSetCC = rebuildSetCC(Combined);
9290 
9291     // We don't have anything interesting to combine to.
9292     if (NewSetCC.getNode() == N)
9293       return SDValue();
9294 
9295     if (NewSetCC)
9296       return NewSetCC;
9297   }
9298 
9299   return Combined;
9300 }
9301 
9302 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
9303   SDValue LHS = N->getOperand(0);
9304   SDValue RHS = N->getOperand(1);
9305   SDValue Carry = N->getOperand(2);
9306   SDValue Cond = N->getOperand(3);
9307 
9308   // If Carry is false, fold to a regular SETCC.
9309   if (isNullConstant(Carry))
9310     return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
9311 
9312   return SDValue();
9313 }
9314 
9315 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
9316 /// a build_vector of constants.
9317 /// This function is called by the DAGCombiner when visiting sext/zext/aext
9318 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
9319 /// Vector extends are not folded if operations are legal; this is to
9320 /// avoid introducing illegal build_vector dag nodes.
9321 static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
9322                                          SelectionDAG &DAG, bool LegalTypes) {
9323   unsigned Opcode = N->getOpcode();
9324   SDValue N0 = N->getOperand(0);
9325   EVT VT = N->getValueType(0);
9326   SDLoc DL(N);
9327 
9328   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
9329          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
9330          Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
9331          && "Expected EXTEND dag node in input!");
9332 
9333   // fold (sext c1) -> c1
9334   // fold (zext c1) -> c1
9335   // fold (aext c1) -> c1
9336   if (isa<ConstantSDNode>(N0))
9337     return DAG.getNode(Opcode, DL, VT, N0);
9338 
9339   // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
9340   // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
9341   // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
9342   if (N0->getOpcode() == ISD::SELECT) {
9343     SDValue Op1 = N0->getOperand(1);
9344     SDValue Op2 = N0->getOperand(2);
9345     if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
9346         (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
9347       // For any_extend, choose sign extension of the constants to allow a
9348       // possible further transform to sign_extend_inreg.i.e.
9349       //
9350       // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
9351       // t2: i64 = any_extend t1
9352       // -->
9353       // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
9354       // -->
9355       // t4: i64 = sign_extend_inreg t3
9356       unsigned FoldOpc = Opcode;
9357       if (FoldOpc == ISD::ANY_EXTEND)
9358         FoldOpc = ISD::SIGN_EXTEND;
9359       return DAG.getSelect(DL, VT, N0->getOperand(0),
9360                            DAG.getNode(FoldOpc, DL, VT, Op1),
9361                            DAG.getNode(FoldOpc, DL, VT, Op2));
9362     }
9363   }
9364 
9365   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
9366   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
9367   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
9368   EVT SVT = VT.getScalarType();
9369   if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
9370       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
9371     return SDValue();
9372 
9373   // We can fold this node into a build_vector.
9374   unsigned VTBits = SVT.getSizeInBits();
9375   unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
9376   SmallVector<SDValue, 8> Elts;
9377   unsigned NumElts = VT.getVectorNumElements();
9378 
9379   // For zero-extensions, UNDEF elements still guarantee to have the upper
9380   // bits set to zero.
9381   bool IsZext =
9382       Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG;
9383 
9384   for (unsigned i = 0; i != NumElts; ++i) {
9385     SDValue Op = N0.getOperand(i);
9386     if (Op.isUndef()) {
9387       Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT));
9388       continue;
9389     }
9390 
9391     SDLoc DL(Op);
9392     // Get the constant value and if needed trunc it to the size of the type.
9393     // Nodes like build_vector might have constants wider than the scalar type.
9394     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
9395     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
9396       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
9397     else
9398       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
9399   }
9400 
9401   return DAG.getBuildVector(VT, DL, Elts);
9402 }
9403 
9404 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
9405 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
9406 // transformation. Returns true if extension are possible and the above
9407 // mentioned transformation is profitable.
9408 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
9409                                     unsigned ExtOpc,
9410                                     SmallVectorImpl<SDNode *> &ExtendNodes,
9411                                     const TargetLowering &TLI) {
9412   bool HasCopyToRegUses = false;
9413   bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
9414   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
9415                             UE = N0.getNode()->use_end();
9416        UI != UE; ++UI) {
9417     SDNode *User = *UI;
9418     if (User == N)
9419       continue;
9420     if (UI.getUse().getResNo() != N0.getResNo())
9421       continue;
9422     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
9423     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
9424       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
9425       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
9426         // Sign bits will be lost after a zext.
9427         return false;
9428       bool Add = false;
9429       for (unsigned i = 0; i != 2; ++i) {
9430         SDValue UseOp = User->getOperand(i);
9431         if (UseOp == N0)
9432           continue;
9433         if (!isa<ConstantSDNode>(UseOp))
9434           return false;
9435         Add = true;
9436       }
9437       if (Add)
9438         ExtendNodes.push_back(User);
9439       continue;
9440     }
9441     // If truncates aren't free and there are users we can't
9442     // extend, it isn't worthwhile.
9443     if (!isTruncFree)
9444       return false;
9445     // Remember if this value is live-out.
9446     if (User->getOpcode() == ISD::CopyToReg)
9447       HasCopyToRegUses = true;
9448   }
9449 
9450   if (HasCopyToRegUses) {
9451     bool BothLiveOut = false;
9452     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
9453          UI != UE; ++UI) {
9454       SDUse &Use = UI.getUse();
9455       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
9456         BothLiveOut = true;
9457         break;
9458       }
9459     }
9460     if (BothLiveOut)
9461       // Both unextended and extended values are live out. There had better be
9462       // a good reason for the transformation.
9463       return ExtendNodes.size();
9464   }
9465   return true;
9466 }
9467 
9468 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
9469                                   SDValue OrigLoad, SDValue ExtLoad,
9470                                   ISD::NodeType ExtType) {
9471   // Extend SetCC uses if necessary.
9472   SDLoc DL(ExtLoad);
9473   for (SDNode *SetCC : SetCCs) {
9474     SmallVector<SDValue, 4> Ops;
9475 
9476     for (unsigned j = 0; j != 2; ++j) {
9477       SDValue SOp = SetCC->getOperand(j);
9478       if (SOp == OrigLoad)
9479         Ops.push_back(ExtLoad);
9480       else
9481         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
9482     }
9483 
9484     Ops.push_back(SetCC->getOperand(2));
9485     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
9486   }
9487 }
9488 
9489 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
9490 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
9491   SDValue N0 = N->getOperand(0);
9492   EVT DstVT = N->getValueType(0);
9493   EVT SrcVT = N0.getValueType();
9494 
9495   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
9496           N->getOpcode() == ISD::ZERO_EXTEND) &&
9497          "Unexpected node type (not an extend)!");
9498 
9499   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
9500   // For example, on a target with legal v4i32, but illegal v8i32, turn:
9501   //   (v8i32 (sext (v8i16 (load x))))
9502   // into:
9503   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
9504   //                          (v4i32 (sextload (x + 16)))))
9505   // Where uses of the original load, i.e.:
9506   //   (v8i16 (load x))
9507   // are replaced with:
9508   //   (v8i16 (truncate
9509   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
9510   //                            (v4i32 (sextload (x + 16)))))))
9511   //
9512   // This combine is only applicable to illegal, but splittable, vectors.
9513   // All legal types, and illegal non-vector types, are handled elsewhere.
9514   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
9515   //
9516   if (N0->getOpcode() != ISD::LOAD)
9517     return SDValue();
9518 
9519   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9520 
9521   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
9522       !N0.hasOneUse() || !LN0->isSimple() ||
9523       !DstVT.isVector() || !DstVT.isPow2VectorType() ||
9524       !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
9525     return SDValue();
9526 
9527   SmallVector<SDNode *, 4> SetCCs;
9528   if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
9529     return SDValue();
9530 
9531   ISD::LoadExtType ExtType =
9532       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
9533 
9534   // Try to split the vector types to get down to legal types.
9535   EVT SplitSrcVT = SrcVT;
9536   EVT SplitDstVT = DstVT;
9537   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
9538          SplitSrcVT.getVectorNumElements() > 1) {
9539     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
9540     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
9541   }
9542 
9543   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
9544     return SDValue();
9545 
9546   assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
9547 
9548   SDLoc DL(N);
9549   const unsigned NumSplits =
9550       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
9551   const unsigned Stride = SplitSrcVT.getStoreSize();
9552   SmallVector<SDValue, 4> Loads;
9553   SmallVector<SDValue, 4> Chains;
9554 
9555   SDValue BasePtr = LN0->getBasePtr();
9556   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
9557     const unsigned Offset = Idx * Stride;
9558     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
9559 
9560     SDValue SplitLoad = DAG.getExtLoad(
9561         ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
9562         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
9563         LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
9564 
9565     BasePtr = DAG.getMemBasePlusOffset(BasePtr, Stride, DL);
9566 
9567     Loads.push_back(SplitLoad.getValue(0));
9568     Chains.push_back(SplitLoad.getValue(1));
9569   }
9570 
9571   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9572   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
9573 
9574   // Simplify TF.
9575   AddToWorklist(NewChain.getNode());
9576 
9577   CombineTo(N, NewValue);
9578 
9579   // Replace uses of the original load (before extension)
9580   // with a truncate of the concatenated sextloaded vectors.
9581   SDValue Trunc =
9582       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
9583   ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
9584   CombineTo(N0.getNode(), Trunc, NewChain);
9585   return SDValue(N, 0); // Return N so it doesn't get rechecked!
9586 }
9587 
9588 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9589 //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9590 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
9591   assert(N->getOpcode() == ISD::ZERO_EXTEND);
9592   EVT VT = N->getValueType(0);
9593   EVT OrigVT = N->getOperand(0).getValueType();
9594   if (TLI.isZExtFree(OrigVT, VT))
9595     return SDValue();
9596 
9597   // and/or/xor
9598   SDValue N0 = N->getOperand(0);
9599   if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
9600         N0.getOpcode() == ISD::XOR) ||
9601       N0.getOperand(1).getOpcode() != ISD::Constant ||
9602       (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
9603     return SDValue();
9604 
9605   // shl/shr
9606   SDValue N1 = N0->getOperand(0);
9607   if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
9608       N1.getOperand(1).getOpcode() != ISD::Constant ||
9609       (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
9610     return SDValue();
9611 
9612   // load
9613   if (!isa<LoadSDNode>(N1.getOperand(0)))
9614     return SDValue();
9615   LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
9616   EVT MemVT = Load->getMemoryVT();
9617   if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
9618       Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
9619     return SDValue();
9620 
9621 
9622   // If the shift op is SHL, the logic op must be AND, otherwise the result
9623   // will be wrong.
9624   if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
9625     return SDValue();
9626 
9627   if (!N0.hasOneUse() || !N1.hasOneUse())
9628     return SDValue();
9629 
9630   SmallVector<SDNode*, 4> SetCCs;
9631   if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
9632                                ISD::ZERO_EXTEND, SetCCs, TLI))
9633     return SDValue();
9634 
9635   // Actually do the transformation.
9636   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
9637                                    Load->getChain(), Load->getBasePtr(),
9638                                    Load->getMemoryVT(), Load->getMemOperand());
9639 
9640   SDLoc DL1(N1);
9641   SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
9642                               N1.getOperand(1));
9643 
9644   APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
9645   SDLoc DL0(N0);
9646   SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
9647                             DAG.getConstant(Mask, DL0, VT));
9648 
9649   ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
9650   CombineTo(N, And);
9651   if (SDValue(Load, 0).hasOneUse()) {
9652     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
9653   } else {
9654     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
9655                                 Load->getValueType(0), ExtLoad);
9656     CombineTo(Load, Trunc, ExtLoad.getValue(1));
9657   }
9658 
9659   // N0 is dead at this point.
9660   recursivelyDeleteUnusedNodes(N0.getNode());
9661 
9662   return SDValue(N,0); // Return N so it doesn't get rechecked!
9663 }
9664 
9665 /// If we're narrowing or widening the result of a vector select and the final
9666 /// size is the same size as a setcc (compare) feeding the select, then try to
9667 /// apply the cast operation to the select's operands because matching vector
9668 /// sizes for a select condition and other operands should be more efficient.
9669 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
9670   unsigned CastOpcode = Cast->getOpcode();
9671   assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
9672           CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
9673           CastOpcode == ISD::FP_ROUND) &&
9674          "Unexpected opcode for vector select narrowing/widening");
9675 
9676   // We only do this transform before legal ops because the pattern may be
9677   // obfuscated by target-specific operations after legalization. Do not create
9678   // an illegal select op, however, because that may be difficult to lower.
9679   EVT VT = Cast->getValueType(0);
9680   if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
9681     return SDValue();
9682 
9683   SDValue VSel = Cast->getOperand(0);
9684   if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
9685       VSel.getOperand(0).getOpcode() != ISD::SETCC)
9686     return SDValue();
9687 
9688   // Does the setcc have the same vector size as the casted select?
9689   SDValue SetCC = VSel.getOperand(0);
9690   EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
9691   if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
9692     return SDValue();
9693 
9694   // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
9695   SDValue A = VSel.getOperand(1);
9696   SDValue B = VSel.getOperand(2);
9697   SDValue CastA, CastB;
9698   SDLoc DL(Cast);
9699   if (CastOpcode == ISD::FP_ROUND) {
9700     // FP_ROUND (fptrunc) has an extra flag operand to pass along.
9701     CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
9702     CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
9703   } else {
9704     CastA = DAG.getNode(CastOpcode, DL, VT, A);
9705     CastB = DAG.getNode(CastOpcode, DL, VT, B);
9706   }
9707   return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
9708 }
9709 
9710 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9711 // fold ([s|z]ext (     extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9712 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
9713                                      const TargetLowering &TLI, EVT VT,
9714                                      bool LegalOperations, SDNode *N,
9715                                      SDValue N0, ISD::LoadExtType ExtLoadType) {
9716   SDNode *N0Node = N0.getNode();
9717   bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
9718                                                    : ISD::isZEXTLoad(N0Node);
9719   if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
9720       !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
9721     return SDValue();
9722 
9723   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9724   EVT MemVT = LN0->getMemoryVT();
9725   if ((LegalOperations || !LN0->isSimple() ||
9726        VT.isVector()) &&
9727       !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
9728     return SDValue();
9729 
9730   SDValue ExtLoad =
9731       DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
9732                      LN0->getBasePtr(), MemVT, LN0->getMemOperand());
9733   Combiner.CombineTo(N, ExtLoad);
9734   DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9735   if (LN0->use_empty())
9736     Combiner.recursivelyDeleteUnusedNodes(LN0);
9737   return SDValue(N, 0); // Return N so it doesn't get rechecked!
9738 }
9739 
9740 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9741 // Only generate vector extloads when 1) they're legal, and 2) they are
9742 // deemed desirable by the target.
9743 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
9744                                   const TargetLowering &TLI, EVT VT,
9745                                   bool LegalOperations, SDNode *N, SDValue N0,
9746                                   ISD::LoadExtType ExtLoadType,
9747                                   ISD::NodeType ExtOpc) {
9748   if (!ISD::isNON_EXTLoad(N0.getNode()) ||
9749       !ISD::isUNINDEXEDLoad(N0.getNode()) ||
9750       ((LegalOperations || VT.isVector() ||
9751         !cast<LoadSDNode>(N0)->isSimple()) &&
9752        !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
9753     return {};
9754 
9755   bool DoXform = true;
9756   SmallVector<SDNode *, 4> SetCCs;
9757   if (!N0.hasOneUse())
9758     DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
9759   if (VT.isVector())
9760     DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
9761   if (!DoXform)
9762     return {};
9763 
9764   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9765   SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
9766                                    LN0->getBasePtr(), N0.getValueType(),
9767                                    LN0->getMemOperand());
9768   Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
9769   // If the load value is used only by N, replace it via CombineTo N.
9770   bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
9771   Combiner.CombineTo(N, ExtLoad);
9772   if (NoReplaceTrunc) {
9773     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
9774     Combiner.recursivelyDeleteUnusedNodes(LN0);
9775   } else {
9776     SDValue Trunc =
9777         DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
9778     Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
9779   }
9780   return SDValue(N, 0); // Return N so it doesn't get rechecked!
9781 }
9782 
9783 static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG,
9784                                         const TargetLowering &TLI, EVT VT,
9785                                         SDNode *N, SDValue N0,
9786                                         ISD::LoadExtType ExtLoadType,
9787                                         ISD::NodeType ExtOpc) {
9788   if (!N0.hasOneUse())
9789     return SDValue();
9790 
9791   MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0);
9792   if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
9793     return SDValue();
9794 
9795   if (!TLI.isLoadExtLegal(ExtLoadType, VT, Ld->getValueType(0)))
9796     return SDValue();
9797 
9798   if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
9799     return SDValue();
9800 
9801   SDLoc dl(Ld);
9802   SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
9803   SDValue NewLoad = DAG.getMaskedLoad(
9804       VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
9805       PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
9806       ExtLoadType, Ld->isExpandingLoad());
9807   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
9808   return NewLoad;
9809 }
9810 
9811 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG,
9812                                        bool LegalOperations) {
9813   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
9814           N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
9815 
9816   SDValue SetCC = N->getOperand(0);
9817   if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
9818       !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
9819     return SDValue();
9820 
9821   SDValue X = SetCC.getOperand(0);
9822   SDValue Ones = SetCC.getOperand(1);
9823   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
9824   EVT VT = N->getValueType(0);
9825   EVT XVT = X.getValueType();
9826   // setge X, C is canonicalized to setgt, so we do not need to match that
9827   // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
9828   // not require the 'not' op.
9829   if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
9830     // Invert and smear/shift the sign bit:
9831     // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
9832     // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
9833     SDLoc DL(N);
9834     unsigned ShCt = VT.getSizeInBits() - 1;
9835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9836     if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
9837       SDValue NotX = DAG.getNOT(DL, X, VT);
9838       SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
9839       auto ShiftOpcode =
9840         N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
9841       return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
9842     }
9843   }
9844   return SDValue();
9845 }
9846 
9847 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
9848   SDValue N0 = N->getOperand(0);
9849   EVT VT = N->getValueType(0);
9850   SDLoc DL(N);
9851 
9852   if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
9853     return Res;
9854 
9855   // fold (sext (sext x)) -> (sext x)
9856   // fold (sext (aext x)) -> (sext x)
9857   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
9858     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
9859 
9860   if (N0.getOpcode() == ISD::TRUNCATE) {
9861     // fold (sext (truncate (load x))) -> (sext (smaller load x))
9862     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
9863     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
9864       SDNode *oye = N0.getOperand(0).getNode();
9865       if (NarrowLoad.getNode() != N0.getNode()) {
9866         CombineTo(N0.getNode(), NarrowLoad);
9867         // CombineTo deleted the truncate, if needed, but not what's under it.
9868         AddToWorklist(oye);
9869       }
9870       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9871     }
9872 
9873     // See if the value being truncated is already sign extended.  If so, just
9874     // eliminate the trunc/sext pair.
9875     SDValue Op = N0.getOperand(0);
9876     unsigned OpBits   = Op.getScalarValueSizeInBits();
9877     unsigned MidBits  = N0.getScalarValueSizeInBits();
9878     unsigned DestBits = VT.getScalarSizeInBits();
9879     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
9880 
9881     if (OpBits == DestBits) {
9882       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
9883       // bits, it is already ready.
9884       if (NumSignBits > DestBits-MidBits)
9885         return Op;
9886     } else if (OpBits < DestBits) {
9887       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
9888       // bits, just sext from i32.
9889       if (NumSignBits > OpBits-MidBits)
9890         return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
9891     } else {
9892       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
9893       // bits, just truncate to i32.
9894       if (NumSignBits > OpBits-MidBits)
9895         return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
9896     }
9897 
9898     // fold (sext (truncate x)) -> (sextinreg x).
9899     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
9900                                                  N0.getValueType())) {
9901       if (OpBits < DestBits)
9902         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
9903       else if (OpBits > DestBits)
9904         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
9905       return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
9906                          DAG.getValueType(N0.getValueType()));
9907     }
9908   }
9909 
9910   // Try to simplify (sext (load x)).
9911   if (SDValue foldedExt =
9912           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
9913                              ISD::SEXTLOAD, ISD::SIGN_EXTEND))
9914     return foldedExt;
9915 
9916   if (SDValue foldedExt =
9917       tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD,
9918                                ISD::SIGN_EXTEND))
9919     return foldedExt;
9920 
9921   // fold (sext (load x)) to multiple smaller sextloads.
9922   // Only on illegal but splittable vectors.
9923   if (SDValue ExtLoad = CombineExtLoad(N))
9924     return ExtLoad;
9925 
9926   // Try to simplify (sext (sextload x)).
9927   if (SDValue foldedExt = tryToFoldExtOfExtload(
9928           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
9929     return foldedExt;
9930 
9931   // fold (sext (and/or/xor (load x), cst)) ->
9932   //      (and/or/xor (sextload x), (sext cst))
9933   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
9934        N0.getOpcode() == ISD::XOR) &&
9935       isa<LoadSDNode>(N0.getOperand(0)) &&
9936       N0.getOperand(1).getOpcode() == ISD::Constant &&
9937       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
9938     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
9939     EVT MemVT = LN00->getMemoryVT();
9940     if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
9941       LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
9942       SmallVector<SDNode*, 4> SetCCs;
9943       bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
9944                                              ISD::SIGN_EXTEND, SetCCs, TLI);
9945       if (DoXform) {
9946         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
9947                                          LN00->getChain(), LN00->getBasePtr(),
9948                                          LN00->getMemoryVT(),
9949                                          LN00->getMemOperand());
9950         APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
9951         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
9952                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
9953         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
9954         bool NoReplaceTruncAnd = !N0.hasOneUse();
9955         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
9956         CombineTo(N, And);
9957         // If N0 has multiple uses, change other uses as well.
9958         if (NoReplaceTruncAnd) {
9959           SDValue TruncAnd =
9960               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
9961           CombineTo(N0.getNode(), TruncAnd);
9962         }
9963         if (NoReplaceTrunc) {
9964           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
9965         } else {
9966           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
9967                                       LN00->getValueType(0), ExtLoad);
9968           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
9969         }
9970         return SDValue(N,0); // Return N so it doesn't get rechecked!
9971       }
9972     }
9973   }
9974 
9975   if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
9976     return V;
9977 
9978   if (N0.getOpcode() == ISD::SETCC) {
9979     SDValue N00 = N0.getOperand(0);
9980     SDValue N01 = N0.getOperand(1);
9981     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
9982     EVT N00VT = N0.getOperand(0).getValueType();
9983 
9984     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
9985     // Only do this before legalize for now.
9986     if (VT.isVector() && !LegalOperations &&
9987         TLI.getBooleanContents(N00VT) ==
9988             TargetLowering::ZeroOrNegativeOneBooleanContent) {
9989       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
9990       // of the same size as the compared operands. Only optimize sext(setcc())
9991       // if this is the case.
9992       EVT SVT = getSetCCResultType(N00VT);
9993 
9994       // If we already have the desired type, don't change it.
9995       if (SVT != N0.getValueType()) {
9996         // We know that the # elements of the results is the same as the
9997         // # elements of the compare (and the # elements of the compare result
9998         // for that matter).  Check to see that they are the same size.  If so,
9999         // we know that the element size of the sext'd result matches the
10000         // element size of the compare operands.
10001         if (VT.getSizeInBits() == SVT.getSizeInBits())
10002           return DAG.getSetCC(DL, VT, N00, N01, CC);
10003 
10004         // If the desired elements are smaller or larger than the source
10005         // elements, we can use a matching integer vector type and then
10006         // truncate/sign extend.
10007         EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
10008         if (SVT == MatchingVecType) {
10009           SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
10010           return DAG.getSExtOrTrunc(VsetCC, DL, VT);
10011         }
10012       }
10013     }
10014 
10015     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
10016     // Here, T can be 1 or -1, depending on the type of the setcc and
10017     // getBooleanContents().
10018     unsigned SetCCWidth = N0.getScalarValueSizeInBits();
10019 
10020     // To determine the "true" side of the select, we need to know the high bit
10021     // of the value returned by the setcc if it evaluates to true.
10022     // If the type of the setcc is i1, then the true case of the select is just
10023     // sext(i1 1), that is, -1.
10024     // If the type of the setcc is larger (say, i8) then the value of the high
10025     // bit depends on getBooleanContents(), so ask TLI for a real "true" value
10026     // of the appropriate width.
10027     SDValue ExtTrueVal = (SetCCWidth == 1)
10028                              ? DAG.getAllOnesConstant(DL, VT)
10029                              : DAG.getBoolConstant(true, DL, VT, N00VT);
10030     SDValue Zero = DAG.getConstant(0, DL, VT);
10031     if (SDValue SCC =
10032             SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
10033       return SCC;
10034 
10035     if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
10036       EVT SetCCVT = getSetCCResultType(N00VT);
10037       // Don't do this transform for i1 because there's a select transform
10038       // that would reverse it.
10039       // TODO: We should not do this transform at all without a target hook
10040       // because a sext is likely cheaper than a select?
10041       if (SetCCVT.getScalarSizeInBits() != 1 &&
10042           (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
10043         SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
10044         return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
10045       }
10046     }
10047   }
10048 
10049   // fold (sext x) -> (zext x) if the sign bit is known zero.
10050   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
10051       DAG.SignBitIsZero(N0))
10052     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
10053 
10054   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10055     return NewVSel;
10056 
10057   // Eliminate this sign extend by doing a negation in the destination type:
10058   // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
10059   if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
10060       isNullOrNullSplat(N0.getOperand(0)) &&
10061       N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND &&
10062       TLI.isOperationLegalOrCustom(ISD::SUB, VT)) {
10063     SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
10064     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext);
10065   }
10066   // Eliminate this sign extend by doing a decrement in the destination type:
10067   // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
10068   if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
10069       isAllOnesOrAllOnesSplat(N0.getOperand(1)) &&
10070       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
10071       TLI.isOperationLegalOrCustom(ISD::ADD, VT)) {
10072     SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
10073     return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
10074   }
10075 
10076   return SDValue();
10077 }
10078 
10079 // isTruncateOf - If N is a truncate of some other value, return true, record
10080 // the value being truncated in Op and which of Op's bits are zero/one in Known.
10081 // This function computes KnownBits to avoid a duplicated call to
10082 // computeKnownBits in the caller.
10083 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
10084                          KnownBits &Known) {
10085   if (N->getOpcode() == ISD::TRUNCATE) {
10086     Op = N->getOperand(0);
10087     Known = DAG.computeKnownBits(Op);
10088     return true;
10089   }
10090 
10091   if (N.getOpcode() != ISD::SETCC ||
10092       N.getValueType().getScalarType() != MVT::i1 ||
10093       cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE)
10094     return false;
10095 
10096   SDValue Op0 = N->getOperand(0);
10097   SDValue Op1 = N->getOperand(1);
10098   assert(Op0.getValueType() == Op1.getValueType());
10099 
10100   if (isNullOrNullSplat(Op0))
10101     Op = Op1;
10102   else if (isNullOrNullSplat(Op1))
10103     Op = Op0;
10104   else
10105     return false;
10106 
10107   Known = DAG.computeKnownBits(Op);
10108 
10109   return (Known.Zero | 1).isAllOnesValue();
10110 }
10111 
10112 /// Given an extending node with a pop-count operand, if the target does not
10113 /// support a pop-count in the narrow source type but does support it in the
10114 /// destination type, widen the pop-count to the destination type.
10115 static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) {
10116   assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
10117           Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op");
10118 
10119   SDValue CtPop = Extend->getOperand(0);
10120   if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
10121     return SDValue();
10122 
10123   EVT VT = Extend->getValueType(0);
10124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10125   if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) ||
10126       !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT))
10127     return SDValue();
10128 
10129   // zext (ctpop X) --> ctpop (zext X)
10130   SDLoc DL(Extend);
10131   SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
10132   return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
10133 }
10134 
10135 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
10136   SDValue N0 = N->getOperand(0);
10137   EVT VT = N->getValueType(0);
10138 
10139   if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10140     return Res;
10141 
10142   // fold (zext (zext x)) -> (zext x)
10143   // fold (zext (aext x)) -> (zext x)
10144   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
10145     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
10146                        N0.getOperand(0));
10147 
10148   // fold (zext (truncate x)) -> (zext x) or
10149   //      (zext (truncate x)) -> (truncate x)
10150   // This is valid when the truncated bits of x are already zero.
10151   SDValue Op;
10152   KnownBits Known;
10153   if (isTruncateOf(DAG, N0, Op, Known)) {
10154     APInt TruncatedBits =
10155       (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
10156       APInt(Op.getScalarValueSizeInBits(), 0) :
10157       APInt::getBitsSet(Op.getScalarValueSizeInBits(),
10158                         N0.getScalarValueSizeInBits(),
10159                         std::min(Op.getScalarValueSizeInBits(),
10160                                  VT.getScalarSizeInBits()));
10161     if (TruncatedBits.isSubsetOf(Known.Zero))
10162       return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
10163   }
10164 
10165   // fold (zext (truncate x)) -> (and x, mask)
10166   if (N0.getOpcode() == ISD::TRUNCATE) {
10167     // fold (zext (truncate (load x))) -> (zext (smaller load x))
10168     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
10169     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
10170       SDNode *oye = N0.getOperand(0).getNode();
10171       if (NarrowLoad.getNode() != N0.getNode()) {
10172         CombineTo(N0.getNode(), NarrowLoad);
10173         // CombineTo deleted the truncate, if needed, but not what's under it.
10174         AddToWorklist(oye);
10175       }
10176       return SDValue(N, 0); // Return N so it doesn't get rechecked!
10177     }
10178 
10179     EVT SrcVT = N0.getOperand(0).getValueType();
10180     EVT MinVT = N0.getValueType();
10181 
10182     // Try to mask before the extension to avoid having to generate a larger mask,
10183     // possibly over several sub-vectors.
10184     if (SrcVT.bitsLT(VT) && VT.isVector()) {
10185       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
10186                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
10187         SDValue Op = N0.getOperand(0);
10188         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
10189         AddToWorklist(Op.getNode());
10190         SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
10191         // Transfer the debug info; the new node is equivalent to N0.
10192         DAG.transferDbgValues(N0, ZExtOrTrunc);
10193         return ZExtOrTrunc;
10194       }
10195     }
10196 
10197     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
10198       SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
10199       AddToWorklist(Op.getNode());
10200       SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
10201       // We may safely transfer the debug info describing the truncate node over
10202       // to the equivalent and operation.
10203       DAG.transferDbgValues(N0, And);
10204       return And;
10205     }
10206   }
10207 
10208   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
10209   // if either of the casts is not free.
10210   if (N0.getOpcode() == ISD::AND &&
10211       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
10212       N0.getOperand(1).getOpcode() == ISD::Constant &&
10213       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
10214                            N0.getValueType()) ||
10215        !TLI.isZExtFree(N0.getValueType(), VT))) {
10216     SDValue X = N0.getOperand(0).getOperand(0);
10217     X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
10218     APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
10219     SDLoc DL(N);
10220     return DAG.getNode(ISD::AND, DL, VT,
10221                        X, DAG.getConstant(Mask, DL, VT));
10222   }
10223 
10224   // Try to simplify (zext (load x)).
10225   if (SDValue foldedExt =
10226           tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
10227                              ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
10228     return foldedExt;
10229 
10230   if (SDValue foldedExt =
10231       tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD,
10232                                ISD::ZERO_EXTEND))
10233     return foldedExt;
10234 
10235   // fold (zext (load x)) to multiple smaller zextloads.
10236   // Only on illegal but splittable vectors.
10237   if (SDValue ExtLoad = CombineExtLoad(N))
10238     return ExtLoad;
10239 
10240   // fold (zext (and/or/xor (load x), cst)) ->
10241   //      (and/or/xor (zextload x), (zext cst))
10242   // Unless (and (load x) cst) will match as a zextload already and has
10243   // additional users.
10244   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
10245        N0.getOpcode() == ISD::XOR) &&
10246       isa<LoadSDNode>(N0.getOperand(0)) &&
10247       N0.getOperand(1).getOpcode() == ISD::Constant &&
10248       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
10249     LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
10250     EVT MemVT = LN00->getMemoryVT();
10251     if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
10252         LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
10253       bool DoXform = true;
10254       SmallVector<SDNode*, 4> SetCCs;
10255       if (!N0.hasOneUse()) {
10256         if (N0.getOpcode() == ISD::AND) {
10257           auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
10258           EVT LoadResultTy = AndC->getValueType(0);
10259           EVT ExtVT;
10260           if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
10261             DoXform = false;
10262         }
10263       }
10264       if (DoXform)
10265         DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
10266                                           ISD::ZERO_EXTEND, SetCCs, TLI);
10267       if (DoXform) {
10268         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
10269                                          LN00->getChain(), LN00->getBasePtr(),
10270                                          LN00->getMemoryVT(),
10271                                          LN00->getMemOperand());
10272         APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
10273         SDLoc DL(N);
10274         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
10275                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
10276         ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
10277         bool NoReplaceTruncAnd = !N0.hasOneUse();
10278         bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
10279         CombineTo(N, And);
10280         // If N0 has multiple uses, change other uses as well.
10281         if (NoReplaceTruncAnd) {
10282           SDValue TruncAnd =
10283               DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
10284           CombineTo(N0.getNode(), TruncAnd);
10285         }
10286         if (NoReplaceTrunc) {
10287           DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
10288         } else {
10289           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
10290                                       LN00->getValueType(0), ExtLoad);
10291           CombineTo(LN00, Trunc, ExtLoad.getValue(1));
10292         }
10293         return SDValue(N,0); // Return N so it doesn't get rechecked!
10294       }
10295     }
10296   }
10297 
10298   // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
10299   //      (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
10300   if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
10301     return ZExtLoad;
10302 
10303   // Try to simplify (zext (zextload x)).
10304   if (SDValue foldedExt = tryToFoldExtOfExtload(
10305           DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
10306     return foldedExt;
10307 
10308   if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
10309     return V;
10310 
10311   if (N0.getOpcode() == ISD::SETCC) {
10312     // Only do this before legalize for now.
10313     if (!LegalOperations && VT.isVector() &&
10314         N0.getValueType().getVectorElementType() == MVT::i1) {
10315       EVT N00VT = N0.getOperand(0).getValueType();
10316       if (getSetCCResultType(N00VT) == N0.getValueType())
10317         return SDValue();
10318 
10319       // We know that the # elements of the results is the same as the #
10320       // elements of the compare (and the # elements of the compare result for
10321       // that matter). Check to see that they are the same size. If so, we know
10322       // that the element size of the sext'd result matches the element size of
10323       // the compare operands.
10324       SDLoc DL(N);
10325       if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
10326         // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
10327         SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
10328                                      N0.getOperand(1), N0.getOperand(2));
10329         return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
10330       }
10331 
10332       // If the desired elements are smaller or larger than the source
10333       // elements we can use a matching integer vector type and then
10334       // truncate/any extend followed by zext_in_reg.
10335       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
10336       SDValue VsetCC =
10337           DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
10338                       N0.getOperand(1), N0.getOperand(2));
10339       return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
10340                                     N0.getValueType());
10341     }
10342 
10343     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
10344     SDLoc DL(N);
10345     if (SDValue SCC = SimplifySelectCC(
10346             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
10347             DAG.getConstant(0, DL, VT),
10348             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
10349       return SCC;
10350   }
10351 
10352   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
10353   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
10354       isa<ConstantSDNode>(N0.getOperand(1)) &&
10355       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
10356       N0.hasOneUse()) {
10357     SDValue ShAmt = N0.getOperand(1);
10358     if (N0.getOpcode() == ISD::SHL) {
10359       SDValue InnerZExt = N0.getOperand(0);
10360       // If the original shl may be shifting out bits, do not perform this
10361       // transformation.
10362       unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
10363         InnerZExt.getOperand(0).getValueSizeInBits();
10364       if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits))
10365         return SDValue();
10366     }
10367 
10368     SDLoc DL(N);
10369 
10370     // Ensure that the shift amount is wide enough for the shifted value.
10371     if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
10372       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
10373 
10374     return DAG.getNode(N0.getOpcode(), DL, VT,
10375                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
10376                        ShAmt);
10377   }
10378 
10379   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10380     return NewVSel;
10381 
10382   if (SDValue NewCtPop = widenCtPop(N, DAG))
10383     return NewCtPop;
10384 
10385   return SDValue();
10386 }
10387 
10388 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
10389   SDValue N0 = N->getOperand(0);
10390   EVT VT = N->getValueType(0);
10391 
10392   if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10393     return Res;
10394 
10395   // fold (aext (aext x)) -> (aext x)
10396   // fold (aext (zext x)) -> (zext x)
10397   // fold (aext (sext x)) -> (sext x)
10398   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
10399       N0.getOpcode() == ISD::ZERO_EXTEND ||
10400       N0.getOpcode() == ISD::SIGN_EXTEND)
10401     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
10402 
10403   // fold (aext (truncate (load x))) -> (aext (smaller load x))
10404   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
10405   if (N0.getOpcode() == ISD::TRUNCATE) {
10406     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
10407       SDNode *oye = N0.getOperand(0).getNode();
10408       if (NarrowLoad.getNode() != N0.getNode()) {
10409         CombineTo(N0.getNode(), NarrowLoad);
10410         // CombineTo deleted the truncate, if needed, but not what's under it.
10411         AddToWorklist(oye);
10412       }
10413       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10414     }
10415   }
10416 
10417   // fold (aext (truncate x))
10418   if (N0.getOpcode() == ISD::TRUNCATE)
10419     return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
10420 
10421   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
10422   // if the trunc is not free.
10423   if (N0.getOpcode() == ISD::AND &&
10424       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
10425       N0.getOperand(1).getOpcode() == ISD::Constant &&
10426       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
10427                           N0.getValueType())) {
10428     SDLoc DL(N);
10429     SDValue X = N0.getOperand(0).getOperand(0);
10430     X = DAG.getAnyExtOrTrunc(X, DL, VT);
10431     APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
10432     return DAG.getNode(ISD::AND, DL, VT,
10433                        X, DAG.getConstant(Mask, DL, VT));
10434   }
10435 
10436   // fold (aext (load x)) -> (aext (truncate (extload x)))
10437   // None of the supported targets knows how to perform load and any_ext
10438   // on vectors in one instruction.  We only perform this transformation on
10439   // scalars.
10440   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
10441       ISD::isUNINDEXEDLoad(N0.getNode()) &&
10442       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10443     bool DoXform = true;
10444     SmallVector<SDNode*, 4> SetCCs;
10445     if (!N0.hasOneUse())
10446       DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs,
10447                                         TLI);
10448     if (DoXform) {
10449       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10450       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10451                                        LN0->getChain(),
10452                                        LN0->getBasePtr(), N0.getValueType(),
10453                                        LN0->getMemOperand());
10454       ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
10455       // If the load value is used only by N, replace it via CombineTo N.
10456       bool NoReplaceTrunc = N0.hasOneUse();
10457       CombineTo(N, ExtLoad);
10458       if (NoReplaceTrunc) {
10459         DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
10460         recursivelyDeleteUnusedNodes(LN0);
10461       } else {
10462         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
10463                                     N0.getValueType(), ExtLoad);
10464         CombineTo(LN0, Trunc, ExtLoad.getValue(1));
10465       }
10466       return SDValue(N, 0); // Return N so it doesn't get rechecked!
10467     }
10468   }
10469 
10470   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
10471   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
10472   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
10473   if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
10474       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
10475     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10476     ISD::LoadExtType ExtType = LN0->getExtensionType();
10477     EVT MemVT = LN0->getMemoryVT();
10478     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
10479       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
10480                                        VT, LN0->getChain(), LN0->getBasePtr(),
10481                                        MemVT, LN0->getMemOperand());
10482       CombineTo(N, ExtLoad);
10483       DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
10484       recursivelyDeleteUnusedNodes(LN0);
10485       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10486     }
10487   }
10488 
10489   if (N0.getOpcode() == ISD::SETCC) {
10490     // For vectors:
10491     // aext(setcc) -> vsetcc
10492     // aext(setcc) -> truncate(vsetcc)
10493     // aext(setcc) -> aext(vsetcc)
10494     // Only do this before legalize for now.
10495     if (VT.isVector() && !LegalOperations) {
10496       EVT N00VT = N0.getOperand(0).getValueType();
10497       if (getSetCCResultType(N00VT) == N0.getValueType())
10498         return SDValue();
10499 
10500       // We know that the # elements of the results is the same as the
10501       // # elements of the compare (and the # elements of the compare result
10502       // for that matter).  Check to see that they are the same size.  If so,
10503       // we know that the element size of the sext'd result matches the
10504       // element size of the compare operands.
10505       if (VT.getSizeInBits() == N00VT.getSizeInBits())
10506         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
10507                              N0.getOperand(1),
10508                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
10509 
10510       // If the desired elements are smaller or larger than the source
10511       // elements we can use a matching integer vector type and then
10512       // truncate/any extend
10513       EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
10514       SDValue VsetCC =
10515         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
10516                       N0.getOperand(1),
10517                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
10518       return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
10519     }
10520 
10521     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
10522     SDLoc DL(N);
10523     if (SDValue SCC = SimplifySelectCC(
10524             DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
10525             DAG.getConstant(0, DL, VT),
10526             cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
10527       return SCC;
10528   }
10529 
10530   if (SDValue NewCtPop = widenCtPop(N, DAG))
10531     return NewCtPop;
10532 
10533   return SDValue();
10534 }
10535 
10536 SDValue DAGCombiner::visitAssertExt(SDNode *N) {
10537   unsigned Opcode = N->getOpcode();
10538   SDValue N0 = N->getOperand(0);
10539   SDValue N1 = N->getOperand(1);
10540   EVT AssertVT = cast<VTSDNode>(N1)->getVT();
10541 
10542   // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
10543   if (N0.getOpcode() == Opcode &&
10544       AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
10545     return N0;
10546 
10547   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
10548       N0.getOperand(0).getOpcode() == Opcode) {
10549     // We have an assert, truncate, assert sandwich. Make one stronger assert
10550     // by asserting on the smallest asserted type to the larger source type.
10551     // This eliminates the later assert:
10552     // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
10553     // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
10554     SDValue BigA = N0.getOperand(0);
10555     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
10556     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
10557            "Asserting zero/sign-extended bits to a type larger than the "
10558            "truncated destination does not provide information");
10559 
10560     SDLoc DL(N);
10561     EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
10562     SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
10563     SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
10564                                     BigA.getOperand(0), MinAssertVTVal);
10565     return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
10566   }
10567 
10568   // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
10569   // than X. Just move the AssertZext in front of the truncate and drop the
10570   // AssertSExt.
10571   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
10572       N0.getOperand(0).getOpcode() == ISD::AssertSext &&
10573       Opcode == ISD::AssertZext) {
10574     SDValue BigA = N0.getOperand(0);
10575     EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
10576     assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
10577            "Asserting zero/sign-extended bits to a type larger than the "
10578            "truncated destination does not provide information");
10579 
10580     if (AssertVT.bitsLT(BigA_AssertVT)) {
10581       SDLoc DL(N);
10582       SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
10583                                       BigA.getOperand(0), N1);
10584       return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
10585     }
10586   }
10587 
10588   return SDValue();
10589 }
10590 
10591 /// If the result of a wider load is shifted to right of N  bits and then
10592 /// truncated to a narrower type and where N is a multiple of number of bits of
10593 /// the narrower type, transform it to a narrower load from address + N / num of
10594 /// bits of new type. Also narrow the load if the result is masked with an AND
10595 /// to effectively produce a smaller type. If the result is to be extended, also
10596 /// fold the extension to form a extending load.
10597 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
10598   unsigned Opc = N->getOpcode();
10599 
10600   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
10601   SDValue N0 = N->getOperand(0);
10602   EVT VT = N->getValueType(0);
10603   EVT ExtVT = VT;
10604 
10605   // This transformation isn't valid for vector loads.
10606   if (VT.isVector())
10607     return SDValue();
10608 
10609   unsigned ShAmt = 0;
10610   bool HasShiftedOffset = false;
10611   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
10612   // extended to VT.
10613   if (Opc == ISD::SIGN_EXTEND_INREG) {
10614     ExtType = ISD::SEXTLOAD;
10615     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10616   } else if (Opc == ISD::SRL) {
10617     // Another special-case: SRL is basically zero-extending a narrower value,
10618     // or it maybe shifting a higher subword, half or byte into the lowest
10619     // bits.
10620     ExtType = ISD::ZEXTLOAD;
10621     N0 = SDValue(N, 0);
10622 
10623     auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0));
10624     auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10625     if (!N01 || !LN0)
10626       return SDValue();
10627 
10628     uint64_t ShiftAmt = N01->getZExtValue();
10629     uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits();
10630     if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt)
10631       ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt);
10632     else
10633       ExtVT = EVT::getIntegerVT(*DAG.getContext(),
10634                                 VT.getSizeInBits() - ShiftAmt);
10635   } else if (Opc == ISD::AND) {
10636     // An AND with a constant mask is the same as a truncate + zero-extend.
10637     auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
10638     if (!AndC)
10639       return SDValue();
10640 
10641     const APInt &Mask = AndC->getAPIntValue();
10642     unsigned ActiveBits = 0;
10643     if (Mask.isMask()) {
10644       ActiveBits = Mask.countTrailingOnes();
10645     } else if (Mask.isShiftedMask()) {
10646       ShAmt = Mask.countTrailingZeros();
10647       APInt ShiftedMask = Mask.lshr(ShAmt);
10648       ActiveBits = ShiftedMask.countTrailingOnes();
10649       HasShiftedOffset = true;
10650     } else
10651       return SDValue();
10652 
10653     ExtType = ISD::ZEXTLOAD;
10654     ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
10655   }
10656 
10657   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
10658     SDValue SRL = N0;
10659     if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) {
10660       ShAmt = ConstShift->getZExtValue();
10661       unsigned EVTBits = ExtVT.getSizeInBits();
10662       // Is the shift amount a multiple of size of VT?
10663       if ((ShAmt & (EVTBits-1)) == 0) {
10664         N0 = N0.getOperand(0);
10665         // Is the load width a multiple of size of VT?
10666         if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
10667           return SDValue();
10668       }
10669 
10670       // At this point, we must have a load or else we can't do the transform.
10671       auto *LN0 = dyn_cast<LoadSDNode>(N0);
10672       if (!LN0) return SDValue();
10673 
10674       // Because a SRL must be assumed to *need* to zero-extend the high bits
10675       // (as opposed to anyext the high bits), we can't combine the zextload
10676       // lowering of SRL and an sextload.
10677       if (LN0->getExtensionType() == ISD::SEXTLOAD)
10678         return SDValue();
10679 
10680       // If the shift amount is larger than the input type then we're not
10681       // accessing any of the loaded bytes.  If the load was a zextload/extload
10682       // then the result of the shift+trunc is zero/undef (handled elsewhere).
10683       if (ShAmt >= LN0->getMemoryVT().getSizeInBits())
10684         return SDValue();
10685 
10686       // If the SRL is only used by a masking AND, we may be able to adjust
10687       // the ExtVT to make the AND redundant.
10688       SDNode *Mask = *(SRL->use_begin());
10689       if (Mask->getOpcode() == ISD::AND &&
10690           isa<ConstantSDNode>(Mask->getOperand(1))) {
10691         const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
10692         if (ShiftMask.isMask()) {
10693           EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
10694                                            ShiftMask.countTrailingOnes());
10695           // If the mask is smaller, recompute the type.
10696           if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) &&
10697               TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT))
10698             ExtVT = MaskedVT;
10699         }
10700       }
10701     }
10702   }
10703 
10704   // If the load is shifted left (and the result isn't shifted back right),
10705   // we can fold the truncate through the shift.
10706   unsigned ShLeftAmt = 0;
10707   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
10708       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
10709     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
10710       ShLeftAmt = N01->getZExtValue();
10711       N0 = N0.getOperand(0);
10712     }
10713   }
10714 
10715   // If we haven't found a load, we can't narrow it.
10716   if (!isa<LoadSDNode>(N0))
10717     return SDValue();
10718 
10719   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10720   // Reducing the width of a volatile load is illegal.  For atomics, we may be
10721   // able to reduce the width provided we never widen again. (see D66309)
10722   if (!LN0->isSimple() ||
10723       !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
10724     return SDValue();
10725 
10726   auto AdjustBigEndianShift = [&](unsigned ShAmt) {
10727     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
10728     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
10729     return LVTStoreBits - EVTStoreBits - ShAmt;
10730   };
10731 
10732   // For big endian targets, we need to adjust the offset to the pointer to
10733   // load the correct bytes.
10734   if (DAG.getDataLayout().isBigEndian())
10735     ShAmt = AdjustBigEndianShift(ShAmt);
10736 
10737   uint64_t PtrOff = ShAmt / 8;
10738   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
10739   SDLoc DL(LN0);
10740   // The original load itself didn't wrap, so an offset within it doesn't.
10741   SDNodeFlags Flags;
10742   Flags.setNoUnsignedWrap(true);
10743   SDValue NewPtr =
10744       DAG.getMemBasePlusOffset(LN0->getBasePtr(), PtrOff, DL, Flags);
10745   AddToWorklist(NewPtr.getNode());
10746 
10747   SDValue Load;
10748   if (ExtType == ISD::NON_EXTLOAD)
10749     Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
10750                        LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
10751                        LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
10752   else
10753     Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
10754                           LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
10755                           NewAlign, LN0->getMemOperand()->getFlags(),
10756                           LN0->getAAInfo());
10757 
10758   // Replace the old load's chain with the new load's chain.
10759   WorklistRemover DeadNodes(*this);
10760   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
10761 
10762   // Shift the result left, if we've swallowed a left shift.
10763   SDValue Result = Load;
10764   if (ShLeftAmt != 0) {
10765     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
10766     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
10767       ShImmTy = VT;
10768     // If the shift amount is as large as the result size (but, presumably,
10769     // no larger than the source) then the useful bits of the result are
10770     // zero; we can't simply return the shortened shift, because the result
10771     // of that operation is undefined.
10772     if (ShLeftAmt >= VT.getSizeInBits())
10773       Result = DAG.getConstant(0, DL, VT);
10774     else
10775       Result = DAG.getNode(ISD::SHL, DL, VT,
10776                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
10777   }
10778 
10779   if (HasShiftedOffset) {
10780     // Recalculate the shift amount after it has been altered to calculate
10781     // the offset.
10782     if (DAG.getDataLayout().isBigEndian())
10783       ShAmt = AdjustBigEndianShift(ShAmt);
10784 
10785     // We're using a shifted mask, so the load now has an offset. This means
10786     // that data has been loaded into the lower bytes than it would have been
10787     // before, so we need to shl the loaded data into the correct position in the
10788     // register.
10789     SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT);
10790     Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
10791     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
10792   }
10793 
10794   // Return the new loaded value.
10795   return Result;
10796 }
10797 
10798 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
10799   SDValue N0 = N->getOperand(0);
10800   SDValue N1 = N->getOperand(1);
10801   EVT VT = N->getValueType(0);
10802   EVT EVT = cast<VTSDNode>(N1)->getVT();
10803   unsigned VTBits = VT.getScalarSizeInBits();
10804   unsigned EVTBits = EVT.getScalarSizeInBits();
10805 
10806   if (N0.isUndef())
10807     return DAG.getUNDEF(VT);
10808 
10809   // fold (sext_in_reg c1) -> c1
10810   if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
10811     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
10812 
10813   // If the input is already sign extended, just drop the extension.
10814   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
10815     return N0;
10816 
10817   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
10818   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
10819       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
10820     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
10821                        N0.getOperand(0), N1);
10822 
10823   // fold (sext_in_reg (sext x)) -> (sext x)
10824   // fold (sext_in_reg (aext x)) -> (sext x)
10825   // if x is small enough or if we know that x has more than 1 sign bit and the
10826   // sign_extend_inreg is extending from one of them.
10827   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
10828     SDValue N00 = N0.getOperand(0);
10829     unsigned N00Bits = N00.getScalarValueSizeInBits();
10830     if ((N00Bits <= EVTBits ||
10831          (N00Bits - DAG.ComputeNumSignBits(N00)) < EVTBits) &&
10832         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
10833       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00);
10834   }
10835 
10836   // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
10837   if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
10838        N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
10839        N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
10840       N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
10841     if (!LegalOperations ||
10842         TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
10843       return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT,
10844                          N0.getOperand(0));
10845   }
10846 
10847   // fold (sext_in_reg (zext x)) -> (sext x)
10848   // iff we are extending the source sign bit.
10849   if (N0.getOpcode() == ISD::ZERO_EXTEND) {
10850     SDValue N00 = N0.getOperand(0);
10851     if (N00.getScalarValueSizeInBits() == EVTBits &&
10852         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
10853       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
10854   }
10855 
10856   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
10857   if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
10858     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
10859 
10860   // fold operands of sext_in_reg based on knowledge that the top bits are not
10861   // demanded.
10862   if (SimplifyDemandedBits(SDValue(N, 0)))
10863     return SDValue(N, 0);
10864 
10865   // fold (sext_in_reg (load x)) -> (smaller sextload x)
10866   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
10867   if (SDValue NarrowLoad = ReduceLoadWidth(N))
10868     return NarrowLoad;
10869 
10870   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
10871   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
10872   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
10873   if (N0.getOpcode() == ISD::SRL) {
10874     if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
10875       if (ShAmt->getAPIntValue().ule(VTBits - EVTBits)) {
10876         // We can turn this into an SRA iff the input to the SRL is already sign
10877         // extended enough.
10878         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
10879         if (((VTBits - EVTBits) - ShAmt->getZExtValue()) < InSignBits)
10880           return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
10881                              N0.getOperand(1));
10882       }
10883   }
10884 
10885   // fold (sext_inreg (extload x)) -> (sextload x)
10886   // If sextload is not supported by target, we can only do the combine when
10887   // load has one use. Doing otherwise can block folding the extload with other
10888   // extends that the target does support.
10889   if (ISD::isEXTLoad(N0.getNode()) &&
10890       ISD::isUNINDEXEDLoad(N0.getNode()) &&
10891       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10892       ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() &&
10893         N0.hasOneUse()) ||
10894        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
10895     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10896     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
10897                                      LN0->getChain(),
10898                                      LN0->getBasePtr(), EVT,
10899                                      LN0->getMemOperand());
10900     CombineTo(N, ExtLoad);
10901     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
10902     AddToWorklist(ExtLoad.getNode());
10903     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10904   }
10905   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
10906   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
10907       N0.hasOneUse() &&
10908       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
10909       ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) &&
10910        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
10911     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10912     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
10913                                      LN0->getChain(),
10914                                      LN0->getBasePtr(), EVT,
10915                                      LN0->getMemOperand());
10916     CombineTo(N, ExtLoad);
10917     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
10918     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
10919   }
10920 
10921   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
10922   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
10923     if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
10924                                            N0.getOperand(1), false))
10925       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
10926                          BSwap, N1);
10927   }
10928 
10929   return SDValue();
10930 }
10931 
10932 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
10933   SDValue N0 = N->getOperand(0);
10934   EVT VT = N->getValueType(0);
10935 
10936   if (N0.isUndef())
10937     return DAG.getUNDEF(VT);
10938 
10939   if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10940     return Res;
10941 
10942   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
10943     return SDValue(N, 0);
10944 
10945   return SDValue();
10946 }
10947 
10948 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
10949   SDValue N0 = N->getOperand(0);
10950   EVT VT = N->getValueType(0);
10951 
10952   if (N0.isUndef())
10953     return DAG.getUNDEF(VT);
10954 
10955   if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
10956     return Res;
10957 
10958   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
10959     return SDValue(N, 0);
10960 
10961   return SDValue();
10962 }
10963 
10964 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
10965   SDValue N0 = N->getOperand(0);
10966   EVT VT = N->getValueType(0);
10967   EVT SrcVT = N0.getValueType();
10968   bool isLE = DAG.getDataLayout().isLittleEndian();
10969 
10970   // noop truncate
10971   if (SrcVT == VT)
10972     return N0;
10973 
10974   // fold (truncate (truncate x)) -> (truncate x)
10975   if (N0.getOpcode() == ISD::TRUNCATE)
10976     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
10977 
10978   // fold (truncate c1) -> c1
10979   if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
10980     SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
10981     if (C.getNode() != N)
10982       return C;
10983   }
10984 
10985   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
10986   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
10987       N0.getOpcode() == ISD::SIGN_EXTEND ||
10988       N0.getOpcode() == ISD::ANY_EXTEND) {
10989     // if the source is smaller than the dest, we still need an extend.
10990     if (N0.getOperand(0).getValueType().bitsLT(VT))
10991       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
10992     // if the source is larger than the dest, than we just need the truncate.
10993     if (N0.getOperand(0).getValueType().bitsGT(VT))
10994       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
10995     // if the source and dest are the same type, we can drop both the extend
10996     // and the truncate.
10997     return N0.getOperand(0);
10998   }
10999 
11000   // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
11001   if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
11002     return SDValue();
11003 
11004   // Fold extract-and-trunc into a narrow extract. For example:
11005   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
11006   //   i32 y = TRUNCATE(i64 x)
11007   //        -- becomes --
11008   //   v16i8 b = BITCAST (v2i64 val)
11009   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
11010   //
11011   // Note: We only run this optimization after type legalization (which often
11012   // creates this pattern) and before operation legalization after which
11013   // we need to be more careful about the vector instructions that we generate.
11014   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
11015       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
11016     EVT VecTy = N0.getOperand(0).getValueType();
11017     EVT ExTy = N0.getValueType();
11018     EVT TrTy = N->getValueType(0);
11019 
11020     unsigned NumElem = VecTy.getVectorNumElements();
11021     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
11022 
11023     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
11024     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
11025 
11026     SDValue EltNo = N0->getOperand(1);
11027     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
11028       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11029       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
11030 
11031       SDLoc DL(N);
11032       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
11033                          DAG.getBitcast(NVT, N0.getOperand(0)),
11034                          DAG.getVectorIdxConstant(Index, DL));
11035     }
11036   }
11037 
11038   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
11039   if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
11040     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
11041         TLI.isTruncateFree(SrcVT, VT)) {
11042       SDLoc SL(N0);
11043       SDValue Cond = N0.getOperand(0);
11044       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
11045       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
11046       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
11047     }
11048   }
11049 
11050   // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
11051   if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
11052       (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
11053       TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
11054     SDValue Amt = N0.getOperand(1);
11055     KnownBits Known = DAG.computeKnownBits(Amt);
11056     unsigned Size = VT.getScalarSizeInBits();
11057     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
11058       SDLoc SL(N);
11059       EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
11060 
11061       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
11062       if (AmtVT != Amt.getValueType()) {
11063         Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
11064         AddToWorklist(Amt.getNode());
11065       }
11066       return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
11067     }
11068   }
11069 
11070   // Attempt to pre-truncate BUILD_VECTOR sources.
11071   if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
11072       TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) &&
11073       // Avoid creating illegal types if running after type legalizer.
11074       (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
11075     SDLoc DL(N);
11076     EVT SVT = VT.getScalarType();
11077     SmallVector<SDValue, 8> TruncOps;
11078     for (const SDValue &Op : N0->op_values()) {
11079       SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op);
11080       TruncOps.push_back(TruncOp);
11081     }
11082     return DAG.getBuildVector(VT, DL, TruncOps);
11083   }
11084 
11085   // Fold a series of buildvector, bitcast, and truncate if possible.
11086   // For example fold
11087   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
11088   //   (2xi32 (buildvector x, y)).
11089   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
11090       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11091       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11092       N0.getOperand(0).hasOneUse()) {
11093     SDValue BuildVect = N0.getOperand(0);
11094     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
11095     EVT TruncVecEltTy = VT.getVectorElementType();
11096 
11097     // Check that the element types match.
11098     if (BuildVectEltTy == TruncVecEltTy) {
11099       // Now we only need to compute the offset of the truncated elements.
11100       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
11101       unsigned TruncVecNumElts = VT.getVectorNumElements();
11102       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
11103 
11104       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
11105              "Invalid number of elements");
11106 
11107       SmallVector<SDValue, 8> Opnds;
11108       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
11109         Opnds.push_back(BuildVect.getOperand(i));
11110 
11111       return DAG.getBuildVector(VT, SDLoc(N), Opnds);
11112     }
11113   }
11114 
11115   // See if we can simplify the input to this truncate through knowledge that
11116   // only the low bits are being used.
11117   // For example "trunc (or (shl x, 8), y)" // -> trunc y
11118   // Currently we only perform this optimization on scalars because vectors
11119   // may have different active low bits.
11120   if (!VT.isVector()) {
11121     APInt Mask =
11122         APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
11123     if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
11124       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
11125   }
11126 
11127   // fold (truncate (load x)) -> (smaller load x)
11128   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
11129   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
11130     if (SDValue Reduced = ReduceLoadWidth(N))
11131       return Reduced;
11132 
11133     // Handle the case where the load remains an extending load even
11134     // after truncation.
11135     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
11136       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11137       if (LN0->isSimple() &&
11138           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
11139         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
11140                                          VT, LN0->getChain(), LN0->getBasePtr(),
11141                                          LN0->getMemoryVT(),
11142                                          LN0->getMemOperand());
11143         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
11144         return NewLoad;
11145       }
11146     }
11147   }
11148 
11149   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
11150   // where ... are all 'undef'.
11151   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
11152     SmallVector<EVT, 8> VTs;
11153     SDValue V;
11154     unsigned Idx = 0;
11155     unsigned NumDefs = 0;
11156 
11157     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11158       SDValue X = N0.getOperand(i);
11159       if (!X.isUndef()) {
11160         V = X;
11161         Idx = i;
11162         NumDefs++;
11163       }
11164       // Stop if more than one members are non-undef.
11165       if (NumDefs > 1)
11166         break;
11167       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
11168                                      VT.getVectorElementType(),
11169                                      X.getValueType().getVectorNumElements()));
11170     }
11171 
11172     if (NumDefs == 0)
11173       return DAG.getUNDEF(VT);
11174 
11175     if (NumDefs == 1) {
11176       assert(V.getNode() && "The single defined operand is empty!");
11177       SmallVector<SDValue, 8> Opnds;
11178       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
11179         if (i != Idx) {
11180           Opnds.push_back(DAG.getUNDEF(VTs[i]));
11181           continue;
11182         }
11183         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
11184         AddToWorklist(NV.getNode());
11185         Opnds.push_back(NV);
11186       }
11187       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
11188     }
11189   }
11190 
11191   // Fold truncate of a bitcast of a vector to an extract of the low vector
11192   // element.
11193   //
11194   // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
11195   if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
11196     SDValue VecSrc = N0.getOperand(0);
11197     EVT VecSrcVT = VecSrc.getValueType();
11198     if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT &&
11199         (!LegalOperations ||
11200          TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
11201       SDLoc SL(N);
11202 
11203       unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
11204       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc,
11205                          DAG.getVectorIdxConstant(Idx, SL));
11206     }
11207   }
11208 
11209   // Simplify the operands using demanded-bits information.
11210   if (!VT.isVector() &&
11211       SimplifyDemandedBits(SDValue(N, 0)))
11212     return SDValue(N, 0);
11213 
11214   // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
11215   // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
11216   // When the adde's carry is not used.
11217   if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
11218       N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
11219       // We only do for addcarry before legalize operation
11220       ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) ||
11221        TLI.isOperationLegal(N0.getOpcode(), VT))) {
11222     SDLoc SL(N);
11223     auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
11224     auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
11225     auto VTs = DAG.getVTList(VT, N0->getValueType(1));
11226     return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
11227   }
11228 
11229   // fold (truncate (extract_subvector(ext x))) ->
11230   //      (extract_subvector x)
11231   // TODO: This can be generalized to cover cases where the truncate and extract
11232   // do not fully cancel each other out.
11233   if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
11234     SDValue N00 = N0.getOperand(0);
11235     if (N00.getOpcode() == ISD::SIGN_EXTEND ||
11236         N00.getOpcode() == ISD::ZERO_EXTEND ||
11237         N00.getOpcode() == ISD::ANY_EXTEND) {
11238       if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
11239           VT.getVectorElementType())
11240         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
11241                            N00.getOperand(0), N0.getOperand(1));
11242     }
11243   }
11244 
11245   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
11246     return NewVSel;
11247 
11248   // Narrow a suitable binary operation with a non-opaque constant operand by
11249   // moving it ahead of the truncate. This is limited to pre-legalization
11250   // because targets may prefer a wider type during later combines and invert
11251   // this transform.
11252   switch (N0.getOpcode()) {
11253   case ISD::ADD:
11254   case ISD::SUB:
11255   case ISD::MUL:
11256   case ISD::AND:
11257   case ISD::OR:
11258   case ISD::XOR:
11259     if (!LegalOperations && N0.hasOneUse() &&
11260         (isConstantOrConstantVector(N0.getOperand(0), true) ||
11261          isConstantOrConstantVector(N0.getOperand(1), true))) {
11262       // TODO: We already restricted this to pre-legalization, but for vectors
11263       // we are extra cautious to not create an unsupported operation.
11264       // Target-specific changes are likely needed to avoid regressions here.
11265       if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
11266         SDLoc DL(N);
11267         SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
11268         SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
11269         return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR);
11270       }
11271     }
11272   }
11273 
11274   return SDValue();
11275 }
11276 
11277 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
11278   SDValue Elt = N->getOperand(i);
11279   if (Elt.getOpcode() != ISD::MERGE_VALUES)
11280     return Elt.getNode();
11281   return Elt.getOperand(Elt.getResNo()).getNode();
11282 }
11283 
11284 /// build_pair (load, load) -> load
11285 /// if load locations are consecutive.
11286 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
11287   assert(N->getOpcode() == ISD::BUILD_PAIR);
11288 
11289   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
11290   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
11291 
11292   // A BUILD_PAIR is always having the least significant part in elt 0 and the
11293   // most significant part in elt 1. So when combining into one large load, we
11294   // need to consider the endianness.
11295   if (DAG.getDataLayout().isBigEndian())
11296     std::swap(LD1, LD2);
11297 
11298   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
11299       LD1->getAddressSpace() != LD2->getAddressSpace())
11300     return SDValue();
11301   EVT LD1VT = LD1->getValueType(0);
11302   unsigned LD1Bytes = LD1VT.getStoreSize();
11303   if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
11304       DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
11305     unsigned Align = LD1->getAlignment();
11306     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11307         VT.getTypeForEVT(*DAG.getContext()));
11308 
11309     if (NewAlign <= Align &&
11310         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
11311       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
11312                          LD1->getPointerInfo(), Align);
11313   }
11314 
11315   return SDValue();
11316 }
11317 
11318 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
11319   // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
11320   // and Lo parts; on big-endian machines it doesn't.
11321   return DAG.getDataLayout().isBigEndian() ? 1 : 0;
11322 }
11323 
11324 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
11325                                     const TargetLowering &TLI) {
11326   // If this is not a bitcast to an FP type or if the target doesn't have
11327   // IEEE754-compliant FP logic, we're done.
11328   EVT VT = N->getValueType(0);
11329   if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
11330     return SDValue();
11331 
11332   // TODO: Handle cases where the integer constant is a different scalar
11333   // bitwidth to the FP.
11334   SDValue N0 = N->getOperand(0);
11335   EVT SourceVT = N0.getValueType();
11336   if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
11337     return SDValue();
11338 
11339   unsigned FPOpcode;
11340   APInt SignMask;
11341   switch (N0.getOpcode()) {
11342   case ISD::AND:
11343     FPOpcode = ISD::FABS;
11344     SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
11345     break;
11346   case ISD::XOR:
11347     FPOpcode = ISD::FNEG;
11348     SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
11349     break;
11350   case ISD::OR:
11351     FPOpcode = ISD::FABS;
11352     SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
11353     break;
11354   default:
11355     return SDValue();
11356   }
11357 
11358   // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
11359   // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
11360   // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
11361   //   fneg (fabs X)
11362   SDValue LogicOp0 = N0.getOperand(0);
11363   ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
11364   if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
11365       LogicOp0.getOpcode() == ISD::BITCAST &&
11366       LogicOp0.getOperand(0).getValueType() == VT) {
11367     SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0));
11368     NumFPLogicOpsConv++;
11369     if (N0.getOpcode() == ISD::OR)
11370       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
11371     return FPOp;
11372   }
11373 
11374   return SDValue();
11375 }
11376 
11377 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
11378   SDValue N0 = N->getOperand(0);
11379   EVT VT = N->getValueType(0);
11380 
11381   if (N0.isUndef())
11382     return DAG.getUNDEF(VT);
11383 
11384   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
11385   // Only do this before legalize types, unless both types are integer and the
11386   // scalar type is legal. Only do this before legalize ops, since the target
11387   // maybe depending on the bitcast.
11388   // First check to see if this is all constant.
11389   // TODO: Support FP bitcasts after legalize types.
11390   if (VT.isVector() &&
11391       (!LegalTypes ||
11392        (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
11393         TLI.isTypeLegal(VT.getVectorElementType()))) &&
11394       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
11395       cast<BuildVectorSDNode>(N0)->isConstant())
11396     return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(),
11397                                              VT.getVectorElementType());
11398 
11399   // If the input is a constant, let getNode fold it.
11400   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
11401     // If we can't allow illegal operations, we need to check that this is just
11402     // a fp -> int or int -> conversion and that the resulting operation will
11403     // be legal.
11404     if (!LegalOperations ||
11405         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
11406          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
11407         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
11408          TLI.isOperationLegal(ISD::Constant, VT))) {
11409       SDValue C = DAG.getBitcast(VT, N0);
11410       if (C.getNode() != N)
11411         return C;
11412     }
11413   }
11414 
11415   // (conv (conv x, t1), t2) -> (conv x, t2)
11416   if (N0.getOpcode() == ISD::BITCAST)
11417     return DAG.getBitcast(VT, N0.getOperand(0));
11418 
11419   // fold (conv (load x)) -> (load (conv*)x)
11420   // If the resultant load doesn't need a higher alignment than the original!
11421   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11422       // Do not remove the cast if the types differ in endian layout.
11423       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
11424           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
11425       // If the load is volatile, we only want to change the load type if the
11426       // resulting load is legal. Otherwise we might increase the number of
11427       // memory accesses. We don't care if the original type was legal or not
11428       // as we assume software couldn't rely on the number of accesses of an
11429       // illegal type.
11430       ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) ||
11431        TLI.isOperationLegal(ISD::LOAD, VT))) {
11432     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11433 
11434     if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
11435                                     *LN0->getMemOperand())) {
11436       SDValue Load =
11437           DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
11438                       LN0->getPointerInfo(), LN0->getAlignment(),
11439                       LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
11440       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
11441       return Load;
11442     }
11443   }
11444 
11445   if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
11446     return V;
11447 
11448   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
11449   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
11450   //
11451   // For ppc_fp128:
11452   // fold (bitcast (fneg x)) ->
11453   //     flipbit = signbit
11454   //     (xor (bitcast x) (build_pair flipbit, flipbit))
11455   //
11456   // fold (bitcast (fabs x)) ->
11457   //     flipbit = (and (extract_element (bitcast x), 0), signbit)
11458   //     (xor (bitcast x) (build_pair flipbit, flipbit))
11459   // This often reduces constant pool loads.
11460   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
11461        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
11462       N0.getNode()->hasOneUse() && VT.isInteger() &&
11463       !VT.isVector() && !N0.getValueType().isVector()) {
11464     SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
11465     AddToWorklist(NewConv.getNode());
11466 
11467     SDLoc DL(N);
11468     if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
11469       assert(VT.getSizeInBits() == 128);
11470       SDValue SignBit = DAG.getConstant(
11471           APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
11472       SDValue FlipBit;
11473       if (N0.getOpcode() == ISD::FNEG) {
11474         FlipBit = SignBit;
11475         AddToWorklist(FlipBit.getNode());
11476       } else {
11477         assert(N0.getOpcode() == ISD::FABS);
11478         SDValue Hi =
11479             DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
11480                         DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
11481                                               SDLoc(NewConv)));
11482         AddToWorklist(Hi.getNode());
11483         FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
11484         AddToWorklist(FlipBit.getNode());
11485       }
11486       SDValue FlipBits =
11487           DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
11488       AddToWorklist(FlipBits.getNode());
11489       return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
11490     }
11491     APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
11492     if (N0.getOpcode() == ISD::FNEG)
11493       return DAG.getNode(ISD::XOR, DL, VT,
11494                          NewConv, DAG.getConstant(SignBit, DL, VT));
11495     assert(N0.getOpcode() == ISD::FABS);
11496     return DAG.getNode(ISD::AND, DL, VT,
11497                        NewConv, DAG.getConstant(~SignBit, DL, VT));
11498   }
11499 
11500   // fold (bitconvert (fcopysign cst, x)) ->
11501   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
11502   // Note that we don't handle (copysign x, cst) because this can always be
11503   // folded to an fneg or fabs.
11504   //
11505   // For ppc_fp128:
11506   // fold (bitcast (fcopysign cst, x)) ->
11507   //     flipbit = (and (extract_element
11508   //                     (xor (bitcast cst), (bitcast x)), 0),
11509   //                    signbit)
11510   //     (xor (bitcast cst) (build_pair flipbit, flipbit))
11511   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
11512       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
11513       VT.isInteger() && !VT.isVector()) {
11514     unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
11515     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
11516     if (isTypeLegal(IntXVT)) {
11517       SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
11518       AddToWorklist(X.getNode());
11519 
11520       // If X has a different width than the result/lhs, sext it or truncate it.
11521       unsigned VTWidth = VT.getSizeInBits();
11522       if (OrigXWidth < VTWidth) {
11523         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
11524         AddToWorklist(X.getNode());
11525       } else if (OrigXWidth > VTWidth) {
11526         // To get the sign bit in the right place, we have to shift it right
11527         // before truncating.
11528         SDLoc DL(X);
11529         X = DAG.getNode(ISD::SRL, DL,
11530                         X.getValueType(), X,
11531                         DAG.getConstant(OrigXWidth-VTWidth, DL,
11532                                         X.getValueType()));
11533         AddToWorklist(X.getNode());
11534         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
11535         AddToWorklist(X.getNode());
11536       }
11537 
11538       if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
11539         APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
11540         SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
11541         AddToWorklist(Cst.getNode());
11542         SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
11543         AddToWorklist(X.getNode());
11544         SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
11545         AddToWorklist(XorResult.getNode());
11546         SDValue XorResult64 = DAG.getNode(
11547             ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
11548             DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
11549                                   SDLoc(XorResult)));
11550         AddToWorklist(XorResult64.getNode());
11551         SDValue FlipBit =
11552             DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
11553                         DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
11554         AddToWorklist(FlipBit.getNode());
11555         SDValue FlipBits =
11556             DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
11557         AddToWorklist(FlipBits.getNode());
11558         return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
11559       }
11560       APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
11561       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
11562                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
11563       AddToWorklist(X.getNode());
11564 
11565       SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
11566       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
11567                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
11568       AddToWorklist(Cst.getNode());
11569 
11570       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
11571     }
11572   }
11573 
11574   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
11575   if (N0.getOpcode() == ISD::BUILD_PAIR)
11576     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
11577       return CombineLD;
11578 
11579   // Remove double bitcasts from shuffles - this is often a legacy of
11580   // XformToShuffleWithZero being used to combine bitmaskings (of
11581   // float vectors bitcast to integer vectors) into shuffles.
11582   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
11583   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
11584       N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
11585       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
11586       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
11587     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
11588 
11589     // If operands are a bitcast, peek through if it casts the original VT.
11590     // If operands are a constant, just bitcast back to original VT.
11591     auto PeekThroughBitcast = [&](SDValue Op) {
11592       if (Op.getOpcode() == ISD::BITCAST &&
11593           Op.getOperand(0).getValueType() == VT)
11594         return SDValue(Op.getOperand(0));
11595       if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
11596           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
11597         return DAG.getBitcast(VT, Op);
11598       return SDValue();
11599     };
11600 
11601     // FIXME: If either input vector is bitcast, try to convert the shuffle to
11602     // the result type of this bitcast. This would eliminate at least one
11603     // bitcast. See the transform in InstCombine.
11604     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
11605     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
11606     if (!(SV0 && SV1))
11607       return SDValue();
11608 
11609     int MaskScale =
11610         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
11611     SmallVector<int, 8> NewMask;
11612     for (int M : SVN->getMask())
11613       for (int i = 0; i != MaskScale; ++i)
11614         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
11615 
11616     SDValue LegalShuffle =
11617         TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
11618     if (LegalShuffle)
11619       return LegalShuffle;
11620   }
11621 
11622   return SDValue();
11623 }
11624 
11625 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
11626   EVT VT = N->getValueType(0);
11627   return CombineConsecutiveLoads(N, VT);
11628 }
11629 
11630 SDValue DAGCombiner::visitFREEZE(SDNode *N) {
11631   SDValue N0 = N->getOperand(0);
11632 
11633   // (freeze (freeze x)) -> (freeze x)
11634   if (N0.getOpcode() == ISD::FREEZE)
11635     return N0;
11636 
11637   // If the input is a constant, return it.
11638   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0))
11639     return N0;
11640 
11641   return SDValue();
11642 }
11643 
11644 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
11645 /// operands. DstEltVT indicates the destination element value type.
11646 SDValue DAGCombiner::
11647 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
11648   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
11649 
11650   // If this is already the right type, we're done.
11651   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
11652 
11653   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
11654   unsigned DstBitSize = DstEltVT.getSizeInBits();
11655 
11656   // If this is a conversion of N elements of one type to N elements of another
11657   // type, convert each element.  This handles FP<->INT cases.
11658   if (SrcBitSize == DstBitSize) {
11659     SmallVector<SDValue, 8> Ops;
11660     for (SDValue Op : BV->op_values()) {
11661       // If the vector element type is not legal, the BUILD_VECTOR operands
11662       // are promoted and implicitly truncated.  Make that explicit here.
11663       if (Op.getValueType() != SrcEltVT)
11664         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
11665       Ops.push_back(DAG.getBitcast(DstEltVT, Op));
11666       AddToWorklist(Ops.back().getNode());
11667     }
11668     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
11669                               BV->getValueType(0).getVectorNumElements());
11670     return DAG.getBuildVector(VT, SDLoc(BV), Ops);
11671   }
11672 
11673   // Otherwise, we're growing or shrinking the elements.  To avoid having to
11674   // handle annoying details of growing/shrinking FP values, we convert them to
11675   // int first.
11676   if (SrcEltVT.isFloatingPoint()) {
11677     // Convert the input float vector to a int vector where the elements are the
11678     // same sizes.
11679     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
11680     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
11681     SrcEltVT = IntVT;
11682   }
11683 
11684   // Now we know the input is an integer vector.  If the output is a FP type,
11685   // convert to integer first, then to FP of the right size.
11686   if (DstEltVT.isFloatingPoint()) {
11687     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
11688     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
11689 
11690     // Next, convert to FP elements of the same size.
11691     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
11692   }
11693 
11694   SDLoc DL(BV);
11695 
11696   // Okay, we know the src/dst types are both integers of differing types.
11697   // Handling growing first.
11698   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
11699   if (SrcBitSize < DstBitSize) {
11700     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
11701 
11702     SmallVector<SDValue, 8> Ops;
11703     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
11704          i += NumInputsPerOutput) {
11705       bool isLE = DAG.getDataLayout().isLittleEndian();
11706       APInt NewBits = APInt(DstBitSize, 0);
11707       bool EltIsUndef = true;
11708       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
11709         // Shift the previously computed bits over.
11710         NewBits <<= SrcBitSize;
11711         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
11712         if (Op.isUndef()) continue;
11713         EltIsUndef = false;
11714 
11715         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
11716                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
11717       }
11718 
11719       if (EltIsUndef)
11720         Ops.push_back(DAG.getUNDEF(DstEltVT));
11721       else
11722         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
11723     }
11724 
11725     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
11726     return DAG.getBuildVector(VT, DL, Ops);
11727   }
11728 
11729   // Finally, this must be the case where we are shrinking elements: each input
11730   // turns into multiple outputs.
11731   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
11732   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
11733                             NumOutputsPerInput*BV->getNumOperands());
11734   SmallVector<SDValue, 8> Ops;
11735 
11736   for (const SDValue &Op : BV->op_values()) {
11737     if (Op.isUndef()) {
11738       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
11739       continue;
11740     }
11741 
11742     APInt OpVal = cast<ConstantSDNode>(Op)->
11743                   getAPIntValue().zextOrTrunc(SrcBitSize);
11744 
11745     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
11746       APInt ThisVal = OpVal.trunc(DstBitSize);
11747       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
11748       OpVal.lshrInPlace(DstBitSize);
11749     }
11750 
11751     // For big endian targets, swap the order of the pieces of each element.
11752     if (DAG.getDataLayout().isBigEndian())
11753       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
11754   }
11755 
11756   return DAG.getBuildVector(VT, DL, Ops);
11757 }
11758 
11759 static bool isContractable(SDNode *N) {
11760   SDNodeFlags F = N->getFlags();
11761   return F.hasAllowContract() || F.hasAllowReassociation();
11762 }
11763 
11764 /// Try to perform FMA combining on a given FADD node.
11765 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
11766   SDValue N0 = N->getOperand(0);
11767   SDValue N1 = N->getOperand(1);
11768   EVT VT = N->getValueType(0);
11769   SDLoc SL(N);
11770 
11771   const TargetOptions &Options = DAG.getTarget().Options;
11772 
11773   // Floating-point multiply-add with intermediate rounding.
11774   bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
11775 
11776   // Floating-point multiply-add without intermediate rounding.
11777   bool HasFMA =
11778       TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
11779       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
11780 
11781   // No valid opcode, do not combine.
11782   if (!HasFMAD && !HasFMA)
11783     return SDValue();
11784 
11785   SDNodeFlags Flags = N->getFlags();
11786   bool CanFuse = Options.UnsafeFPMath || isContractable(N);
11787   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
11788                               CanFuse || HasFMAD);
11789   // If the addition is not contractable, do not combine.
11790   if (!AllowFusionGlobally && !isContractable(N))
11791     return SDValue();
11792 
11793   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
11794   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
11795     return SDValue();
11796 
11797   // Always prefer FMAD to FMA for precision.
11798   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
11799   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
11800 
11801   // Is the node an FMUL and contractable either due to global flags or
11802   // SDNodeFlags.
11803   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
11804     if (N.getOpcode() != ISD::FMUL)
11805       return false;
11806     return AllowFusionGlobally || isContractable(N.getNode());
11807   };
11808   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
11809   // prefer to fold the multiply with fewer uses.
11810   if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
11811     if (N0.getNode()->use_size() > N1.getNode()->use_size())
11812       std::swap(N0, N1);
11813   }
11814 
11815   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
11816   if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
11817     return DAG.getNode(PreferredFusedOpcode, SL, VT,
11818                        N0.getOperand(0), N0.getOperand(1), N1, Flags);
11819   }
11820 
11821   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
11822   // Note: Commutes FADD operands.
11823   if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
11824     return DAG.getNode(PreferredFusedOpcode, SL, VT,
11825                        N1.getOperand(0), N1.getOperand(1), N0, Flags);
11826   }
11827 
11828   // Look through FP_EXTEND nodes to do more combining.
11829 
11830   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
11831   if (N0.getOpcode() == ISD::FP_EXTEND) {
11832     SDValue N00 = N0.getOperand(0);
11833     if (isContractableFMUL(N00) &&
11834         TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11835                             N00.getValueType())) {
11836       return DAG.getNode(PreferredFusedOpcode, SL, VT,
11837                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
11838                                      N00.getOperand(0)),
11839                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
11840                                      N00.getOperand(1)), N1, Flags);
11841     }
11842   }
11843 
11844   // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
11845   // Note: Commutes FADD operands.
11846   if (N1.getOpcode() == ISD::FP_EXTEND) {
11847     SDValue N10 = N1.getOperand(0);
11848     if (isContractableFMUL(N10) &&
11849         TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11850                             N10.getValueType())) {
11851       return DAG.getNode(PreferredFusedOpcode, SL, VT,
11852                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
11853                                      N10.getOperand(0)),
11854                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
11855                                      N10.getOperand(1)), N0, Flags);
11856     }
11857   }
11858 
11859   // More folding opportunities when target permits.
11860   if (Aggressive) {
11861     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
11862     if (CanFuse &&
11863         N0.getOpcode() == PreferredFusedOpcode &&
11864         N0.getOperand(2).getOpcode() == ISD::FMUL &&
11865         N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
11866       return DAG.getNode(PreferredFusedOpcode, SL, VT,
11867                          N0.getOperand(0), N0.getOperand(1),
11868                          DAG.getNode(PreferredFusedOpcode, SL, VT,
11869                                      N0.getOperand(2).getOperand(0),
11870                                      N0.getOperand(2).getOperand(1),
11871                                      N1, Flags), Flags);
11872     }
11873 
11874     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
11875     if (CanFuse &&
11876         N1->getOpcode() == PreferredFusedOpcode &&
11877         N1.getOperand(2).getOpcode() == ISD::FMUL &&
11878         N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
11879       return DAG.getNode(PreferredFusedOpcode, SL, VT,
11880                          N1.getOperand(0), N1.getOperand(1),
11881                          DAG.getNode(PreferredFusedOpcode, SL, VT,
11882                                      N1.getOperand(2).getOperand(0),
11883                                      N1.getOperand(2).getOperand(1),
11884                                      N0, Flags), Flags);
11885     }
11886 
11887 
11888     // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
11889     //   -> (fma x, y, (fma (fpext u), (fpext v), z))
11890     auto FoldFAddFMAFPExtFMul = [&] (
11891       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
11892       SDNodeFlags Flags) {
11893       return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
11894                          DAG.getNode(PreferredFusedOpcode, SL, VT,
11895                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
11896                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
11897                                      Z, Flags), Flags);
11898     };
11899     if (N0.getOpcode() == PreferredFusedOpcode) {
11900       SDValue N02 = N0.getOperand(2);
11901       if (N02.getOpcode() == ISD::FP_EXTEND) {
11902         SDValue N020 = N02.getOperand(0);
11903         if (isContractableFMUL(N020) &&
11904             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11905                                 N020.getValueType())) {
11906           return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
11907                                       N020.getOperand(0), N020.getOperand(1),
11908                                       N1, Flags);
11909         }
11910       }
11911     }
11912 
11913     // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
11914     //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
11915     // FIXME: This turns two single-precision and one double-precision
11916     // operation into two double-precision operations, which might not be
11917     // interesting for all targets, especially GPUs.
11918     auto FoldFAddFPExtFMAFMul = [&] (
11919       SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z,
11920       SDNodeFlags Flags) {
11921       return DAG.getNode(PreferredFusedOpcode, SL, VT,
11922                          DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
11923                          DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
11924                          DAG.getNode(PreferredFusedOpcode, SL, VT,
11925                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
11926                                      DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
11927                                      Z, Flags), Flags);
11928     };
11929     if (N0.getOpcode() == ISD::FP_EXTEND) {
11930       SDValue N00 = N0.getOperand(0);
11931       if (N00.getOpcode() == PreferredFusedOpcode) {
11932         SDValue N002 = N00.getOperand(2);
11933         if (isContractableFMUL(N002) &&
11934             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11935                                 N00.getValueType())) {
11936           return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
11937                                       N002.getOperand(0), N002.getOperand(1),
11938                                       N1, Flags);
11939         }
11940       }
11941     }
11942 
11943     // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
11944     //   -> (fma y, z, (fma (fpext u), (fpext v), x))
11945     if (N1.getOpcode() == PreferredFusedOpcode) {
11946       SDValue N12 = N1.getOperand(2);
11947       if (N12.getOpcode() == ISD::FP_EXTEND) {
11948         SDValue N120 = N12.getOperand(0);
11949         if (isContractableFMUL(N120) &&
11950             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11951                                 N120.getValueType())) {
11952           return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
11953                                       N120.getOperand(0), N120.getOperand(1),
11954                                       N0, Flags);
11955         }
11956       }
11957     }
11958 
11959     // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
11960     //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
11961     // FIXME: This turns two single-precision and one double-precision
11962     // operation into two double-precision operations, which might not be
11963     // interesting for all targets, especially GPUs.
11964     if (N1.getOpcode() == ISD::FP_EXTEND) {
11965       SDValue N10 = N1.getOperand(0);
11966       if (N10.getOpcode() == PreferredFusedOpcode) {
11967         SDValue N102 = N10.getOperand(2);
11968         if (isContractableFMUL(N102) &&
11969             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
11970                                 N10.getValueType())) {
11971           return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
11972                                       N102.getOperand(0), N102.getOperand(1),
11973                                       N0, Flags);
11974         }
11975       }
11976     }
11977   }
11978 
11979   return SDValue();
11980 }
11981 
11982 /// Try to perform FMA combining on a given FSUB node.
11983 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
11984   SDValue N0 = N->getOperand(0);
11985   SDValue N1 = N->getOperand(1);
11986   EVT VT = N->getValueType(0);
11987   SDLoc SL(N);
11988 
11989   const TargetOptions &Options = DAG.getTarget().Options;
11990   // Floating-point multiply-add with intermediate rounding.
11991   bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
11992 
11993   // Floating-point multiply-add without intermediate rounding.
11994   bool HasFMA =
11995       TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
11996       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
11997 
11998   // No valid opcode, do not combine.
11999   if (!HasFMAD && !HasFMA)
12000     return SDValue();
12001 
12002   const SDNodeFlags Flags = N->getFlags();
12003   bool CanFuse = Options.UnsafeFPMath || isContractable(N);
12004   bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
12005                               CanFuse || HasFMAD);
12006 
12007   // If the subtraction is not contractable, do not combine.
12008   if (!AllowFusionGlobally && !isContractable(N))
12009     return SDValue();
12010 
12011   const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
12012   if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
12013     return SDValue();
12014 
12015   // Always prefer FMAD to FMA for precision.
12016   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
12017   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
12018   bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros();
12019 
12020   // Is the node an FMUL and contractable either due to global flags or
12021   // SDNodeFlags.
12022   auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
12023     if (N.getOpcode() != ISD::FMUL)
12024       return false;
12025     return AllowFusionGlobally || isContractable(N.getNode());
12026   };
12027 
12028   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
12029   auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
12030     if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
12031       return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
12032                          XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z),
12033                          Flags);
12034     }
12035     return SDValue();
12036   };
12037 
12038   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
12039   // Note: Commutes FSUB operands.
12040   auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
12041     if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
12042       return DAG.getNode(PreferredFusedOpcode, SL, VT,
12043                          DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
12044                          YZ.getOperand(1), X, Flags);
12045     }
12046     return SDValue();
12047   };
12048 
12049   // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
12050   // prefer to fold the multiply with fewer uses.
12051   if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
12052       (N0.getNode()->use_size() > N1.getNode()->use_size())) {
12053     // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
12054     if (SDValue V = tryToFoldXSubYZ(N0, N1))
12055       return V;
12056     // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
12057     if (SDValue V = tryToFoldXYSubZ(N0, N1))
12058       return V;
12059   } else {
12060     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
12061     if (SDValue V = tryToFoldXYSubZ(N0, N1))
12062       return V;
12063     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
12064     if (SDValue V = tryToFoldXSubYZ(N0, N1))
12065       return V;
12066   }
12067 
12068   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
12069   if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
12070       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
12071     SDValue N00 = N0.getOperand(0).getOperand(0);
12072     SDValue N01 = N0.getOperand(0).getOperand(1);
12073     return DAG.getNode(PreferredFusedOpcode, SL, VT,
12074                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
12075                        DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
12076   }
12077 
12078   // Look through FP_EXTEND nodes to do more combining.
12079 
12080   // fold (fsub (fpext (fmul x, y)), z)
12081   //   -> (fma (fpext x), (fpext y), (fneg z))
12082   if (N0.getOpcode() == ISD::FP_EXTEND) {
12083     SDValue N00 = N0.getOperand(0);
12084     if (isContractableFMUL(N00) &&
12085         TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12086                             N00.getValueType())) {
12087       return DAG.getNode(PreferredFusedOpcode, SL, VT,
12088                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12089                                      N00.getOperand(0)),
12090                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12091                                      N00.getOperand(1)),
12092                          DAG.getNode(ISD::FNEG, SL, VT, N1), Flags);
12093     }
12094   }
12095 
12096   // fold (fsub x, (fpext (fmul y, z)))
12097   //   -> (fma (fneg (fpext y)), (fpext z), x)
12098   // Note: Commutes FSUB operands.
12099   if (N1.getOpcode() == ISD::FP_EXTEND) {
12100     SDValue N10 = N1.getOperand(0);
12101     if (isContractableFMUL(N10) &&
12102         TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12103                             N10.getValueType())) {
12104       return DAG.getNode(PreferredFusedOpcode, SL, VT,
12105                          DAG.getNode(ISD::FNEG, SL, VT,
12106                                      DAG.getNode(ISD::FP_EXTEND, SL, VT,
12107                                                  N10.getOperand(0))),
12108                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12109                                      N10.getOperand(1)),
12110                          N0, Flags);
12111     }
12112   }
12113 
12114   // fold (fsub (fpext (fneg (fmul, x, y))), z)
12115   //   -> (fneg (fma (fpext x), (fpext y), z))
12116   // Note: This could be removed with appropriate canonicalization of the
12117   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
12118   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
12119   // from implementing the canonicalization in visitFSUB.
12120   if (N0.getOpcode() == ISD::FP_EXTEND) {
12121     SDValue N00 = N0.getOperand(0);
12122     if (N00.getOpcode() == ISD::FNEG) {
12123       SDValue N000 = N00.getOperand(0);
12124       if (isContractableFMUL(N000) &&
12125           TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12126                               N00.getValueType())) {
12127         return DAG.getNode(ISD::FNEG, SL, VT,
12128                            DAG.getNode(PreferredFusedOpcode, SL, VT,
12129                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12130                                                    N000.getOperand(0)),
12131                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12132                                                    N000.getOperand(1)),
12133                                        N1, Flags));
12134       }
12135     }
12136   }
12137 
12138   // fold (fsub (fneg (fpext (fmul, x, y))), z)
12139   //   -> (fneg (fma (fpext x)), (fpext y), z)
12140   // Note: This could be removed with appropriate canonicalization of the
12141   // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
12142   // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
12143   // from implementing the canonicalization in visitFSUB.
12144   if (N0.getOpcode() == ISD::FNEG) {
12145     SDValue N00 = N0.getOperand(0);
12146     if (N00.getOpcode() == ISD::FP_EXTEND) {
12147       SDValue N000 = N00.getOperand(0);
12148       if (isContractableFMUL(N000) &&
12149           TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12150                               N000.getValueType())) {
12151         return DAG.getNode(ISD::FNEG, SL, VT,
12152                            DAG.getNode(PreferredFusedOpcode, SL, VT,
12153                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12154                                                    N000.getOperand(0)),
12155                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12156                                                    N000.getOperand(1)),
12157                                        N1, Flags));
12158       }
12159     }
12160   }
12161 
12162   // More folding opportunities when target permits.
12163   if (Aggressive) {
12164     // fold (fsub (fma x, y, (fmul u, v)), z)
12165     //   -> (fma x, y (fma u, v, (fneg z)))
12166     if (CanFuse && N0.getOpcode() == PreferredFusedOpcode &&
12167         isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
12168         N0.getOperand(2)->hasOneUse()) {
12169       return DAG.getNode(PreferredFusedOpcode, SL, VT,
12170                          N0.getOperand(0), N0.getOperand(1),
12171                          DAG.getNode(PreferredFusedOpcode, SL, VT,
12172                                      N0.getOperand(2).getOperand(0),
12173                                      N0.getOperand(2).getOperand(1),
12174                                      DAG.getNode(ISD::FNEG, SL, VT,
12175                                                  N1), Flags), Flags);
12176     }
12177 
12178     // fold (fsub x, (fma y, z, (fmul u, v)))
12179     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
12180     if (CanFuse && N1.getOpcode() == PreferredFusedOpcode &&
12181         isContractableFMUL(N1.getOperand(2)) &&
12182         N1->hasOneUse() && NoSignedZero) {
12183       SDValue N20 = N1.getOperand(2).getOperand(0);
12184       SDValue N21 = N1.getOperand(2).getOperand(1);
12185       return DAG.getNode(PreferredFusedOpcode, SL, VT,
12186                          DAG.getNode(ISD::FNEG, SL, VT,
12187                                      N1.getOperand(0)),
12188                          N1.getOperand(1),
12189                          DAG.getNode(PreferredFusedOpcode, SL, VT,
12190                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
12191                                      N21, N0, Flags), Flags);
12192     }
12193 
12194 
12195     // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
12196     //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
12197     if (N0.getOpcode() == PreferredFusedOpcode &&
12198         N0->hasOneUse()) {
12199       SDValue N02 = N0.getOperand(2);
12200       if (N02.getOpcode() == ISD::FP_EXTEND) {
12201         SDValue N020 = N02.getOperand(0);
12202         if (isContractableFMUL(N020) &&
12203             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12204                                 N020.getValueType())) {
12205           return DAG.getNode(PreferredFusedOpcode, SL, VT,
12206                              N0.getOperand(0), N0.getOperand(1),
12207                              DAG.getNode(PreferredFusedOpcode, SL, VT,
12208                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12209                                                      N020.getOperand(0)),
12210                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12211                                                      N020.getOperand(1)),
12212                                          DAG.getNode(ISD::FNEG, SL, VT,
12213                                                      N1), Flags), Flags);
12214         }
12215       }
12216     }
12217 
12218     // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
12219     //   -> (fma (fpext x), (fpext y),
12220     //           (fma (fpext u), (fpext v), (fneg z)))
12221     // FIXME: This turns two single-precision and one double-precision
12222     // operation into two double-precision operations, which might not be
12223     // interesting for all targets, especially GPUs.
12224     if (N0.getOpcode() == ISD::FP_EXTEND) {
12225       SDValue N00 = N0.getOperand(0);
12226       if (N00.getOpcode() == PreferredFusedOpcode) {
12227         SDValue N002 = N00.getOperand(2);
12228         if (isContractableFMUL(N002) &&
12229             TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12230                                 N00.getValueType())) {
12231           return DAG.getNode(PreferredFusedOpcode, SL, VT,
12232                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
12233                                          N00.getOperand(0)),
12234                              DAG.getNode(ISD::FP_EXTEND, SL, VT,
12235                                          N00.getOperand(1)),
12236                              DAG.getNode(PreferredFusedOpcode, SL, VT,
12237                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12238                                                      N002.getOperand(0)),
12239                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
12240                                                      N002.getOperand(1)),
12241                                          DAG.getNode(ISD::FNEG, SL, VT,
12242                                                      N1), Flags), Flags);
12243         }
12244       }
12245     }
12246 
12247     // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
12248     //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
12249     if (N1.getOpcode() == PreferredFusedOpcode &&
12250         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
12251         N1->hasOneUse()) {
12252       SDValue N120 = N1.getOperand(2).getOperand(0);
12253       if (isContractableFMUL(N120) &&
12254           TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12255                               N120.getValueType())) {
12256         SDValue N1200 = N120.getOperand(0);
12257         SDValue N1201 = N120.getOperand(1);
12258         return DAG.getNode(PreferredFusedOpcode, SL, VT,
12259                            DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
12260                            N1.getOperand(1),
12261                            DAG.getNode(PreferredFusedOpcode, SL, VT,
12262                                        DAG.getNode(ISD::FNEG, SL, VT,
12263                                                    DAG.getNode(ISD::FP_EXTEND, SL,
12264                                                                VT, N1200)),
12265                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12266                                                    N1201),
12267                                        N0, Flags), Flags);
12268       }
12269     }
12270 
12271     // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
12272     //   -> (fma (fneg (fpext y)), (fpext z),
12273     //           (fma (fneg (fpext u)), (fpext v), x))
12274     // FIXME: This turns two single-precision and one double-precision
12275     // operation into two double-precision operations, which might not be
12276     // interesting for all targets, especially GPUs.
12277     if (N1.getOpcode() == ISD::FP_EXTEND &&
12278         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
12279       SDValue CvtSrc = N1.getOperand(0);
12280       SDValue N100 = CvtSrc.getOperand(0);
12281       SDValue N101 = CvtSrc.getOperand(1);
12282       SDValue N102 = CvtSrc.getOperand(2);
12283       if (isContractableFMUL(N102) &&
12284           TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
12285                               CvtSrc.getValueType())) {
12286         SDValue N1020 = N102.getOperand(0);
12287         SDValue N1021 = N102.getOperand(1);
12288         return DAG.getNode(PreferredFusedOpcode, SL, VT,
12289                            DAG.getNode(ISD::FNEG, SL, VT,
12290                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12291                                                    N100)),
12292                            DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
12293                            DAG.getNode(PreferredFusedOpcode, SL, VT,
12294                                        DAG.getNode(ISD::FNEG, SL, VT,
12295                                                    DAG.getNode(ISD::FP_EXTEND, SL,
12296                                                                VT, N1020)),
12297                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
12298                                                    N1021),
12299                                        N0, Flags), Flags);
12300       }
12301     }
12302   }
12303 
12304   return SDValue();
12305 }
12306 
12307 /// Try to perform FMA combining on a given FMUL node based on the distributive
12308 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
12309 /// subtraction instead of addition).
12310 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
12311   SDValue N0 = N->getOperand(0);
12312   SDValue N1 = N->getOperand(1);
12313   EVT VT = N->getValueType(0);
12314   SDLoc SL(N);
12315   const SDNodeFlags Flags = N->getFlags();
12316 
12317   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
12318 
12319   const TargetOptions &Options = DAG.getTarget().Options;
12320 
12321   // The transforms below are incorrect when x == 0 and y == inf, because the
12322   // intermediate multiplication produces a nan.
12323   if (!Options.NoInfsFPMath)
12324     return SDValue();
12325 
12326   // Floating-point multiply-add without intermediate rounding.
12327   bool HasFMA =
12328       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
12329       TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
12330       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
12331 
12332   // Floating-point multiply-add with intermediate rounding. This can result
12333   // in a less precise result due to the changed rounding order.
12334   bool HasFMAD = Options.UnsafeFPMath &&
12335                  (LegalOperations && TLI.isFMADLegal(DAG, N));
12336 
12337   // No valid opcode, do not combine.
12338   if (!HasFMAD && !HasFMA)
12339     return SDValue();
12340 
12341   // Always prefer FMAD to FMA for precision.
12342   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
12343   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
12344 
12345   // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
12346   // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
12347   auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
12348     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
12349       if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
12350         if (C->isExactlyValue(+1.0))
12351           return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
12352                              Y, Flags);
12353         if (C->isExactlyValue(-1.0))
12354           return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
12355                              DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
12356       }
12357     }
12358     return SDValue();
12359   };
12360 
12361   if (SDValue FMA = FuseFADD(N0, N1, Flags))
12362     return FMA;
12363   if (SDValue FMA = FuseFADD(N1, N0, Flags))
12364     return FMA;
12365 
12366   // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
12367   // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
12368   // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
12369   // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
12370   auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) {
12371     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
12372       if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
12373         if (C0->isExactlyValue(+1.0))
12374           return DAG.getNode(PreferredFusedOpcode, SL, VT,
12375                              DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
12376                              Y, Flags);
12377         if (C0->isExactlyValue(-1.0))
12378           return DAG.getNode(PreferredFusedOpcode, SL, VT,
12379                              DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
12380                              DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
12381       }
12382       if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
12383         if (C1->isExactlyValue(+1.0))
12384           return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
12385                              DAG.getNode(ISD::FNEG, SL, VT, Y), Flags);
12386         if (C1->isExactlyValue(-1.0))
12387           return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
12388                              Y, Flags);
12389       }
12390     }
12391     return SDValue();
12392   };
12393 
12394   if (SDValue FMA = FuseFSUB(N0, N1, Flags))
12395     return FMA;
12396   if (SDValue FMA = FuseFSUB(N1, N0, Flags))
12397     return FMA;
12398 
12399   return SDValue();
12400 }
12401 
12402 SDValue DAGCombiner::visitFADD(SDNode *N) {
12403   SDValue N0 = N->getOperand(0);
12404   SDValue N1 = N->getOperand(1);
12405   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
12406   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
12407   EVT VT = N->getValueType(0);
12408   SDLoc DL(N);
12409   const TargetOptions &Options = DAG.getTarget().Options;
12410   const SDNodeFlags Flags = N->getFlags();
12411 
12412   if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
12413     return R;
12414 
12415   // fold vector ops
12416   if (VT.isVector())
12417     if (SDValue FoldedVOp = SimplifyVBinOp(N))
12418       return FoldedVOp;
12419 
12420   // fold (fadd c1, c2) -> c1 + c2
12421   if (N0CFP && N1CFP)
12422     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
12423 
12424   // canonicalize constant to RHS
12425   if (N0CFP && !N1CFP)
12426     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
12427 
12428   // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
12429   ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
12430   if (N1C && N1C->isZero())
12431     if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())
12432       return N0;
12433 
12434   if (SDValue NewSel = foldBinOpIntoSelect(N))
12435     return NewSel;
12436 
12437   // fold (fadd A, (fneg B)) -> (fsub A, B)
12438   if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
12439     if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
12440             N1, DAG, LegalOperations, ForCodeSize))
12441       return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1, Flags);
12442 
12443   // fold (fadd (fneg A), B) -> (fsub B, A)
12444   if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
12445     if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
12446             N0, DAG, LegalOperations, ForCodeSize))
12447       return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0, Flags);
12448 
12449   auto isFMulNegTwo = [](SDValue FMul) {
12450     if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
12451       return false;
12452     auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
12453     return C && C->isExactlyValue(-2.0);
12454   };
12455 
12456   // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
12457   if (isFMulNegTwo(N0)) {
12458     SDValue B = N0.getOperand(0);
12459     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags);
12460     return DAG.getNode(ISD::FSUB, DL, VT, N1, Add, Flags);
12461   }
12462   // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
12463   if (isFMulNegTwo(N1)) {
12464     SDValue B = N1.getOperand(0);
12465     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags);
12466     return DAG.getNode(ISD::FSUB, DL, VT, N0, Add, Flags);
12467   }
12468 
12469   // No FP constant should be created after legalization as Instruction
12470   // Selection pass has a hard time dealing with FP constants.
12471   bool AllowNewConst = (Level < AfterLegalizeDAG);
12472 
12473   // If nnan is enabled, fold lots of things.
12474   if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) {
12475     // If allowed, fold (fadd (fneg x), x) -> 0.0
12476     if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
12477       return DAG.getConstantFP(0.0, DL, VT);
12478 
12479     // If allowed, fold (fadd x, (fneg x)) -> 0.0
12480     if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
12481       return DAG.getConstantFP(0.0, DL, VT);
12482   }
12483 
12484   // If 'unsafe math' or reassoc and nsz, fold lots of things.
12485   // TODO: break out portions of the transformations below for which Unsafe is
12486   //       considered and which do not require both nsz and reassoc
12487   if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
12488        (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
12489       AllowNewConst) {
12490     // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
12491     if (N1CFP && N0.getOpcode() == ISD::FADD &&
12492         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
12493       SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags);
12494       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags);
12495     }
12496 
12497     // We can fold chains of FADD's of the same value into multiplications.
12498     // This transform is not safe in general because we are reducing the number
12499     // of rounding steps.
12500     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
12501       if (N0.getOpcode() == ISD::FMUL) {
12502         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
12503         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
12504 
12505         // (fadd (fmul x, c), x) -> (fmul x, c+1)
12506         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
12507           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
12508                                        DAG.getConstantFP(1.0, DL, VT), Flags);
12509           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
12510         }
12511 
12512         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
12513         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
12514             N1.getOperand(0) == N1.getOperand(1) &&
12515             N0.getOperand(0) == N1.getOperand(0)) {
12516           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
12517                                        DAG.getConstantFP(2.0, DL, VT), Flags);
12518           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
12519         }
12520       }
12521 
12522       if (N1.getOpcode() == ISD::FMUL) {
12523         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
12524         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
12525 
12526         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
12527         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
12528           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
12529                                        DAG.getConstantFP(1.0, DL, VT), Flags);
12530           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
12531         }
12532 
12533         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
12534         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
12535             N0.getOperand(0) == N0.getOperand(1) &&
12536             N1.getOperand(0) == N0.getOperand(0)) {
12537           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
12538                                        DAG.getConstantFP(2.0, DL, VT), Flags);
12539           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
12540         }
12541       }
12542 
12543       if (N0.getOpcode() == ISD::FADD) {
12544         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
12545         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
12546         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
12547             (N0.getOperand(0) == N1)) {
12548           return DAG.getNode(ISD::FMUL, DL, VT,
12549                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
12550         }
12551       }
12552 
12553       if (N1.getOpcode() == ISD::FADD) {
12554         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
12555         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
12556         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
12557             N1.getOperand(0) == N0) {
12558           return DAG.getNode(ISD::FMUL, DL, VT,
12559                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
12560         }
12561       }
12562 
12563       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
12564       if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
12565           N0.getOperand(0) == N0.getOperand(1) &&
12566           N1.getOperand(0) == N1.getOperand(1) &&
12567           N0.getOperand(0) == N1.getOperand(0)) {
12568         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
12569                            DAG.getConstantFP(4.0, DL, VT), Flags);
12570       }
12571     }
12572   } // enable-unsafe-fp-math
12573 
12574   // FADD -> FMA combines:
12575   if (SDValue Fused = visitFADDForFMACombine(N)) {
12576     AddToWorklist(Fused.getNode());
12577     return Fused;
12578   }
12579   return SDValue();
12580 }
12581 
12582 SDValue DAGCombiner::visitFSUB(SDNode *N) {
12583   SDValue N0 = N->getOperand(0);
12584   SDValue N1 = N->getOperand(1);
12585   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
12586   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
12587   EVT VT = N->getValueType(0);
12588   SDLoc DL(N);
12589   const TargetOptions &Options = DAG.getTarget().Options;
12590   const SDNodeFlags Flags = N->getFlags();
12591 
12592   if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
12593     return R;
12594 
12595   // fold vector ops
12596   if (VT.isVector())
12597     if (SDValue FoldedVOp = SimplifyVBinOp(N))
12598       return FoldedVOp;
12599 
12600   // fold (fsub c1, c2) -> c1-c2
12601   if (N0CFP && N1CFP)
12602     return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
12603 
12604   if (SDValue NewSel = foldBinOpIntoSelect(N))
12605     return NewSel;
12606 
12607   // (fsub A, 0) -> A
12608   if (N1CFP && N1CFP->isZero()) {
12609     if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath ||
12610         Flags.hasNoSignedZeros()) {
12611       return N0;
12612     }
12613   }
12614 
12615   if (N0 == N1) {
12616     // (fsub x, x) -> 0.0
12617     if (Options.NoNaNsFPMath || Flags.hasNoNaNs())
12618       return DAG.getConstantFP(0.0f, DL, VT);
12619   }
12620 
12621   // (fsub -0.0, N1) -> -N1
12622   // NOTE: It is safe to transform an FSUB(-0.0,X) into an FNEG(X), since the
12623   //       FSUB does not specify the sign bit of a NaN. Also note that for
12624   //       the same reason, the inverse transform is not safe, unless fast math
12625   //       flags are in play.
12626   if (N0CFP && N0CFP->isZero()) {
12627     if (N0CFP->isNegative() ||
12628         (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) {
12629       if (SDValue NegN1 =
12630               TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
12631         return NegN1;
12632       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
12633         return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
12634     }
12635   }
12636 
12637   if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
12638        (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
12639       N1.getOpcode() == ISD::FADD) {
12640     // X - (X + Y) -> -Y
12641     if (N0 == N1->getOperand(0))
12642       return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1), Flags);
12643     // X - (Y + X) -> -Y
12644     if (N0 == N1->getOperand(1))
12645       return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0), Flags);
12646   }
12647 
12648   // fold (fsub A, (fneg B)) -> (fadd A, B)
12649   if (SDValue NegN1 =
12650           TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
12651     return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1, Flags);
12652 
12653   // FSUB -> FMA combines:
12654   if (SDValue Fused = visitFSUBForFMACombine(N)) {
12655     AddToWorklist(Fused.getNode());
12656     return Fused;
12657   }
12658 
12659   return SDValue();
12660 }
12661 
12662 SDValue DAGCombiner::visitFMUL(SDNode *N) {
12663   SDValue N0 = N->getOperand(0);
12664   SDValue N1 = N->getOperand(1);
12665   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
12666   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
12667   EVT VT = N->getValueType(0);
12668   SDLoc DL(N);
12669   const TargetOptions &Options = DAG.getTarget().Options;
12670   const SDNodeFlags Flags = N->getFlags();
12671 
12672   if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
12673     return R;
12674 
12675   // fold vector ops
12676   if (VT.isVector()) {
12677     // This just handles C1 * C2 for vectors. Other vector folds are below.
12678     if (SDValue FoldedVOp = SimplifyVBinOp(N))
12679       return FoldedVOp;
12680   }
12681 
12682   // fold (fmul c1, c2) -> c1*c2
12683   if (N0CFP && N1CFP)
12684     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
12685 
12686   // canonicalize constant to RHS
12687   if (isConstantFPBuildVectorOrConstantFP(N0) &&
12688      !isConstantFPBuildVectorOrConstantFP(N1))
12689     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
12690 
12691   if (SDValue NewSel = foldBinOpIntoSelect(N))
12692     return NewSel;
12693 
12694   if ((Options.NoNaNsFPMath && Options.NoSignedZerosFPMath) ||
12695       (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) {
12696     // fold (fmul A, 0) -> 0
12697     if (N1CFP && N1CFP->isZero())
12698       return N1;
12699   }
12700 
12701   if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) {
12702     // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
12703     if (isConstantFPBuildVectorOrConstantFP(N1) &&
12704         N0.getOpcode() == ISD::FMUL) {
12705       SDValue N00 = N0.getOperand(0);
12706       SDValue N01 = N0.getOperand(1);
12707       // Avoid an infinite loop by making sure that N00 is not a constant
12708       // (the inner multiply has not been constant folded yet).
12709       if (isConstantFPBuildVectorOrConstantFP(N01) &&
12710           !isConstantFPBuildVectorOrConstantFP(N00)) {
12711         SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
12712         return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
12713       }
12714     }
12715 
12716     // Match a special-case: we convert X * 2.0 into fadd.
12717     // fmul (fadd X, X), C -> fmul X, 2.0 * C
12718     if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
12719         N0.getOperand(0) == N0.getOperand(1)) {
12720       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
12721       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
12722       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
12723     }
12724   }
12725 
12726   // fold (fmul X, 2.0) -> (fadd X, X)
12727   if (N1CFP && N1CFP->isExactlyValue(+2.0))
12728     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
12729 
12730   // fold (fmul X, -1.0) -> (fneg X)
12731   if (N1CFP && N1CFP->isExactlyValue(-1.0))
12732     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
12733       return DAG.getNode(ISD::FNEG, DL, VT, N0);
12734 
12735   // -N0 * -N1 --> N0 * N1
12736   TargetLowering::NegatibleCost CostN0 =
12737       TargetLowering::NegatibleCost::Expensive;
12738   TargetLowering::NegatibleCost CostN1 =
12739       TargetLowering::NegatibleCost::Expensive;
12740   SDValue NegN0 =
12741       TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
12742   SDValue NegN1 =
12743       TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
12744   if (NegN0 && NegN1 &&
12745       (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
12746        CostN1 == TargetLowering::NegatibleCost::Cheaper))
12747     return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1, Flags);
12748 
12749   // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
12750   // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
12751   if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
12752       (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
12753       TLI.isOperationLegal(ISD::FABS, VT)) {
12754     SDValue Select = N0, X = N1;
12755     if (Select.getOpcode() != ISD::SELECT)
12756       std::swap(Select, X);
12757 
12758     SDValue Cond = Select.getOperand(0);
12759     auto TrueOpnd  = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
12760     auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
12761 
12762     if (TrueOpnd && FalseOpnd &&
12763         Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
12764         isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
12765         cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
12766       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12767       switch (CC) {
12768       default: break;
12769       case ISD::SETOLT:
12770       case ISD::SETULT:
12771       case ISD::SETOLE:
12772       case ISD::SETULE:
12773       case ISD::SETLT:
12774       case ISD::SETLE:
12775         std::swap(TrueOpnd, FalseOpnd);
12776         LLVM_FALLTHROUGH;
12777       case ISD::SETOGT:
12778       case ISD::SETUGT:
12779       case ISD::SETOGE:
12780       case ISD::SETUGE:
12781       case ISD::SETGT:
12782       case ISD::SETGE:
12783         if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
12784             TLI.isOperationLegal(ISD::FNEG, VT))
12785           return DAG.getNode(ISD::FNEG, DL, VT,
12786                    DAG.getNode(ISD::FABS, DL, VT, X));
12787         if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
12788           return DAG.getNode(ISD::FABS, DL, VT, X);
12789 
12790         break;
12791       }
12792     }
12793   }
12794 
12795   // FMUL -> FMA combines:
12796   if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
12797     AddToWorklist(Fused.getNode());
12798     return Fused;
12799   }
12800 
12801   return SDValue();
12802 }
12803 
12804 SDValue DAGCombiner::visitFMA(SDNode *N) {
12805   SDValue N0 = N->getOperand(0);
12806   SDValue N1 = N->getOperand(1);
12807   SDValue N2 = N->getOperand(2);
12808   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
12809   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
12810   EVT VT = N->getValueType(0);
12811   SDLoc DL(N);
12812   const TargetOptions &Options = DAG.getTarget().Options;
12813 
12814   // FMA nodes have flags that propagate to the created nodes.
12815   const SDNodeFlags Flags = N->getFlags();
12816   bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N);
12817 
12818   // Constant fold FMA.
12819   if (isa<ConstantFPSDNode>(N0) &&
12820       isa<ConstantFPSDNode>(N1) &&
12821       isa<ConstantFPSDNode>(N2)) {
12822     return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
12823   }
12824 
12825   // (-N0 * -N1) + N2 --> (N0 * N1) + N2
12826   TargetLowering::NegatibleCost CostN0 =
12827       TargetLowering::NegatibleCost::Expensive;
12828   TargetLowering::NegatibleCost CostN1 =
12829       TargetLowering::NegatibleCost::Expensive;
12830   SDValue NegN0 =
12831       TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
12832   SDValue NegN1 =
12833       TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
12834   if (NegN0 && NegN1 &&
12835       (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
12836        CostN1 == TargetLowering::NegatibleCost::Cheaper))
12837     return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2, Flags);
12838 
12839   if (UnsafeFPMath) {
12840     if (N0CFP && N0CFP->isZero())
12841       return N2;
12842     if (N1CFP && N1CFP->isZero())
12843       return N2;
12844   }
12845   // TODO: The FMA node should have flags that propagate to these nodes.
12846   if (N0CFP && N0CFP->isExactlyValue(1.0))
12847     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
12848   if (N1CFP && N1CFP->isExactlyValue(1.0))
12849     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
12850 
12851   // Canonicalize (fma c, x, y) -> (fma x, c, y)
12852   if (isConstantFPBuildVectorOrConstantFP(N0) &&
12853      !isConstantFPBuildVectorOrConstantFP(N1))
12854     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
12855 
12856   if (UnsafeFPMath) {
12857     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
12858     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
12859         isConstantFPBuildVectorOrConstantFP(N1) &&
12860         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
12861       return DAG.getNode(ISD::FMUL, DL, VT, N0,
12862                          DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
12863                                      Flags), Flags);
12864     }
12865 
12866     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
12867     if (N0.getOpcode() == ISD::FMUL &&
12868         isConstantFPBuildVectorOrConstantFP(N1) &&
12869         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
12870       return DAG.getNode(ISD::FMA, DL, VT,
12871                          N0.getOperand(0),
12872                          DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
12873                                      Flags),
12874                          N2);
12875     }
12876   }
12877 
12878   // (fma x, 1, y) -> (fadd x, y)
12879   // (fma x, -1, y) -> (fadd (fneg x), y)
12880   if (N1CFP) {
12881     if (N1CFP->isExactlyValue(1.0))
12882       // TODO: The FMA node should have flags that propagate to this node.
12883       return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
12884 
12885     if (N1CFP->isExactlyValue(-1.0) &&
12886         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
12887       SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
12888       AddToWorklist(RHSNeg.getNode());
12889       // TODO: The FMA node should have flags that propagate to this node.
12890       return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
12891     }
12892 
12893     // fma (fneg x), K, y -> fma x -K, y
12894     if (N0.getOpcode() == ISD::FNEG &&
12895         (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
12896          (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT,
12897                                               ForCodeSize)))) {
12898       return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
12899                          DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2);
12900     }
12901   }
12902 
12903   if (UnsafeFPMath) {
12904     // (fma x, c, x) -> (fmul x, (c+1))
12905     if (N1CFP && N0 == N2) {
12906       return DAG.getNode(ISD::FMUL, DL, VT, N0,
12907                          DAG.getNode(ISD::FADD, DL, VT, N1,
12908                                      DAG.getConstantFP(1.0, DL, VT), Flags),
12909                          Flags);
12910     }
12911 
12912     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
12913     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
12914       return DAG.getNode(ISD::FMUL, DL, VT, N0,
12915                          DAG.getNode(ISD::FADD, DL, VT, N1,
12916                                      DAG.getConstantFP(-1.0, DL, VT), Flags),
12917                          Flags);
12918     }
12919   }
12920 
12921   // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z))
12922   // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z))
12923   if (!TLI.isFNegFree(VT))
12924     if (SDValue Neg = TLI.getCheaperNegatedExpression(
12925             SDValue(N, 0), DAG, LegalOperations, ForCodeSize))
12926       return DAG.getNode(ISD::FNEG, DL, VT, Neg, Flags);
12927   return SDValue();
12928 }
12929 
12930 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12931 // reciprocal.
12932 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
12933 // Notice that this is not always beneficial. One reason is different targets
12934 // may have different costs for FDIV and FMUL, so sometimes the cost of two
12935 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
12936 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
12937 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
12938   // TODO: Limit this transform based on optsize/minsize - it always creates at
12939   //       least 1 extra instruction. But the perf win may be substantial enough
12940   //       that only minsize should restrict this.
12941   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
12942   const SDNodeFlags Flags = N->getFlags();
12943   if (!UnsafeMath && !Flags.hasAllowReciprocal())
12944     return SDValue();
12945 
12946   // Skip if current node is a reciprocal/fneg-reciprocal.
12947   SDValue N0 = N->getOperand(0);
12948   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
12949   if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0)))
12950     return SDValue();
12951 
12952   // Exit early if the target does not want this transform or if there can't
12953   // possibly be enough uses of the divisor to make the transform worthwhile.
12954   SDValue N1 = N->getOperand(1);
12955   unsigned MinUses = TLI.combineRepeatedFPDivisors();
12956 
12957   // For splat vectors, scale the number of uses by the splat factor. If we can
12958   // convert the division into a scalar op, that will likely be much faster.
12959   unsigned NumElts = 1;
12960   EVT VT = N->getValueType(0);
12961   if (VT.isVector() && DAG.isSplatValue(N1))
12962     NumElts = VT.getVectorNumElements();
12963 
12964   if (!MinUses || (N1->use_size() * NumElts) < MinUses)
12965     return SDValue();
12966 
12967   // Find all FDIV users of the same divisor.
12968   // Use a set because duplicates may be present in the user list.
12969   SetVector<SDNode *> Users;
12970   for (auto *U : N1->uses()) {
12971     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
12972       // This division is eligible for optimization only if global unsafe math
12973       // is enabled or if this division allows reciprocal formation.
12974       if (UnsafeMath || U->getFlags().hasAllowReciprocal())
12975         Users.insert(U);
12976     }
12977   }
12978 
12979   // Now that we have the actual number of divisor uses, make sure it meets
12980   // the minimum threshold specified by the target.
12981   if ((Users.size() * NumElts) < MinUses)
12982     return SDValue();
12983 
12984   SDLoc DL(N);
12985   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
12986   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
12987 
12988   // Dividend / Divisor -> Dividend * Reciprocal
12989   for (auto *U : Users) {
12990     SDValue Dividend = U->getOperand(0);
12991     if (Dividend != FPOne) {
12992       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
12993                                     Reciprocal, Flags);
12994       CombineTo(U, NewNode);
12995     } else if (U != Reciprocal.getNode()) {
12996       // In the absence of fast-math-flags, this user node is always the
12997       // same node as Reciprocal, but with FMF they may be different nodes.
12998       CombineTo(U, Reciprocal);
12999     }
13000   }
13001   return SDValue(N, 0);  // N was replaced.
13002 }
13003 
13004 SDValue DAGCombiner::visitFDIV(SDNode *N) {
13005   SDValue N0 = N->getOperand(0);
13006   SDValue N1 = N->getOperand(1);
13007   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
13008   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
13009   EVT VT = N->getValueType(0);
13010   SDLoc DL(N);
13011   const TargetOptions &Options = DAG.getTarget().Options;
13012   SDNodeFlags Flags = N->getFlags();
13013 
13014   if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
13015     return R;
13016 
13017   // fold vector ops
13018   if (VT.isVector())
13019     if (SDValue FoldedVOp = SimplifyVBinOp(N))
13020       return FoldedVOp;
13021 
13022   // fold (fdiv c1, c2) -> c1/c2
13023   if (N0CFP && N1CFP)
13024     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
13025 
13026   if (SDValue NewSel = foldBinOpIntoSelect(N))
13027     return NewSel;
13028 
13029   if (SDValue V = combineRepeatedFPDivisors(N))
13030     return V;
13031 
13032   if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) {
13033     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
13034     if (N1CFP) {
13035       // Compute the reciprocal 1.0 / c2.
13036       const APFloat &N1APF = N1CFP->getValueAPF();
13037       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
13038       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
13039       // Only do the transform if the reciprocal is a legal fp immediate that
13040       // isn't too nasty (eg NaN, denormal, ...).
13041       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
13042           (!LegalOperations ||
13043            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
13044            // backend)... we should handle this gracefully after Legalize.
13045            // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
13046            TLI.isOperationLegal(ISD::ConstantFP, VT) ||
13047            TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
13048         return DAG.getNode(ISD::FMUL, DL, VT, N0,
13049                            DAG.getConstantFP(Recip, DL, VT), Flags);
13050     }
13051 
13052     // If this FDIV is part of a reciprocal square root, it may be folded
13053     // into a target-specific square root estimate instruction.
13054     if (N1.getOpcode() == ISD::FSQRT) {
13055       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags))
13056         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
13057     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
13058                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
13059       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
13060                                           Flags)) {
13061         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
13062         AddToWorklist(RV.getNode());
13063         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
13064       }
13065     } else if (N1.getOpcode() == ISD::FP_ROUND &&
13066                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
13067       if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
13068                                           Flags)) {
13069         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
13070         AddToWorklist(RV.getNode());
13071         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
13072       }
13073     } else if (N1.getOpcode() == ISD::FMUL) {
13074       // Look through an FMUL. Even though this won't remove the FDIV directly,
13075       // it's still worthwhile to get rid of the FSQRT if possible.
13076       SDValue SqrtOp;
13077       SDValue OtherOp;
13078       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
13079         SqrtOp = N1.getOperand(0);
13080         OtherOp = N1.getOperand(1);
13081       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
13082         SqrtOp = N1.getOperand(1);
13083         OtherOp = N1.getOperand(0);
13084       }
13085       if (SqrtOp.getNode()) {
13086         // We found a FSQRT, so try to make this fold:
13087         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
13088         if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
13089           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
13090           AddToWorklist(RV.getNode());
13091           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
13092         }
13093       }
13094     }
13095 
13096     // Fold into a reciprocal estimate and multiply instead of a real divide.
13097     if (SDValue RV = BuildDivEstimate(N0, N1, Flags))
13098       return RV;
13099   }
13100 
13101   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
13102   TargetLowering::NegatibleCost CostN0 =
13103       TargetLowering::NegatibleCost::Expensive;
13104   TargetLowering::NegatibleCost CostN1 =
13105       TargetLowering::NegatibleCost::Expensive;
13106   SDValue NegN0 =
13107       TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
13108   SDValue NegN1 =
13109       TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
13110   if (NegN0 && NegN1 &&
13111       (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
13112        CostN1 == TargetLowering::NegatibleCost::Cheaper))
13113     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1, Flags);
13114 
13115   return SDValue();
13116 }
13117 
13118 SDValue DAGCombiner::visitFREM(SDNode *N) {
13119   SDValue N0 = N->getOperand(0);
13120   SDValue N1 = N->getOperand(1);
13121   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
13122   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
13123   EVT VT = N->getValueType(0);
13124   SDNodeFlags Flags = N->getFlags();
13125 
13126   if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
13127     return R;
13128 
13129   // fold (frem c1, c2) -> fmod(c1,c2)
13130   if (N0CFP && N1CFP)
13131     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
13132 
13133   if (SDValue NewSel = foldBinOpIntoSelect(N))
13134     return NewSel;
13135 
13136   return SDValue();
13137 }
13138 
13139 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
13140   SDNodeFlags Flags = N->getFlags();
13141   const TargetOptions &Options = DAG.getTarget().Options;
13142 
13143   // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as:
13144   // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN
13145   if ((!Options.UnsafeFPMath && !Flags.hasApproximateFuncs()) ||
13146       (!Options.NoInfsFPMath && !Flags.hasNoInfs()))
13147     return SDValue();
13148 
13149   SDValue N0 = N->getOperand(0);
13150   if (TLI.isFsqrtCheap(N0, DAG))
13151     return SDValue();
13152 
13153   // FSQRT nodes have flags that propagate to the created nodes.
13154   return buildSqrtEstimate(N0, Flags);
13155 }
13156 
13157 /// copysign(x, fp_extend(y)) -> copysign(x, y)
13158 /// copysign(x, fp_round(y)) -> copysign(x, y)
13159 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
13160   SDValue N1 = N->getOperand(1);
13161   if ((N1.getOpcode() == ISD::FP_EXTEND ||
13162        N1.getOpcode() == ISD::FP_ROUND)) {
13163     // Do not optimize out type conversion of f128 type yet.
13164     // For some targets like x86_64, configuration is changed to keep one f128
13165     // value in one SSE register, but instruction selection cannot handle
13166     // FCOPYSIGN on SSE registers yet.
13167     EVT N1VT = N1->getValueType(0);
13168     EVT N1Op0VT = N1->getOperand(0).getValueType();
13169     return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
13170   }
13171   return false;
13172 }
13173 
13174 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
13175   SDValue N0 = N->getOperand(0);
13176   SDValue N1 = N->getOperand(1);
13177   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
13178   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
13179   EVT VT = N->getValueType(0);
13180 
13181   if (N0CFP && N1CFP) // Constant fold
13182     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
13183 
13184   if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) {
13185     const APFloat &V = N1C->getValueAPF();
13186     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
13187     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
13188     if (!V.isNegative()) {
13189       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
13190         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
13191     } else {
13192       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
13193         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
13194                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
13195     }
13196   }
13197 
13198   // copysign(fabs(x), y) -> copysign(x, y)
13199   // copysign(fneg(x), y) -> copysign(x, y)
13200   // copysign(copysign(x,z), y) -> copysign(x, y)
13201   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
13202       N0.getOpcode() == ISD::FCOPYSIGN)
13203     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
13204 
13205   // copysign(x, abs(y)) -> abs(x)
13206   if (N1.getOpcode() == ISD::FABS)
13207     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
13208 
13209   // copysign(x, copysign(y,z)) -> copysign(x, z)
13210   if (N1.getOpcode() == ISD::FCOPYSIGN)
13211     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
13212 
13213   // copysign(x, fp_extend(y)) -> copysign(x, y)
13214   // copysign(x, fp_round(y)) -> copysign(x, y)
13215   if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
13216     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
13217 
13218   return SDValue();
13219 }
13220 
13221 SDValue DAGCombiner::visitFPOW(SDNode *N) {
13222   ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1));
13223   if (!ExponentC)
13224     return SDValue();
13225 
13226   // Try to convert x ** (1/3) into cube root.
13227   // TODO: Handle the various flavors of long double.
13228   // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
13229   //       Some range near 1/3 should be fine.
13230   EVT VT = N->getValueType(0);
13231   if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) ||
13232       (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) {
13233     // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
13234     // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
13235     // pow(-val, 1/3) =  nan; cbrt(-val) = -num.
13236     // For regular numbers, rounding may cause the results to differ.
13237     // Therefore, we require { nsz ninf nnan afn } for this transform.
13238     // TODO: We could select out the special cases if we don't have nsz/ninf.
13239     SDNodeFlags Flags = N->getFlags();
13240     if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() ||
13241         !Flags.hasApproximateFuncs())
13242       return SDValue();
13243 
13244     // Do not create a cbrt() libcall if the target does not have it, and do not
13245     // turn a pow that has lowering support into a cbrt() libcall.
13246     if (!DAG.getLibInfo().has(LibFunc_cbrt) ||
13247         (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) &&
13248          DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT)))
13249       return SDValue();
13250 
13251     return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0), Flags);
13252   }
13253 
13254   // Try to convert x ** (1/4) and x ** (3/4) into square roots.
13255   // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
13256   // TODO: This could be extended (using a target hook) to handle smaller
13257   // power-of-2 fractional exponents.
13258   bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25);
13259   bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75);
13260   if (ExponentIs025 || ExponentIs075) {
13261     // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
13262     // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) =  NaN.
13263     // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
13264     // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) =  NaN.
13265     // For regular numbers, rounding may cause the results to differ.
13266     // Therefore, we require { nsz ninf afn } for this transform.
13267     // TODO: We could select out the special cases if we don't have nsz/ninf.
13268     SDNodeFlags Flags = N->getFlags();
13269 
13270     // We only need no signed zeros for the 0.25 case.
13271     if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() ||
13272         !Flags.hasApproximateFuncs())
13273       return SDValue();
13274 
13275     // Don't double the number of libcalls. We are trying to inline fast code.
13276     if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT))
13277       return SDValue();
13278 
13279     // Assume that libcalls are the smallest code.
13280     // TODO: This restriction should probably be lifted for vectors.
13281     if (ForCodeSize)
13282       return SDValue();
13283 
13284     // pow(X, 0.25) --> sqrt(sqrt(X))
13285     SDLoc DL(N);
13286     SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0), Flags);
13287     SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt, Flags);
13288     if (ExponentIs025)
13289       return SqrtSqrt;
13290     // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
13291     return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt, Flags);
13292   }
13293 
13294   return SDValue();
13295 }
13296 
13297 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
13298                                const TargetLowering &TLI) {
13299   // This optimization is guarded by a function attribute because it may produce
13300   // unexpected results. Ie, programs may be relying on the platform-specific
13301   // undefined behavior when the float-to-int conversion overflows.
13302   const Function &F = DAG.getMachineFunction().getFunction();
13303   Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow");
13304   if (StrictOverflow.getValueAsString().equals("false"))
13305     return SDValue();
13306 
13307   // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
13308   // replacing casts with a libcall. We also must be allowed to ignore -0.0
13309   // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
13310   // conversions would return +0.0.
13311   // FIXME: We should be able to use node-level FMF here.
13312   // TODO: If strict math, should we use FABS (+ range check for signed cast)?
13313   EVT VT = N->getValueType(0);
13314   if (!TLI.isOperationLegal(ISD::FTRUNC, VT) ||
13315       !DAG.getTarget().Options.NoSignedZerosFPMath)
13316     return SDValue();
13317 
13318   // fptosi/fptoui round towards zero, so converting from FP to integer and
13319   // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
13320   SDValue N0 = N->getOperand(0);
13321   if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
13322       N0.getOperand(0).getValueType() == VT)
13323     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
13324 
13325   if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
13326       N0.getOperand(0).getValueType() == VT)
13327     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
13328 
13329   return SDValue();
13330 }
13331 
13332 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
13333   SDValue N0 = N->getOperand(0);
13334   EVT VT = N->getValueType(0);
13335   EVT OpVT = N0.getValueType();
13336 
13337   // [us]itofp(undef) = 0, because the result value is bounded.
13338   if (N0.isUndef())
13339     return DAG.getConstantFP(0.0, SDLoc(N), VT);
13340 
13341   // fold (sint_to_fp c1) -> c1fp
13342   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
13343       // ...but only if the target supports immediate floating-point values
13344       (!LegalOperations ||
13345        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
13346     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
13347 
13348   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
13349   // but UINT_TO_FP is legal on this target, try to convert.
13350   if (!hasOperation(ISD::SINT_TO_FP, OpVT) &&
13351       hasOperation(ISD::UINT_TO_FP, OpVT)) {
13352     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
13353     if (DAG.SignBitIsZero(N0))
13354       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
13355   }
13356 
13357   // The next optimizations are desirable only if SELECT_CC can be lowered.
13358   // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0)
13359   if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
13360       !VT.isVector() &&
13361       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
13362     SDLoc DL(N);
13363     return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT),
13364                          DAG.getConstantFP(0.0, DL, VT));
13365   }
13366 
13367   // fold (sint_to_fp (zext (setcc x, y, cc))) ->
13368   //      (select (setcc x, y, cc), 1.0, 0.0)
13369   if (N0.getOpcode() == ISD::ZERO_EXTEND &&
13370       N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() &&
13371       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
13372     SDLoc DL(N);
13373     return DAG.getSelect(DL, VT, N0.getOperand(0),
13374                          DAG.getConstantFP(1.0, DL, VT),
13375                          DAG.getConstantFP(0.0, DL, VT));
13376   }
13377 
13378   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
13379     return FTrunc;
13380 
13381   return SDValue();
13382 }
13383 
13384 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
13385   SDValue N0 = N->getOperand(0);
13386   EVT VT = N->getValueType(0);
13387   EVT OpVT = N0.getValueType();
13388 
13389   // [us]itofp(undef) = 0, because the result value is bounded.
13390   if (N0.isUndef())
13391     return DAG.getConstantFP(0.0, SDLoc(N), VT);
13392 
13393   // fold (uint_to_fp c1) -> c1fp
13394   if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
13395       // ...but only if the target supports immediate floating-point values
13396       (!LegalOperations ||
13397        TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
13398     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
13399 
13400   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
13401   // but SINT_TO_FP is legal on this target, try to convert.
13402   if (!hasOperation(ISD::UINT_TO_FP, OpVT) &&
13403       hasOperation(ISD::SINT_TO_FP, OpVT)) {
13404     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
13405     if (DAG.SignBitIsZero(N0))
13406       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
13407   }
13408 
13409   // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0)
13410   if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
13411       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
13412     SDLoc DL(N);
13413     return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT),
13414                          DAG.getConstantFP(0.0, DL, VT));
13415   }
13416 
13417   if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
13418     return FTrunc;
13419 
13420   return SDValue();
13421 }
13422 
13423 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
13424 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
13425   SDValue N0 = N->getOperand(0);
13426   EVT VT = N->getValueType(0);
13427 
13428   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
13429     return SDValue();
13430 
13431   SDValue Src = N0.getOperand(0);
13432   EVT SrcVT = Src.getValueType();
13433   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
13434   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
13435 
13436   // We can safely assume the conversion won't overflow the output range,
13437   // because (for example) (uint8_t)18293.f is undefined behavior.
13438 
13439   // Since we can assume the conversion won't overflow, our decision as to
13440   // whether the input will fit in the float should depend on the minimum
13441   // of the input range and output range.
13442 
13443   // This means this is also safe for a signed input and unsigned output, since
13444   // a negative input would lead to undefined behavior.
13445   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
13446   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
13447   unsigned ActualSize = std::min(InputSize, OutputSize);
13448   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
13449 
13450   // We can only fold away the float conversion if the input range can be
13451   // represented exactly in the float range.
13452   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
13453     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
13454       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
13455                                                        : ISD::ZERO_EXTEND;
13456       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
13457     }
13458     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
13459       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
13460     return DAG.getBitcast(VT, Src);
13461   }
13462   return SDValue();
13463 }
13464 
13465 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
13466   SDValue N0 = N->getOperand(0);
13467   EVT VT = N->getValueType(0);
13468 
13469   // fold (fp_to_sint undef) -> undef
13470   if (N0.isUndef())
13471     return DAG.getUNDEF(VT);
13472 
13473   // fold (fp_to_sint c1fp) -> c1
13474   if (isConstantFPBuildVectorOrConstantFP(N0))
13475     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
13476 
13477   return FoldIntToFPToInt(N, DAG);
13478 }
13479 
13480 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
13481   SDValue N0 = N->getOperand(0);
13482   EVT VT = N->getValueType(0);
13483 
13484   // fold (fp_to_uint undef) -> undef
13485   if (N0.isUndef())
13486     return DAG.getUNDEF(VT);
13487 
13488   // fold (fp_to_uint c1fp) -> c1
13489   if (isConstantFPBuildVectorOrConstantFP(N0))
13490     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
13491 
13492   return FoldIntToFPToInt(N, DAG);
13493 }
13494 
13495 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
13496   SDValue N0 = N->getOperand(0);
13497   SDValue N1 = N->getOperand(1);
13498   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
13499   EVT VT = N->getValueType(0);
13500 
13501   // fold (fp_round c1fp) -> c1fp
13502   if (N0CFP)
13503     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
13504 
13505   // fold (fp_round (fp_extend x)) -> x
13506   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
13507     return N0.getOperand(0);
13508 
13509   // fold (fp_round (fp_round x)) -> (fp_round x)
13510   if (N0.getOpcode() == ISD::FP_ROUND) {
13511     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
13512     const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
13513 
13514     // Skip this folding if it results in an fp_round from f80 to f16.
13515     //
13516     // f80 to f16 always generates an expensive (and as yet, unimplemented)
13517     // libcall to __truncxfhf2 instead of selecting native f16 conversion
13518     // instructions from f32 or f64.  Moreover, the first (value-preserving)
13519     // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
13520     // x86.
13521     if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
13522       return SDValue();
13523 
13524     // If the first fp_round isn't a value preserving truncation, it might
13525     // introduce a tie in the second fp_round, that wouldn't occur in the
13526     // single-step fp_round we want to fold to.
13527     // In other words, double rounding isn't the same as rounding.
13528     // Also, this is a value preserving truncation iff both fp_round's are.
13529     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
13530       SDLoc DL(N);
13531       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
13532                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
13533     }
13534   }
13535 
13536   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
13537   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
13538     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
13539                               N0.getOperand(0), N1);
13540     AddToWorklist(Tmp.getNode());
13541     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
13542                        Tmp, N0.getOperand(1));
13543   }
13544 
13545   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
13546     return NewVSel;
13547 
13548   return SDValue();
13549 }
13550 
13551 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
13552   SDValue N0 = N->getOperand(0);
13553   EVT VT = N->getValueType(0);
13554 
13555   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
13556   if (N->hasOneUse() &&
13557       N->use_begin()->getOpcode() == ISD::FP_ROUND)
13558     return SDValue();
13559 
13560   // fold (fp_extend c1fp) -> c1fp
13561   if (isConstantFPBuildVectorOrConstantFP(N0))
13562     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
13563 
13564   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
13565   if (N0.getOpcode() == ISD::FP16_TO_FP &&
13566       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
13567     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
13568 
13569   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
13570   // value of X.
13571   if (N0.getOpcode() == ISD::FP_ROUND
13572       && N0.getConstantOperandVal(1) == 1) {
13573     SDValue In = N0.getOperand(0);
13574     if (In.getValueType() == VT) return In;
13575     if (VT.bitsLT(In.getValueType()))
13576       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
13577                          In, N0.getOperand(1));
13578     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
13579   }
13580 
13581   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
13582   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
13583        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
13584     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13585     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
13586                                      LN0->getChain(),
13587                                      LN0->getBasePtr(), N0.getValueType(),
13588                                      LN0->getMemOperand());
13589     CombineTo(N, ExtLoad);
13590     CombineTo(N0.getNode(),
13591               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
13592                           N0.getValueType(), ExtLoad,
13593                           DAG.getIntPtrConstant(1, SDLoc(N0))),
13594               ExtLoad.getValue(1));
13595     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
13596   }
13597 
13598   if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
13599     return NewVSel;
13600 
13601   return SDValue();
13602 }
13603 
13604 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
13605   SDValue N0 = N->getOperand(0);
13606   EVT VT = N->getValueType(0);
13607 
13608   // fold (fceil c1) -> fceil(c1)
13609   if (isConstantFPBuildVectorOrConstantFP(N0))
13610     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
13611 
13612   return SDValue();
13613 }
13614 
13615 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
13616   SDValue N0 = N->getOperand(0);
13617   EVT VT = N->getValueType(0);
13618 
13619   // fold (ftrunc c1) -> ftrunc(c1)
13620   if (isConstantFPBuildVectorOrConstantFP(N0))
13621     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
13622 
13623   // fold ftrunc (known rounded int x) -> x
13624   // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
13625   // likely to be generated to extract integer from a rounded floating value.
13626   switch (N0.getOpcode()) {
13627   default: break;
13628   case ISD::FRINT:
13629   case ISD::FTRUNC:
13630   case ISD::FNEARBYINT:
13631   case ISD::FFLOOR:
13632   case ISD::FCEIL:
13633     return N0;
13634   }
13635 
13636   return SDValue();
13637 }
13638 
13639 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
13640   SDValue N0 = N->getOperand(0);
13641   EVT VT = N->getValueType(0);
13642 
13643   // fold (ffloor c1) -> ffloor(c1)
13644   if (isConstantFPBuildVectorOrConstantFP(N0))
13645     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
13646 
13647   return SDValue();
13648 }
13649 
13650 // FIXME: FNEG and FABS have a lot in common; refactor.
13651 SDValue DAGCombiner::visitFNEG(SDNode *N) {
13652   SDValue N0 = N->getOperand(0);
13653   EVT VT = N->getValueType(0);
13654 
13655   // Constant fold FNEG.
13656   if (isConstantFPBuildVectorOrConstantFP(N0))
13657     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
13658 
13659   if (SDValue NegN0 =
13660           TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize))
13661     return NegN0;
13662 
13663   // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
13664   // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't
13665   // know it was called from a context with a nsz flag if the input fsub does
13666   // not.
13667   if (N0.getOpcode() == ISD::FSUB &&
13668       (DAG.getTarget().Options.NoSignedZerosFPMath ||
13669        N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) {
13670     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1),
13671                        N0.getOperand(0), N->getFlags());
13672   }
13673 
13674   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
13675   // constant pool values.
13676   if (!TLI.isFNegFree(VT) &&
13677       N0.getOpcode() == ISD::BITCAST &&
13678       N0.getNode()->hasOneUse()) {
13679     SDValue Int = N0.getOperand(0);
13680     EVT IntVT = Int.getValueType();
13681     if (IntVT.isInteger() && !IntVT.isVector()) {
13682       APInt SignMask;
13683       if (N0.getValueType().isVector()) {
13684         // For a vector, get a mask such as 0x80... per scalar element
13685         // and splat it.
13686         SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
13687         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
13688       } else {
13689         // For a scalar, just generate 0x80...
13690         SignMask = APInt::getSignMask(IntVT.getSizeInBits());
13691       }
13692       SDLoc DL0(N0);
13693       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
13694                         DAG.getConstant(SignMask, DL0, IntVT));
13695       AddToWorklist(Int.getNode());
13696       return DAG.getBitcast(VT, Int);
13697     }
13698   }
13699 
13700   // (fneg (fmul c, x)) -> (fmul -c, x)
13701   if (N0.getOpcode() == ISD::FMUL &&
13702       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
13703     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
13704     if (CFP1) {
13705       APFloat CVal = CFP1->getValueAPF();
13706       CVal.changeSign();
13707       if (LegalDAG && (TLI.isFPImmLegal(CVal, VT, ForCodeSize) ||
13708                        TLI.isOperationLegal(ISD::ConstantFP, VT)))
13709         return DAG.getNode(
13710             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
13711             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
13712             N0->getFlags());
13713     }
13714   }
13715 
13716   return SDValue();
13717 }
13718 
13719 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N,
13720                             APFloat (*Op)(const APFloat &, const APFloat &)) {
13721   SDValue N0 = N->getOperand(0);
13722   SDValue N1 = N->getOperand(1);
13723   EVT VT = N->getValueType(0);
13724   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
13725   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
13726 
13727   if (N0CFP && N1CFP) {
13728     const APFloat &C0 = N0CFP->getValueAPF();
13729     const APFloat &C1 = N1CFP->getValueAPF();
13730     return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT);
13731   }
13732 
13733   // Canonicalize to constant on RHS.
13734   if (isConstantFPBuildVectorOrConstantFP(N0) &&
13735       !isConstantFPBuildVectorOrConstantFP(N1))
13736     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
13737 
13738   return SDValue();
13739 }
13740 
13741 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
13742   return visitFMinMax(DAG, N, minnum);
13743 }
13744 
13745 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
13746   return visitFMinMax(DAG, N, maxnum);
13747 }
13748 
13749 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) {
13750   return visitFMinMax(DAG, N, minimum);
13751 }
13752 
13753 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) {
13754   return visitFMinMax(DAG, N, maximum);
13755 }
13756 
13757 SDValue DAGCombiner::visitFABS(SDNode *N) {
13758   SDValue N0 = N->getOperand(0);
13759   EVT VT = N->getValueType(0);
13760 
13761   // fold (fabs c1) -> fabs(c1)
13762   if (isConstantFPBuildVectorOrConstantFP(N0))
13763     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
13764 
13765   // fold (fabs (fabs x)) -> (fabs x)
13766   if (N0.getOpcode() == ISD::FABS)
13767     return N->getOperand(0);
13768 
13769   // fold (fabs (fneg x)) -> (fabs x)
13770   // fold (fabs (fcopysign x, y)) -> (fabs x)
13771   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
13772     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
13773 
13774   // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads.
13775   if (!TLI.isFAbsFree(VT) && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
13776     SDValue Int = N0.getOperand(0);
13777     EVT IntVT = Int.getValueType();
13778     if (IntVT.isInteger() && !IntVT.isVector()) {
13779       APInt SignMask;
13780       if (N0.getValueType().isVector()) {
13781         // For a vector, get a mask such as 0x7f... per scalar element
13782         // and splat it.
13783         SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
13784         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
13785       } else {
13786         // For a scalar, just generate 0x7f...
13787         SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
13788       }
13789       SDLoc DL(N0);
13790       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
13791                         DAG.getConstant(SignMask, DL, IntVT));
13792       AddToWorklist(Int.getNode());
13793       return DAG.getBitcast(N->getValueType(0), Int);
13794     }
13795   }
13796 
13797   return SDValue();
13798 }
13799 
13800 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
13801   SDValue Chain = N->getOperand(0);
13802   SDValue N1 = N->getOperand(1);
13803   SDValue N2 = N->getOperand(2);
13804 
13805   // If N is a constant we could fold this into a fallthrough or unconditional
13806   // branch. However that doesn't happen very often in normal code, because
13807   // Instcombine/SimplifyCFG should have handled the available opportunities.
13808   // If we did this folding here, it would be necessary to update the
13809   // MachineBasicBlock CFG, which is awkward.
13810 
13811   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
13812   // on the target.
13813   if (N1.getOpcode() == ISD::SETCC &&
13814       TLI.isOperationLegalOrCustom(ISD::BR_CC,
13815                                    N1.getOperand(0).getValueType())) {
13816     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
13817                        Chain, N1.getOperand(2),
13818                        N1.getOperand(0), N1.getOperand(1), N2);
13819   }
13820 
13821   if (N1.hasOneUse()) {
13822     // rebuildSetCC calls visitXor which may change the Chain when there is a
13823     // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes.
13824     HandleSDNode ChainHandle(Chain);
13825     if (SDValue NewN1 = rebuildSetCC(N1))
13826       return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other,
13827                          ChainHandle.getValue(), NewN1, N2);
13828   }
13829 
13830   return SDValue();
13831 }
13832 
13833 SDValue DAGCombiner::rebuildSetCC(SDValue N) {
13834   if (N.getOpcode() == ISD::SRL ||
13835       (N.getOpcode() == ISD::TRUNCATE &&
13836        (N.getOperand(0).hasOneUse() &&
13837         N.getOperand(0).getOpcode() == ISD::SRL))) {
13838     // Look pass the truncate.
13839     if (N.getOpcode() == ISD::TRUNCATE)
13840       N = N.getOperand(0);
13841 
13842     // Match this pattern so that we can generate simpler code:
13843     //
13844     //   %a = ...
13845     //   %b = and i32 %a, 2
13846     //   %c = srl i32 %b, 1
13847     //   brcond i32 %c ...
13848     //
13849     // into
13850     //
13851     //   %a = ...
13852     //   %b = and i32 %a, 2
13853     //   %c = setcc eq %b, 0
13854     //   brcond %c ...
13855     //
13856     // This applies only when the AND constant value has one bit set and the
13857     // SRL constant is equal to the log2 of the AND constant. The back-end is
13858     // smart enough to convert the result into a TEST/JMP sequence.
13859     SDValue Op0 = N.getOperand(0);
13860     SDValue Op1 = N.getOperand(1);
13861 
13862     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
13863       SDValue AndOp1 = Op0.getOperand(1);
13864 
13865       if (AndOp1.getOpcode() == ISD::Constant) {
13866         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
13867 
13868         if (AndConst.isPowerOf2() &&
13869             cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
13870           SDLoc DL(N);
13871           return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
13872                               Op0, DAG.getConstant(0, DL, Op0.getValueType()),
13873                               ISD::SETNE);
13874         }
13875       }
13876     }
13877   }
13878 
13879   // Transform br(xor(x, y)) -> br(x != y)
13880   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
13881   if (N.getOpcode() == ISD::XOR) {
13882     // Because we may call this on a speculatively constructed
13883     // SimplifiedSetCC Node, we need to simplify this node first.
13884     // Ideally this should be folded into SimplifySetCC and not
13885     // here. For now, grab a handle to N so we don't lose it from
13886     // replacements interal to the visit.
13887     HandleSDNode XORHandle(N);
13888     while (N.getOpcode() == ISD::XOR) {
13889       SDValue Tmp = visitXOR(N.getNode());
13890       // No simplification done.
13891       if (!Tmp.getNode())
13892         break;
13893       // Returning N is form in-visit replacement that may invalidated
13894       // N. Grab value from Handle.
13895       if (Tmp.getNode() == N.getNode())
13896         N = XORHandle.getValue();
13897       else // Node simplified. Try simplifying again.
13898         N = Tmp;
13899     }
13900 
13901     if (N.getOpcode() != ISD::XOR)
13902       return N;
13903 
13904     SDNode *TheXor = N.getNode();
13905 
13906     SDValue Op0 = TheXor->getOperand(0);
13907     SDValue Op1 = TheXor->getOperand(1);
13908 
13909     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
13910       bool Equal = false;
13911       if (isOneConstant(Op0) && Op0.hasOneUse() &&
13912           Op0.getOpcode() == ISD::XOR) {
13913         TheXor = Op0.getNode();
13914         Equal = true;
13915       }
13916 
13917       EVT SetCCVT = N.getValueType();
13918       if (LegalTypes)
13919         SetCCVT = getSetCCResultType(SetCCVT);
13920       // Replace the uses of XOR with SETCC
13921       return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1,
13922                           Equal ? ISD::SETEQ : ISD::SETNE);
13923     }
13924   }
13925 
13926   return SDValue();
13927 }
13928 
13929 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
13930 //
13931 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
13932   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
13933   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
13934 
13935   // If N is a constant we could fold this into a fallthrough or unconditional
13936   // branch. However that doesn't happen very often in normal code, because
13937   // Instcombine/SimplifyCFG should have handled the available opportunities.
13938   // If we did this folding here, it would be necessary to update the
13939   // MachineBasicBlock CFG, which is awkward.
13940 
13941   // Use SimplifySetCC to simplify SETCC's.
13942   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
13943                                CondLHS, CondRHS, CC->get(), SDLoc(N),
13944                                false);
13945   if (Simp.getNode()) AddToWorklist(Simp.getNode());
13946 
13947   // fold to a simpler setcc
13948   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
13949     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
13950                        N->getOperand(0), Simp.getOperand(2),
13951                        Simp.getOperand(0), Simp.getOperand(1),
13952                        N->getOperand(4));
13953 
13954   return SDValue();
13955 }
13956 
13957 /// Return true if 'Use' is a load or a store that uses N as its base pointer
13958 /// and that N may be folded in the load / store addressing mode.
13959 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
13960                                     SelectionDAG &DAG,
13961                                     const TargetLowering &TLI) {
13962   EVT VT;
13963   unsigned AS;
13964 
13965   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
13966     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
13967       return false;
13968     VT = LD->getMemoryVT();
13969     AS = LD->getAddressSpace();
13970   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
13971     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
13972       return false;
13973     VT = ST->getMemoryVT();
13974     AS = ST->getAddressSpace();
13975   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) {
13976     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
13977       return false;
13978     VT = LD->getMemoryVT();
13979     AS = LD->getAddressSpace();
13980   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) {
13981     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
13982       return false;
13983     VT = ST->getMemoryVT();
13984     AS = ST->getAddressSpace();
13985   } else
13986     return false;
13987 
13988   TargetLowering::AddrMode AM;
13989   if (N->getOpcode() == ISD::ADD) {
13990     AM.HasBaseReg = true;
13991     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
13992     if (Offset)
13993       // [reg +/- imm]
13994       AM.BaseOffs = Offset->getSExtValue();
13995     else
13996       // [reg +/- reg]
13997       AM.Scale = 1;
13998   } else if (N->getOpcode() == ISD::SUB) {
13999     AM.HasBaseReg = true;
14000     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
14001     if (Offset)
14002       // [reg +/- imm]
14003       AM.BaseOffs = -Offset->getSExtValue();
14004     else
14005       // [reg +/- reg]
14006       AM.Scale = 1;
14007   } else
14008     return false;
14009 
14010   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
14011                                    VT.getTypeForEVT(*DAG.getContext()), AS);
14012 }
14013 
14014 static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec,
14015                                      bool &IsLoad, bool &IsMasked, SDValue &Ptr,
14016                                      const TargetLowering &TLI) {
14017   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14018     if (LD->isIndexed())
14019       return false;
14020     EVT VT = LD->getMemoryVT();
14021     if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT))
14022       return false;
14023     Ptr = LD->getBasePtr();
14024   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14025     if (ST->isIndexed())
14026       return false;
14027     EVT VT = ST->getMemoryVT();
14028     if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT))
14029       return false;
14030     Ptr = ST->getBasePtr();
14031     IsLoad = false;
14032   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
14033     if (LD->isIndexed())
14034       return false;
14035     EVT VT = LD->getMemoryVT();
14036     if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) &&
14037         !TLI.isIndexedMaskedLoadLegal(Dec, VT))
14038       return false;
14039     Ptr = LD->getBasePtr();
14040     IsMasked = true;
14041   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
14042     if (ST->isIndexed())
14043       return false;
14044     EVT VT = ST->getMemoryVT();
14045     if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) &&
14046         !TLI.isIndexedMaskedStoreLegal(Dec, VT))
14047       return false;
14048     Ptr = ST->getBasePtr();
14049     IsLoad = false;
14050     IsMasked = true;
14051   } else {
14052     return false;
14053   }
14054   return true;
14055 }
14056 
14057 /// Try turning a load/store into a pre-indexed load/store when the base
14058 /// pointer is an add or subtract and it has other uses besides the load/store.
14059 /// After the transformation, the new indexed load/store has effectively folded
14060 /// the add/subtract in and all of its other uses are redirected to the
14061 /// new load/store.
14062 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
14063   if (Level < AfterLegalizeDAG)
14064     return false;
14065 
14066   bool IsLoad = true;
14067   bool IsMasked = false;
14068   SDValue Ptr;
14069   if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked,
14070                                 Ptr, TLI))
14071     return false;
14072 
14073   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
14074   // out.  There is no reason to make this a preinc/predec.
14075   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
14076       Ptr.getNode()->hasOneUse())
14077     return false;
14078 
14079   // Ask the target to do addressing mode selection.
14080   SDValue BasePtr;
14081   SDValue Offset;
14082   ISD::MemIndexedMode AM = ISD::UNINDEXED;
14083   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
14084     return false;
14085 
14086   // Backends without true r+i pre-indexed forms may need to pass a
14087   // constant base with a variable offset so that constant coercion
14088   // will work with the patterns in canonical form.
14089   bool Swapped = false;
14090   if (isa<ConstantSDNode>(BasePtr)) {
14091     std::swap(BasePtr, Offset);
14092     Swapped = true;
14093   }
14094 
14095   // Don't create a indexed load / store with zero offset.
14096   if (isNullConstant(Offset))
14097     return false;
14098 
14099   // Try turning it into a pre-indexed load / store except when:
14100   // 1) The new base ptr is a frame index.
14101   // 2) If N is a store and the new base ptr is either the same as or is a
14102   //    predecessor of the value being stored.
14103   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
14104   //    that would create a cycle.
14105   // 4) All uses are load / store ops that use it as old base ptr.
14106 
14107   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
14108   // (plus the implicit offset) to a register to preinc anyway.
14109   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
14110     return false;
14111 
14112   // Check #2.
14113   if (!IsLoad) {
14114     SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue()
14115                            : cast<StoreSDNode>(N)->getValue();
14116 
14117     // Would require a copy.
14118     if (Val == BasePtr)
14119       return false;
14120 
14121     // Would create a cycle.
14122     if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode()))
14123       return false;
14124   }
14125 
14126   // Caches for hasPredecessorHelper.
14127   SmallPtrSet<const SDNode *, 32> Visited;
14128   SmallVector<const SDNode *, 16> Worklist;
14129   Worklist.push_back(N);
14130 
14131   // If the offset is a constant, there may be other adds of constants that
14132   // can be folded with this one. We should do this to avoid having to keep
14133   // a copy of the original base pointer.
14134   SmallVector<SDNode *, 16> OtherUses;
14135   if (isa<ConstantSDNode>(Offset))
14136     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
14137                               UE = BasePtr.getNode()->use_end();
14138          UI != UE; ++UI) {
14139       SDUse &Use = UI.getUse();
14140       // Skip the use that is Ptr and uses of other results from BasePtr's
14141       // node (important for nodes that return multiple results).
14142       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
14143         continue;
14144 
14145       if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
14146         continue;
14147 
14148       if (Use.getUser()->getOpcode() != ISD::ADD &&
14149           Use.getUser()->getOpcode() != ISD::SUB) {
14150         OtherUses.clear();
14151         break;
14152       }
14153 
14154       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
14155       if (!isa<ConstantSDNode>(Op1)) {
14156         OtherUses.clear();
14157         break;
14158       }
14159 
14160       // FIXME: In some cases, we can be smarter about this.
14161       if (Op1.getValueType() != Offset.getValueType()) {
14162         OtherUses.clear();
14163         break;
14164       }
14165 
14166       OtherUses.push_back(Use.getUser());
14167     }
14168 
14169   if (Swapped)
14170     std::swap(BasePtr, Offset);
14171 
14172   // Now check for #3 and #4.
14173   bool RealUse = false;
14174 
14175   for (SDNode *Use : Ptr.getNode()->uses()) {
14176     if (Use == N)
14177       continue;
14178     if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
14179       return false;
14180 
14181     // If Ptr may be folded in addressing mode of other use, then it's
14182     // not profitable to do this transformation.
14183     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
14184       RealUse = true;
14185   }
14186 
14187   if (!RealUse)
14188     return false;
14189 
14190   SDValue Result;
14191   if (!IsMasked) {
14192     if (IsLoad)
14193       Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
14194     else
14195       Result =
14196           DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
14197   } else {
14198     if (IsLoad)
14199       Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
14200                                         Offset, AM);
14201     else
14202       Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr,
14203                                          Offset, AM);
14204   }
14205   ++PreIndexedNodes;
14206   ++NodesCombined;
14207   LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
14208              Result.getNode()->dump(&DAG); dbgs() << '\n');
14209   WorklistRemover DeadNodes(*this);
14210   if (IsLoad) {
14211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
14212     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
14213   } else {
14214     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
14215   }
14216 
14217   // Finally, since the node is now dead, remove it from the graph.
14218   deleteAndRecombine(N);
14219 
14220   if (Swapped)
14221     std::swap(BasePtr, Offset);
14222 
14223   // Replace other uses of BasePtr that can be updated to use Ptr
14224   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
14225     unsigned OffsetIdx = 1;
14226     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
14227       OffsetIdx = 0;
14228     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
14229            BasePtr.getNode() && "Expected BasePtr operand");
14230 
14231     // We need to replace ptr0 in the following expression:
14232     //   x0 * offset0 + y0 * ptr0 = t0
14233     // knowing that
14234     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
14235     //
14236     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
14237     // indexed load/store and the expression that needs to be re-written.
14238     //
14239     // Therefore, we have:
14240     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
14241 
14242     ConstantSDNode *CN =
14243       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
14244     int X0, X1, Y0, Y1;
14245     const APInt &Offset0 = CN->getAPIntValue();
14246     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
14247 
14248     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
14249     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
14250     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
14251     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
14252 
14253     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
14254 
14255     APInt CNV = Offset0;
14256     if (X0 < 0) CNV = -CNV;
14257     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
14258     else CNV = CNV - Offset1;
14259 
14260     SDLoc DL(OtherUses[i]);
14261 
14262     // We can now generate the new expression.
14263     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
14264     SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0);
14265 
14266     SDValue NewUse = DAG.getNode(Opcode,
14267                                  DL,
14268                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
14269     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
14270     deleteAndRecombine(OtherUses[i]);
14271   }
14272 
14273   // Replace the uses of Ptr with uses of the updated base value.
14274   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0));
14275   deleteAndRecombine(Ptr.getNode());
14276   AddToWorklist(Result.getNode());
14277 
14278   return true;
14279 }
14280 
14281 static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse,
14282                                    SDValue &BasePtr, SDValue &Offset,
14283                                    ISD::MemIndexedMode &AM,
14284                                    SelectionDAG &DAG,
14285                                    const TargetLowering &TLI) {
14286   if (PtrUse == N ||
14287       (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB))
14288     return false;
14289 
14290   if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG))
14291     return false;
14292 
14293   // Don't create a indexed load / store with zero offset.
14294   if (isNullConstant(Offset))
14295     return false;
14296 
14297   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
14298     return false;
14299 
14300   SmallPtrSet<const SDNode *, 32> Visited;
14301   for (SDNode *Use : BasePtr.getNode()->uses()) {
14302     if (Use == Ptr.getNode())
14303       continue;
14304 
14305     // No if there's a later user which could perform the index instead.
14306     if (isa<MemSDNode>(Use)) {
14307       bool IsLoad = true;
14308       bool IsMasked = false;
14309       SDValue OtherPtr;
14310       if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad,
14311                                    IsMasked, OtherPtr, TLI)) {
14312         SmallVector<const SDNode *, 2> Worklist;
14313         Worklist.push_back(Use);
14314         if (SDNode::hasPredecessorHelper(N, Visited, Worklist))
14315           return false;
14316       }
14317     }
14318 
14319     // If all the uses are load / store addresses, then don't do the
14320     // transformation.
14321     if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) {
14322       for (SDNode *UseUse : Use->uses())
14323         if (canFoldInAddressingMode(Use, UseUse, DAG, TLI))
14324           return false;
14325     }
14326   }
14327   return true;
14328 }
14329 
14330 static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad,
14331                                          bool &IsMasked, SDValue &Ptr,
14332                                          SDValue &BasePtr, SDValue &Offset,
14333                                          ISD::MemIndexedMode &AM,
14334                                          SelectionDAG &DAG,
14335                                          const TargetLowering &TLI) {
14336   if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad,
14337                                 IsMasked, Ptr, TLI) ||
14338       Ptr.getNode()->hasOneUse())
14339     return nullptr;
14340 
14341   // Try turning it into a post-indexed load / store except when
14342   // 1) All uses are load / store ops that use it as base ptr (and
14343   //    it may be folded as addressing mmode).
14344   // 2) Op must be independent of N, i.e. Op is neither a predecessor
14345   //    nor a successor of N. Otherwise, if Op is folded that would
14346   //    create a cycle.
14347   for (SDNode *Op : Ptr->uses()) {
14348     // Check for #1.
14349     if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI))
14350       continue;
14351 
14352     // Check for #2.
14353     SmallPtrSet<const SDNode *, 32> Visited;
14354     SmallVector<const SDNode *, 8> Worklist;
14355     // Ptr is predecessor to both N and Op.
14356     Visited.insert(Ptr.getNode());
14357     Worklist.push_back(N);
14358     Worklist.push_back(Op);
14359     if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) &&
14360         !SDNode::hasPredecessorHelper(Op, Visited, Worklist))
14361       return Op;
14362   }
14363   return nullptr;
14364 }
14365 
14366 /// Try to combine a load/store with a add/sub of the base pointer node into a
14367 /// post-indexed load/store. The transformation folded the add/subtract into the
14368 /// new indexed load/store effectively and all of its uses are redirected to the
14369 /// new load/store.
14370 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
14371   if (Level < AfterLegalizeDAG)
14372     return false;
14373 
14374   bool IsLoad = true;
14375   bool IsMasked = false;
14376   SDValue Ptr;
14377   SDValue BasePtr;
14378   SDValue Offset;
14379   ISD::MemIndexedMode AM = ISD::UNINDEXED;
14380   SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr,
14381                                          Offset, AM, DAG, TLI);
14382   if (!Op)
14383     return false;
14384 
14385   SDValue Result;
14386   if (!IsMasked)
14387     Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
14388                                          Offset, AM)
14389                     : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N),
14390                                           BasePtr, Offset, AM);
14391   else
14392     Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N),
14393                                                BasePtr, Offset, AM)
14394                     : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N),
14395                                                 BasePtr, Offset, AM);
14396   ++PostIndexedNodes;
14397   ++NodesCombined;
14398   LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);
14399              dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);
14400              dbgs() << '\n');
14401   WorklistRemover DeadNodes(*this);
14402   if (IsLoad) {
14403     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
14404     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
14405   } else {
14406     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
14407   }
14408 
14409   // Finally, since the node is now dead, remove it from the graph.
14410   deleteAndRecombine(N);
14411 
14412   // Replace the uses of Use with uses of the updated base value.
14413   DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
14414                                 Result.getValue(IsLoad ? 1 : 0));
14415   deleteAndRecombine(Op);
14416   return true;
14417 }
14418 
14419 /// Return the base-pointer arithmetic from an indexed \p LD.
14420 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
14421   ISD::MemIndexedMode AM = LD->getAddressingMode();
14422   assert(AM != ISD::UNINDEXED);
14423   SDValue BP = LD->getOperand(1);
14424   SDValue Inc = LD->getOperand(2);
14425 
14426   // Some backends use TargetConstants for load offsets, but don't expect
14427   // TargetConstants in general ADD nodes. We can convert these constants into
14428   // regular Constants (if the constant is not opaque).
14429   assert((Inc.getOpcode() != ISD::TargetConstant ||
14430           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
14431          "Cannot split out indexing using opaque target constants");
14432   if (Inc.getOpcode() == ISD::TargetConstant) {
14433     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
14434     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
14435                           ConstInc->getValueType(0));
14436   }
14437 
14438   unsigned Opc =
14439       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
14440   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
14441 }
14442 
14443 static inline int numVectorEltsOrZero(EVT T) {
14444   return T.isVector() ? T.getVectorNumElements() : 0;
14445 }
14446 
14447 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) {
14448   Val = ST->getValue();
14449   EVT STType = Val.getValueType();
14450   EVT STMemType = ST->getMemoryVT();
14451   if (STType == STMemType)
14452     return true;
14453   if (isTypeLegal(STMemType))
14454     return false; // fail.
14455   if (STType.isFloatingPoint() && STMemType.isFloatingPoint() &&
14456       TLI.isOperationLegal(ISD::FTRUNC, STMemType)) {
14457     Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val);
14458     return true;
14459   }
14460   if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) &&
14461       STType.isInteger() && STMemType.isInteger()) {
14462     Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val);
14463     return true;
14464   }
14465   if (STType.getSizeInBits() == STMemType.getSizeInBits()) {
14466     Val = DAG.getBitcast(STMemType, Val);
14467     return true;
14468   }
14469   return false; // fail.
14470 }
14471 
14472 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) {
14473   EVT LDMemType = LD->getMemoryVT();
14474   EVT LDType = LD->getValueType(0);
14475   assert(Val.getValueType() == LDMemType &&
14476          "Attempting to extend value of non-matching type");
14477   if (LDType == LDMemType)
14478     return true;
14479   if (LDMemType.isInteger() && LDType.isInteger()) {
14480     switch (LD->getExtensionType()) {
14481     case ISD::NON_EXTLOAD:
14482       Val = DAG.getBitcast(LDType, Val);
14483       return true;
14484     case ISD::EXTLOAD:
14485       Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val);
14486       return true;
14487     case ISD::SEXTLOAD:
14488       Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val);
14489       return true;
14490     case ISD::ZEXTLOAD:
14491       Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val);
14492       return true;
14493     }
14494   }
14495   return false;
14496 }
14497 
14498 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) {
14499   if (OptLevel == CodeGenOpt::None || !LD->isSimple())
14500     return SDValue();
14501   SDValue Chain = LD->getOperand(0);
14502   StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode());
14503   // TODO: Relax this restriction for unordered atomics (see D66309)
14504   if (!ST || !ST->isSimple())
14505     return SDValue();
14506 
14507   EVT LDType = LD->getValueType(0);
14508   EVT LDMemType = LD->getMemoryVT();
14509   EVT STMemType = ST->getMemoryVT();
14510   EVT STType = ST->getValue().getValueType();
14511 
14512   BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG);
14513   BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG);
14514   int64_t Offset;
14515   if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset))
14516     return SDValue();
14517 
14518   // Normalize for Endianness. After this Offset=0 will denote that the least
14519   // significant bit in the loaded value maps to the least significant bit in
14520   // the stored value). With Offset=n (for n > 0) the loaded value starts at the
14521   // n:th least significant byte of the stored value.
14522   if (DAG.getDataLayout().isBigEndian())
14523     Offset = ((int64_t)STMemType.getStoreSizeInBits() -
14524               (int64_t)LDMemType.getStoreSizeInBits()) / 8 - Offset;
14525 
14526   // Check that the stored value cover all bits that are loaded.
14527   bool STCoversLD =
14528       (Offset >= 0) &&
14529       (Offset * 8 + LDMemType.getSizeInBits() <= STMemType.getSizeInBits());
14530 
14531   auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue {
14532     if (LD->isIndexed()) {
14533       // Cannot handle opaque target constants and we must respect the user's
14534       // request not to split indexes from loads.
14535       if (!canSplitIdx(LD))
14536         return SDValue();
14537       SDValue Idx = SplitIndexingFromLoad(LD);
14538       SDValue Ops[] = {Val, Idx, Chain};
14539       return CombineTo(LD, Ops, 3);
14540     }
14541     return CombineTo(LD, Val, Chain);
14542   };
14543 
14544   if (!STCoversLD)
14545     return SDValue();
14546 
14547   // Memory as copy space (potentially masked).
14548   if (Offset == 0 && LDType == STType && STMemType == LDMemType) {
14549     // Simple case: Direct non-truncating forwarding
14550     if (LDType.getSizeInBits() == LDMemType.getSizeInBits())
14551       return ReplaceLd(LD, ST->getValue(), Chain);
14552     // Can we model the truncate and extension with an and mask?
14553     if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() &&
14554         !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) {
14555       // Mask to size of LDMemType
14556       auto Mask =
14557           DAG.getConstant(APInt::getLowBitsSet(STType.getSizeInBits(),
14558                                                STMemType.getSizeInBits()),
14559                           SDLoc(ST), STType);
14560       auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask);
14561       return ReplaceLd(LD, Val, Chain);
14562     }
14563   }
14564 
14565   // TODO: Deal with nonzero offset.
14566   if (LD->getBasePtr().isUndef() || Offset != 0)
14567     return SDValue();
14568   // Model necessary truncations / extenstions.
14569   SDValue Val;
14570   // Truncate Value To Stored Memory Size.
14571   do {
14572     if (!getTruncatedStoreValue(ST, Val))
14573       continue;
14574     if (!isTypeLegal(LDMemType))
14575       continue;
14576     if (STMemType != LDMemType) {
14577       // TODO: Support vectors? This requires extract_subvector/bitcast.
14578       if (!STMemType.isVector() && !LDMemType.isVector() &&
14579           STMemType.isInteger() && LDMemType.isInteger())
14580         Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val);
14581       else
14582         continue;
14583     }
14584     if (!extendLoadedValueToExtension(LD, Val))
14585       continue;
14586     return ReplaceLd(LD, Val, Chain);
14587   } while (false);
14588 
14589   // On failure, cleanup dead nodes we may have created.
14590   if (Val->use_empty())
14591     deleteAndRecombine(Val.getNode());
14592   return SDValue();
14593 }
14594 
14595 SDValue DAGCombiner::visitLOAD(SDNode *N) {
14596   LoadSDNode *LD  = cast<LoadSDNode>(N);
14597   SDValue Chain = LD->getChain();
14598   SDValue Ptr   = LD->getBasePtr();
14599 
14600   // If load is not volatile and there are no uses of the loaded value (and
14601   // the updated indexed value in case of indexed loads), change uses of the
14602   // chain value into uses of the chain input (i.e. delete the dead load).
14603   // TODO: Allow this for unordered atomics (see D66309)
14604   if (LD->isSimple()) {
14605     if (N->getValueType(1) == MVT::Other) {
14606       // Unindexed loads.
14607       if (!N->hasAnyUseOfValue(0)) {
14608         // It's not safe to use the two value CombineTo variant here. e.g.
14609         // v1, chain2 = load chain1, loc
14610         // v2, chain3 = load chain2, loc
14611         // v3         = add v2, c
14612         // Now we replace use of chain2 with chain1.  This makes the second load
14613         // isomorphic to the one we are deleting, and thus makes this load live.
14614         LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
14615                    dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);
14616                    dbgs() << "\n");
14617         WorklistRemover DeadNodes(*this);
14618         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
14619         AddUsersToWorklist(Chain.getNode());
14620         if (N->use_empty())
14621           deleteAndRecombine(N);
14622 
14623         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
14624       }
14625     } else {
14626       // Indexed loads.
14627       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
14628 
14629       // If this load has an opaque TargetConstant offset, then we cannot split
14630       // the indexing into an add/sub directly (that TargetConstant may not be
14631       // valid for a different type of node, and we cannot convert an opaque
14632       // target constant into a regular constant).
14633       bool CanSplitIdx = canSplitIdx(LD);
14634 
14635       if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) {
14636         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
14637         SDValue Index;
14638         if (N->hasAnyUseOfValue(1) && CanSplitIdx) {
14639           Index = SplitIndexingFromLoad(LD);
14640           // Try to fold the base pointer arithmetic into subsequent loads and
14641           // stores.
14642           AddUsersToWorklist(N);
14643         } else
14644           Index = DAG.getUNDEF(N->getValueType(1));
14645         LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
14646                    dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);
14647                    dbgs() << " and 2 other values\n");
14648         WorklistRemover DeadNodes(*this);
14649         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
14650         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
14651         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
14652         deleteAndRecombine(N);
14653         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
14654       }
14655     }
14656   }
14657 
14658   // If this load is directly stored, replace the load value with the stored
14659   // value.
14660   if (auto V = ForwardStoreValueToDirectLoad(LD))
14661     return V;
14662 
14663   // Try to infer better alignment information than the load already has.
14664   if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) {
14665     if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
14666       if (*Alignment > LD->getAlign() &&
14667           isAligned(*Alignment, LD->getSrcValueOffset())) {
14668         SDValue NewLoad = DAG.getExtLoad(
14669             LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
14670             LD->getPointerInfo(), LD->getMemoryVT(), *Alignment,
14671             LD->getMemOperand()->getFlags(), LD->getAAInfo());
14672         // NewLoad will always be N as we are only refining the alignment
14673         assert(NewLoad.getNode() == N);
14674         (void)NewLoad;
14675       }
14676     }
14677   }
14678 
14679   if (LD->isUnindexed()) {
14680     // Walk up chain skipping non-aliasing memory nodes.
14681     SDValue BetterChain = FindBetterChain(LD, Chain);
14682 
14683     // If there is a better chain.
14684     if (Chain != BetterChain) {
14685       SDValue ReplLoad;
14686 
14687       // Replace the chain to void dependency.
14688       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
14689         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
14690                                BetterChain, Ptr, LD->getMemOperand());
14691       } else {
14692         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
14693                                   LD->getValueType(0),
14694                                   BetterChain, Ptr, LD->getMemoryVT(),
14695                                   LD->getMemOperand());
14696       }
14697 
14698       // Create token factor to keep old chain connected.
14699       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
14700                                   MVT::Other, Chain, ReplLoad.getValue(1));
14701 
14702       // Replace uses with load result and token factor
14703       return CombineTo(N, ReplLoad.getValue(0), Token);
14704     }
14705   }
14706 
14707   // Try transforming N to an indexed load.
14708   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
14709     return SDValue(N, 0);
14710 
14711   // Try to slice up N to more direct loads if the slices are mapped to
14712   // different register banks or pairing can take place.
14713   if (SliceUpLoad(N))
14714     return SDValue(N, 0);
14715 
14716   return SDValue();
14717 }
14718 
14719 namespace {
14720 
14721 /// Helper structure used to slice a load in smaller loads.
14722 /// Basically a slice is obtained from the following sequence:
14723 /// Origin = load Ty1, Base
14724 /// Shift = srl Ty1 Origin, CstTy Amount
14725 /// Inst = trunc Shift to Ty2
14726 ///
14727 /// Then, it will be rewritten into:
14728 /// Slice = load SliceTy, Base + SliceOffset
14729 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
14730 ///
14731 /// SliceTy is deduced from the number of bits that are actually used to
14732 /// build Inst.
14733 struct LoadedSlice {
14734   /// Helper structure used to compute the cost of a slice.
14735   struct Cost {
14736     /// Are we optimizing for code size.
14737     bool ForCodeSize = false;
14738 
14739     /// Various cost.
14740     unsigned Loads = 0;
14741     unsigned Truncates = 0;
14742     unsigned CrossRegisterBanksCopies = 0;
14743     unsigned ZExts = 0;
14744     unsigned Shift = 0;
14745 
14746     explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {}
14747 
14748     /// Get the cost of one isolated slice.
14749     Cost(const LoadedSlice &LS, bool ForCodeSize)
14750         : ForCodeSize(ForCodeSize), Loads(1) {
14751       EVT TruncType = LS.Inst->getValueType(0);
14752       EVT LoadedType = LS.getLoadedType();
14753       if (TruncType != LoadedType &&
14754           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
14755         ZExts = 1;
14756     }
14757 
14758     /// Account for slicing gain in the current cost.
14759     /// Slicing provide a few gains like removing a shift or a
14760     /// truncate. This method allows to grow the cost of the original
14761     /// load with the gain from this slice.
14762     void addSliceGain(const LoadedSlice &LS) {
14763       // Each slice saves a truncate.
14764       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
14765       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
14766                               LS.Inst->getValueType(0)))
14767         ++Truncates;
14768       // If there is a shift amount, this slice gets rid of it.
14769       if (LS.Shift)
14770         ++Shift;
14771       // If this slice can merge a cross register bank copy, account for it.
14772       if (LS.canMergeExpensiveCrossRegisterBankCopy())
14773         ++CrossRegisterBanksCopies;
14774     }
14775 
14776     Cost &operator+=(const Cost &RHS) {
14777       Loads += RHS.Loads;
14778       Truncates += RHS.Truncates;
14779       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
14780       ZExts += RHS.ZExts;
14781       Shift += RHS.Shift;
14782       return *this;
14783     }
14784 
14785     bool operator==(const Cost &RHS) const {
14786       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
14787              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
14788              ZExts == RHS.ZExts && Shift == RHS.Shift;
14789     }
14790 
14791     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
14792 
14793     bool operator<(const Cost &RHS) const {
14794       // Assume cross register banks copies are as expensive as loads.
14795       // FIXME: Do we want some more target hooks?
14796       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
14797       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
14798       // Unless we are optimizing for code size, consider the
14799       // expensive operation first.
14800       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
14801         return ExpensiveOpsLHS < ExpensiveOpsRHS;
14802       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
14803              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
14804     }
14805 
14806     bool operator>(const Cost &RHS) const { return RHS < *this; }
14807 
14808     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
14809 
14810     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
14811   };
14812 
14813   // The last instruction that represent the slice. This should be a
14814   // truncate instruction.
14815   SDNode *Inst;
14816 
14817   // The original load instruction.
14818   LoadSDNode *Origin;
14819 
14820   // The right shift amount in bits from the original load.
14821   unsigned Shift;
14822 
14823   // The DAG from which Origin came from.
14824   // This is used to get some contextual information about legal types, etc.
14825   SelectionDAG *DAG;
14826 
14827   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
14828               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
14829       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
14830 
14831   /// Get the bits used in a chunk of bits \p BitWidth large.
14832   /// \return Result is \p BitWidth and has used bits set to 1 and
14833   ///         not used bits set to 0.
14834   APInt getUsedBits() const {
14835     // Reproduce the trunc(lshr) sequence:
14836     // - Start from the truncated value.
14837     // - Zero extend to the desired bit width.
14838     // - Shift left.
14839     assert(Origin && "No original load to compare against.");
14840     unsigned BitWidth = Origin->getValueSizeInBits(0);
14841     assert(Inst && "This slice is not bound to an instruction");
14842     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
14843            "Extracted slice is bigger than the whole type!");
14844     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
14845     UsedBits.setAllBits();
14846     UsedBits = UsedBits.zext(BitWidth);
14847     UsedBits <<= Shift;
14848     return UsedBits;
14849   }
14850 
14851   /// Get the size of the slice to be loaded in bytes.
14852   unsigned getLoadedSize() const {
14853     unsigned SliceSize = getUsedBits().countPopulation();
14854     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
14855     return SliceSize / 8;
14856   }
14857 
14858   /// Get the type that will be loaded for this slice.
14859   /// Note: This may not be the final type for the slice.
14860   EVT getLoadedType() const {
14861     assert(DAG && "Missing context");
14862     LLVMContext &Ctxt = *DAG->getContext();
14863     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
14864   }
14865 
14866   /// Get the alignment of the load used for this slice.
14867   unsigned getAlignment() const {
14868     unsigned Alignment = Origin->getAlignment();
14869     uint64_t Offset = getOffsetFromBase();
14870     if (Offset != 0)
14871       Alignment = MinAlign(Alignment, Alignment + Offset);
14872     return Alignment;
14873   }
14874 
14875   /// Check if this slice can be rewritten with legal operations.
14876   bool isLegal() const {
14877     // An invalid slice is not legal.
14878     if (!Origin || !Inst || !DAG)
14879       return false;
14880 
14881     // Offsets are for indexed load only, we do not handle that.
14882     if (!Origin->getOffset().isUndef())
14883       return false;
14884 
14885     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
14886 
14887     // Check that the type is legal.
14888     EVT SliceType = getLoadedType();
14889     if (!TLI.isTypeLegal(SliceType))
14890       return false;
14891 
14892     // Check that the load is legal for this type.
14893     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
14894       return false;
14895 
14896     // Check that the offset can be computed.
14897     // 1. Check its type.
14898     EVT PtrType = Origin->getBasePtr().getValueType();
14899     if (PtrType == MVT::Untyped || PtrType.isExtended())
14900       return false;
14901 
14902     // 2. Check that it fits in the immediate.
14903     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
14904       return false;
14905 
14906     // 3. Check that the computation is legal.
14907     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
14908       return false;
14909 
14910     // Check that the zext is legal if it needs one.
14911     EVT TruncateType = Inst->getValueType(0);
14912     if (TruncateType != SliceType &&
14913         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
14914       return false;
14915 
14916     return true;
14917   }
14918 
14919   /// Get the offset in bytes of this slice in the original chunk of
14920   /// bits.
14921   /// \pre DAG != nullptr.
14922   uint64_t getOffsetFromBase() const {
14923     assert(DAG && "Missing context.");
14924     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
14925     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
14926     uint64_t Offset = Shift / 8;
14927     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
14928     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
14929            "The size of the original loaded type is not a multiple of a"
14930            " byte.");
14931     // If Offset is bigger than TySizeInBytes, it means we are loading all
14932     // zeros. This should have been optimized before in the process.
14933     assert(TySizeInBytes > Offset &&
14934            "Invalid shift amount for given loaded size");
14935     if (IsBigEndian)
14936       Offset = TySizeInBytes - Offset - getLoadedSize();
14937     return Offset;
14938   }
14939 
14940   /// Generate the sequence of instructions to load the slice
14941   /// represented by this object and redirect the uses of this slice to
14942   /// this new sequence of instructions.
14943   /// \pre this->Inst && this->Origin are valid Instructions and this
14944   /// object passed the legal check: LoadedSlice::isLegal returned true.
14945   /// \return The last instruction of the sequence used to load the slice.
14946   SDValue loadSlice() const {
14947     assert(Inst && Origin && "Unable to replace a non-existing slice.");
14948     const SDValue &OldBaseAddr = Origin->getBasePtr();
14949     SDValue BaseAddr = OldBaseAddr;
14950     // Get the offset in that chunk of bytes w.r.t. the endianness.
14951     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
14952     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
14953     if (Offset) {
14954       // BaseAddr = BaseAddr + Offset.
14955       EVT ArithType = BaseAddr.getValueType();
14956       SDLoc DL(Origin);
14957       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
14958                               DAG->getConstant(Offset, DL, ArithType));
14959     }
14960 
14961     // Create the type of the loaded slice according to its size.
14962     EVT SliceType = getLoadedType();
14963 
14964     // Create the load for the slice.
14965     SDValue LastInst =
14966         DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
14967                      Origin->getPointerInfo().getWithOffset(Offset),
14968                      getAlignment(), Origin->getMemOperand()->getFlags());
14969     // If the final type is not the same as the loaded type, this means that
14970     // we have to pad with zero. Create a zero extend for that.
14971     EVT FinalType = Inst->getValueType(0);
14972     if (SliceType != FinalType)
14973       LastInst =
14974           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
14975     return LastInst;
14976   }
14977 
14978   /// Check if this slice can be merged with an expensive cross register
14979   /// bank copy. E.g.,
14980   /// i = load i32
14981   /// f = bitcast i32 i to float
14982   bool canMergeExpensiveCrossRegisterBankCopy() const {
14983     if (!Inst || !Inst->hasOneUse())
14984       return false;
14985     SDNode *Use = *Inst->use_begin();
14986     if (Use->getOpcode() != ISD::BITCAST)
14987       return false;
14988     assert(DAG && "Missing context");
14989     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
14990     EVT ResVT = Use->getValueType(0);
14991     const TargetRegisterClass *ResRC =
14992         TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent());
14993     const TargetRegisterClass *ArgRC =
14994         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(),
14995                            Use->getOperand(0)->isDivergent());
14996     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
14997       return false;
14998 
14999     // At this point, we know that we perform a cross-register-bank copy.
15000     // Check if it is expensive.
15001     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
15002     // Assume bitcasts are cheap, unless both register classes do not
15003     // explicitly share a common sub class.
15004     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
15005       return false;
15006 
15007     // Check if it will be merged with the load.
15008     // 1. Check the alignment constraint.
15009     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
15010         ResVT.getTypeForEVT(*DAG->getContext()));
15011 
15012     if (RequiredAlignment > getAlignment())
15013       return false;
15014 
15015     // 2. Check that the load is a legal operation for that type.
15016     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
15017       return false;
15018 
15019     // 3. Check that we do not have a zext in the way.
15020     if (Inst->getValueType(0) != getLoadedType())
15021       return false;
15022 
15023     return true;
15024   }
15025 };
15026 
15027 } // end anonymous namespace
15028 
15029 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
15030 /// \p UsedBits looks like 0..0 1..1 0..0.
15031 static bool areUsedBitsDense(const APInt &UsedBits) {
15032   // If all the bits are one, this is dense!
15033   if (UsedBits.isAllOnesValue())
15034     return true;
15035 
15036   // Get rid of the unused bits on the right.
15037   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
15038   // Get rid of the unused bits on the left.
15039   if (NarrowedUsedBits.countLeadingZeros())
15040     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
15041   // Check that the chunk of bits is completely used.
15042   return NarrowedUsedBits.isAllOnesValue();
15043 }
15044 
15045 /// Check whether or not \p First and \p Second are next to each other
15046 /// in memory. This means that there is no hole between the bits loaded
15047 /// by \p First and the bits loaded by \p Second.
15048 static bool areSlicesNextToEachOther(const LoadedSlice &First,
15049                                      const LoadedSlice &Second) {
15050   assert(First.Origin == Second.Origin && First.Origin &&
15051          "Unable to match different memory origins.");
15052   APInt UsedBits = First.getUsedBits();
15053   assert((UsedBits & Second.getUsedBits()) == 0 &&
15054          "Slices are not supposed to overlap.");
15055   UsedBits |= Second.getUsedBits();
15056   return areUsedBitsDense(UsedBits);
15057 }
15058 
15059 /// Adjust the \p GlobalLSCost according to the target
15060 /// paring capabilities and the layout of the slices.
15061 /// \pre \p GlobalLSCost should account for at least as many loads as
15062 /// there is in the slices in \p LoadedSlices.
15063 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
15064                                  LoadedSlice::Cost &GlobalLSCost) {
15065   unsigned NumberOfSlices = LoadedSlices.size();
15066   // If there is less than 2 elements, no pairing is possible.
15067   if (NumberOfSlices < 2)
15068     return;
15069 
15070   // Sort the slices so that elements that are likely to be next to each
15071   // other in memory are next to each other in the list.
15072   llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
15073     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
15074     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
15075   });
15076   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
15077   // First (resp. Second) is the first (resp. Second) potentially candidate
15078   // to be placed in a paired load.
15079   const LoadedSlice *First = nullptr;
15080   const LoadedSlice *Second = nullptr;
15081   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
15082                 // Set the beginning of the pair.
15083                                                            First = Second) {
15084     Second = &LoadedSlices[CurrSlice];
15085 
15086     // If First is NULL, it means we start a new pair.
15087     // Get to the next slice.
15088     if (!First)
15089       continue;
15090 
15091     EVT LoadedType = First->getLoadedType();
15092 
15093     // If the types of the slices are different, we cannot pair them.
15094     if (LoadedType != Second->getLoadedType())
15095       continue;
15096 
15097     // Check if the target supplies paired loads for this type.
15098     unsigned RequiredAlignment = 0;
15099     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
15100       // move to the next pair, this type is hopeless.
15101       Second = nullptr;
15102       continue;
15103     }
15104     // Check if we meet the alignment requirement.
15105     if (RequiredAlignment > First->getAlignment())
15106       continue;
15107 
15108     // Check that both loads are next to each other in memory.
15109     if (!areSlicesNextToEachOther(*First, *Second))
15110       continue;
15111 
15112     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
15113     --GlobalLSCost.Loads;
15114     // Move to the next pair.
15115     Second = nullptr;
15116   }
15117 }
15118 
15119 /// Check the profitability of all involved LoadedSlice.
15120 /// Currently, it is considered profitable if there is exactly two
15121 /// involved slices (1) which are (2) next to each other in memory, and
15122 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
15123 ///
15124 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
15125 /// the elements themselves.
15126 ///
15127 /// FIXME: When the cost model will be mature enough, we can relax
15128 /// constraints (1) and (2).
15129 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
15130                                 const APInt &UsedBits, bool ForCodeSize) {
15131   unsigned NumberOfSlices = LoadedSlices.size();
15132   if (StressLoadSlicing)
15133     return NumberOfSlices > 1;
15134 
15135   // Check (1).
15136   if (NumberOfSlices != 2)
15137     return false;
15138 
15139   // Check (2).
15140   if (!areUsedBitsDense(UsedBits))
15141     return false;
15142 
15143   // Check (3).
15144   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
15145   // The original code has one big load.
15146   OrigCost.Loads = 1;
15147   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
15148     const LoadedSlice &LS = LoadedSlices[CurrSlice];
15149     // Accumulate the cost of all the slices.
15150     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
15151     GlobalSlicingCost += SliceCost;
15152 
15153     // Account as cost in the original configuration the gain obtained
15154     // with the current slices.
15155     OrigCost.addSliceGain(LS);
15156   }
15157 
15158   // If the target supports paired load, adjust the cost accordingly.
15159   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
15160   return OrigCost > GlobalSlicingCost;
15161 }
15162 
15163 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
15164 /// operations, split it in the various pieces being extracted.
15165 ///
15166 /// This sort of thing is introduced by SROA.
15167 /// This slicing takes care not to insert overlapping loads.
15168 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
15169 bool DAGCombiner::SliceUpLoad(SDNode *N) {
15170   if (Level < AfterLegalizeDAG)
15171     return false;
15172 
15173   LoadSDNode *LD = cast<LoadSDNode>(N);
15174   if (!LD->isSimple() || !ISD::isNormalLoad(LD) ||
15175       !LD->getValueType(0).isInteger())
15176     return false;
15177 
15178   // The algorithm to split up a load of a scalable vector into individual
15179   // elements currently requires knowing the length of the loaded type,
15180   // so will need adjusting to work on scalable vectors.
15181   if (LD->getValueType(0).isScalableVector())
15182     return false;
15183 
15184   // Keep track of already used bits to detect overlapping values.
15185   // In that case, we will just abort the transformation.
15186   APInt UsedBits(LD->getValueSizeInBits(0), 0);
15187 
15188   SmallVector<LoadedSlice, 4> LoadedSlices;
15189 
15190   // Check if this load is used as several smaller chunks of bits.
15191   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
15192   // of computation for each trunc.
15193   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
15194        UI != UIEnd; ++UI) {
15195     // Skip the uses of the chain.
15196     if (UI.getUse().getResNo() != 0)
15197       continue;
15198 
15199     SDNode *User = *UI;
15200     unsigned Shift = 0;
15201 
15202     // Check if this is a trunc(lshr).
15203     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
15204         isa<ConstantSDNode>(User->getOperand(1))) {
15205       Shift = User->getConstantOperandVal(1);
15206       User = *User->use_begin();
15207     }
15208 
15209     // At this point, User is a Truncate, iff we encountered, trunc or
15210     // trunc(lshr).
15211     if (User->getOpcode() != ISD::TRUNCATE)
15212       return false;
15213 
15214     // The width of the type must be a power of 2 and greater than 8-bits.
15215     // Otherwise the load cannot be represented in LLVM IR.
15216     // Moreover, if we shifted with a non-8-bits multiple, the slice
15217     // will be across several bytes. We do not support that.
15218     unsigned Width = User->getValueSizeInBits(0);
15219     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
15220       return false;
15221 
15222     // Build the slice for this chain of computations.
15223     LoadedSlice LS(User, LD, Shift, &DAG);
15224     APInt CurrentUsedBits = LS.getUsedBits();
15225 
15226     // Check if this slice overlaps with another.
15227     if ((CurrentUsedBits & UsedBits) != 0)
15228       return false;
15229     // Update the bits used globally.
15230     UsedBits |= CurrentUsedBits;
15231 
15232     // Check if the new slice would be legal.
15233     if (!LS.isLegal())
15234       return false;
15235 
15236     // Record the slice.
15237     LoadedSlices.push_back(LS);
15238   }
15239 
15240   // Abort slicing if it does not seem to be profitable.
15241   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
15242     return false;
15243 
15244   ++SlicedLoads;
15245 
15246   // Rewrite each chain to use an independent load.
15247   // By construction, each chain can be represented by a unique load.
15248 
15249   // Prepare the argument for the new token factor for all the slices.
15250   SmallVector<SDValue, 8> ArgChains;
15251   for (SmallVectorImpl<LoadedSlice>::const_iterator
15252            LSIt = LoadedSlices.begin(),
15253            LSItEnd = LoadedSlices.end();
15254        LSIt != LSItEnd; ++LSIt) {
15255     SDValue SliceInst = LSIt->loadSlice();
15256     CombineTo(LSIt->Inst, SliceInst, true);
15257     if (SliceInst.getOpcode() != ISD::LOAD)
15258       SliceInst = SliceInst.getOperand(0);
15259     assert(SliceInst->getOpcode() == ISD::LOAD &&
15260            "It takes more than a zext to get to the loaded slice!!");
15261     ArgChains.push_back(SliceInst.getValue(1));
15262   }
15263 
15264   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
15265                               ArgChains);
15266   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
15267   AddToWorklist(Chain.getNode());
15268   return true;
15269 }
15270 
15271 /// Check to see if V is (and load (ptr), imm), where the load is having
15272 /// specific bytes cleared out.  If so, return the byte size being masked out
15273 /// and the shift amount.
15274 static std::pair<unsigned, unsigned>
15275 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
15276   std::pair<unsigned, unsigned> Result(0, 0);
15277 
15278   // Check for the structure we're looking for.
15279   if (V->getOpcode() != ISD::AND ||
15280       !isa<ConstantSDNode>(V->getOperand(1)) ||
15281       !ISD::isNormalLoad(V->getOperand(0).getNode()))
15282     return Result;
15283 
15284   // Check the chain and pointer.
15285   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
15286   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
15287 
15288   // This only handles simple types.
15289   if (V.getValueType() != MVT::i16 &&
15290       V.getValueType() != MVT::i32 &&
15291       V.getValueType() != MVT::i64)
15292     return Result;
15293 
15294   // Check the constant mask.  Invert it so that the bits being masked out are
15295   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
15296   // follow the sign bit for uniformity.
15297   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
15298   unsigned NotMaskLZ = countLeadingZeros(NotMask);
15299   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
15300   unsigned NotMaskTZ = countTrailingZeros(NotMask);
15301   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
15302   if (NotMaskLZ == 64) return Result;  // All zero mask.
15303 
15304   // See if we have a continuous run of bits.  If so, we have 0*1+0*
15305   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
15306     return Result;
15307 
15308   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
15309   if (V.getValueType() != MVT::i64 && NotMaskLZ)
15310     NotMaskLZ -= 64-V.getValueSizeInBits();
15311 
15312   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
15313   switch (MaskedBytes) {
15314   case 1:
15315   case 2:
15316   case 4: break;
15317   default: return Result; // All one mask, or 5-byte mask.
15318   }
15319 
15320   // Verify that the first bit starts at a multiple of mask so that the access
15321   // is aligned the same as the access width.
15322   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
15323 
15324   // For narrowing to be valid, it must be the case that the load the
15325   // immediately preceding memory operation before the store.
15326   if (LD == Chain.getNode())
15327     ; // ok.
15328   else if (Chain->getOpcode() == ISD::TokenFactor &&
15329            SDValue(LD, 1).hasOneUse()) {
15330     // LD has only 1 chain use so they are no indirect dependencies.
15331     if (!LD->isOperandOf(Chain.getNode()))
15332       return Result;
15333   } else
15334     return Result; // Fail.
15335 
15336   Result.first = MaskedBytes;
15337   Result.second = NotMaskTZ/8;
15338   return Result;
15339 }
15340 
15341 /// Check to see if IVal is something that provides a value as specified by
15342 /// MaskInfo. If so, replace the specified store with a narrower store of
15343 /// truncated IVal.
15344 static SDValue
15345 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
15346                                 SDValue IVal, StoreSDNode *St,
15347                                 DAGCombiner *DC) {
15348   unsigned NumBytes = MaskInfo.first;
15349   unsigned ByteShift = MaskInfo.second;
15350   SelectionDAG &DAG = DC->getDAG();
15351 
15352   // Check to see if IVal is all zeros in the part being masked in by the 'or'
15353   // that uses this.  If not, this is not a replacement.
15354   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
15355                                   ByteShift*8, (ByteShift+NumBytes)*8);
15356   if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue();
15357 
15358   // Check that it is legal on the target to do this.  It is legal if the new
15359   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
15360   // legalization (and the target doesn't explicitly think this is a bad idea).
15361   MVT VT = MVT::getIntegerVT(NumBytes * 8);
15362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15363   if (!DC->isTypeLegal(VT))
15364     return SDValue();
15365   if (St->getMemOperand() &&
15366       !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
15367                               *St->getMemOperand()))
15368     return SDValue();
15369 
15370   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
15371   // shifted by ByteShift and truncated down to NumBytes.
15372   if (ByteShift) {
15373     SDLoc DL(IVal);
15374     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
15375                        DAG.getConstant(ByteShift*8, DL,
15376                                     DC->getShiftAmountTy(IVal.getValueType())));
15377   }
15378 
15379   // Figure out the offset for the store and the alignment of the access.
15380   unsigned StOffset;
15381   unsigned NewAlign = St->getAlignment();
15382 
15383   if (DAG.getDataLayout().isLittleEndian())
15384     StOffset = ByteShift;
15385   else
15386     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
15387 
15388   SDValue Ptr = St->getBasePtr();
15389   if (StOffset) {
15390     SDLoc DL(IVal);
15391     Ptr = DAG.getMemBasePlusOffset(Ptr, StOffset, DL);
15392     NewAlign = MinAlign(NewAlign, StOffset);
15393   }
15394 
15395   // Truncate down to the new size.
15396   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
15397 
15398   ++OpsNarrowed;
15399   return DAG
15400       .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
15401                 St->getPointerInfo().getWithOffset(StOffset), NewAlign);
15402 }
15403 
15404 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
15405 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
15406 /// narrowing the load and store if it would end up being a win for performance
15407 /// or code size.
15408 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
15409   StoreSDNode *ST  = cast<StoreSDNode>(N);
15410   if (!ST->isSimple())
15411     return SDValue();
15412 
15413   SDValue Chain = ST->getChain();
15414   SDValue Value = ST->getValue();
15415   SDValue Ptr   = ST->getBasePtr();
15416   EVT VT = Value.getValueType();
15417 
15418   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
15419     return SDValue();
15420 
15421   unsigned Opc = Value.getOpcode();
15422 
15423   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
15424   // is a byte mask indicating a consecutive number of bytes, check to see if
15425   // Y is known to provide just those bytes.  If so, we try to replace the
15426   // load + replace + store sequence with a single (narrower) store, which makes
15427   // the load dead.
15428   if (Opc == ISD::OR) {
15429     std::pair<unsigned, unsigned> MaskedLoad;
15430     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
15431     if (MaskedLoad.first)
15432       if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
15433                                                   Value.getOperand(1), ST,this))
15434         return NewST;
15435 
15436     // Or is commutative, so try swapping X and Y.
15437     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
15438     if (MaskedLoad.first)
15439       if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
15440                                                   Value.getOperand(0), ST,this))
15441         return NewST;
15442   }
15443 
15444   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
15445       Value.getOperand(1).getOpcode() != ISD::Constant)
15446     return SDValue();
15447 
15448   SDValue N0 = Value.getOperand(0);
15449   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
15450       Chain == SDValue(N0.getNode(), 1)) {
15451     LoadSDNode *LD = cast<LoadSDNode>(N0);
15452     if (LD->getBasePtr() != Ptr ||
15453         LD->getPointerInfo().getAddrSpace() !=
15454         ST->getPointerInfo().getAddrSpace())
15455       return SDValue();
15456 
15457     // Find the type to narrow it the load / op / store to.
15458     SDValue N1 = Value.getOperand(1);
15459     unsigned BitWidth = N1.getValueSizeInBits();
15460     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
15461     if (Opc == ISD::AND)
15462       Imm ^= APInt::getAllOnesValue(BitWidth);
15463     if (Imm == 0 || Imm.isAllOnesValue())
15464       return SDValue();
15465     unsigned ShAmt = Imm.countTrailingZeros();
15466     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
15467     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
15468     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
15469     // The narrowing should be profitable, the load/store operation should be
15470     // legal (or custom) and the store size should be equal to the NewVT width.
15471     while (NewBW < BitWidth &&
15472            (NewVT.getStoreSizeInBits() != NewBW ||
15473             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
15474             !TLI.isNarrowingProfitable(VT, NewVT))) {
15475       NewBW = NextPowerOf2(NewBW);
15476       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
15477     }
15478     if (NewBW >= BitWidth)
15479       return SDValue();
15480 
15481     // If the lsb changed does not start at the type bitwidth boundary,
15482     // start at the previous one.
15483     if (ShAmt % NewBW)
15484       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
15485     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
15486                                    std::min(BitWidth, ShAmt + NewBW));
15487     if ((Imm & Mask) == Imm) {
15488       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
15489       if (Opc == ISD::AND)
15490         NewImm ^= APInt::getAllOnesValue(NewBW);
15491       uint64_t PtrOff = ShAmt / 8;
15492       // For big endian targets, we need to adjust the offset to the pointer to
15493       // load the correct bytes.
15494       if (DAG.getDataLayout().isBigEndian())
15495         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
15496 
15497       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
15498       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
15499       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
15500         return SDValue();
15501 
15502       SDValue NewPtr = DAG.getMemBasePlusOffset(Ptr, PtrOff, SDLoc(LD));
15503       SDValue NewLD =
15504           DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
15505                       LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
15506                       LD->getMemOperand()->getFlags(), LD->getAAInfo());
15507       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
15508                                    DAG.getConstant(NewImm, SDLoc(Value),
15509                                                    NewVT));
15510       SDValue NewST =
15511           DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
15512                        ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
15513 
15514       AddToWorklist(NewPtr.getNode());
15515       AddToWorklist(NewLD.getNode());
15516       AddToWorklist(NewVal.getNode());
15517       WorklistRemover DeadNodes(*this);
15518       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
15519       ++OpsNarrowed;
15520       return NewST;
15521     }
15522   }
15523 
15524   return SDValue();
15525 }
15526 
15527 /// For a given floating point load / store pair, if the load value isn't used
15528 /// by any other operations, then consider transforming the pair to integer
15529 /// load / store operations if the target deems the transformation profitable.
15530 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
15531   StoreSDNode *ST  = cast<StoreSDNode>(N);
15532   SDValue Value = ST->getValue();
15533   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
15534       Value.hasOneUse()) {
15535     LoadSDNode *LD = cast<LoadSDNode>(Value);
15536     EVT VT = LD->getMemoryVT();
15537     if (!VT.isFloatingPoint() ||
15538         VT != ST->getMemoryVT() ||
15539         LD->isNonTemporal() ||
15540         ST->isNonTemporal() ||
15541         LD->getPointerInfo().getAddrSpace() != 0 ||
15542         ST->getPointerInfo().getAddrSpace() != 0)
15543       return SDValue();
15544 
15545     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
15546     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
15547         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
15548         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
15549         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
15550       return SDValue();
15551 
15552     unsigned LDAlign = LD->getAlignment();
15553     unsigned STAlign = ST->getAlignment();
15554     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
15555     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
15556     if (LDAlign < ABIAlign || STAlign < ABIAlign)
15557       return SDValue();
15558 
15559     SDValue NewLD =
15560         DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
15561                     LD->getPointerInfo(), LDAlign);
15562 
15563     SDValue NewST =
15564         DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(),
15565                      ST->getPointerInfo(), STAlign);
15566 
15567     AddToWorklist(NewLD.getNode());
15568     AddToWorklist(NewST.getNode());
15569     WorklistRemover DeadNodes(*this);
15570     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
15571     ++LdStFP2Int;
15572     return NewST;
15573   }
15574 
15575   return SDValue();
15576 }
15577 
15578 // This is a helper function for visitMUL to check the profitability
15579 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
15580 // MulNode is the original multiply, AddNode is (add x, c1),
15581 // and ConstNode is c2.
15582 //
15583 // If the (add x, c1) has multiple uses, we could increase
15584 // the number of adds if we make this transformation.
15585 // It would only be worth doing this if we can remove a
15586 // multiply in the process. Check for that here.
15587 // To illustrate:
15588 //     (A + c1) * c3
15589 //     (A + c2) * c3
15590 // We're checking for cases where we have common "c3 * A" expressions.
15591 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
15592                                               SDValue &AddNode,
15593                                               SDValue &ConstNode) {
15594   APInt Val;
15595 
15596   // If the add only has one use, this would be OK to do.
15597   if (AddNode.getNode()->hasOneUse())
15598     return true;
15599 
15600   // Walk all the users of the constant with which we're multiplying.
15601   for (SDNode *Use : ConstNode->uses()) {
15602     if (Use == MulNode) // This use is the one we're on right now. Skip it.
15603       continue;
15604 
15605     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
15606       SDNode *OtherOp;
15607       SDNode *MulVar = AddNode.getOperand(0).getNode();
15608 
15609       // OtherOp is what we're multiplying against the constant.
15610       if (Use->getOperand(0) == ConstNode)
15611         OtherOp = Use->getOperand(1).getNode();
15612       else
15613         OtherOp = Use->getOperand(0).getNode();
15614 
15615       // Check to see if multiply is with the same operand of our "add".
15616       //
15617       //     ConstNode  = CONST
15618       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
15619       //     ...
15620       //     AddNode  = (A + c1)  <-- MulVar is A.
15621       //         = AddNode * ConstNode   <-- current visiting instruction.
15622       //
15623       // If we make this transformation, we will have a common
15624       // multiply (ConstNode * A) that we can save.
15625       if (OtherOp == MulVar)
15626         return true;
15627 
15628       // Now check to see if a future expansion will give us a common
15629       // multiply.
15630       //
15631       //     ConstNode  = CONST
15632       //     AddNode    = (A + c1)
15633       //     ...   = AddNode * ConstNode <-- current visiting instruction.
15634       //     ...
15635       //     OtherOp = (A + c2)
15636       //     Use     = OtherOp * ConstNode <-- visiting Use.
15637       //
15638       // If we make this transformation, we will have a common
15639       // multiply (CONST * A) after we also do the same transformation
15640       // to the "t2" instruction.
15641       if (OtherOp->getOpcode() == ISD::ADD &&
15642           DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
15643           OtherOp->getOperand(0).getNode() == MulVar)
15644         return true;
15645     }
15646   }
15647 
15648   // Didn't find a case where this would be profitable.
15649   return false;
15650 }
15651 
15652 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
15653                                          unsigned NumStores) {
15654   SmallVector<SDValue, 8> Chains;
15655   SmallPtrSet<const SDNode *, 8> Visited;
15656   SDLoc StoreDL(StoreNodes[0].MemNode);
15657 
15658   for (unsigned i = 0; i < NumStores; ++i) {
15659     Visited.insert(StoreNodes[i].MemNode);
15660   }
15661 
15662   // don't include nodes that are children or repeated nodes.
15663   for (unsigned i = 0; i < NumStores; ++i) {
15664     if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second)
15665       Chains.push_back(StoreNodes[i].MemNode->getChain());
15666   }
15667 
15668   assert(Chains.size() > 0 && "Chain should have generated a chain");
15669   return DAG.getTokenFactor(StoreDL, Chains);
15670 }
15671 
15672 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
15673     SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
15674     bool IsConstantSrc, bool UseVector, bool UseTrunc) {
15675   // Make sure we have something to merge.
15676   if (NumStores < 2)
15677     return false;
15678 
15679   // The latest Node in the DAG.
15680   SDLoc DL(StoreNodes[0].MemNode);
15681 
15682   TypeSize ElementSizeBits = MemVT.getStoreSizeInBits();
15683   unsigned SizeInBits = NumStores * ElementSizeBits;
15684   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
15685 
15686   EVT StoreTy;
15687   if (UseVector) {
15688     unsigned Elts = NumStores * NumMemElts;
15689     // Get the type for the merged vector store.
15690     StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
15691   } else
15692     StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
15693 
15694   SDValue StoredVal;
15695   if (UseVector) {
15696     if (IsConstantSrc) {
15697       SmallVector<SDValue, 8> BuildVector;
15698       for (unsigned I = 0; I != NumStores; ++I) {
15699         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
15700         SDValue Val = St->getValue();
15701         // If constant is of the wrong type, convert it now.
15702         if (MemVT != Val.getValueType()) {
15703           Val = peekThroughBitcasts(Val);
15704           // Deal with constants of wrong size.
15705           if (ElementSizeBits != Val.getValueSizeInBits()) {
15706             EVT IntMemVT =
15707                 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
15708             if (isa<ConstantFPSDNode>(Val)) {
15709               // Not clear how to truncate FP values.
15710               return false;
15711             } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
15712               Val = DAG.getConstant(C->getAPIntValue()
15713                                         .zextOrTrunc(Val.getValueSizeInBits())
15714                                         .zextOrTrunc(ElementSizeBits),
15715                                     SDLoc(C), IntMemVT);
15716           }
15717           // Make sure correctly size type is the correct type.
15718           Val = DAG.getBitcast(MemVT, Val);
15719         }
15720         BuildVector.push_back(Val);
15721       }
15722       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
15723                                                : ISD::BUILD_VECTOR,
15724                               DL, StoreTy, BuildVector);
15725     } else {
15726       SmallVector<SDValue, 8> Ops;
15727       for (unsigned i = 0; i < NumStores; ++i) {
15728         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
15729         SDValue Val = peekThroughBitcasts(St->getValue());
15730         // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
15731         // type MemVT. If the underlying value is not the correct
15732         // type, but it is an extraction of an appropriate vector we
15733         // can recast Val to be of the correct type. This may require
15734         // converting between EXTRACT_VECTOR_ELT and
15735         // EXTRACT_SUBVECTOR.
15736         if ((MemVT != Val.getValueType()) &&
15737             (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
15738              Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
15739           EVT MemVTScalarTy = MemVT.getScalarType();
15740           // We may need to add a bitcast here to get types to line up.
15741           if (MemVTScalarTy != Val.getValueType().getScalarType()) {
15742             Val = DAG.getBitcast(MemVT, Val);
15743           } else {
15744             unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR
15745                                             : ISD::EXTRACT_VECTOR_ELT;
15746             SDValue Vec = Val.getOperand(0);
15747             SDValue Idx = Val.getOperand(1);
15748             Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx);
15749           }
15750         }
15751         Ops.push_back(Val);
15752       }
15753 
15754       // Build the extracted vector elements back into a vector.
15755       StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
15756                                                : ISD::BUILD_VECTOR,
15757                               DL, StoreTy, Ops);
15758     }
15759   } else {
15760     // We should always use a vector store when merging extracted vector
15761     // elements, so this path implies a store of constants.
15762     assert(IsConstantSrc && "Merged vector elements should use vector store");
15763 
15764     APInt StoreInt(SizeInBits, 0);
15765 
15766     // Construct a single integer constant which is made of the smaller
15767     // constant inputs.
15768     bool IsLE = DAG.getDataLayout().isLittleEndian();
15769     for (unsigned i = 0; i < NumStores; ++i) {
15770       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
15771       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
15772 
15773       SDValue Val = St->getValue();
15774       Val = peekThroughBitcasts(Val);
15775       StoreInt <<= ElementSizeBits;
15776       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
15777         StoreInt |= C->getAPIntValue()
15778                         .zextOrTrunc(ElementSizeBits)
15779                         .zextOrTrunc(SizeInBits);
15780       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
15781         StoreInt |= C->getValueAPF()
15782                         .bitcastToAPInt()
15783                         .zextOrTrunc(ElementSizeBits)
15784                         .zextOrTrunc(SizeInBits);
15785         // If fp truncation is necessary give up for now.
15786         if (MemVT.getSizeInBits() != ElementSizeBits)
15787           return false;
15788       } else {
15789         llvm_unreachable("Invalid constant element type");
15790       }
15791     }
15792 
15793     // Create the new Load and Store operations.
15794     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
15795   }
15796 
15797   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
15798   SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
15799 
15800   // make sure we use trunc store if it's necessary to be legal.
15801   SDValue NewStore;
15802   if (!UseTrunc) {
15803     NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
15804                             FirstInChain->getPointerInfo(),
15805                             FirstInChain->getAlignment());
15806   } else { // Must be realized as a trunc store
15807     EVT LegalizedStoredValTy =
15808         TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
15809     unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits();
15810     ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
15811     SDValue ExtendedStoreVal =
15812         DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
15813                         LegalizedStoredValTy);
15814     NewStore = DAG.getTruncStore(
15815         NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
15816         FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
15817         FirstInChain->getAlignment(),
15818         FirstInChain->getMemOperand()->getFlags());
15819   }
15820 
15821   // Replace all merged stores with the new store.
15822   for (unsigned i = 0; i < NumStores; ++i)
15823     CombineTo(StoreNodes[i].MemNode, NewStore);
15824 
15825   AddToWorklist(NewChain.getNode());
15826   return true;
15827 }
15828 
15829 void DAGCombiner::getStoreMergeCandidates(
15830     StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
15831     SDNode *&RootNode) {
15832   // This holds the base pointer, index, and the offset in bytes from the base
15833   // pointer.
15834   BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
15835   EVT MemVT = St->getMemoryVT();
15836 
15837   SDValue Val = peekThroughBitcasts(St->getValue());
15838   // We must have a base and an offset.
15839   if (!BasePtr.getBase().getNode())
15840     return;
15841 
15842   // Do not handle stores to undef base pointers.
15843   if (BasePtr.getBase().isUndef())
15844     return;
15845 
15846   bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val);
15847   bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
15848                           Val.getOpcode() == ISD::EXTRACT_SUBVECTOR);
15849   bool IsLoadSrc = isa<LoadSDNode>(Val);
15850   BaseIndexOffset LBasePtr;
15851   // Match on loadbaseptr if relevant.
15852   EVT LoadVT;
15853   if (IsLoadSrc) {
15854     auto *Ld = cast<LoadSDNode>(Val);
15855     LBasePtr = BaseIndexOffset::match(Ld, DAG);
15856     LoadVT = Ld->getMemoryVT();
15857     // Load and store should be the same type.
15858     if (MemVT != LoadVT)
15859       return;
15860     // Loads must only have one use.
15861     if (!Ld->hasNUsesOfValue(1, 0))
15862       return;
15863     // The memory operands must not be volatile/indexed/atomic.
15864     // TODO: May be able to relax for unordered atomics (see D66309)
15865     if (!Ld->isSimple() || Ld->isIndexed())
15866       return;
15867   }
15868   auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
15869                             int64_t &Offset) -> bool {
15870     // The memory operands must not be volatile/indexed/atomic.
15871     // TODO: May be able to relax for unordered atomics (see D66309)
15872     if (!Other->isSimple() ||  Other->isIndexed())
15873       return false;
15874     // Don't mix temporal stores with non-temporal stores.
15875     if (St->isNonTemporal() != Other->isNonTemporal())
15876       return false;
15877     SDValue OtherBC = peekThroughBitcasts(Other->getValue());
15878     // Allow merging constants of different types as integers.
15879     bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
15880                                            : Other->getMemoryVT() != MemVT;
15881     if (IsLoadSrc) {
15882       if (NoTypeMatch)
15883         return false;
15884       // The Load's Base Ptr must also match
15885       if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(OtherBC)) {
15886         BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG);
15887         if (LoadVT != OtherLd->getMemoryVT())
15888           return false;
15889         // Loads must only have one use.
15890         if (!OtherLd->hasNUsesOfValue(1, 0))
15891           return false;
15892         // The memory operands must not be volatile/indexed/atomic.
15893         // TODO: May be able to relax for unordered atomics (see D66309)
15894         if (!OtherLd->isSimple() ||
15895             OtherLd->isIndexed())
15896           return false;
15897         // Don't mix temporal loads with non-temporal loads.
15898         if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal())
15899           return false;
15900         if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
15901           return false;
15902       } else
15903         return false;
15904     }
15905     if (IsConstantSrc) {
15906       if (NoTypeMatch)
15907         return false;
15908       if (!(isa<ConstantSDNode>(OtherBC) || isa<ConstantFPSDNode>(OtherBC)))
15909         return false;
15910     }
15911     if (IsExtractVecSrc) {
15912       // Do not merge truncated stores here.
15913       if (Other->isTruncatingStore())
15914         return false;
15915       if (!MemVT.bitsEq(OtherBC.getValueType()))
15916         return false;
15917       if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
15918           OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR)
15919         return false;
15920     }
15921     Ptr = BaseIndexOffset::match(Other, DAG);
15922     return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
15923   };
15924 
15925   // Check if the pair of StoreNode and the RootNode already bail out many
15926   // times which is over the limit in dependence check.
15927   auto OverLimitInDependenceCheck = [&](SDNode *StoreNode,
15928                                         SDNode *RootNode) -> bool {
15929     auto RootCount = StoreRootCountMap.find(StoreNode);
15930     if (RootCount != StoreRootCountMap.end() &&
15931         RootCount->second.first == RootNode &&
15932         RootCount->second.second > StoreMergeDependenceLimit)
15933       return true;
15934     return false;
15935   };
15936 
15937   // We looking for a root node which is an ancestor to all mergable
15938   // stores. We search up through a load, to our root and then down
15939   // through all children. For instance we will find Store{1,2,3} if
15940   // St is Store1, Store2. or Store3 where the root is not a load
15941   // which always true for nonvolatile ops. TODO: Expand
15942   // the search to find all valid candidates through multiple layers of loads.
15943   //
15944   // Root
15945   // |-------|-------|
15946   // Load    Load    Store3
15947   // |       |
15948   // Store1   Store2
15949   //
15950   // FIXME: We should be able to climb and
15951   // descend TokenFactors to find candidates as well.
15952 
15953   RootNode = St->getChain().getNode();
15954 
15955   unsigned NumNodesExplored = 0;
15956   if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
15957     RootNode = Ldn->getChain().getNode();
15958     for (auto I = RootNode->use_begin(), E = RootNode->use_end();
15959          I != E && NumNodesExplored < 1024; ++I, ++NumNodesExplored)
15960       if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
15961         for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
15962           if (I2.getOperandNo() == 0)
15963             if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
15964               BaseIndexOffset Ptr;
15965               int64_t PtrDiff;
15966               if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15967                   !OverLimitInDependenceCheck(OtherST, RootNode))
15968                 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
15969             }
15970   } else
15971     for (auto I = RootNode->use_begin(), E = RootNode->use_end();
15972          I != E && NumNodesExplored < 1024; ++I, ++NumNodesExplored)
15973       if (I.getOperandNo() == 0)
15974         if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
15975           BaseIndexOffset Ptr;
15976           int64_t PtrDiff;
15977           if (CandidateMatch(OtherST, Ptr, PtrDiff) &&
15978               !OverLimitInDependenceCheck(OtherST, RootNode))
15979             StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
15980         }
15981 }
15982 
15983 // We need to check that merging these stores does not cause a loop in
15984 // the DAG. Any store candidate may depend on another candidate
15985 // indirectly through its operand (we already consider dependencies
15986 // through the chain). Check in parallel by searching up from
15987 // non-chain operands of candidates.
15988 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
15989     SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
15990     SDNode *RootNode) {
15991   // FIXME: We should be able to truncate a full search of
15992   // predecessors by doing a BFS and keeping tabs the originating
15993   // stores from which worklist nodes come from in a similar way to
15994   // TokenFactor simplfication.
15995 
15996   SmallPtrSet<const SDNode *, 32> Visited;
15997   SmallVector<const SDNode *, 8> Worklist;
15998 
15999   // RootNode is a predecessor to all candidates so we need not search
16000   // past it. Add RootNode (peeking through TokenFactors). Do not count
16001   // these towards size check.
16002 
16003   Worklist.push_back(RootNode);
16004   while (!Worklist.empty()) {
16005     auto N = Worklist.pop_back_val();
16006     if (!Visited.insert(N).second)
16007       continue; // Already present in Visited.
16008     if (N->getOpcode() == ISD::TokenFactor) {
16009       for (SDValue Op : N->ops())
16010         Worklist.push_back(Op.getNode());
16011     }
16012   }
16013 
16014   // Don't count pruning nodes towards max.
16015   unsigned int Max = 1024 + Visited.size();
16016   // Search Ops of store candidates.
16017   for (unsigned i = 0; i < NumStores; ++i) {
16018     SDNode *N = StoreNodes[i].MemNode;
16019     // Of the 4 Store Operands:
16020     //   * Chain (Op 0) -> We have already considered these
16021     //                    in candidate selection and can be
16022     //                    safely ignored
16023     //   * Value (Op 1) -> Cycles may happen (e.g. through load chains)
16024     //   * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
16025     //                       but aren't necessarily fromt the same base node, so
16026     //                       cycles possible (e.g. via indexed store).
16027     //   * (Op 3) -> Represents the pre or post-indexing offset (or undef for
16028     //               non-indexed stores). Not constant on all targets (e.g. ARM)
16029     //               and so can participate in a cycle.
16030     for (unsigned j = 1; j < N->getNumOperands(); ++j)
16031       Worklist.push_back(N->getOperand(j).getNode());
16032   }
16033   // Search through DAG. We can stop early if we find a store node.
16034   for (unsigned i = 0; i < NumStores; ++i)
16035     if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
16036                                      Max)) {
16037       // If the searching bail out, record the StoreNode and RootNode in the
16038       // StoreRootCountMap. If we have seen the pair many times over a limit,
16039       // we won't add the StoreNode into StoreNodes set again.
16040       if (Visited.size() >= Max) {
16041         auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode];
16042         if (RootCount.first == RootNode)
16043           RootCount.second++;
16044         else
16045           RootCount = {RootNode, 1};
16046       }
16047       return false;
16048     }
16049   return true;
16050 }
16051 
16052 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
16053   if (OptLevel == CodeGenOpt::None || !EnableStoreMerging)
16054     return false;
16055 
16056   // TODO: Extend this function to merge stores of scalable vectors.
16057   // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8>
16058   // store since we know <vscale x 16 x i8> is exactly twice as large as
16059   // <vscale x 8 x i8>). Until then, bail out for scalable vectors.
16060   EVT MemVT = St->getMemoryVT();
16061   if (MemVT.isScalableVector())
16062     return false;
16063 
16064   int64_t ElementSizeBytes = MemVT.getStoreSize();
16065   unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
16066 
16067   if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
16068     return false;
16069 
16070   bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute(
16071       Attribute::NoImplicitFloat);
16072 
16073   // This function cannot currently deal with non-byte-sized memory sizes.
16074   if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits())
16075     return false;
16076 
16077   if (!MemVT.isSimple())
16078     return false;
16079 
16080   // Perform an early exit check. Do not bother looking at stored values that
16081   // are not constants, loads, or extracted vector elements.
16082   SDValue StoredVal = peekThroughBitcasts(St->getValue());
16083   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
16084   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
16085                        isa<ConstantFPSDNode>(StoredVal);
16086   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
16087                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
16088   bool IsNonTemporalStore = St->isNonTemporal();
16089   bool IsNonTemporalLoad =
16090       IsLoadSrc && cast<LoadSDNode>(StoredVal)->isNonTemporal();
16091 
16092   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
16093     return false;
16094 
16095   SmallVector<MemOpLink, 8> StoreNodes;
16096   SDNode *RootNode;
16097   // Find potential store merge candidates by searching through chain sub-DAG
16098   getStoreMergeCandidates(St, StoreNodes, RootNode);
16099 
16100   // Check if there is anything to merge.
16101   if (StoreNodes.size() < 2)
16102     return false;
16103 
16104   // Sort the memory operands according to their distance from the
16105   // base pointer.
16106   llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) {
16107     return LHS.OffsetFromBase < RHS.OffsetFromBase;
16108   });
16109 
16110   // Store Merge attempts to merge the lowest stores. This generally
16111   // works out as if successful, as the remaining stores are checked
16112   // after the first collection of stores is merged. However, in the
16113   // case that a non-mergeable store is found first, e.g., {p[-2],
16114   // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
16115   // mergeable cases. To prevent this, we prune such stores from the
16116   // front of StoreNodes here.
16117 
16118   bool RV = false;
16119   while (StoreNodes.size() > 1) {
16120     size_t StartIdx = 0;
16121     while ((StartIdx + 1 < StoreNodes.size()) &&
16122            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
16123                StoreNodes[StartIdx + 1].OffsetFromBase)
16124       ++StartIdx;
16125 
16126     // Bail if we don't have enough candidates to merge.
16127     if (StartIdx + 1 >= StoreNodes.size())
16128       return RV;
16129 
16130     if (StartIdx)
16131       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
16132 
16133     // Scan the memory operations on the chain and find the first
16134     // non-consecutive store memory address.
16135     unsigned NumConsecutiveStores = 1;
16136     int64_t StartAddress = StoreNodes[0].OffsetFromBase;
16137     // Check that the addresses are consecutive starting from the second
16138     // element in the list of stores.
16139     for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
16140       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
16141       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
16142         break;
16143       NumConsecutiveStores = i + 1;
16144     }
16145 
16146     if (NumConsecutiveStores < 2) {
16147       StoreNodes.erase(StoreNodes.begin(),
16148                        StoreNodes.begin() + NumConsecutiveStores);
16149       continue;
16150     }
16151 
16152     // The node with the lowest store address.
16153     LLVMContext &Context = *DAG.getContext();
16154     const DataLayout &DL = DAG.getDataLayout();
16155 
16156     // Store the constants into memory as one consecutive store.
16157     if (IsConstantSrc) {
16158       while (NumConsecutiveStores >= 2) {
16159         LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
16160         unsigned FirstStoreAS = FirstInChain->getAddressSpace();
16161         unsigned FirstStoreAlign = FirstInChain->getAlignment();
16162         unsigned LastLegalType = 1;
16163         unsigned LastLegalVectorType = 1;
16164         bool LastIntegerTrunc = false;
16165         bool NonZero = false;
16166         unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
16167         for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
16168           StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
16169           SDValue StoredVal = ST->getValue();
16170           bool IsElementZero = false;
16171           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
16172             IsElementZero = C->isNullValue();
16173           else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
16174             IsElementZero = C->getConstantFPValue()->isNullValue();
16175           if (IsElementZero) {
16176             if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
16177               FirstZeroAfterNonZero = i;
16178           }
16179           NonZero |= !IsElementZero;
16180 
16181           // Find a legal type for the constant store.
16182           unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
16183           EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
16184           bool IsFast = false;
16185 
16186           // Break early when size is too large to be legal.
16187           if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
16188             break;
16189 
16190           if (TLI.isTypeLegal(StoreTy) &&
16191               TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
16192               TLI.allowsMemoryAccess(Context, DL, StoreTy,
16193                                      *FirstInChain->getMemOperand(), &IsFast) &&
16194               IsFast) {
16195             LastIntegerTrunc = false;
16196             LastLegalType = i + 1;
16197             // Or check whether a truncstore is legal.
16198           } else if (TLI.getTypeAction(Context, StoreTy) ==
16199                      TargetLowering::TypePromoteInteger) {
16200             EVT LegalizedStoredValTy =
16201                 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
16202             if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
16203                 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
16204                 TLI.allowsMemoryAccess(Context, DL, StoreTy,
16205                                        *FirstInChain->getMemOperand(),
16206                                        &IsFast) &&
16207                 IsFast) {
16208               LastIntegerTrunc = true;
16209               LastLegalType = i + 1;
16210             }
16211           }
16212 
16213           // We only use vectors if the constant is known to be zero or the
16214           // target allows it and the function is not marked with the
16215           // noimplicitfloat attribute.
16216           if ((!NonZero ||
16217                TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
16218               !NoVectors) {
16219             // Find a legal type for the vector store.
16220             unsigned Elts = (i + 1) * NumMemElts;
16221             EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
16222             if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
16223                 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
16224                 TLI.allowsMemoryAccess(
16225                     Context, DL, Ty, *FirstInChain->getMemOperand(), &IsFast) &&
16226                 IsFast)
16227               LastLegalVectorType = i + 1;
16228           }
16229         }
16230 
16231         bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
16232         unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
16233 
16234         // Check if we found a legal integer type that creates a meaningful
16235         // merge.
16236         if (NumElem < 2) {
16237           // We know that candidate stores are in order and of correct
16238           // shape. While there is no mergeable sequence from the
16239           // beginning one may start later in the sequence. The only
16240           // reason a merge of size N could have failed where another of
16241           // the same size would not have, is if the alignment has
16242           // improved or we've dropped a non-zero value. Drop as many
16243           // candidates as we can here.
16244           unsigned NumSkip = 1;
16245           while (
16246               (NumSkip < NumConsecutiveStores) &&
16247               (NumSkip < FirstZeroAfterNonZero) &&
16248               (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
16249             NumSkip++;
16250 
16251           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
16252           NumConsecutiveStores -= NumSkip;
16253           continue;
16254         }
16255 
16256         // Check that we can merge these candidates without causing a cycle.
16257         if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
16258                                                       RootNode)) {
16259           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
16260           NumConsecutiveStores -= NumElem;
16261           continue;
16262         }
16263 
16264         RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true,
16265                                               UseVector, LastIntegerTrunc);
16266 
16267         // Remove merged stores for next iteration.
16268         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
16269         NumConsecutiveStores -= NumElem;
16270       }
16271       continue;
16272     }
16273 
16274     // When extracting multiple vector elements, try to store them
16275     // in one vector store rather than a sequence of scalar stores.
16276     if (IsExtractVecSrc) {
16277       // Loop on Consecutive Stores on success.
16278       while (NumConsecutiveStores >= 2) {
16279         LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
16280         unsigned FirstStoreAS = FirstInChain->getAddressSpace();
16281         unsigned FirstStoreAlign = FirstInChain->getAlignment();
16282         unsigned NumStoresToMerge = 1;
16283         for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
16284           // Find a legal type for the vector store.
16285           unsigned Elts = (i + 1) * NumMemElts;
16286           EVT Ty =
16287               EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
16288           bool IsFast = false;
16289 
16290           // Break early when size is too large to be legal.
16291           if (Ty.getSizeInBits() > MaximumLegalStoreInBits)
16292             break;
16293 
16294           if (TLI.isTypeLegal(Ty) &&
16295               TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
16296               TLI.allowsMemoryAccess(Context, DL, Ty,
16297                                      *FirstInChain->getMemOperand(), &IsFast) &&
16298               IsFast)
16299             NumStoresToMerge = i + 1;
16300         }
16301 
16302         // Check if we found a legal integer type creating a meaningful
16303         // merge.
16304         if (NumStoresToMerge < 2) {
16305           // We know that candidate stores are in order and of correct
16306           // shape. While there is no mergeable sequence from the
16307           // beginning one may start later in the sequence. The only
16308           // reason a merge of size N could have failed where another of
16309           // the same size would not have, is if the alignment has
16310           // improved. Drop as many candidates as we can here.
16311           unsigned NumSkip = 1;
16312           while (
16313               (NumSkip < NumConsecutiveStores) &&
16314               (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
16315             NumSkip++;
16316 
16317           StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
16318           NumConsecutiveStores -= NumSkip;
16319           continue;
16320         }
16321 
16322         // Check that we can merge these candidates without causing a cycle.
16323         if (!checkMergeStoreCandidatesForDependencies(
16324                 StoreNodes, NumStoresToMerge, RootNode)) {
16325           StoreNodes.erase(StoreNodes.begin(),
16326                            StoreNodes.begin() + NumStoresToMerge);
16327           NumConsecutiveStores -= NumStoresToMerge;
16328           continue;
16329         }
16330 
16331         RV |= MergeStoresOfConstantsOrVecElts(
16332             StoreNodes, MemVT, NumStoresToMerge, false, true, false);
16333 
16334         StoreNodes.erase(StoreNodes.begin(),
16335                          StoreNodes.begin() + NumStoresToMerge);
16336         NumConsecutiveStores -= NumStoresToMerge;
16337       }
16338       continue;
16339     }
16340 
16341     // Below we handle the case of multiple consecutive stores that
16342     // come from multiple consecutive loads. We merge them into a single
16343     // wide load and a single wide store.
16344 
16345     // Look for load nodes which are used by the stored values.
16346     SmallVector<MemOpLink, 8> LoadNodes;
16347 
16348     // Find acceptable loads. Loads need to have the same chain (token factor),
16349     // must not be zext, volatile, indexed, and they must be consecutive.
16350     BaseIndexOffset LdBasePtr;
16351 
16352     for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
16353       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
16354       SDValue Val = peekThroughBitcasts(St->getValue());
16355       LoadSDNode *Ld = cast<LoadSDNode>(Val);
16356 
16357       BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
16358       // If this is not the first ptr that we check.
16359       int64_t LdOffset = 0;
16360       if (LdBasePtr.getBase().getNode()) {
16361         // The base ptr must be the same.
16362         if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
16363           break;
16364       } else {
16365         // Check that all other base pointers are the same as this one.
16366         LdBasePtr = LdPtr;
16367       }
16368 
16369       // We found a potential memory operand to merge.
16370       LoadNodes.push_back(MemOpLink(Ld, LdOffset));
16371     }
16372 
16373     while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) {
16374       // If we have load/store pair instructions and we only have two values,
16375       // don't bother merging.
16376       unsigned RequiredAlignment;
16377       if (LoadNodes.size() == 2 &&
16378           TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
16379           StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
16380         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
16381         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2);
16382         break;
16383       }
16384       LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
16385       unsigned FirstStoreAS = FirstInChain->getAddressSpace();
16386       unsigned FirstStoreAlign = FirstInChain->getAlignment();
16387       LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
16388       unsigned FirstLoadAlign = FirstLoad->getAlignment();
16389 
16390       // Scan the memory operations on the chain and find the first
16391       // non-consecutive load memory address. These variables hold the index in
16392       // the store node array.
16393 
16394       unsigned LastConsecutiveLoad = 1;
16395 
16396       // This variable refers to the size and not index in the array.
16397       unsigned LastLegalVectorType = 1;
16398       unsigned LastLegalIntegerType = 1;
16399       bool isDereferenceable = true;
16400       bool DoIntegerTruncate = false;
16401       StartAddress = LoadNodes[0].OffsetFromBase;
16402       SDValue FirstChain = FirstLoad->getChain();
16403       for (unsigned i = 1; i < LoadNodes.size(); ++i) {
16404         // All loads must share the same chain.
16405         if (LoadNodes[i].MemNode->getChain() != FirstChain)
16406           break;
16407 
16408         int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
16409         if (CurrAddress - StartAddress != (ElementSizeBytes * i))
16410           break;
16411         LastConsecutiveLoad = i;
16412 
16413         if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
16414           isDereferenceable = false;
16415 
16416         // Find a legal type for the vector store.
16417         unsigned Elts = (i + 1) * NumMemElts;
16418         EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
16419 
16420         // Break early when size is too large to be legal.
16421         if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
16422           break;
16423 
16424         bool IsFastSt = false;
16425         bool IsFastLd = false;
16426         if (TLI.isTypeLegal(StoreTy) &&
16427             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
16428             TLI.allowsMemoryAccess(Context, DL, StoreTy,
16429                                    *FirstInChain->getMemOperand(), &IsFastSt) &&
16430             IsFastSt &&
16431             TLI.allowsMemoryAccess(Context, DL, StoreTy,
16432                                    *FirstLoad->getMemOperand(), &IsFastLd) &&
16433             IsFastLd) {
16434           LastLegalVectorType = i + 1;
16435         }
16436 
16437         // Find a legal type for the integer store.
16438         unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
16439         StoreTy = EVT::getIntegerVT(Context, SizeInBits);
16440         if (TLI.isTypeLegal(StoreTy) &&
16441             TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
16442             TLI.allowsMemoryAccess(Context, DL, StoreTy,
16443                                    *FirstInChain->getMemOperand(), &IsFastSt) &&
16444             IsFastSt &&
16445             TLI.allowsMemoryAccess(Context, DL, StoreTy,
16446                                    *FirstLoad->getMemOperand(), &IsFastLd) &&
16447             IsFastLd) {
16448           LastLegalIntegerType = i + 1;
16449           DoIntegerTruncate = false;
16450           // Or check whether a truncstore and extload is legal.
16451         } else if (TLI.getTypeAction(Context, StoreTy) ==
16452                    TargetLowering::TypePromoteInteger) {
16453           EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy);
16454           if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
16455               TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) &&
16456               TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy,
16457                                  StoreTy) &&
16458               TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy,
16459                                  StoreTy) &&
16460               TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) &&
16461               TLI.allowsMemoryAccess(Context, DL, StoreTy,
16462                                      *FirstInChain->getMemOperand(),
16463                                      &IsFastSt) &&
16464               IsFastSt &&
16465               TLI.allowsMemoryAccess(Context, DL, StoreTy,
16466                                      *FirstLoad->getMemOperand(), &IsFastLd) &&
16467               IsFastLd) {
16468             LastLegalIntegerType = i + 1;
16469             DoIntegerTruncate = true;
16470           }
16471         }
16472       }
16473 
16474       // Only use vector types if the vector type is larger than the integer
16475       // type. If they are the same, use integers.
16476       bool UseVectorTy =
16477           LastLegalVectorType > LastLegalIntegerType && !NoVectors;
16478       unsigned LastLegalType =
16479           std::max(LastLegalVectorType, LastLegalIntegerType);
16480 
16481       // We add +1 here because the LastXXX variables refer to location while
16482       // the NumElem refers to array/index size.
16483       unsigned NumElem =
16484           std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
16485       NumElem = std::min(LastLegalType, NumElem);
16486 
16487       if (NumElem < 2) {
16488         // We know that candidate stores are in order and of correct
16489         // shape. While there is no mergeable sequence from the
16490         // beginning one may start later in the sequence. The only
16491         // reason a merge of size N could have failed where another of
16492         // the same size would not have is if the alignment or either
16493         // the load or store has improved. Drop as many candidates as we
16494         // can here.
16495         unsigned NumSkip = 1;
16496         while ((NumSkip < LoadNodes.size()) &&
16497                (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) &&
16498                (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
16499           NumSkip++;
16500         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
16501         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip);
16502         NumConsecutiveStores -= NumSkip;
16503         continue;
16504       }
16505 
16506       // Check that we can merge these candidates without causing a cycle.
16507       if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
16508                                                     RootNode)) {
16509         StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
16510         LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
16511         NumConsecutiveStores -= NumElem;
16512         continue;
16513       }
16514 
16515       // Find if it is better to use vectors or integers to load and store
16516       // to memory.
16517       EVT JointMemOpVT;
16518       if (UseVectorTy) {
16519         // Find a legal type for the vector store.
16520         unsigned Elts = NumElem * NumMemElts;
16521         JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
16522       } else {
16523         unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
16524         JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
16525       }
16526 
16527       SDLoc LoadDL(LoadNodes[0].MemNode);
16528       SDLoc StoreDL(StoreNodes[0].MemNode);
16529 
16530       // The merged loads are required to have the same incoming chain, so
16531       // using the first's chain is acceptable.
16532 
16533       SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
16534       AddToWorklist(NewStoreChain.getNode());
16535 
16536       MachineMemOperand::Flags LdMMOFlags =
16537           isDereferenceable ? MachineMemOperand::MODereferenceable
16538                             : MachineMemOperand::MONone;
16539       if (IsNonTemporalLoad)
16540         LdMMOFlags |= MachineMemOperand::MONonTemporal;
16541 
16542       MachineMemOperand::Flags StMMOFlags =
16543           IsNonTemporalStore ? MachineMemOperand::MONonTemporal
16544                              : MachineMemOperand::MONone;
16545 
16546       SDValue NewLoad, NewStore;
16547       if (UseVectorTy || !DoIntegerTruncate) {
16548         NewLoad =
16549             DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
16550                         FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
16551                         FirstLoadAlign, LdMMOFlags);
16552         NewStore = DAG.getStore(
16553             NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
16554             FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags);
16555       } else { // This must be the truncstore/extload case
16556         EVT ExtendedTy =
16557             TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
16558         NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy,
16559                                  FirstLoad->getChain(), FirstLoad->getBasePtr(),
16560                                  FirstLoad->getPointerInfo(), JointMemOpVT,
16561                                  FirstLoadAlign, LdMMOFlags);
16562         NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
16563                                      FirstInChain->getBasePtr(),
16564                                      FirstInChain->getPointerInfo(),
16565                                      JointMemOpVT, FirstInChain->getAlignment(),
16566                                      FirstInChain->getMemOperand()->getFlags());
16567       }
16568 
16569       // Transfer chain users from old loads to the new load.
16570       for (unsigned i = 0; i < NumElem; ++i) {
16571         LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
16572         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
16573                                       SDValue(NewLoad.getNode(), 1));
16574       }
16575 
16576       // Replace the all stores with the new store. Recursively remove
16577       // corresponding value if its no longer used.
16578       for (unsigned i = 0; i < NumElem; ++i) {
16579         SDValue Val = StoreNodes[i].MemNode->getOperand(1);
16580         CombineTo(StoreNodes[i].MemNode, NewStore);
16581         if (Val.getNode()->use_empty())
16582           recursivelyDeleteUnusedNodes(Val.getNode());
16583       }
16584 
16585       RV = true;
16586       StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
16587       LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
16588       NumConsecutiveStores -= NumElem;
16589     }
16590   }
16591   return RV;
16592 }
16593 
16594 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
16595   SDLoc SL(ST);
16596   SDValue ReplStore;
16597 
16598   // Replace the chain to avoid dependency.
16599   if (ST->isTruncatingStore()) {
16600     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
16601                                   ST->getBasePtr(), ST->getMemoryVT(),
16602                                   ST->getMemOperand());
16603   } else {
16604     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
16605                              ST->getMemOperand());
16606   }
16607 
16608   // Create token to keep both nodes around.
16609   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
16610                               MVT::Other, ST->getChain(), ReplStore);
16611 
16612   // Make sure the new and old chains are cleaned up.
16613   AddToWorklist(Token.getNode());
16614 
16615   // Don't add users to work list.
16616   return CombineTo(ST, Token, false);
16617 }
16618 
16619 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
16620   SDValue Value = ST->getValue();
16621   if (Value.getOpcode() == ISD::TargetConstantFP)
16622     return SDValue();
16623 
16624   if (!ISD::isNormalStore(ST))
16625     return SDValue();
16626 
16627   SDLoc DL(ST);
16628 
16629   SDValue Chain = ST->getChain();
16630   SDValue Ptr = ST->getBasePtr();
16631 
16632   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
16633 
16634   // NOTE: If the original store is volatile, this transform must not increase
16635   // the number of stores.  For example, on x86-32 an f64 can be stored in one
16636   // processor operation but an i64 (which is not legal) requires two.  So the
16637   // transform should not be done in this case.
16638 
16639   SDValue Tmp;
16640   switch (CFP->getSimpleValueType(0).SimpleTy) {
16641   default:
16642     llvm_unreachable("Unknown FP type");
16643   case MVT::f16:    // We don't do this for these yet.
16644   case MVT::f80:
16645   case MVT::f128:
16646   case MVT::ppcf128:
16647     return SDValue();
16648   case MVT::f32:
16649     if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) ||
16650         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
16651       ;
16652       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
16653                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
16654                             MVT::i32);
16655       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
16656     }
16657 
16658     return SDValue();
16659   case MVT::f64:
16660     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
16661          ST->isSimple()) ||
16662         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
16663       ;
16664       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
16665                             getZExtValue(), SDLoc(CFP), MVT::i64);
16666       return DAG.getStore(Chain, DL, Tmp,
16667                           Ptr, ST->getMemOperand());
16668     }
16669 
16670     if (ST->isSimple() &&
16671         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
16672       // Many FP stores are not made apparent until after legalize, e.g. for
16673       // argument passing.  Since this is so common, custom legalize the
16674       // 64-bit integer store into two 32-bit stores.
16675       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
16676       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
16677       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
16678       if (DAG.getDataLayout().isBigEndian())
16679         std::swap(Lo, Hi);
16680 
16681       unsigned Alignment = ST->getAlignment();
16682       MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
16683       AAMDNodes AAInfo = ST->getAAInfo();
16684 
16685       SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
16686                                  ST->getAlignment(), MMOFlags, AAInfo);
16687       Ptr = DAG.getMemBasePlusOffset(Ptr, 4, DL);
16688       Alignment = MinAlign(Alignment, 4U);
16689       SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
16690                                  ST->getPointerInfo().getWithOffset(4),
16691                                  Alignment, MMOFlags, AAInfo);
16692       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
16693                          St0, St1);
16694     }
16695 
16696     return SDValue();
16697   }
16698 }
16699 
16700 SDValue DAGCombiner::visitSTORE(SDNode *N) {
16701   StoreSDNode *ST  = cast<StoreSDNode>(N);
16702   SDValue Chain = ST->getChain();
16703   SDValue Value = ST->getValue();
16704   SDValue Ptr   = ST->getBasePtr();
16705 
16706   // If this is a store of a bit convert, store the input value if the
16707   // resultant store does not need a higher alignment than the original.
16708   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
16709       ST->isUnindexed()) {
16710     EVT SVT = Value.getOperand(0).getValueType();
16711     // If the store is volatile, we only want to change the store type if the
16712     // resulting store is legal. Otherwise we might increase the number of
16713     // memory accesses. We don't care if the original type was legal or not
16714     // as we assume software couldn't rely on the number of accesses of an
16715     // illegal type.
16716     // TODO: May be able to relax for unordered atomics (see D66309)
16717     if (((!LegalOperations && ST->isSimple()) ||
16718          TLI.isOperationLegal(ISD::STORE, SVT)) &&
16719         TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT,
16720                                      DAG, *ST->getMemOperand())) {
16721       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
16722                           ST->getMemOperand());
16723     }
16724   }
16725 
16726   // Turn 'store undef, Ptr' -> nothing.
16727   if (Value.isUndef() && ST->isUnindexed())
16728     return Chain;
16729 
16730   // Try to infer better alignment information than the store already has.
16731   if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) {
16732     if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
16733       if (*Alignment > ST->getAlign() &&
16734           isAligned(*Alignment, ST->getSrcValueOffset())) {
16735         SDValue NewStore =
16736             DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
16737                               ST->getMemoryVT(), *Alignment,
16738                               ST->getMemOperand()->getFlags(), ST->getAAInfo());
16739         // NewStore will always be N as we are only refining the alignment
16740         assert(NewStore.getNode() == N);
16741         (void)NewStore;
16742       }
16743     }
16744   }
16745 
16746   // Try transforming a pair floating point load / store ops to integer
16747   // load / store ops.
16748   if (SDValue NewST = TransformFPLoadStorePair(N))
16749     return NewST;
16750 
16751   // Try transforming several stores into STORE (BSWAP).
16752   if (SDValue Store = MatchStoreCombine(ST))
16753     return Store;
16754 
16755   if (ST->isUnindexed()) {
16756     // Walk up chain skipping non-aliasing memory nodes, on this store and any
16757     // adjacent stores.
16758     if (findBetterNeighborChains(ST)) {
16759       // replaceStoreChain uses CombineTo, which handled all of the worklist
16760       // manipulation. Return the original node to not do anything else.
16761       return SDValue(ST, 0);
16762     }
16763     Chain = ST->getChain();
16764   }
16765 
16766   // FIXME: is there such a thing as a truncating indexed store?
16767   if (ST->isTruncatingStore() && ST->isUnindexed() &&
16768       Value.getValueType().isInteger() &&
16769       (!isa<ConstantSDNode>(Value) ||
16770        !cast<ConstantSDNode>(Value)->isOpaque())) {
16771     APInt TruncDemandedBits =
16772         APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
16773                              ST->getMemoryVT().getScalarSizeInBits());
16774 
16775     // See if we can simplify the input to this truncstore with knowledge that
16776     // only the low bits are being used.  For example:
16777     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
16778     AddToWorklist(Value.getNode());
16779     if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits))
16780       return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(),
16781                                ST->getMemOperand());
16782 
16783     // Otherwise, see if we can simplify the operation with
16784     // SimplifyDemandedBits, which only works if the value has a single use.
16785     if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
16786       // Re-visit the store if anything changed and the store hasn't been merged
16787       // with another node (N is deleted) SimplifyDemandedBits will add Value's
16788       // node back to the worklist if necessary, but we also need to re-visit
16789       // the Store node itself.
16790       if (N->getOpcode() != ISD::DELETED_NODE)
16791         AddToWorklist(N);
16792       return SDValue(N, 0);
16793     }
16794   }
16795 
16796   // If this is a load followed by a store to the same location, then the store
16797   // is dead/noop.
16798   // TODO: Can relax for unordered atomics (see D66309)
16799   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
16800     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
16801         ST->isUnindexed() && ST->isSimple() &&
16802         // There can't be any side effects between the load and store, such as
16803         // a call or store.
16804         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
16805       // The store is dead, remove it.
16806       return Chain;
16807     }
16808   }
16809 
16810   // TODO: Can relax for unordered atomics (see D66309)
16811   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
16812     if (ST->isUnindexed() && ST->isSimple() &&
16813         ST1->isUnindexed() && ST1->isSimple()) {
16814       if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value &&
16815           ST->getMemoryVT() == ST1->getMemoryVT()) {
16816         // If this is a store followed by a store with the same value to the
16817         // same location, then the store is dead/noop.
16818         return Chain;
16819       }
16820 
16821       if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
16822           !ST1->getBasePtr().isUndef() &&
16823           // BaseIndexOffset and the code below requires knowing the size
16824           // of a vector, so bail out if MemoryVT is scalable.
16825           !ST1->getMemoryVT().isScalableVector()) {
16826         const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG);
16827         const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG);
16828         unsigned STBitSize = ST->getMemoryVT().getSizeInBits();
16829         unsigned ChainBitSize = ST1->getMemoryVT().getSizeInBits();
16830         // If this is a store who's preceding store to a subset of the current
16831         // location and no one other node is chained to that store we can
16832         // effectively drop the store. Do not remove stores to undef as they may
16833         // be used as data sinks.
16834         if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) {
16835           CombineTo(ST1, ST1->getChain());
16836           return SDValue();
16837         }
16838       }
16839     }
16840   }
16841 
16842   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
16843   // truncating store.  We can do this even if this is already a truncstore.
16844   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
16845       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
16846       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
16847                             ST->getMemoryVT())) {
16848     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
16849                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
16850   }
16851 
16852   // Always perform this optimization before types are legal. If the target
16853   // prefers, also try this after legalization to catch stores that were created
16854   // by intrinsics or other nodes.
16855   if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) {
16856     while (true) {
16857       // There can be multiple store sequences on the same chain.
16858       // Keep trying to merge store sequences until we are unable to do so
16859       // or until we merge the last store on the chain.
16860       bool Changed = MergeConsecutiveStores(ST);
16861       if (!Changed) break;
16862       // Return N as merge only uses CombineTo and no worklist clean
16863       // up is necessary.
16864       if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
16865         return SDValue(N, 0);
16866     }
16867   }
16868 
16869   // Try transforming N to an indexed store.
16870   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
16871     return SDValue(N, 0);
16872 
16873   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
16874   //
16875   // Make sure to do this only after attempting to merge stores in order to
16876   //  avoid changing the types of some subset of stores due to visit order,
16877   //  preventing their merging.
16878   if (isa<ConstantFPSDNode>(ST->getValue())) {
16879     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
16880       return NewSt;
16881   }
16882 
16883   if (SDValue NewSt = splitMergedValStore(ST))
16884     return NewSt;
16885 
16886   return ReduceLoadOpStoreWidth(N);
16887 }
16888 
16889 SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) {
16890   const auto *LifetimeEnd = cast<LifetimeSDNode>(N);
16891   if (!LifetimeEnd->hasOffset())
16892     return SDValue();
16893 
16894   const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(),
16895                                         LifetimeEnd->getOffset(), false);
16896 
16897   // We walk up the chains to find stores.
16898   SmallVector<SDValue, 8> Chains = {N->getOperand(0)};
16899   while (!Chains.empty()) {
16900     SDValue Chain = Chains.back();
16901     Chains.pop_back();
16902     if (!Chain.hasOneUse())
16903       continue;
16904     switch (Chain.getOpcode()) {
16905     case ISD::TokenFactor:
16906       for (unsigned Nops = Chain.getNumOperands(); Nops;)
16907         Chains.push_back(Chain.getOperand(--Nops));
16908       break;
16909     case ISD::LIFETIME_START:
16910     case ISD::LIFETIME_END:
16911       // We can forward past any lifetime start/end that can be proven not to
16912       // alias the node.
16913       if (!isAlias(Chain.getNode(), N))
16914         Chains.push_back(Chain.getOperand(0));
16915       break;
16916     case ISD::STORE: {
16917       StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain);
16918       // TODO: Can relax for unordered atomics (see D66309)
16919       if (!ST->isSimple() || ST->isIndexed())
16920         continue;
16921       const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG);
16922       // If we store purely within object bounds just before its lifetime ends,
16923       // we can remove the store.
16924       if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase,
16925                                    ST->getMemoryVT().getStoreSizeInBits())) {
16926         LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump();
16927                    dbgs() << "\nwithin LIFETIME_END of : ";
16928                    LifetimeEndBase.dump(); dbgs() << "\n");
16929         CombineTo(ST, ST->getChain());
16930         return SDValue(N, 0);
16931       }
16932     }
16933     }
16934   }
16935   return SDValue();
16936 }
16937 
16938 /// For the instruction sequence of store below, F and I values
16939 /// are bundled together as an i64 value before being stored into memory.
16940 /// Sometimes it is more efficent to generate separate stores for F and I,
16941 /// which can remove the bitwise instructions or sink them to colder places.
16942 ///
16943 ///   (store (or (zext (bitcast F to i32) to i64),
16944 ///              (shl (zext I to i64), 32)), addr)  -->
16945 ///   (store F, addr) and (store I, addr+4)
16946 ///
16947 /// Similarly, splitting for other merged store can also be beneficial, like:
16948 /// For pair of {i32, i32}, i64 store --> two i32 stores.
16949 /// For pair of {i32, i16}, i64 store --> two i32 stores.
16950 /// For pair of {i16, i16}, i32 store --> two i16 stores.
16951 /// For pair of {i16, i8},  i32 store --> two i16 stores.
16952 /// For pair of {i8, i8},   i16 store --> two i8 stores.
16953 ///
16954 /// We allow each target to determine specifically which kind of splitting is
16955 /// supported.
16956 ///
16957 /// The store patterns are commonly seen from the simple code snippet below
16958 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
16959 ///   void goo(const std::pair<int, float> &);
16960 ///   hoo() {
16961 ///     ...
16962 ///     goo(std::make_pair(tmp, ftmp));
16963 ///     ...
16964 ///   }
16965 ///
16966 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
16967   if (OptLevel == CodeGenOpt::None)
16968     return SDValue();
16969 
16970   // Can't change the number of memory accesses for a volatile store or break
16971   // atomicity for an atomic one.
16972   if (!ST->isSimple())
16973     return SDValue();
16974 
16975   SDValue Val = ST->getValue();
16976   SDLoc DL(ST);
16977 
16978   // Match OR operand.
16979   if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
16980     return SDValue();
16981 
16982   // Match SHL operand and get Lower and Higher parts of Val.
16983   SDValue Op1 = Val.getOperand(0);
16984   SDValue Op2 = Val.getOperand(1);
16985   SDValue Lo, Hi;
16986   if (Op1.getOpcode() != ISD::SHL) {
16987     std::swap(Op1, Op2);
16988     if (Op1.getOpcode() != ISD::SHL)
16989       return SDValue();
16990   }
16991   Lo = Op2;
16992   Hi = Op1.getOperand(0);
16993   if (!Op1.hasOneUse())
16994     return SDValue();
16995 
16996   // Match shift amount to HalfValBitSize.
16997   unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
16998   ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
16999   if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
17000     return SDValue();
17001 
17002   // Lo and Hi are zero-extended from int with size less equal than 32
17003   // to i64.
17004   if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
17005       !Lo.getOperand(0).getValueType().isScalarInteger() ||
17006       Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
17007       Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
17008       !Hi.getOperand(0).getValueType().isScalarInteger() ||
17009       Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
17010     return SDValue();
17011 
17012   // Use the EVT of low and high parts before bitcast as the input
17013   // of target query.
17014   EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
17015                   ? Lo.getOperand(0).getValueType()
17016                   : Lo.getValueType();
17017   EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
17018                    ? Hi.getOperand(0).getValueType()
17019                    : Hi.getValueType();
17020   if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
17021     return SDValue();
17022 
17023   // Start to split store.
17024   unsigned Alignment = ST->getAlignment();
17025   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
17026   AAMDNodes AAInfo = ST->getAAInfo();
17027 
17028   // Change the sizes of Lo and Hi's value types to HalfValBitSize.
17029   EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
17030   Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
17031   Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
17032 
17033   SDValue Chain = ST->getChain();
17034   SDValue Ptr = ST->getBasePtr();
17035   // Lower value store.
17036   SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
17037                              ST->getAlignment(), MMOFlags, AAInfo);
17038   Ptr = DAG.getMemBasePlusOffset(Ptr, HalfValBitSize / 8, DL);
17039   // Higher value store.
17040   SDValue St1 =
17041       DAG.getStore(St0, DL, Hi, Ptr,
17042                    ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
17043                    Alignment / 2, MMOFlags, AAInfo);
17044   return St1;
17045 }
17046 
17047 /// Convert a disguised subvector insertion into a shuffle:
17048 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
17049   assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT &&
17050          "Expected extract_vector_elt");
17051   SDValue InsertVal = N->getOperand(1);
17052   SDValue Vec = N->getOperand(0);
17053 
17054   // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N),
17055   // InsIndex)
17056   //   --> (vector_shuffle X, Y) and variations where shuffle operands may be
17057   //   CONCAT_VECTORS.
17058   if (Vec.getOpcode() == ISD::VECTOR_SHUFFLE && Vec.hasOneUse() &&
17059       InsertVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
17060       isa<ConstantSDNode>(InsertVal.getOperand(1))) {
17061     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Vec.getNode());
17062     ArrayRef<int> Mask = SVN->getMask();
17063 
17064     SDValue X = Vec.getOperand(0);
17065     SDValue Y = Vec.getOperand(1);
17066 
17067     // Vec's operand 0 is using indices from 0 to N-1 and
17068     // operand 1 from N to 2N - 1, where N is the number of
17069     // elements in the vectors.
17070     SDValue InsertVal0 = InsertVal.getOperand(0);
17071     int ElementOffset = -1;
17072 
17073     // We explore the inputs of the shuffle in order to see if we find the
17074     // source of the extract_vector_elt. If so, we can use it to modify the
17075     // shuffle rather than perform an insert_vector_elt.
17076     SmallVector<std::pair<int, SDValue>, 8> ArgWorkList;
17077     ArgWorkList.emplace_back(Mask.size(), Y);
17078     ArgWorkList.emplace_back(0, X);
17079 
17080     while (!ArgWorkList.empty()) {
17081       int ArgOffset;
17082       SDValue ArgVal;
17083       std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val();
17084 
17085       if (ArgVal == InsertVal0) {
17086         ElementOffset = ArgOffset;
17087         break;
17088       }
17089 
17090       // Peek through concat_vector.
17091       if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) {
17092         int CurrentArgOffset =
17093             ArgOffset + ArgVal.getValueType().getVectorNumElements();
17094         int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements();
17095         for (SDValue Op : reverse(ArgVal->ops())) {
17096           CurrentArgOffset -= Step;
17097           ArgWorkList.emplace_back(CurrentArgOffset, Op);
17098         }
17099 
17100         // Make sure we went through all the elements and did not screw up index
17101         // computation.
17102         assert(CurrentArgOffset == ArgOffset);
17103       }
17104     }
17105 
17106     if (ElementOffset != -1) {
17107       SmallVector<int, 16> NewMask(Mask.begin(), Mask.end());
17108 
17109       auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1));
17110       NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue();
17111       assert(NewMask[InsIndex] <
17112                  (int)(2 * Vec.getValueType().getVectorNumElements()) &&
17113              NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound");
17114 
17115       SDValue LegalShuffle =
17116               TLI.buildLegalVectorShuffle(Vec.getValueType(), SDLoc(N), X,
17117                                           Y, NewMask, DAG);
17118       if (LegalShuffle)
17119         return LegalShuffle;
17120     }
17121   }
17122 
17123   // insert_vector_elt V, (bitcast X from vector type), IdxC -->
17124   // bitcast(shuffle (bitcast V), (extended X), Mask)
17125   // Note: We do not use an insert_subvector node because that requires a
17126   // legal subvector type.
17127   if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
17128       !InsertVal.getOperand(0).getValueType().isVector())
17129     return SDValue();
17130 
17131   SDValue SubVec = InsertVal.getOperand(0);
17132   SDValue DestVec = N->getOperand(0);
17133   EVT SubVecVT = SubVec.getValueType();
17134   EVT VT = DestVec.getValueType();
17135   unsigned NumSrcElts = SubVecVT.getVectorNumElements();
17136   unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
17137   unsigned NumMaskVals = ExtendRatio * NumSrcElts;
17138 
17139   // Step 1: Create a shuffle mask that implements this insert operation. The
17140   // vector that we are inserting into will be operand 0 of the shuffle, so
17141   // those elements are just 'i'. The inserted subvector is in the first
17142   // positions of operand 1 of the shuffle. Example:
17143   // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
17144   SmallVector<int, 16> Mask(NumMaskVals);
17145   for (unsigned i = 0; i != NumMaskVals; ++i) {
17146     if (i / NumSrcElts == InsIndex)
17147       Mask[i] = (i % NumSrcElts) + NumMaskVals;
17148     else
17149       Mask[i] = i;
17150   }
17151 
17152   // Bail out if the target can not handle the shuffle we want to create.
17153   EVT SubVecEltVT = SubVecVT.getVectorElementType();
17154   EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
17155   if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
17156     return SDValue();
17157 
17158   // Step 2: Create a wide vector from the inserted source vector by appending
17159   // undefined elements. This is the same size as our destination vector.
17160   SDLoc DL(N);
17161   SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
17162   ConcatOps[0] = SubVec;
17163   SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
17164 
17165   // Step 3: Shuffle in the padded subvector.
17166   SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
17167   SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
17168   AddToWorklist(PaddedSubV.getNode());
17169   AddToWorklist(DestVecBC.getNode());
17170   AddToWorklist(Shuf.getNode());
17171   return DAG.getBitcast(VT, Shuf);
17172 }
17173 
17174 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
17175   SDValue InVec = N->getOperand(0);
17176   SDValue InVal = N->getOperand(1);
17177   SDValue EltNo = N->getOperand(2);
17178   SDLoc DL(N);
17179 
17180   EVT VT = InVec.getValueType();
17181   auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
17182 
17183   // Insert into out-of-bounds element is undefined.
17184   if (IndexC && VT.isFixedLengthVector() &&
17185       IndexC->getZExtValue() >= VT.getVectorNumElements())
17186     return DAG.getUNDEF(VT);
17187 
17188   // Remove redundant insertions:
17189   // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
17190   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
17191       InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
17192     return InVec;
17193 
17194   if (!IndexC) {
17195     // If this is variable insert to undef vector, it might be better to splat:
17196     // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
17197     if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) {
17198       if (VT.isScalableVector())
17199         return DAG.getSplatVector(VT, DL, InVal);
17200       else {
17201         SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal);
17202         return DAG.getBuildVector(VT, DL, Ops);
17203       }
17204     }
17205     return SDValue();
17206   }
17207 
17208   if (VT.isScalableVector())
17209     return SDValue();
17210 
17211   unsigned NumElts = VT.getVectorNumElements();
17212 
17213   // We must know which element is being inserted for folds below here.
17214   unsigned Elt = IndexC->getZExtValue();
17215   if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
17216     return Shuf;
17217 
17218   // Canonicalize insert_vector_elt dag nodes.
17219   // Example:
17220   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
17221   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
17222   //
17223   // Do this only if the child insert_vector node has one use; also
17224   // do this only if indices are both constants and Idx1 < Idx0.
17225   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
17226       && isa<ConstantSDNode>(InVec.getOperand(2))) {
17227     unsigned OtherElt = InVec.getConstantOperandVal(2);
17228     if (Elt < OtherElt) {
17229       // Swap nodes.
17230       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
17231                                   InVec.getOperand(0), InVal, EltNo);
17232       AddToWorklist(NewOp.getNode());
17233       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
17234                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
17235     }
17236   }
17237 
17238   // If we can't generate a legal BUILD_VECTOR, exit
17239   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
17240     return SDValue();
17241 
17242   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
17243   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
17244   // vector elements.
17245   SmallVector<SDValue, 8> Ops;
17246   // Do not combine these two vectors if the output vector will not replace
17247   // the input vector.
17248   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
17249     Ops.append(InVec.getNode()->op_begin(),
17250                InVec.getNode()->op_end());
17251   } else if (InVec.isUndef()) {
17252     Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType()));
17253   } else {
17254     return SDValue();
17255   }
17256   assert(Ops.size() == NumElts && "Unexpected vector size");
17257 
17258   // Insert the element
17259   if (Elt < Ops.size()) {
17260     // All the operands of BUILD_VECTOR must have the same type;
17261     // we enforce that here.
17262     EVT OpVT = Ops[0].getValueType();
17263     Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
17264   }
17265 
17266   // Return the new vector
17267   return DAG.getBuildVector(VT, DL, Ops);
17268 }
17269 
17270 SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
17271                                                   SDValue EltNo,
17272                                                   LoadSDNode *OriginalLoad) {
17273   assert(OriginalLoad->isSimple());
17274 
17275   EVT ResultVT = EVE->getValueType(0);
17276   EVT VecEltVT = InVecVT.getVectorElementType();
17277   unsigned Align = OriginalLoad->getAlignment();
17278   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
17279       VecEltVT.getTypeForEVT(*DAG.getContext()));
17280 
17281   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
17282     return SDValue();
17283 
17284   ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
17285     ISD::NON_EXTLOAD : ISD::EXTLOAD;
17286   if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
17287     return SDValue();
17288 
17289   Align = NewAlign;
17290 
17291   SDValue NewPtr = OriginalLoad->getBasePtr();
17292   SDValue Offset;
17293   EVT PtrType = NewPtr.getValueType();
17294   MachinePointerInfo MPI;
17295   SDLoc DL(EVE);
17296   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
17297     int Elt = ConstEltNo->getZExtValue();
17298     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
17299     Offset = DAG.getConstant(PtrOff, DL, PtrType);
17300     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
17301   } else {
17302     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
17303     Offset = DAG.getNode(
17304         ISD::MUL, DL, PtrType, Offset,
17305         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
17306     // Discard the pointer info except the address space because the memory
17307     // operand can't represent this new access since the offset is variable.
17308     MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
17309   }
17310   NewPtr = DAG.getMemBasePlusOffset(NewPtr, Offset, DL);
17311 
17312   // The replacement we need to do here is a little tricky: we need to
17313   // replace an extractelement of a load with a load.
17314   // Use ReplaceAllUsesOfValuesWith to do the replacement.
17315   // Note that this replacement assumes that the extractvalue is the only
17316   // use of the load; that's okay because we don't want to perform this
17317   // transformation in other cases anyway.
17318   SDValue Load;
17319   SDValue Chain;
17320   if (ResultVT.bitsGT(VecEltVT)) {
17321     // If the result type of vextract is wider than the load, then issue an
17322     // extending load instead.
17323     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
17324                                                   VecEltVT)
17325                                    ? ISD::ZEXTLOAD
17326                                    : ISD::EXTLOAD;
17327     Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
17328                           OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
17329                           Align, OriginalLoad->getMemOperand()->getFlags(),
17330                           OriginalLoad->getAAInfo());
17331     Chain = Load.getValue(1);
17332   } else {
17333     Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
17334                        MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
17335                        OriginalLoad->getAAInfo());
17336     Chain = Load.getValue(1);
17337     if (ResultVT.bitsLT(VecEltVT))
17338       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
17339     else
17340       Load = DAG.getBitcast(ResultVT, Load);
17341   }
17342   WorklistRemover DeadNodes(*this);
17343   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
17344   SDValue To[] = { Load, Chain };
17345   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
17346   // Make sure to revisit this node to clean it up; it will usually be dead.
17347   AddToWorklist(EVE);
17348   // Since we're explicitly calling ReplaceAllUses, add the new node to the
17349   // worklist explicitly as well.
17350   AddToWorklistWithUsers(Load.getNode());
17351   ++OpsNarrowed;
17352   return SDValue(EVE, 0);
17353 }
17354 
17355 /// Transform a vector binary operation into a scalar binary operation by moving
17356 /// the math/logic after an extract element of a vector.
17357 static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG,
17358                                        bool LegalOperations) {
17359   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17360   SDValue Vec = ExtElt->getOperand(0);
17361   SDValue Index = ExtElt->getOperand(1);
17362   auto *IndexC = dyn_cast<ConstantSDNode>(Index);
17363   if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() ||
17364       Vec.getNode()->getNumValues() != 1)
17365     return SDValue();
17366 
17367   // Targets may want to avoid this to prevent an expensive register transfer.
17368   if (!TLI.shouldScalarizeBinop(Vec))
17369     return SDValue();
17370 
17371   // Extracting an element of a vector constant is constant-folded, so this
17372   // transform is just replacing a vector op with a scalar op while moving the
17373   // extract.
17374   SDValue Op0 = Vec.getOperand(0);
17375   SDValue Op1 = Vec.getOperand(1);
17376   if (isAnyConstantBuildVector(Op0, true) ||
17377       isAnyConstantBuildVector(Op1, true)) {
17378     // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
17379     // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
17380     SDLoc DL(ExtElt);
17381     EVT VT = ExtElt->getValueType(0);
17382     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index);
17383     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index);
17384     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1);
17385   }
17386 
17387   return SDValue();
17388 }
17389 
17390 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
17391   SDValue VecOp = N->getOperand(0);
17392   SDValue Index = N->getOperand(1);
17393   EVT ScalarVT = N->getValueType(0);
17394   EVT VecVT = VecOp.getValueType();
17395   if (VecOp.isUndef())
17396     return DAG.getUNDEF(ScalarVT);
17397 
17398   // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
17399   //
17400   // This only really matters if the index is non-constant since other combines
17401   // on the constant elements already work.
17402   SDLoc DL(N);
17403   if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT &&
17404       Index == VecOp.getOperand(2)) {
17405     SDValue Elt = VecOp.getOperand(1);
17406     return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt;
17407   }
17408 
17409   // (vextract (scalar_to_vector val, 0) -> val
17410   if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) {
17411     // Only 0'th element of SCALAR_TO_VECTOR is defined.
17412     if (DAG.isKnownNeverZero(Index))
17413       return DAG.getUNDEF(ScalarVT);
17414 
17415     // Check if the result type doesn't match the inserted element type. A
17416     // SCALAR_TO_VECTOR may truncate the inserted element and the
17417     // EXTRACT_VECTOR_ELT may widen the extracted vector.
17418     SDValue InOp = VecOp.getOperand(0);
17419     if (InOp.getValueType() != ScalarVT) {
17420       assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
17421       return DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
17422     }
17423     return InOp;
17424   }
17425 
17426   // extract_vector_elt of out-of-bounds element -> UNDEF
17427   auto *IndexC = dyn_cast<ConstantSDNode>(Index);
17428   unsigned NumElts = VecVT.getVectorNumElements();
17429   unsigned VecEltBitWidth = VecVT.getScalarSizeInBits();
17430   if (IndexC && IndexC->getAPIntValue().uge(NumElts))
17431     return DAG.getUNDEF(ScalarVT);
17432 
17433   // extract_vector_elt (build_vector x, y), 1 -> y
17434   if (IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR &&
17435       TLI.isTypeLegal(VecVT) &&
17436       (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) {
17437     SDValue Elt = VecOp.getOperand(IndexC->getZExtValue());
17438     EVT InEltVT = Elt.getValueType();
17439 
17440     // Sometimes build_vector's scalar input types do not match result type.
17441     if (ScalarVT == InEltVT)
17442       return Elt;
17443 
17444     // TODO: It may be useful to truncate if free if the build_vector implicitly
17445     // converts.
17446   }
17447 
17448   // TODO: These transforms should not require the 'hasOneUse' restriction, but
17449   // there are regressions on multiple targets without it. We can end up with a
17450   // mess of scalar and vector code if we reduce only part of the DAG to scalar.
17451   if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() &&
17452       VecOp.hasOneUse()) {
17453     // The vector index of the LSBs of the source depend on the endian-ness.
17454     bool IsLE = DAG.getDataLayout().isLittleEndian();
17455     unsigned ExtractIndex = IndexC->getZExtValue();
17456     // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
17457     unsigned BCTruncElt = IsLE ? 0 : NumElts - 1;
17458     SDValue BCSrc = VecOp.getOperand(0);
17459     if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger())
17460       return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc);
17461 
17462     if (LegalTypes && BCSrc.getValueType().isInteger() &&
17463         BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) {
17464       // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
17465       // trunc i64 X to i32
17466       SDValue X = BCSrc.getOperand(0);
17467       assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() &&
17468              "Extract element and scalar to vector can't change element type "
17469              "from FP to integer.");
17470       unsigned XBitWidth = X.getValueSizeInBits();
17471       BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1;
17472 
17473       // An extract element return value type can be wider than its vector
17474       // operand element type. In that case, the high bits are undefined, so
17475       // it's possible that we may need to extend rather than truncate.
17476       if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) {
17477         assert(XBitWidth % VecEltBitWidth == 0 &&
17478                "Scalar bitwidth must be a multiple of vector element bitwidth");
17479         return DAG.getAnyExtOrTrunc(X, DL, ScalarVT);
17480       }
17481     }
17482   }
17483 
17484   if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations))
17485     return BO;
17486 
17487   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
17488   // We only perform this optimization before the op legalization phase because
17489   // we may introduce new vector instructions which are not backed by TD
17490   // patterns. For example on AVX, extracting elements from a wide vector
17491   // without using extract_subvector. However, if we can find an underlying
17492   // scalar value, then we can always use that.
17493   if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
17494     auto *Shuf = cast<ShuffleVectorSDNode>(VecOp);
17495     // Find the new index to extract from.
17496     int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue());
17497 
17498     // Extracting an undef index is undef.
17499     if (OrigElt == -1)
17500       return DAG.getUNDEF(ScalarVT);
17501 
17502     // Select the right vector half to extract from.
17503     SDValue SVInVec;
17504     if (OrigElt < (int)NumElts) {
17505       SVInVec = VecOp.getOperand(0);
17506     } else {
17507       SVInVec = VecOp.getOperand(1);
17508       OrigElt -= NumElts;
17509     }
17510 
17511     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
17512       SDValue InOp = SVInVec.getOperand(OrigElt);
17513       if (InOp.getValueType() != ScalarVT) {
17514         assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
17515         InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
17516       }
17517 
17518       return InOp;
17519     }
17520 
17521     // FIXME: We should handle recursing on other vector shuffles and
17522     // scalar_to_vector here as well.
17523 
17524     if (!LegalOperations ||
17525         // FIXME: Should really be just isOperationLegalOrCustom.
17526         TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) ||
17527         TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) {
17528       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec,
17529                          DAG.getVectorIdxConstant(OrigElt, DL));
17530     }
17531   }
17532 
17533   // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
17534   // simplify it based on the (valid) extraction indices.
17535   if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) {
17536         return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
17537                Use->getOperand(0) == VecOp &&
17538                isa<ConstantSDNode>(Use->getOperand(1));
17539       })) {
17540     APInt DemandedElts = APInt::getNullValue(NumElts);
17541     for (SDNode *Use : VecOp->uses()) {
17542       auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1));
17543       if (CstElt->getAPIntValue().ult(NumElts))
17544         DemandedElts.setBit(CstElt->getZExtValue());
17545     }
17546     if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) {
17547       // We simplified the vector operand of this extract element. If this
17548       // extract is not dead, visit it again so it is folded properly.
17549       if (N->getOpcode() != ISD::DELETED_NODE)
17550         AddToWorklist(N);
17551       return SDValue(N, 0);
17552     }
17553     APInt DemandedBits = APInt::getAllOnesValue(VecEltBitWidth);
17554     if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) {
17555       // We simplified the vector operand of this extract element. If this
17556       // extract is not dead, visit it again so it is folded properly.
17557       if (N->getOpcode() != ISD::DELETED_NODE)
17558         AddToWorklist(N);
17559       return SDValue(N, 0);
17560     }
17561   }
17562 
17563   // Everything under here is trying to match an extract of a loaded value.
17564   // If the result of load has to be truncated, then it's not necessarily
17565   // profitable.
17566   bool BCNumEltsChanged = false;
17567   EVT ExtVT = VecVT.getVectorElementType();
17568   EVT LVT = ExtVT;
17569   if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT))
17570     return SDValue();
17571 
17572   if (VecOp.getOpcode() == ISD::BITCAST) {
17573     // Don't duplicate a load with other uses.
17574     if (!VecOp.hasOneUse())
17575       return SDValue();
17576 
17577     EVT BCVT = VecOp.getOperand(0).getValueType();
17578     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
17579       return SDValue();
17580     if (NumElts != BCVT.getVectorNumElements())
17581       BCNumEltsChanged = true;
17582     VecOp = VecOp.getOperand(0);
17583     ExtVT = BCVT.getVectorElementType();
17584   }
17585 
17586   // extract (vector load $addr), i --> load $addr + i * size
17587   if (!LegalOperations && !IndexC && VecOp.hasOneUse() &&
17588       ISD::isNormalLoad(VecOp.getNode()) &&
17589       !Index->hasPredecessor(VecOp.getNode())) {
17590     auto *VecLoad = dyn_cast<LoadSDNode>(VecOp);
17591     if (VecLoad && VecLoad->isSimple())
17592       return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad);
17593   }
17594 
17595   // Perform only after legalization to ensure build_vector / vector_shuffle
17596   // optimizations have already been done.
17597   if (!LegalOperations || !IndexC)
17598     return SDValue();
17599 
17600   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
17601   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
17602   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
17603   int Elt = IndexC->getZExtValue();
17604   LoadSDNode *LN0 = nullptr;
17605   if (ISD::isNormalLoad(VecOp.getNode())) {
17606     LN0 = cast<LoadSDNode>(VecOp);
17607   } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
17608              VecOp.getOperand(0).getValueType() == ExtVT &&
17609              ISD::isNormalLoad(VecOp.getOperand(0).getNode())) {
17610     // Don't duplicate a load with other uses.
17611     if (!VecOp.hasOneUse())
17612       return SDValue();
17613 
17614     LN0 = cast<LoadSDNode>(VecOp.getOperand(0));
17615   }
17616   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) {
17617     // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
17618     // =>
17619     // (load $addr+1*size)
17620 
17621     // Don't duplicate a load with other uses.
17622     if (!VecOp.hasOneUse())
17623       return SDValue();
17624 
17625     // If the bit convert changed the number of elements, it is unsafe
17626     // to examine the mask.
17627     if (BCNumEltsChanged)
17628       return SDValue();
17629 
17630     // Select the input vector, guarding against out of range extract vector.
17631     int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt);
17632     VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1);
17633 
17634     if (VecOp.getOpcode() == ISD::BITCAST) {
17635       // Don't duplicate a load with other uses.
17636       if (!VecOp.hasOneUse())
17637         return SDValue();
17638 
17639       VecOp = VecOp.getOperand(0);
17640     }
17641     if (ISD::isNormalLoad(VecOp.getNode())) {
17642       LN0 = cast<LoadSDNode>(VecOp);
17643       Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts;
17644       Index = DAG.getConstant(Elt, DL, Index.getValueType());
17645     }
17646   } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS &&
17647              !BCNumEltsChanged && VecVT.getVectorElementType() == ScalarVT) {
17648     // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0
17649     //      -> extract_vector_elt a, 0
17650     // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1
17651     //      -> extract_vector_elt a, 1
17652     // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2
17653     //      -> extract_vector_elt b, 0
17654     // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3
17655     //      -> extract_vector_elt b, 1
17656     SDLoc SL(N);
17657     EVT ConcatVT = VecOp.getOperand(0).getValueType();
17658     unsigned ConcatNumElts = ConcatVT.getVectorNumElements();
17659     SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL,
17660                                      Index.getValueType());
17661 
17662     SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts);
17663     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL,
17664                               ConcatVT.getVectorElementType(),
17665                               ConcatOp, NewIdx);
17666     return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt);
17667   }
17668 
17669   // Make sure we found a non-volatile load and the extractelement is
17670   // the only use.
17671   if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple())
17672     return SDValue();
17673 
17674   // If Idx was -1 above, Elt is going to be -1, so just return undef.
17675   if (Elt == -1)
17676     return DAG.getUNDEF(LVT);
17677 
17678   return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0);
17679 }
17680 
17681 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
17682 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
17683   // We perform this optimization post type-legalization because
17684   // the type-legalizer often scalarizes integer-promoted vectors.
17685   // Performing this optimization before may create bit-casts which
17686   // will be type-legalized to complex code sequences.
17687   // We perform this optimization only before the operation legalizer because we
17688   // may introduce illegal operations.
17689   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
17690     return SDValue();
17691 
17692   unsigned NumInScalars = N->getNumOperands();
17693   SDLoc DL(N);
17694   EVT VT = N->getValueType(0);
17695 
17696   // Check to see if this is a BUILD_VECTOR of a bunch of values
17697   // which come from any_extend or zero_extend nodes. If so, we can create
17698   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
17699   // optimizations. We do not handle sign-extend because we can't fill the sign
17700   // using shuffles.
17701   EVT SourceType = MVT::Other;
17702   bool AllAnyExt = true;
17703 
17704   for (unsigned i = 0; i != NumInScalars; ++i) {
17705     SDValue In = N->getOperand(i);
17706     // Ignore undef inputs.
17707     if (In.isUndef()) continue;
17708 
17709     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
17710     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
17711 
17712     // Abort if the element is not an extension.
17713     if (!ZeroExt && !AnyExt) {
17714       SourceType = MVT::Other;
17715       break;
17716     }
17717 
17718     // The input is a ZeroExt or AnyExt. Check the original type.
17719     EVT InTy = In.getOperand(0).getValueType();
17720 
17721     // Check that all of the widened source types are the same.
17722     if (SourceType == MVT::Other)
17723       // First time.
17724       SourceType = InTy;
17725     else if (InTy != SourceType) {
17726       // Multiple income types. Abort.
17727       SourceType = MVT::Other;
17728       break;
17729     }
17730 
17731     // Check if all of the extends are ANY_EXTENDs.
17732     AllAnyExt &= AnyExt;
17733   }
17734 
17735   // In order to have valid types, all of the inputs must be extended from the
17736   // same source type and all of the inputs must be any or zero extend.
17737   // Scalar sizes must be a power of two.
17738   EVT OutScalarTy = VT.getScalarType();
17739   bool ValidTypes = SourceType != MVT::Other &&
17740                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
17741                  isPowerOf2_32(SourceType.getSizeInBits());
17742 
17743   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
17744   // turn into a single shuffle instruction.
17745   if (!ValidTypes)
17746     return SDValue();
17747 
17748   bool isLE = DAG.getDataLayout().isLittleEndian();
17749   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
17750   assert(ElemRatio > 1 && "Invalid element size ratio");
17751   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
17752                                DAG.getConstant(0, DL, SourceType);
17753 
17754   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
17755   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
17756 
17757   // Populate the new build_vector
17758   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
17759     SDValue Cast = N->getOperand(i);
17760     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
17761             Cast.getOpcode() == ISD::ZERO_EXTEND ||
17762             Cast.isUndef()) && "Invalid cast opcode");
17763     SDValue In;
17764     if (Cast.isUndef())
17765       In = DAG.getUNDEF(SourceType);
17766     else
17767       In = Cast->getOperand(0);
17768     unsigned Index = isLE ? (i * ElemRatio) :
17769                             (i * ElemRatio + (ElemRatio - 1));
17770 
17771     assert(Index < Ops.size() && "Invalid index");
17772     Ops[Index] = In;
17773   }
17774 
17775   // The type of the new BUILD_VECTOR node.
17776   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
17777   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
17778          "Invalid vector size");
17779   // Check if the new vector type is legal.
17780   if (!isTypeLegal(VecVT) ||
17781       (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) &&
17782        TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)))
17783     return SDValue();
17784 
17785   // Make the new BUILD_VECTOR.
17786   SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
17787 
17788   // The new BUILD_VECTOR node has the potential to be further optimized.
17789   AddToWorklist(BV.getNode());
17790   // Bitcast to the desired type.
17791   return DAG.getBitcast(VT, BV);
17792 }
17793 
17794 // Simplify (build_vec (trunc $1)
17795 //                     (trunc (srl $1 half-width))
17796 //                     (trunc (srl $1 (2 * half-width))) …)
17797 // to (bitcast $1)
17798 SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) {
17799   assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
17800 
17801   // Only for little endian
17802   if (!DAG.getDataLayout().isLittleEndian())
17803     return SDValue();
17804 
17805   SDLoc DL(N);
17806   EVT VT = N->getValueType(0);
17807   EVT OutScalarTy = VT.getScalarType();
17808   uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits();
17809 
17810   // Only for power of two types to be sure that bitcast works well
17811   if (!isPowerOf2_64(ScalarTypeBitsize))
17812     return SDValue();
17813 
17814   unsigned NumInScalars = N->getNumOperands();
17815 
17816   // Look through bitcasts
17817   auto PeekThroughBitcast = [](SDValue Op) {
17818     if (Op.getOpcode() == ISD::BITCAST)
17819       return Op.getOperand(0);
17820     return Op;
17821   };
17822 
17823   // The source value where all the parts are extracted.
17824   SDValue Src;
17825   for (unsigned i = 0; i != NumInScalars; ++i) {
17826     SDValue In = PeekThroughBitcast(N->getOperand(i));
17827     // Ignore undef inputs.
17828     if (In.isUndef()) continue;
17829 
17830     if (In.getOpcode() != ISD::TRUNCATE)
17831       return SDValue();
17832 
17833     In = PeekThroughBitcast(In.getOperand(0));
17834 
17835     if (In.getOpcode() != ISD::SRL) {
17836       // For now only build_vec without shuffling, handle shifts here in the
17837       // future.
17838       if (i != 0)
17839         return SDValue();
17840 
17841       Src = In;
17842     } else {
17843       // In is SRL
17844       SDValue part = PeekThroughBitcast(In.getOperand(0));
17845 
17846       if (!Src) {
17847         Src = part;
17848       } else if (Src != part) {
17849         // Vector parts do not stem from the same variable
17850         return SDValue();
17851       }
17852 
17853       SDValue ShiftAmtVal = In.getOperand(1);
17854       if (!isa<ConstantSDNode>(ShiftAmtVal))
17855         return SDValue();
17856 
17857       uint64_t ShiftAmt = In.getNode()->getConstantOperandVal(1);
17858 
17859       // The extracted value is not extracted at the right position
17860       if (ShiftAmt != i * ScalarTypeBitsize)
17861         return SDValue();
17862     }
17863   }
17864 
17865   // Only cast if the size is the same
17866   if (Src.getValueType().getSizeInBits() != VT.getSizeInBits())
17867     return SDValue();
17868 
17869   return DAG.getBitcast(VT, Src);
17870 }
17871 
17872 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
17873                                            ArrayRef<int> VectorMask,
17874                                            SDValue VecIn1, SDValue VecIn2,
17875                                            unsigned LeftIdx, bool DidSplitVec) {
17876   SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
17877 
17878   EVT VT = N->getValueType(0);
17879   EVT InVT1 = VecIn1.getValueType();
17880   EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
17881 
17882   unsigned NumElems = VT.getVectorNumElements();
17883   unsigned ShuffleNumElems = NumElems;
17884 
17885   // If we artificially split a vector in two already, then the offsets in the
17886   // operands will all be based off of VecIn1, even those in VecIn2.
17887   unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements();
17888 
17889   // We can't generate a shuffle node with mismatched input and output types.
17890   // Try to make the types match the type of the output.
17891   if (InVT1 != VT || InVT2 != VT) {
17892     if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
17893       // If the output vector length is a multiple of both input lengths,
17894       // we can concatenate them and pad the rest with undefs.
17895       unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
17896       assert(NumConcats >= 2 && "Concat needs at least two inputs!");
17897       SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
17898       ConcatOps[0] = VecIn1;
17899       ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
17900       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
17901       VecIn2 = SDValue();
17902     } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
17903       if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
17904         return SDValue();
17905 
17906       if (!VecIn2.getNode()) {
17907         // If we only have one input vector, and it's twice the size of the
17908         // output, split it in two.
17909         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
17910                              DAG.getVectorIdxConstant(NumElems, DL));
17911         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
17912         // Since we now have shorter input vectors, adjust the offset of the
17913         // second vector's start.
17914         Vec2Offset = NumElems;
17915       } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
17916         // VecIn1 is wider than the output, and we have another, possibly
17917         // smaller input. Pad the smaller input with undefs, shuffle at the
17918         // input vector width, and extract the output.
17919         // The shuffle type is different than VT, so check legality again.
17920         if (LegalOperations &&
17921             !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
17922           return SDValue();
17923 
17924         // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
17925         // lower it back into a BUILD_VECTOR. So if the inserted type is
17926         // illegal, don't even try.
17927         if (InVT1 != InVT2) {
17928           if (!TLI.isTypeLegal(InVT2))
17929             return SDValue();
17930           VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
17931                                DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
17932         }
17933         ShuffleNumElems = NumElems * 2;
17934       } else {
17935         // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
17936         // than VecIn1. We can't handle this for now - this case will disappear
17937         // when we start sorting the vectors by type.
17938         return SDValue();
17939       }
17940     } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
17941                InVT1.getSizeInBits() == VT.getSizeInBits()) {
17942       SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
17943       ConcatOps[0] = VecIn2;
17944       VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
17945     } else {
17946       // TODO: Support cases where the length mismatch isn't exactly by a
17947       // factor of 2.
17948       // TODO: Move this check upwards, so that if we have bad type
17949       // mismatches, we don't create any DAG nodes.
17950       return SDValue();
17951     }
17952   }
17953 
17954   // Initialize mask to undef.
17955   SmallVector<int, 8> Mask(ShuffleNumElems, -1);
17956 
17957   // Only need to run up to the number of elements actually used, not the
17958   // total number of elements in the shuffle - if we are shuffling a wider
17959   // vector, the high lanes should be set to undef.
17960   for (unsigned i = 0; i != NumElems; ++i) {
17961     if (VectorMask[i] <= 0)
17962       continue;
17963 
17964     unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
17965     if (VectorMask[i] == (int)LeftIdx) {
17966       Mask[i] = ExtIndex;
17967     } else if (VectorMask[i] == (int)LeftIdx + 1) {
17968       Mask[i] = Vec2Offset + ExtIndex;
17969     }
17970   }
17971 
17972   // The type the input vectors may have changed above.
17973   InVT1 = VecIn1.getValueType();
17974 
17975   // If we already have a VecIn2, it should have the same type as VecIn1.
17976   // If we don't, get an undef/zero vector of the appropriate type.
17977   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
17978   assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
17979 
17980   SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
17981   if (ShuffleNumElems > NumElems)
17982     Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
17983 
17984   return Shuffle;
17985 }
17986 
17987 static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) {
17988   assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
17989 
17990   // First, determine where the build vector is not undef.
17991   // TODO: We could extend this to handle zero elements as well as undefs.
17992   int NumBVOps = BV->getNumOperands();
17993   int ZextElt = -1;
17994   for (int i = 0; i != NumBVOps; ++i) {
17995     SDValue Op = BV->getOperand(i);
17996     if (Op.isUndef())
17997       continue;
17998     if (ZextElt == -1)
17999       ZextElt = i;
18000     else
18001       return SDValue();
18002   }
18003   // Bail out if there's no non-undef element.
18004   if (ZextElt == -1)
18005     return SDValue();
18006 
18007   // The build vector contains some number of undef elements and exactly
18008   // one other element. That other element must be a zero-extended scalar
18009   // extracted from a vector at a constant index to turn this into a shuffle.
18010   // Also, require that the build vector does not implicitly truncate/extend
18011   // its elements.
18012   // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
18013   EVT VT = BV->getValueType(0);
18014   SDValue Zext = BV->getOperand(ZextElt);
18015   if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() ||
18016       Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18017       !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) ||
18018       Zext.getValueSizeInBits() != VT.getScalarSizeInBits())
18019     return SDValue();
18020 
18021   // The zero-extend must be a multiple of the source size, and we must be
18022   // building a vector of the same size as the source of the extract element.
18023   SDValue Extract = Zext.getOperand(0);
18024   unsigned DestSize = Zext.getValueSizeInBits();
18025   unsigned SrcSize = Extract.getValueSizeInBits();
18026   if (DestSize % SrcSize != 0 ||
18027       Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits())
18028     return SDValue();
18029 
18030   // Create a shuffle mask that will combine the extracted element with zeros
18031   // and undefs.
18032   int ZextRatio = DestSize / SrcSize;
18033   int NumMaskElts = NumBVOps * ZextRatio;
18034   SmallVector<int, 32> ShufMask(NumMaskElts, -1);
18035   for (int i = 0; i != NumMaskElts; ++i) {
18036     if (i / ZextRatio == ZextElt) {
18037       // The low bits of the (potentially translated) extracted element map to
18038       // the source vector. The high bits map to zero. We will use a zero vector
18039       // as the 2nd source operand of the shuffle, so use the 1st element of
18040       // that vector (mask value is number-of-elements) for the high bits.
18041       if (i % ZextRatio == 0)
18042         ShufMask[i] = Extract.getConstantOperandVal(1);
18043       else
18044         ShufMask[i] = NumMaskElts;
18045     }
18046 
18047     // Undef elements of the build vector remain undef because we initialize
18048     // the shuffle mask with -1.
18049   }
18050 
18051   // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
18052   // bitcast (shuffle V, ZeroVec, VectorMask)
18053   SDLoc DL(BV);
18054   EVT VecVT = Extract.getOperand(0).getValueType();
18055   SDValue ZeroVec = DAG.getConstant(0, DL, VecVT);
18056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18057   SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0),
18058                                              ZeroVec, ShufMask, DAG);
18059   if (!Shuf)
18060     return SDValue();
18061   return DAG.getBitcast(VT, Shuf);
18062 }
18063 
18064 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
18065 // operations. If the types of the vectors we're extracting from allow it,
18066 // turn this into a vector_shuffle node.
18067 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
18068   SDLoc DL(N);
18069   EVT VT = N->getValueType(0);
18070 
18071   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
18072   if (!isTypeLegal(VT))
18073     return SDValue();
18074 
18075   if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG))
18076     return V;
18077 
18078   // May only combine to shuffle after legalize if shuffle is legal.
18079   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
18080     return SDValue();
18081 
18082   bool UsesZeroVector = false;
18083   unsigned NumElems = N->getNumOperands();
18084 
18085   // Record, for each element of the newly built vector, which input vector
18086   // that element comes from. -1 stands for undef, 0 for the zero vector,
18087   // and positive values for the input vectors.
18088   // VectorMask maps each element to its vector number, and VecIn maps vector
18089   // numbers to their initial SDValues.
18090 
18091   SmallVector<int, 8> VectorMask(NumElems, -1);
18092   SmallVector<SDValue, 8> VecIn;
18093   VecIn.push_back(SDValue());
18094 
18095   for (unsigned i = 0; i != NumElems; ++i) {
18096     SDValue Op = N->getOperand(i);
18097 
18098     if (Op.isUndef())
18099       continue;
18100 
18101     // See if we can use a blend with a zero vector.
18102     // TODO: Should we generalize this to a blend with an arbitrary constant
18103     // vector?
18104     if (isNullConstant(Op) || isNullFPConstant(Op)) {
18105       UsesZeroVector = true;
18106       VectorMask[i] = 0;
18107       continue;
18108     }
18109 
18110     // Not an undef or zero. If the input is something other than an
18111     // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
18112     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18113         !isa<ConstantSDNode>(Op.getOperand(1)))
18114       return SDValue();
18115     SDValue ExtractedFromVec = Op.getOperand(0);
18116 
18117     const APInt &ExtractIdx = Op.getConstantOperandAPInt(1);
18118     if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
18119       return SDValue();
18120 
18121     // All inputs must have the same element type as the output.
18122     if (VT.getVectorElementType() !=
18123         ExtractedFromVec.getValueType().getVectorElementType())
18124       return SDValue();
18125 
18126     // Have we seen this input vector before?
18127     // The vectors are expected to be tiny (usually 1 or 2 elements), so using
18128     // a map back from SDValues to numbers isn't worth it.
18129     unsigned Idx = std::distance(
18130         VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
18131     if (Idx == VecIn.size())
18132       VecIn.push_back(ExtractedFromVec);
18133 
18134     VectorMask[i] = Idx;
18135   }
18136 
18137   // If we didn't find at least one input vector, bail out.
18138   if (VecIn.size() < 2)
18139     return SDValue();
18140 
18141   // If all the Operands of BUILD_VECTOR extract from same
18142   // vector, then split the vector efficiently based on the maximum
18143   // vector access index and adjust the VectorMask and
18144   // VecIn accordingly.
18145   bool DidSplitVec = false;
18146   if (VecIn.size() == 2) {
18147     unsigned MaxIndex = 0;
18148     unsigned NearestPow2 = 0;
18149     SDValue Vec = VecIn.back();
18150     EVT InVT = Vec.getValueType();
18151     SmallVector<unsigned, 8> IndexVec(NumElems, 0);
18152 
18153     for (unsigned i = 0; i < NumElems; i++) {
18154       if (VectorMask[i] <= 0)
18155         continue;
18156       unsigned Index = N->getOperand(i).getConstantOperandVal(1);
18157       IndexVec[i] = Index;
18158       MaxIndex = std::max(MaxIndex, Index);
18159     }
18160 
18161     NearestPow2 = PowerOf2Ceil(MaxIndex);
18162     if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
18163         NumElems * 2 < NearestPow2) {
18164       unsigned SplitSize = NearestPow2 / 2;
18165       EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
18166                                      InVT.getVectorElementType(), SplitSize);
18167       if (TLI.isTypeLegal(SplitVT)) {
18168         SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
18169                                      DAG.getVectorIdxConstant(SplitSize, DL));
18170         SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
18171                                      DAG.getVectorIdxConstant(0, DL));
18172         VecIn.pop_back();
18173         VecIn.push_back(VecIn1);
18174         VecIn.push_back(VecIn2);
18175         DidSplitVec = true;
18176 
18177         for (unsigned i = 0; i < NumElems; i++) {
18178           if (VectorMask[i] <= 0)
18179             continue;
18180           VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
18181         }
18182       }
18183     }
18184   }
18185 
18186   // TODO: We want to sort the vectors by descending length, so that adjacent
18187   // pairs have similar length, and the longer vector is always first in the
18188   // pair.
18189 
18190   // TODO: Should this fire if some of the input vectors has illegal type (like
18191   // it does now), or should we let legalization run its course first?
18192 
18193   // Shuffle phase:
18194   // Take pairs of vectors, and shuffle them so that the result has elements
18195   // from these vectors in the correct places.
18196   // For example, given:
18197   // t10: i32 = extract_vector_elt t1, Constant:i64<0>
18198   // t11: i32 = extract_vector_elt t2, Constant:i64<0>
18199   // t12: i32 = extract_vector_elt t3, Constant:i64<0>
18200   // t13: i32 = extract_vector_elt t1, Constant:i64<1>
18201   // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
18202   // We will generate:
18203   // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
18204   // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
18205   SmallVector<SDValue, 4> Shuffles;
18206   for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
18207     unsigned LeftIdx = 2 * In + 1;
18208     SDValue VecLeft = VecIn[LeftIdx];
18209     SDValue VecRight =
18210         (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
18211 
18212     if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
18213                                                 VecRight, LeftIdx, DidSplitVec))
18214       Shuffles.push_back(Shuffle);
18215     else
18216       return SDValue();
18217   }
18218 
18219   // If we need the zero vector as an "ingredient" in the blend tree, add it
18220   // to the list of shuffles.
18221   if (UsesZeroVector)
18222     Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
18223                                       : DAG.getConstantFP(0.0, DL, VT));
18224 
18225   // If we only have one shuffle, we're done.
18226   if (Shuffles.size() == 1)
18227     return Shuffles[0];
18228 
18229   // Update the vector mask to point to the post-shuffle vectors.
18230   for (int &Vec : VectorMask)
18231     if (Vec == 0)
18232       Vec = Shuffles.size() - 1;
18233     else
18234       Vec = (Vec - 1) / 2;
18235 
18236   // More than one shuffle. Generate a binary tree of blends, e.g. if from
18237   // the previous step we got the set of shuffles t10, t11, t12, t13, we will
18238   // generate:
18239   // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
18240   // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
18241   // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
18242   // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
18243   // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
18244   // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
18245   // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
18246 
18247   // Make sure the initial size of the shuffle list is even.
18248   if (Shuffles.size() % 2)
18249     Shuffles.push_back(DAG.getUNDEF(VT));
18250 
18251   for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
18252     if (CurSize % 2) {
18253       Shuffles[CurSize] = DAG.getUNDEF(VT);
18254       CurSize++;
18255     }
18256     for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
18257       int Left = 2 * In;
18258       int Right = 2 * In + 1;
18259       SmallVector<int, 8> Mask(NumElems, -1);
18260       for (unsigned i = 0; i != NumElems; ++i) {
18261         if (VectorMask[i] == Left) {
18262           Mask[i] = i;
18263           VectorMask[i] = In;
18264         } else if (VectorMask[i] == Right) {
18265           Mask[i] = i + NumElems;
18266           VectorMask[i] = In;
18267         }
18268       }
18269 
18270       Shuffles[In] =
18271           DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
18272     }
18273   }
18274   return Shuffles[0];
18275 }
18276 
18277 // Try to turn a build vector of zero extends of extract vector elts into a
18278 // a vector zero extend and possibly an extract subvector.
18279 // TODO: Support sign extend?
18280 // TODO: Allow undef elements?
18281 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
18282   if (LegalOperations)
18283     return SDValue();
18284 
18285   EVT VT = N->getValueType(0);
18286 
18287   bool FoundZeroExtend = false;
18288   SDValue Op0 = N->getOperand(0);
18289   auto checkElem = [&](SDValue Op) -> int64_t {
18290     unsigned Opc = Op.getOpcode();
18291     FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND);
18292     if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) &&
18293         Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
18294         Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
18295       if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
18296         return C->getZExtValue();
18297     return -1;
18298   };
18299 
18300   // Make sure the first element matches
18301   // (zext (extract_vector_elt X, C))
18302   int64_t Offset = checkElem(Op0);
18303   if (Offset < 0)
18304     return SDValue();
18305 
18306   unsigned NumElems = N->getNumOperands();
18307   SDValue In = Op0.getOperand(0).getOperand(0);
18308   EVT InSVT = In.getValueType().getScalarType();
18309   EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
18310 
18311   // Don't create an illegal input type after type legalization.
18312   if (LegalTypes && !TLI.isTypeLegal(InVT))
18313     return SDValue();
18314 
18315   // Ensure all the elements come from the same vector and are adjacent.
18316   for (unsigned i = 1; i != NumElems; ++i) {
18317     if ((Offset + i) != checkElem(N->getOperand(i)))
18318       return SDValue();
18319   }
18320 
18321   SDLoc DL(N);
18322   In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
18323                    Op0.getOperand(0).getOperand(1));
18324   return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL,
18325                      VT, In);
18326 }
18327 
18328 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
18329   EVT VT = N->getValueType(0);
18330 
18331   // A vector built entirely of undefs is undef.
18332   if (ISD::allOperandsUndef(N))
18333     return DAG.getUNDEF(VT);
18334 
18335   // If this is a splat of a bitcast from another vector, change to a
18336   // concat_vector.
18337   // For example:
18338   //   (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
18339   //     (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
18340   //
18341   // If X is a build_vector itself, the concat can become a larger build_vector.
18342   // TODO: Maybe this is useful for non-splat too?
18343   if (!LegalOperations) {
18344     if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
18345       Splat = peekThroughBitcasts(Splat);
18346       EVT SrcVT = Splat.getValueType();
18347       if (SrcVT.isVector()) {
18348         unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
18349         EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
18350                                      SrcVT.getVectorElementType(), NumElts);
18351         if (!LegalTypes || TLI.isTypeLegal(NewVT)) {
18352           SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
18353           SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N),
18354                                        NewVT, Ops);
18355           return DAG.getBitcast(VT, Concat);
18356         }
18357       }
18358     }
18359   }
18360 
18361   // A splat of a single element is a SPLAT_VECTOR if supported on the target.
18362   if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand)
18363     if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) {
18364       assert(!V.isUndef() && "Splat of undef should have been handled earlier");
18365       return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V);
18366     }
18367 
18368   // Check if we can express BUILD VECTOR via subvector extract.
18369   if (!LegalTypes && (N->getNumOperands() > 1)) {
18370     SDValue Op0 = N->getOperand(0);
18371     auto checkElem = [&](SDValue Op) -> uint64_t {
18372       if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
18373           (Op0.getOperand(0) == Op.getOperand(0)))
18374         if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
18375           return CNode->getZExtValue();
18376       return -1;
18377     };
18378 
18379     int Offset = checkElem(Op0);
18380     for (unsigned i = 0; i < N->getNumOperands(); ++i) {
18381       if (Offset + i != checkElem(N->getOperand(i))) {
18382         Offset = -1;
18383         break;
18384       }
18385     }
18386 
18387     if ((Offset == 0) &&
18388         (Op0.getOperand(0).getValueType() == N->getValueType(0)))
18389       return Op0.getOperand(0);
18390     if ((Offset != -1) &&
18391         ((Offset % N->getValueType(0).getVectorNumElements()) ==
18392          0)) // IDX must be multiple of output size.
18393       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
18394                          Op0.getOperand(0), Op0.getOperand(1));
18395   }
18396 
18397   if (SDValue V = convertBuildVecZextToZext(N))
18398     return V;
18399 
18400   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
18401     return V;
18402 
18403   if (SDValue V = reduceBuildVecTruncToBitCast(N))
18404     return V;
18405 
18406   if (SDValue V = reduceBuildVecToShuffle(N))
18407     return V;
18408 
18409   return SDValue();
18410 }
18411 
18412 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
18413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18414   EVT OpVT = N->getOperand(0).getValueType();
18415 
18416   // If the operands are legal vectors, leave them alone.
18417   if (TLI.isTypeLegal(OpVT))
18418     return SDValue();
18419 
18420   SDLoc DL(N);
18421   EVT VT = N->getValueType(0);
18422   SmallVector<SDValue, 8> Ops;
18423 
18424   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
18425   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
18426 
18427   // Keep track of what we encounter.
18428   bool AnyInteger = false;
18429   bool AnyFP = false;
18430   for (const SDValue &Op : N->ops()) {
18431     if (ISD::BITCAST == Op.getOpcode() &&
18432         !Op.getOperand(0).getValueType().isVector())
18433       Ops.push_back(Op.getOperand(0));
18434     else if (ISD::UNDEF == Op.getOpcode())
18435       Ops.push_back(ScalarUndef);
18436     else
18437       return SDValue();
18438 
18439     // Note whether we encounter an integer or floating point scalar.
18440     // If it's neither, bail out, it could be something weird like x86mmx.
18441     EVT LastOpVT = Ops.back().getValueType();
18442     if (LastOpVT.isFloatingPoint())
18443       AnyFP = true;
18444     else if (LastOpVT.isInteger())
18445       AnyInteger = true;
18446     else
18447       return SDValue();
18448   }
18449 
18450   // If any of the operands is a floating point scalar bitcast to a vector,
18451   // use floating point types throughout, and bitcast everything.
18452   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
18453   if (AnyFP) {
18454     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
18455     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
18456     if (AnyInteger) {
18457       for (SDValue &Op : Ops) {
18458         if (Op.getValueType() == SVT)
18459           continue;
18460         if (Op.isUndef())
18461           Op = ScalarUndef;
18462         else
18463           Op = DAG.getBitcast(SVT, Op);
18464       }
18465     }
18466   }
18467 
18468   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
18469                                VT.getSizeInBits() / SVT.getSizeInBits());
18470   return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
18471 }
18472 
18473 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
18474 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
18475 // most two distinct vectors the same size as the result, attempt to turn this
18476 // into a legal shuffle.
18477 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
18478   EVT VT = N->getValueType(0);
18479   EVT OpVT = N->getOperand(0).getValueType();
18480   int NumElts = VT.getVectorNumElements();
18481   int NumOpElts = OpVT.getVectorNumElements();
18482 
18483   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
18484   SmallVector<int, 8> Mask;
18485 
18486   for (SDValue Op : N->ops()) {
18487     Op = peekThroughBitcasts(Op);
18488 
18489     // UNDEF nodes convert to UNDEF shuffle mask values.
18490     if (Op.isUndef()) {
18491       Mask.append((unsigned)NumOpElts, -1);
18492       continue;
18493     }
18494 
18495     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
18496       return SDValue();
18497 
18498     // What vector are we extracting the subvector from and at what index?
18499     SDValue ExtVec = Op.getOperand(0);
18500     int ExtIdx = Op.getConstantOperandVal(1);
18501 
18502     // We want the EVT of the original extraction to correctly scale the
18503     // extraction index.
18504     EVT ExtVT = ExtVec.getValueType();
18505     ExtVec = peekThroughBitcasts(ExtVec);
18506 
18507     // UNDEF nodes convert to UNDEF shuffle mask values.
18508     if (ExtVec.isUndef()) {
18509       Mask.append((unsigned)NumOpElts, -1);
18510       continue;
18511     }
18512 
18513     // Ensure that we are extracting a subvector from a vector the same
18514     // size as the result.
18515     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
18516       return SDValue();
18517 
18518     // Scale the subvector index to account for any bitcast.
18519     int NumExtElts = ExtVT.getVectorNumElements();
18520     if (0 == (NumExtElts % NumElts))
18521       ExtIdx /= (NumExtElts / NumElts);
18522     else if (0 == (NumElts % NumExtElts))
18523       ExtIdx *= (NumElts / NumExtElts);
18524     else
18525       return SDValue();
18526 
18527     // At most we can reference 2 inputs in the final shuffle.
18528     if (SV0.isUndef() || SV0 == ExtVec) {
18529       SV0 = ExtVec;
18530       for (int i = 0; i != NumOpElts; ++i)
18531         Mask.push_back(i + ExtIdx);
18532     } else if (SV1.isUndef() || SV1 == ExtVec) {
18533       SV1 = ExtVec;
18534       for (int i = 0; i != NumOpElts; ++i)
18535         Mask.push_back(i + ExtIdx + NumElts);
18536     } else {
18537       return SDValue();
18538     }
18539   }
18540 
18541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18542   return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
18543                                      DAG.getBitcast(VT, SV1), Mask, DAG);
18544 }
18545 
18546 static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) {
18547   unsigned CastOpcode = N->getOperand(0).getOpcode();
18548   switch (CastOpcode) {
18549   case ISD::SINT_TO_FP:
18550   case ISD::UINT_TO_FP:
18551   case ISD::FP_TO_SINT:
18552   case ISD::FP_TO_UINT:
18553     // TODO: Allow more opcodes?
18554     //  case ISD::BITCAST:
18555     //  case ISD::TRUNCATE:
18556     //  case ISD::ZERO_EXTEND:
18557     //  case ISD::SIGN_EXTEND:
18558     //  case ISD::FP_EXTEND:
18559     break;
18560   default:
18561     return SDValue();
18562   }
18563 
18564   EVT SrcVT = N->getOperand(0).getOperand(0).getValueType();
18565   if (!SrcVT.isVector())
18566     return SDValue();
18567 
18568   // All operands of the concat must be the same kind of cast from the same
18569   // source type.
18570   SmallVector<SDValue, 4> SrcOps;
18571   for (SDValue Op : N->ops()) {
18572     if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() ||
18573         Op.getOperand(0).getValueType() != SrcVT)
18574       return SDValue();
18575     SrcOps.push_back(Op.getOperand(0));
18576   }
18577 
18578   // The wider cast must be supported by the target. This is unusual because
18579   // the operation support type parameter depends on the opcode. In addition,
18580   // check the other type in the cast to make sure this is really legal.
18581   EVT VT = N->getValueType(0);
18582   EVT SrcEltVT = SrcVT.getVectorElementType();
18583   unsigned NumElts = SrcVT.getVectorElementCount().Min * N->getNumOperands();
18584   EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts);
18585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18586   switch (CastOpcode) {
18587   case ISD::SINT_TO_FP:
18588   case ISD::UINT_TO_FP:
18589     if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) ||
18590         !TLI.isTypeLegal(VT))
18591       return SDValue();
18592     break;
18593   case ISD::FP_TO_SINT:
18594   case ISD::FP_TO_UINT:
18595     if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) ||
18596         !TLI.isTypeLegal(ConcatSrcVT))
18597       return SDValue();
18598     break;
18599   default:
18600     llvm_unreachable("Unexpected cast opcode");
18601   }
18602 
18603   // concat (cast X), (cast Y)... -> cast (concat X, Y...)
18604   SDLoc DL(N);
18605   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps);
18606   return DAG.getNode(CastOpcode, DL, VT, NewConcat);
18607 }
18608 
18609 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
18610   // If we only have one input vector, we don't need to do any concatenation.
18611   if (N->getNumOperands() == 1)
18612     return N->getOperand(0);
18613 
18614   // Check if all of the operands are undefs.
18615   EVT VT = N->getValueType(0);
18616   if (ISD::allOperandsUndef(N))
18617     return DAG.getUNDEF(VT);
18618 
18619   // Optimize concat_vectors where all but the first of the vectors are undef.
18620   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
18621         return Op.isUndef();
18622       })) {
18623     SDValue In = N->getOperand(0);
18624     assert(In.getValueType().isVector() && "Must concat vectors");
18625 
18626     // If the input is a concat_vectors, just make a larger concat by padding
18627     // with smaller undefs.
18628     if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) {
18629       unsigned NumOps = N->getNumOperands() * In.getNumOperands();
18630       SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end());
18631       Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType()));
18632       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
18633     }
18634 
18635     SDValue Scalar = peekThroughOneUseBitcasts(In);
18636 
18637     // concat_vectors(scalar_to_vector(scalar), undef) ->
18638     //     scalar_to_vector(scalar)
18639     if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR &&
18640          Scalar.hasOneUse()) {
18641       EVT SVT = Scalar.getValueType().getVectorElementType();
18642       if (SVT == Scalar.getOperand(0).getValueType())
18643         Scalar = Scalar.getOperand(0);
18644     }
18645 
18646     // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
18647     if (!Scalar.getValueType().isVector()) {
18648       // If the bitcast type isn't legal, it might be a trunc of a legal type;
18649       // look through the trunc so we can still do the transform:
18650       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
18651       if (Scalar->getOpcode() == ISD::TRUNCATE &&
18652           !TLI.isTypeLegal(Scalar.getValueType()) &&
18653           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
18654         Scalar = Scalar->getOperand(0);
18655 
18656       EVT SclTy = Scalar.getValueType();
18657 
18658       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
18659         return SDValue();
18660 
18661       // Bail out if the vector size is not a multiple of the scalar size.
18662       if (VT.getSizeInBits() % SclTy.getSizeInBits())
18663         return SDValue();
18664 
18665       unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
18666       if (VNTNumElms < 2)
18667         return SDValue();
18668 
18669       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
18670       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
18671         return SDValue();
18672 
18673       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
18674       return DAG.getBitcast(VT, Res);
18675     }
18676   }
18677 
18678   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
18679   // We have already tested above for an UNDEF only concatenation.
18680   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
18681   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
18682   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
18683     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
18684   };
18685   if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
18686     SmallVector<SDValue, 8> Opnds;
18687     EVT SVT = VT.getScalarType();
18688 
18689     EVT MinVT = SVT;
18690     if (!SVT.isFloatingPoint()) {
18691       // If BUILD_VECTOR are from built from integer, they may have different
18692       // operand types. Get the smallest type and truncate all operands to it.
18693       bool FoundMinVT = false;
18694       for (const SDValue &Op : N->ops())
18695         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
18696           EVT OpSVT = Op.getOperand(0).getValueType();
18697           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
18698           FoundMinVT = true;
18699         }
18700       assert(FoundMinVT && "Concat vector type mismatch");
18701     }
18702 
18703     for (const SDValue &Op : N->ops()) {
18704       EVT OpVT = Op.getValueType();
18705       unsigned NumElts = OpVT.getVectorNumElements();
18706 
18707       if (ISD::UNDEF == Op.getOpcode())
18708         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
18709 
18710       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
18711         if (SVT.isFloatingPoint()) {
18712           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
18713           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
18714         } else {
18715           for (unsigned i = 0; i != NumElts; ++i)
18716             Opnds.push_back(
18717                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
18718         }
18719       }
18720     }
18721 
18722     assert(VT.getVectorNumElements() == Opnds.size() &&
18723            "Concat vector type mismatch");
18724     return DAG.getBuildVector(VT, SDLoc(N), Opnds);
18725   }
18726 
18727   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
18728   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
18729     return V;
18730 
18731   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
18732   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
18733     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
18734       return V;
18735 
18736   if (SDValue V = combineConcatVectorOfCasts(N, DAG))
18737     return V;
18738 
18739   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
18740   // nodes often generate nop CONCAT_VECTOR nodes.
18741   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
18742   // place the incoming vectors at the exact same location.
18743   SDValue SingleSource = SDValue();
18744   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
18745 
18746   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
18747     SDValue Op = N->getOperand(i);
18748 
18749     if (Op.isUndef())
18750       continue;
18751 
18752     // Check if this is the identity extract:
18753     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
18754       return SDValue();
18755 
18756     // Find the single incoming vector for the extract_subvector.
18757     if (SingleSource.getNode()) {
18758       if (Op.getOperand(0) != SingleSource)
18759         return SDValue();
18760     } else {
18761       SingleSource = Op.getOperand(0);
18762 
18763       // Check the source type is the same as the type of the result.
18764       // If not, this concat may extend the vector, so we can not
18765       // optimize it away.
18766       if (SingleSource.getValueType() != N->getValueType(0))
18767         return SDValue();
18768     }
18769 
18770     // Check that we are reading from the identity index.
18771     unsigned IdentityIndex = i * PartNumElem;
18772     if (Op.getConstantOperandAPInt(1) != IdentityIndex)
18773       return SDValue();
18774   }
18775 
18776   if (SingleSource.getNode())
18777     return SingleSource;
18778 
18779   return SDValue();
18780 }
18781 
18782 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
18783 // if the subvector can be sourced for free.
18784 static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) {
18785   if (V.getOpcode() == ISD::INSERT_SUBVECTOR &&
18786       V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) {
18787     return V.getOperand(1);
18788   }
18789   auto *IndexC = dyn_cast<ConstantSDNode>(Index);
18790   if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS &&
18791       V.getOperand(0).getValueType() == SubVT &&
18792       (IndexC->getZExtValue() % SubVT.getVectorNumElements()) == 0) {
18793     uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorNumElements();
18794     return V.getOperand(SubIdx);
18795   }
18796   return SDValue();
18797 }
18798 
18799 static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract,
18800                                               SelectionDAG &DAG) {
18801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18802   SDValue BinOp = Extract->getOperand(0);
18803   unsigned BinOpcode = BinOp.getOpcode();
18804   if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1)
18805     return SDValue();
18806 
18807   EVT VecVT = BinOp.getValueType();
18808   SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1);
18809   if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType())
18810     return SDValue();
18811 
18812   SDValue Index = Extract->getOperand(1);
18813   EVT SubVT = Extract->getValueType(0);
18814   if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT))
18815     return SDValue();
18816 
18817   SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT);
18818   SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT);
18819 
18820   // TODO: We could handle the case where only 1 operand is being inserted by
18821   //       creating an extract of the other operand, but that requires checking
18822   //       number of uses and/or costs.
18823   if (!Sub0 || !Sub1)
18824     return SDValue();
18825 
18826   // We are inserting both operands of the wide binop only to extract back
18827   // to the narrow vector size. Eliminate all of the insert/extract:
18828   // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
18829   return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1,
18830                      BinOp->getFlags());
18831 }
18832 
18833 /// If we are extracting a subvector produced by a wide binary operator try
18834 /// to use a narrow binary operator and/or avoid concatenation and extraction.
18835 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
18836   // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
18837   // some of these bailouts with other transforms.
18838 
18839   if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG))
18840     return V;
18841 
18842   // The extract index must be a constant, so we can map it to a concat operand.
18843   auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
18844   if (!ExtractIndexC)
18845     return SDValue();
18846 
18847   // We are looking for an optionally bitcasted wide vector binary operator
18848   // feeding an extract subvector.
18849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18850   SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0));
18851   unsigned BOpcode = BinOp.getOpcode();
18852   if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1)
18853     return SDValue();
18854 
18855   // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be
18856   // reduced to the unary fneg when it is visited, and we probably want to deal
18857   // with fneg in a target-specific way.
18858   if (BOpcode == ISD::FSUB) {
18859     auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true);
18860     if (C && C->getValueAPF().isNegZero())
18861       return SDValue();
18862   }
18863 
18864   // The binop must be a vector type, so we can extract some fraction of it.
18865   EVT WideBVT = BinOp.getValueType();
18866   if (!WideBVT.isVector())
18867     return SDValue();
18868 
18869   EVT VT = Extract->getValueType(0);
18870   unsigned ExtractIndex = ExtractIndexC->getZExtValue();
18871   assert(ExtractIndex % VT.getVectorNumElements() == 0 &&
18872          "Extract index is not a multiple of the vector length.");
18873 
18874   // Bail out if this is not a proper multiple width extraction.
18875   unsigned WideWidth = WideBVT.getSizeInBits();
18876   unsigned NarrowWidth = VT.getSizeInBits();
18877   if (WideWidth % NarrowWidth != 0)
18878     return SDValue();
18879 
18880   // Bail out if we are extracting a fraction of a single operation. This can
18881   // occur because we potentially looked through a bitcast of the binop.
18882   unsigned NarrowingRatio = WideWidth / NarrowWidth;
18883   unsigned WideNumElts = WideBVT.getVectorNumElements();
18884   if (WideNumElts % NarrowingRatio != 0)
18885     return SDValue();
18886 
18887   // Bail out if the target does not support a narrower version of the binop.
18888   EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
18889                                    WideNumElts / NarrowingRatio);
18890   if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
18891     return SDValue();
18892 
18893   // If extraction is cheap, we don't need to look at the binop operands
18894   // for concat ops. The narrow binop alone makes this transform profitable.
18895   // We can't just reuse the original extract index operand because we may have
18896   // bitcasted.
18897   unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements();
18898   unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
18899   if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) &&
18900       BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) {
18901     // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
18902     SDLoc DL(Extract);
18903     SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL);
18904     SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18905                             BinOp.getOperand(0), NewExtIndex);
18906     SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18907                             BinOp.getOperand(1), NewExtIndex);
18908     SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y,
18909                                       BinOp.getNode()->getFlags());
18910     return DAG.getBitcast(VT, NarrowBinOp);
18911   }
18912 
18913   // Only handle the case where we are doubling and then halving. A larger ratio
18914   // may require more than two narrow binops to replace the wide binop.
18915   if (NarrowingRatio != 2)
18916     return SDValue();
18917 
18918   // TODO: The motivating case for this transform is an x86 AVX1 target. That
18919   // target has temptingly almost legal versions of bitwise logic ops in 256-bit
18920   // flavors, but no other 256-bit integer support. This could be extended to
18921   // handle any binop, but that may require fixing/adding other folds to avoid
18922   // codegen regressions.
18923   if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
18924     return SDValue();
18925 
18926   // We need at least one concatenation operation of a binop operand to make
18927   // this transform worthwhile. The concat must double the input vector sizes.
18928   auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue {
18929     if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2)
18930       return V.getOperand(ConcatOpNum);
18931     return SDValue();
18932   };
18933   SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0)));
18934   SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1)));
18935 
18936   if (SubVecL || SubVecR) {
18937     // If a binop operand was not the result of a concat, we must extract a
18938     // half-sized operand for our new narrow binop:
18939     // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
18940     // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
18941     // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
18942     SDLoc DL(Extract);
18943     SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL);
18944     SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL)
18945                         : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18946                                       BinOp.getOperand(0), IndexC);
18947 
18948     SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR)
18949                         : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
18950                                       BinOp.getOperand(1), IndexC);
18951 
18952     SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
18953     return DAG.getBitcast(VT, NarrowBinOp);
18954   }
18955 
18956   return SDValue();
18957 }
18958 
18959 /// If we are extracting a subvector from a wide vector load, convert to a
18960 /// narrow load to eliminate the extraction:
18961 /// (extract_subvector (load wide vector)) --> (load narrow vector)
18962 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
18963   // TODO: Add support for big-endian. The offset calculation must be adjusted.
18964   if (DAG.getDataLayout().isBigEndian())
18965     return SDValue();
18966 
18967   auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
18968   auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
18969   if (!Ld || Ld->getExtensionType() || !Ld->isSimple() ||
18970       !ExtIdx)
18971     return SDValue();
18972 
18973   // Allow targets to opt-out.
18974   EVT VT = Extract->getValueType(0);
18975 
18976   // We can only create byte sized loads.
18977   if (!VT.isByteSized())
18978     return SDValue();
18979 
18980   unsigned Index = ExtIdx->getZExtValue();
18981   unsigned NumElts = VT.getVectorNumElements();
18982 
18983   // If the index is a multiple of the extract element count, we can offset the
18984   // address by the store size multiplied by the subvector index. Otherwise if
18985   // the scalar type is byte sized, we can just use the index multiplied by
18986   // the element size in bytes as the offset.
18987   unsigned Offset;
18988   if (Index % NumElts == 0)
18989     Offset = (Index / NumElts) * VT.getStoreSize();
18990   else if (VT.getScalarType().isByteSized())
18991     Offset = Index * VT.getScalarType().getStoreSize();
18992   else
18993     return SDValue();
18994 
18995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18996   if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT))
18997     return SDValue();
18998 
18999   // The narrow load will be offset from the base address of the old load if
19000   // we are extracting from something besides index 0 (little-endian).
19001   SDLoc DL(Extract);
19002   SDValue BaseAddr = Ld->getBasePtr();
19003 
19004   // TODO: Use "BaseIndexOffset" to make this more effective.
19005   SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
19006   MachineFunction &MF = DAG.getMachineFunction();
19007   MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
19008                                                    VT.getStoreSize());
19009   SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
19010   DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
19011   return NewLd;
19012 }
19013 
19014 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) {
19015   EVT NVT = N->getValueType(0);
19016   SDValue V = N->getOperand(0);
19017   uint64_t ExtIdx = N->getConstantOperandVal(1);
19018 
19019   // Extract from UNDEF is UNDEF.
19020   if (V.isUndef())
19021     return DAG.getUNDEF(NVT);
19022 
19023   if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
19024     if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
19025       return NarrowLoad;
19026 
19027   // Combine an extract of an extract into a single extract_subvector.
19028   // ext (ext X, C), 0 --> ext X, C
19029   if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) {
19030     if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(),
19031                                     V.getConstantOperandVal(1)) &&
19032         TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) {
19033       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0),
19034                          V.getOperand(1));
19035     }
19036   }
19037 
19038   // Try to move vector bitcast after extract_subv by scaling extraction index:
19039   // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
19040   if (V.getOpcode() == ISD::BITCAST &&
19041       V.getOperand(0).getValueType().isVector()) {
19042     SDValue SrcOp = V.getOperand(0);
19043     EVT SrcVT = SrcOp.getValueType();
19044     unsigned SrcNumElts = SrcVT.getVectorNumElements();
19045     unsigned DestNumElts = V.getValueType().getVectorNumElements();
19046     if ((SrcNumElts % DestNumElts) == 0) {
19047       unsigned SrcDestRatio = SrcNumElts / DestNumElts;
19048       unsigned NewExtNumElts = NVT.getVectorNumElements() * SrcDestRatio;
19049       EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
19050                                       NewExtNumElts);
19051       if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
19052         SDLoc DL(N);
19053         SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL);
19054         SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
19055                                          V.getOperand(0), NewIndex);
19056         return DAG.getBitcast(NVT, NewExtract);
19057       }
19058     }
19059     if ((DestNumElts % SrcNumElts) == 0) {
19060       unsigned DestSrcRatio = DestNumElts / SrcNumElts;
19061       if ((NVT.getVectorNumElements() % DestSrcRatio) == 0) {
19062         unsigned NewExtNumElts = NVT.getVectorNumElements() / DestSrcRatio;
19063         EVT ScalarVT = SrcVT.getScalarType();
19064         if ((ExtIdx % DestSrcRatio) == 0) {
19065           SDLoc DL(N);
19066           unsigned IndexValScaled = ExtIdx / DestSrcRatio;
19067           EVT NewExtVT =
19068               EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtNumElts);
19069           if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
19070             SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
19071             SDValue NewExtract =
19072                 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
19073                             V.getOperand(0), NewIndex);
19074             return DAG.getBitcast(NVT, NewExtract);
19075           }
19076           if (NewExtNumElts == 1 &&
19077               TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) {
19078             SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
19079             SDValue NewExtract =
19080                 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT,
19081                             V.getOperand(0), NewIndex);
19082             return DAG.getBitcast(NVT, NewExtract);
19083           }
19084         }
19085       }
19086     }
19087   }
19088 
19089   if (V.getOpcode() == ISD::CONCAT_VECTORS) {
19090     unsigned ExtNumElts = NVT.getVectorNumElements();
19091     EVT ConcatSrcVT = V.getOperand(0).getValueType();
19092     assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() &&
19093            "Concat and extract subvector do not change element type");
19094     assert((ExtIdx % ExtNumElts) == 0 &&
19095            "Extract index is not a multiple of the input vector length.");
19096 
19097     unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorNumElements();
19098     unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts;
19099 
19100     // If the concatenated source types match this extract, it's a direct
19101     // simplification:
19102     // extract_subvec (concat V1, V2, ...), i --> Vi
19103     if (ConcatSrcNumElts == ExtNumElts)
19104       return V.getOperand(ConcatOpIdx);
19105 
19106     // If the concatenated source vectors are a multiple length of this extract,
19107     // then extract a fraction of one of those source vectors directly from a
19108     // concat operand. Example:
19109     //   v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 -->
19110     //   v2i8 extract_subvec v8i8 Y, 6
19111     if (ConcatSrcNumElts % ExtNumElts == 0) {
19112       SDLoc DL(N);
19113       unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts;
19114       assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts &&
19115              "Trying to extract from >1 concat operand?");
19116       assert(NewExtIdx % ExtNumElts == 0 &&
19117              "Extract index is not a multiple of the input vector length.");
19118       SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL);
19119       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT,
19120                          V.getOperand(ConcatOpIdx), NewIndexC);
19121     }
19122   }
19123 
19124   V = peekThroughBitcasts(V);
19125 
19126   // If the input is a build vector. Try to make a smaller build vector.
19127   if (V.getOpcode() == ISD::BUILD_VECTOR) {
19128     EVT InVT = V.getValueType();
19129     unsigned ExtractSize = NVT.getSizeInBits();
19130     unsigned EltSize = InVT.getScalarSizeInBits();
19131     // Only do this if we won't split any elements.
19132     if (ExtractSize % EltSize == 0) {
19133       unsigned NumElems = ExtractSize / EltSize;
19134       EVT EltVT = InVT.getVectorElementType();
19135       EVT ExtractVT =
19136           NumElems == 1 ? EltVT
19137                         : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems);
19138       if ((Level < AfterLegalizeDAG ||
19139            (NumElems == 1 ||
19140             TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) &&
19141           (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
19142         unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize;
19143 
19144         if (NumElems == 1) {
19145           SDValue Src = V->getOperand(IdxVal);
19146           if (EltVT != Src.getValueType())
19147             Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src);
19148           return DAG.getBitcast(NVT, Src);
19149         }
19150 
19151         // Extract the pieces from the original build_vector.
19152         SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
19153                                               V->ops().slice(IdxVal, NumElems));
19154         return DAG.getBitcast(NVT, BuildVec);
19155       }
19156     }
19157   }
19158 
19159   if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
19160     // Handle only simple case where vector being inserted and vector
19161     // being extracted are of same size.
19162     EVT SmallVT = V.getOperand(1).getValueType();
19163     if (!NVT.bitsEq(SmallVT))
19164       return SDValue();
19165 
19166     // Combine:
19167     //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
19168     // Into:
19169     //    indices are equal or bit offsets are equal => V1
19170     //    otherwise => (extract_subvec V1, ExtIdx)
19171     uint64_t InsIdx = V.getConstantOperandVal(2);
19172     if (InsIdx * SmallVT.getScalarSizeInBits() ==
19173         ExtIdx * NVT.getScalarSizeInBits())
19174       return DAG.getBitcast(NVT, V.getOperand(1));
19175     return DAG.getNode(
19176         ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
19177         DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)),
19178         N->getOperand(1));
19179   }
19180 
19181   if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
19182     return NarrowBOp;
19183 
19184   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
19185     return SDValue(N, 0);
19186 
19187   return SDValue();
19188 }
19189 
19190 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
19191 /// followed by concatenation. Narrow vector ops may have better performance
19192 /// than wide ops, and this can unlock further narrowing of other vector ops.
19193 /// Targets can invert this transform later if it is not profitable.
19194 static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf,
19195                                          SelectionDAG &DAG) {
19196   SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1);
19197   if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
19198       N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 ||
19199       !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef())
19200     return SDValue();
19201 
19202   // Split the wide shuffle mask into halves. Any mask element that is accessing
19203   // operand 1 is offset down to account for narrowing of the vectors.
19204   ArrayRef<int> Mask = Shuf->getMask();
19205   EVT VT = Shuf->getValueType(0);
19206   unsigned NumElts = VT.getVectorNumElements();
19207   unsigned HalfNumElts = NumElts / 2;
19208   SmallVector<int, 16> Mask0(HalfNumElts, -1);
19209   SmallVector<int, 16> Mask1(HalfNumElts, -1);
19210   for (unsigned i = 0; i != NumElts; ++i) {
19211     if (Mask[i] == -1)
19212       continue;
19213     int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts;
19214     if (i < HalfNumElts)
19215       Mask0[i] = M;
19216     else
19217       Mask1[i - HalfNumElts] = M;
19218   }
19219 
19220   // Ask the target if this is a valid transform.
19221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19222   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
19223                                 HalfNumElts);
19224   if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) ||
19225       !TLI.isShuffleMaskLegal(Mask1, HalfVT))
19226     return SDValue();
19227 
19228   // shuffle (concat X, undef), (concat Y, undef), Mask -->
19229   // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
19230   SDValue X = N0.getOperand(0), Y = N1.getOperand(0);
19231   SDLoc DL(Shuf);
19232   SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0);
19233   SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1);
19234   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1);
19235 }
19236 
19237 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
19238 // or turn a shuffle of a single concat into simpler shuffle then concat.
19239 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
19240   EVT VT = N->getValueType(0);
19241   unsigned NumElts = VT.getVectorNumElements();
19242 
19243   SDValue N0 = N->getOperand(0);
19244   SDValue N1 = N->getOperand(1);
19245   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
19246   ArrayRef<int> Mask = SVN->getMask();
19247 
19248   SmallVector<SDValue, 4> Ops;
19249   EVT ConcatVT = N0.getOperand(0).getValueType();
19250   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
19251   unsigned NumConcats = NumElts / NumElemsPerConcat;
19252 
19253   auto IsUndefMaskElt = [](int i) { return i == -1; };
19254 
19255   // Special case: shuffle(concat(A,B)) can be more efficiently represented
19256   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
19257   // half vector elements.
19258   if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
19259       llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat),
19260                    IsUndefMaskElt)) {
19261     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0),
19262                               N0.getOperand(1),
19263                               Mask.slice(0, NumElemsPerConcat));
19264     N1 = DAG.getUNDEF(ConcatVT);
19265     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
19266   }
19267 
19268   // Look at every vector that's inserted. We're looking for exact
19269   // subvector-sized copies from a concatenated vector
19270   for (unsigned I = 0; I != NumConcats; ++I) {
19271     unsigned Begin = I * NumElemsPerConcat;
19272     ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat);
19273 
19274     // Make sure we're dealing with a copy.
19275     if (llvm::all_of(SubMask, IsUndefMaskElt)) {
19276       Ops.push_back(DAG.getUNDEF(ConcatVT));
19277       continue;
19278     }
19279 
19280     int OpIdx = -1;
19281     for (int i = 0; i != (int)NumElemsPerConcat; ++i) {
19282       if (IsUndefMaskElt(SubMask[i]))
19283         continue;
19284       if ((SubMask[i] % (int)NumElemsPerConcat) != i)
19285         return SDValue();
19286       int EltOpIdx = SubMask[i] / NumElemsPerConcat;
19287       if (0 <= OpIdx && EltOpIdx != OpIdx)
19288         return SDValue();
19289       OpIdx = EltOpIdx;
19290     }
19291     assert(0 <= OpIdx && "Unknown concat_vectors op");
19292 
19293     if (OpIdx < (int)N0.getNumOperands())
19294       Ops.push_back(N0.getOperand(OpIdx));
19295     else
19296       Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands()));
19297   }
19298 
19299   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
19300 }
19301 
19302 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
19303 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
19304 //
19305 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
19306 // a simplification in some sense, but it isn't appropriate in general: some
19307 // BUILD_VECTORs are substantially cheaper than others. The general case
19308 // of a BUILD_VECTOR requires inserting each element individually (or
19309 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
19310 // all constants is a single constant pool load.  A BUILD_VECTOR where each
19311 // element is identical is a splat.  A BUILD_VECTOR where most of the operands
19312 // are undef lowers to a small number of element insertions.
19313 //
19314 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
19315 // We don't fold shuffles where one side is a non-zero constant, and we don't
19316 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
19317 // non-constant operands. This seems to work out reasonably well in practice.
19318 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
19319                                        SelectionDAG &DAG,
19320                                        const TargetLowering &TLI) {
19321   EVT VT = SVN->getValueType(0);
19322   unsigned NumElts = VT.getVectorNumElements();
19323   SDValue N0 = SVN->getOperand(0);
19324   SDValue N1 = SVN->getOperand(1);
19325 
19326   if (!N0->hasOneUse())
19327     return SDValue();
19328 
19329   // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
19330   // discussed above.
19331   if (!N1.isUndef()) {
19332     if (!N1->hasOneUse())
19333       return SDValue();
19334 
19335     bool N0AnyConst = isAnyConstantBuildVector(N0);
19336     bool N1AnyConst = isAnyConstantBuildVector(N1);
19337     if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
19338       return SDValue();
19339     if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
19340       return SDValue();
19341   }
19342 
19343   // If both inputs are splats of the same value then we can safely merge this
19344   // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
19345   bool IsSplat = false;
19346   auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
19347   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
19348   if (BV0 && BV1)
19349     if (SDValue Splat0 = BV0->getSplatValue())
19350       IsSplat = (Splat0 == BV1->getSplatValue());
19351 
19352   SmallVector<SDValue, 8> Ops;
19353   SmallSet<SDValue, 16> DuplicateOps;
19354   for (int M : SVN->getMask()) {
19355     SDValue Op = DAG.getUNDEF(VT.getScalarType());
19356     if (M >= 0) {
19357       int Idx = M < (int)NumElts ? M : M - NumElts;
19358       SDValue &S = (M < (int)NumElts ? N0 : N1);
19359       if (S.getOpcode() == ISD::BUILD_VECTOR) {
19360         Op = S.getOperand(Idx);
19361       } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
19362         SDValue Op0 = S.getOperand(0);
19363         Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType());
19364       } else {
19365         // Operand can't be combined - bail out.
19366         return SDValue();
19367       }
19368     }
19369 
19370     // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
19371     // generating a splat; semantically, this is fine, but it's likely to
19372     // generate low-quality code if the target can't reconstruct an appropriate
19373     // shuffle.
19374     if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
19375       if (!IsSplat && !DuplicateOps.insert(Op).second)
19376         return SDValue();
19377 
19378     Ops.push_back(Op);
19379   }
19380 
19381   // BUILD_VECTOR requires all inputs to be of the same type, find the
19382   // maximum type and extend them all.
19383   EVT SVT = VT.getScalarType();
19384   if (SVT.isInteger())
19385     for (SDValue &Op : Ops)
19386       SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
19387   if (SVT != VT.getScalarType())
19388     for (SDValue &Op : Ops)
19389       Op = TLI.isZExtFree(Op.getValueType(), SVT)
19390                ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
19391                : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
19392   return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
19393 }
19394 
19395 // Match shuffles that can be converted to any_vector_extend_in_reg.
19396 // This is often generated during legalization.
19397 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
19398 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
19399 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
19400                                             SelectionDAG &DAG,
19401                                             const TargetLowering &TLI,
19402                                             bool LegalOperations) {
19403   EVT VT = SVN->getValueType(0);
19404   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
19405 
19406   // TODO Add support for big-endian when we have a test case.
19407   if (!VT.isInteger() || IsBigEndian)
19408     return SDValue();
19409 
19410   unsigned NumElts = VT.getVectorNumElements();
19411   unsigned EltSizeInBits = VT.getScalarSizeInBits();
19412   ArrayRef<int> Mask = SVN->getMask();
19413   SDValue N0 = SVN->getOperand(0);
19414 
19415   // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
19416   auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
19417     for (unsigned i = 0; i != NumElts; ++i) {
19418       if (Mask[i] < 0)
19419         continue;
19420       if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
19421         continue;
19422       return false;
19423     }
19424     return true;
19425   };
19426 
19427   // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
19428   // power-of-2 extensions as they are the most likely.
19429   for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
19430     // Check for non power of 2 vector sizes
19431     if (NumElts % Scale != 0)
19432       continue;
19433     if (!isAnyExtend(Scale))
19434       continue;
19435 
19436     EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
19437     EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
19438     // Never create an illegal type. Only create unsupported operations if we
19439     // are pre-legalization.
19440     if (TLI.isTypeLegal(OutVT))
19441       if (!LegalOperations ||
19442           TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
19443         return DAG.getBitcast(VT,
19444                               DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG,
19445                                           SDLoc(SVN), OutVT, N0));
19446   }
19447 
19448   return SDValue();
19449 }
19450 
19451 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
19452 // each source element of a large type into the lowest elements of a smaller
19453 // destination type. This is often generated during legalization.
19454 // If the source node itself was a '*_extend_vector_inreg' node then we should
19455 // then be able to remove it.
19456 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
19457                                         SelectionDAG &DAG) {
19458   EVT VT = SVN->getValueType(0);
19459   bool IsBigEndian = DAG.getDataLayout().isBigEndian();
19460 
19461   // TODO Add support for big-endian when we have a test case.
19462   if (!VT.isInteger() || IsBigEndian)
19463     return SDValue();
19464 
19465   SDValue N0 = peekThroughBitcasts(SVN->getOperand(0));
19466 
19467   unsigned Opcode = N0.getOpcode();
19468   if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
19469       Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
19470       Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
19471     return SDValue();
19472 
19473   SDValue N00 = N0.getOperand(0);
19474   ArrayRef<int> Mask = SVN->getMask();
19475   unsigned NumElts = VT.getVectorNumElements();
19476   unsigned EltSizeInBits = VT.getScalarSizeInBits();
19477   unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
19478   unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
19479 
19480   if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
19481     return SDValue();
19482   unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
19483 
19484   // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
19485   // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
19486   // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
19487   auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
19488     for (unsigned i = 0; i != NumElts; ++i) {
19489       if (Mask[i] < 0)
19490         continue;
19491       if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
19492         continue;
19493       return false;
19494     }
19495     return true;
19496   };
19497 
19498   // At the moment we just handle the case where we've truncated back to the
19499   // same size as before the extension.
19500   // TODO: handle more extension/truncation cases as cases arise.
19501   if (EltSizeInBits != ExtSrcSizeInBits)
19502     return SDValue();
19503 
19504   // We can remove *extend_vector_inreg only if the truncation happens at
19505   // the same scale as the extension.
19506   if (isTruncate(ExtScale))
19507     return DAG.getBitcast(VT, N00);
19508 
19509   return SDValue();
19510 }
19511 
19512 // Combine shuffles of splat-shuffles of the form:
19513 // shuffle (shuffle V, undef, splat-mask), undef, M
19514 // If splat-mask contains undef elements, we need to be careful about
19515 // introducing undef's in the folded mask which are not the result of composing
19516 // the masks of the shuffles.
19517 static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf,
19518                                         SelectionDAG &DAG) {
19519   if (!Shuf->getOperand(1).isUndef())
19520     return SDValue();
19521   auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
19522   if (!Splat || !Splat->isSplat())
19523     return SDValue();
19524 
19525   ArrayRef<int> ShufMask = Shuf->getMask();
19526   ArrayRef<int> SplatMask = Splat->getMask();
19527   assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch");
19528 
19529   // Prefer simplifying to the splat-shuffle, if possible. This is legal if
19530   // every undef mask element in the splat-shuffle has a corresponding undef
19531   // element in the user-shuffle's mask or if the composition of mask elements
19532   // would result in undef.
19533   // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
19534   // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
19535   //   In this case it is not legal to simplify to the splat-shuffle because we
19536   //   may be exposing the users of the shuffle an undef element at index 1
19537   //   which was not there before the combine.
19538   // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
19539   //   In this case the composition of masks yields SplatMask, so it's ok to
19540   //   simplify to the splat-shuffle.
19541   // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
19542   //   In this case the composed mask includes all undef elements of SplatMask
19543   //   and in addition sets element zero to undef. It is safe to simplify to
19544   //   the splat-shuffle.
19545   auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
19546                                        ArrayRef<int> SplatMask) {
19547     for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
19548       if (UserMask[i] != -1 && SplatMask[i] == -1 &&
19549           SplatMask[UserMask[i]] != -1)
19550         return false;
19551     return true;
19552   };
19553   if (CanSimplifyToExistingSplat(ShufMask, SplatMask))
19554     return Shuf->getOperand(0);
19555 
19556   // Create a new shuffle with a mask that is composed of the two shuffles'
19557   // masks.
19558   SmallVector<int, 32> NewMask;
19559   for (int Idx : ShufMask)
19560     NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
19561 
19562   return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
19563                               Splat->getOperand(0), Splat->getOperand(1),
19564                               NewMask);
19565 }
19566 
19567 /// Combine shuffle of shuffle of the form:
19568 /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X
19569 static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf,
19570                                      SelectionDAG &DAG) {
19571   if (!OuterShuf->getOperand(1).isUndef())
19572     return SDValue();
19573   auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0));
19574   if (!InnerShuf || !InnerShuf->getOperand(1).isUndef())
19575     return SDValue();
19576 
19577   ArrayRef<int> OuterMask = OuterShuf->getMask();
19578   ArrayRef<int> InnerMask = InnerShuf->getMask();
19579   unsigned NumElts = OuterMask.size();
19580   assert(NumElts == InnerMask.size() && "Mask length mismatch");
19581   SmallVector<int, 32> CombinedMask(NumElts, -1);
19582   int SplatIndex = -1;
19583   for (unsigned i = 0; i != NumElts; ++i) {
19584     // Undef lanes remain undef.
19585     int OuterMaskElt = OuterMask[i];
19586     if (OuterMaskElt == -1)
19587       continue;
19588 
19589     // Peek through the shuffle masks to get the underlying source element.
19590     int InnerMaskElt = InnerMask[OuterMaskElt];
19591     if (InnerMaskElt == -1)
19592       continue;
19593 
19594     // Initialize the splatted element.
19595     if (SplatIndex == -1)
19596       SplatIndex = InnerMaskElt;
19597 
19598     // Non-matching index - this is not a splat.
19599     if (SplatIndex != InnerMaskElt)
19600       return SDValue();
19601 
19602     CombinedMask[i] = InnerMaskElt;
19603   }
19604   assert((all_of(CombinedMask, [](int M) { return M == -1; }) ||
19605           getSplatIndex(CombinedMask) != -1) &&
19606          "Expected a splat mask");
19607 
19608   // TODO: The transform may be a win even if the mask is not legal.
19609   EVT VT = OuterShuf->getValueType(0);
19610   assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types");
19611   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT))
19612     return SDValue();
19613 
19614   return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0),
19615                               InnerShuf->getOperand(1), CombinedMask);
19616 }
19617 
19618 /// If the shuffle mask is taking exactly one element from the first vector
19619 /// operand and passing through all other elements from the second vector
19620 /// operand, return the index of the mask element that is choosing an element
19621 /// from the first operand. Otherwise, return -1.
19622 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
19623   int MaskSize = Mask.size();
19624   int EltFromOp0 = -1;
19625   // TODO: This does not match if there are undef elements in the shuffle mask.
19626   // Should we ignore undefs in the shuffle mask instead? The trade-off is
19627   // removing an instruction (a shuffle), but losing the knowledge that some
19628   // vector lanes are not needed.
19629   for (int i = 0; i != MaskSize; ++i) {
19630     if (Mask[i] >= 0 && Mask[i] < MaskSize) {
19631       // We're looking for a shuffle of exactly one element from operand 0.
19632       if (EltFromOp0 != -1)
19633         return -1;
19634       EltFromOp0 = i;
19635     } else if (Mask[i] != i + MaskSize) {
19636       // Nothing from operand 1 can change lanes.
19637       return -1;
19638     }
19639   }
19640   return EltFromOp0;
19641 }
19642 
19643 /// If a shuffle inserts exactly one element from a source vector operand into
19644 /// another vector operand and we can access the specified element as a scalar,
19645 /// then we can eliminate the shuffle.
19646 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
19647                                       SelectionDAG &DAG) {
19648   // First, check if we are taking one element of a vector and shuffling that
19649   // element into another vector.
19650   ArrayRef<int> Mask = Shuf->getMask();
19651   SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
19652   SDValue Op0 = Shuf->getOperand(0);
19653   SDValue Op1 = Shuf->getOperand(1);
19654   int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
19655   if (ShufOp0Index == -1) {
19656     // Commute mask and check again.
19657     ShuffleVectorSDNode::commuteMask(CommutedMask);
19658     ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
19659     if (ShufOp0Index == -1)
19660       return SDValue();
19661     // Commute operands to match the commuted shuffle mask.
19662     std::swap(Op0, Op1);
19663     Mask = CommutedMask;
19664   }
19665 
19666   // The shuffle inserts exactly one element from operand 0 into operand 1.
19667   // Now see if we can access that element as a scalar via a real insert element
19668   // instruction.
19669   // TODO: We can try harder to locate the element as a scalar. Examples: it
19670   // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
19671   assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
19672          "Shuffle mask value must be from operand 0");
19673   if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
19674     return SDValue();
19675 
19676   auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
19677   if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
19678     return SDValue();
19679 
19680   // There's an existing insertelement with constant insertion index, so we
19681   // don't need to check the legality/profitability of a replacement operation
19682   // that differs at most in the constant value. The target should be able to
19683   // lower any of those in a similar way. If not, legalization will expand this
19684   // to a scalar-to-vector plus shuffle.
19685   //
19686   // Note that the shuffle may move the scalar from the position that the insert
19687   // element used. Therefore, our new insert element occurs at the shuffle's
19688   // mask index value, not the insert's index value.
19689   // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
19690   SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf));
19691   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
19692                      Op1, Op0.getOperand(1), NewInsIndex);
19693 }
19694 
19695 /// If we have a unary shuffle of a shuffle, see if it can be folded away
19696 /// completely. This has the potential to lose undef knowledge because the first
19697 /// shuffle may not have an undef mask element where the second one does. So
19698 /// only call this after doing simplifications based on demanded elements.
19699 static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) {
19700   // shuf (shuf0 X, Y, Mask0), undef, Mask
19701   auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
19702   if (!Shuf0 || !Shuf->getOperand(1).isUndef())
19703     return SDValue();
19704 
19705   ArrayRef<int> Mask = Shuf->getMask();
19706   ArrayRef<int> Mask0 = Shuf0->getMask();
19707   for (int i = 0, e = (int)Mask.size(); i != e; ++i) {
19708     // Ignore undef elements.
19709     if (Mask[i] == -1)
19710       continue;
19711     assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value");
19712 
19713     // Is the element of the shuffle operand chosen by this shuffle the same as
19714     // the element chosen by the shuffle operand itself?
19715     if (Mask0[Mask[i]] != Mask0[i])
19716       return SDValue();
19717   }
19718   // Every element of this shuffle is identical to the result of the previous
19719   // shuffle, so we can replace this value.
19720   return Shuf->getOperand(0);
19721 }
19722 
19723 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
19724   EVT VT = N->getValueType(0);
19725   unsigned NumElts = VT.getVectorNumElements();
19726 
19727   SDValue N0 = N->getOperand(0);
19728   SDValue N1 = N->getOperand(1);
19729 
19730   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
19731 
19732   // Canonicalize shuffle undef, undef -> undef
19733   if (N0.isUndef() && N1.isUndef())
19734     return DAG.getUNDEF(VT);
19735 
19736   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
19737 
19738   // Canonicalize shuffle v, v -> v, undef
19739   if (N0 == N1) {
19740     SmallVector<int, 8> NewMask;
19741     for (unsigned i = 0; i != NumElts; ++i) {
19742       int Idx = SVN->getMaskElt(i);
19743       if (Idx >= (int)NumElts) Idx -= NumElts;
19744       NewMask.push_back(Idx);
19745     }
19746     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
19747   }
19748 
19749   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
19750   if (N0.isUndef())
19751     return DAG.getCommutedVectorShuffle(*SVN);
19752 
19753   // Remove references to rhs if it is undef
19754   if (N1.isUndef()) {
19755     bool Changed = false;
19756     SmallVector<int, 8> NewMask;
19757     for (unsigned i = 0; i != NumElts; ++i) {
19758       int Idx = SVN->getMaskElt(i);
19759       if (Idx >= (int)NumElts) {
19760         Idx = -1;
19761         Changed = true;
19762       }
19763       NewMask.push_back(Idx);
19764     }
19765     if (Changed)
19766       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
19767   }
19768 
19769   if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
19770     return InsElt;
19771 
19772   // A shuffle of a single vector that is a splatted value can always be folded.
19773   if (SDValue V = combineShuffleOfSplatVal(SVN, DAG))
19774     return V;
19775 
19776   if (SDValue V = formSplatFromShuffles(SVN, DAG))
19777     return V;
19778 
19779   // If it is a splat, check if the argument vector is another splat or a
19780   // build_vector.
19781   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
19782     int SplatIndex = SVN->getSplatIndex();
19783     if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) &&
19784         TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) {
19785       // splat (vector_bo L, R), Index -->
19786       // splat (scalar_bo (extelt L, Index), (extelt R, Index))
19787       SDValue L = N0.getOperand(0), R = N0.getOperand(1);
19788       SDLoc DL(N);
19789       EVT EltVT = VT.getScalarType();
19790       SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL);
19791       SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index);
19792       SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index);
19793       SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR,
19794                                   N0.getNode()->getFlags());
19795       SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO);
19796       SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0);
19797       return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask);
19798     }
19799 
19800     // If this is a bit convert that changes the element type of the vector but
19801     // not the number of vector elements, look through it.  Be careful not to
19802     // look though conversions that change things like v4f32 to v2f64.
19803     SDNode *V = N0.getNode();
19804     if (V->getOpcode() == ISD::BITCAST) {
19805       SDValue ConvInput = V->getOperand(0);
19806       if (ConvInput.getValueType().isVector() &&
19807           ConvInput.getValueType().getVectorNumElements() == NumElts)
19808         V = ConvInput.getNode();
19809     }
19810 
19811     if (V->getOpcode() == ISD::BUILD_VECTOR) {
19812       assert(V->getNumOperands() == NumElts &&
19813              "BUILD_VECTOR has wrong number of operands");
19814       SDValue Base;
19815       bool AllSame = true;
19816       for (unsigned i = 0; i != NumElts; ++i) {
19817         if (!V->getOperand(i).isUndef()) {
19818           Base = V->getOperand(i);
19819           break;
19820         }
19821       }
19822       // Splat of <u, u, u, u>, return <u, u, u, u>
19823       if (!Base.getNode())
19824         return N0;
19825       for (unsigned i = 0; i != NumElts; ++i) {
19826         if (V->getOperand(i) != Base) {
19827           AllSame = false;
19828           break;
19829         }
19830       }
19831       // Splat of <x, x, x, x>, return <x, x, x, x>
19832       if (AllSame)
19833         return N0;
19834 
19835       // Canonicalize any other splat as a build_vector.
19836       SDValue Splatted = V->getOperand(SplatIndex);
19837       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
19838       SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
19839 
19840       // We may have jumped through bitcasts, so the type of the
19841       // BUILD_VECTOR may not match the type of the shuffle.
19842       if (V->getValueType(0) != VT)
19843         NewBV = DAG.getBitcast(VT, NewBV);
19844       return NewBV;
19845     }
19846   }
19847 
19848   // Simplify source operands based on shuffle mask.
19849   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
19850     return SDValue(N, 0);
19851 
19852   // This is intentionally placed after demanded elements simplification because
19853   // it could eliminate knowledge of undef elements created by this shuffle.
19854   if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN))
19855     return ShufOp;
19856 
19857   // Match shuffles that can be converted to any_vector_extend_in_reg.
19858   if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
19859     return V;
19860 
19861   // Combine "truncate_vector_in_reg" style shuffles.
19862   if (SDValue V = combineTruncationShuffle(SVN, DAG))
19863     return V;
19864 
19865   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
19866       Level < AfterLegalizeVectorOps &&
19867       (N1.isUndef() ||
19868       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
19869        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
19870     if (SDValue V = partitionShuffleOfConcats(N, DAG))
19871       return V;
19872   }
19873 
19874   // A shuffle of a concat of the same narrow vector can be reduced to use
19875   // only low-half elements of a concat with undef:
19876   // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask'
19877   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() &&
19878       N0.getNumOperands() == 2 &&
19879       N0.getOperand(0) == N0.getOperand(1)) {
19880     int HalfNumElts = (int)NumElts / 2;
19881     SmallVector<int, 8> NewMask;
19882     for (unsigned i = 0; i != NumElts; ++i) {
19883       int Idx = SVN->getMaskElt(i);
19884       if (Idx >= HalfNumElts) {
19885         assert(Idx < (int)NumElts && "Shuffle mask chooses undef op");
19886         Idx -= HalfNumElts;
19887       }
19888       NewMask.push_back(Idx);
19889     }
19890     if (TLI.isShuffleMaskLegal(NewMask, VT)) {
19891       SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType());
19892       SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
19893                                    N0.getOperand(0), UndefVec);
19894       return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask);
19895     }
19896   }
19897 
19898   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
19899   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
19900   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT))
19901     if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
19902       return Res;
19903 
19904   // If this shuffle only has a single input that is a bitcasted shuffle,
19905   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
19906   // back to their original types.
19907   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
19908       N1.isUndef() && Level < AfterLegalizeVectorOps &&
19909       TLI.isTypeLegal(VT)) {
19910 
19911     SDValue BC0 = peekThroughOneUseBitcasts(N0);
19912     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
19913       EVT SVT = VT.getScalarType();
19914       EVT InnerVT = BC0->getValueType(0);
19915       EVT InnerSVT = InnerVT.getScalarType();
19916 
19917       // Determine which shuffle works with the smaller scalar type.
19918       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
19919       EVT ScaleSVT = ScaleVT.getScalarType();
19920 
19921       if (TLI.isTypeLegal(ScaleVT) &&
19922           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
19923           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
19924         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
19925         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
19926 
19927         // Scale the shuffle masks to the smaller scalar type.
19928         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
19929         SmallVector<int, 8> InnerMask;
19930         SmallVector<int, 8> OuterMask;
19931         narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask);
19932         narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask);
19933 
19934         // Merge the shuffle masks.
19935         SmallVector<int, 8> NewMask;
19936         for (int M : OuterMask)
19937           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
19938 
19939         // Test for shuffle mask legality over both commutations.
19940         SDValue SV0 = BC0->getOperand(0);
19941         SDValue SV1 = BC0->getOperand(1);
19942         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
19943         if (!LegalMask) {
19944           std::swap(SV0, SV1);
19945           ShuffleVectorSDNode::commuteMask(NewMask);
19946           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
19947         }
19948 
19949         if (LegalMask) {
19950           SV0 = DAG.getBitcast(ScaleVT, SV0);
19951           SV1 = DAG.getBitcast(ScaleVT, SV1);
19952           return DAG.getBitcast(
19953               VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
19954         }
19955       }
19956     }
19957   }
19958 
19959   // Canonicalize shuffles according to rules:
19960   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
19961   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
19962   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
19963   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
19964       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
19965       TLI.isTypeLegal(VT)) {
19966     // The incoming shuffle must be of the same type as the result of the
19967     // current shuffle.
19968     assert(N1->getOperand(0).getValueType() == VT &&
19969            "Shuffle types don't match");
19970 
19971     SDValue SV0 = N1->getOperand(0);
19972     SDValue SV1 = N1->getOperand(1);
19973     bool HasSameOp0 = N0 == SV0;
19974     bool IsSV1Undef = SV1.isUndef();
19975     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
19976       // Commute the operands of this shuffle so that next rule
19977       // will trigger.
19978       return DAG.getCommutedVectorShuffle(*SVN);
19979   }
19980 
19981   // Try to fold according to rules:
19982   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
19983   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
19984   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
19985   // Don't try to fold shuffles with illegal type.
19986   // Only fold if this shuffle is the only user of the other shuffle.
19987   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
19988       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
19989     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
19990 
19991     // Don't try to fold splats; they're likely to simplify somehow, or they
19992     // might be free.
19993     if (OtherSV->isSplat())
19994       return SDValue();
19995 
19996     // The incoming shuffle must be of the same type as the result of the
19997     // current shuffle.
19998     assert(OtherSV->getOperand(0).getValueType() == VT &&
19999            "Shuffle types don't match");
20000 
20001     SDValue SV0, SV1;
20002     SmallVector<int, 4> Mask;
20003     // Compute the combined shuffle mask for a shuffle with SV0 as the first
20004     // operand, and SV1 as the second operand.
20005     for (unsigned i = 0; i != NumElts; ++i) {
20006       int Idx = SVN->getMaskElt(i);
20007       if (Idx < 0) {
20008         // Propagate Undef.
20009         Mask.push_back(Idx);
20010         continue;
20011       }
20012 
20013       SDValue CurrentVec;
20014       if (Idx < (int)NumElts) {
20015         // This shuffle index refers to the inner shuffle N0. Lookup the inner
20016         // shuffle mask to identify which vector is actually referenced.
20017         Idx = OtherSV->getMaskElt(Idx);
20018         if (Idx < 0) {
20019           // Propagate Undef.
20020           Mask.push_back(Idx);
20021           continue;
20022         }
20023 
20024         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
20025                                            : OtherSV->getOperand(1);
20026       } else {
20027         // This shuffle index references an element within N1.
20028         CurrentVec = N1;
20029       }
20030 
20031       // Simple case where 'CurrentVec' is UNDEF.
20032       if (CurrentVec.isUndef()) {
20033         Mask.push_back(-1);
20034         continue;
20035       }
20036 
20037       // Canonicalize the shuffle index. We don't know yet if CurrentVec
20038       // will be the first or second operand of the combined shuffle.
20039       Idx = Idx % NumElts;
20040       if (!SV0.getNode() || SV0 == CurrentVec) {
20041         // Ok. CurrentVec is the left hand side.
20042         // Update the mask accordingly.
20043         SV0 = CurrentVec;
20044         Mask.push_back(Idx);
20045         continue;
20046       }
20047 
20048       // Bail out if we cannot convert the shuffle pair into a single shuffle.
20049       if (SV1.getNode() && SV1 != CurrentVec)
20050         return SDValue();
20051 
20052       // Ok. CurrentVec is the right hand side.
20053       // Update the mask accordingly.
20054       SV1 = CurrentVec;
20055       Mask.push_back(Idx + NumElts);
20056     }
20057 
20058     // Check if all indices in Mask are Undef. In case, propagate Undef.
20059     bool isUndefMask = true;
20060     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
20061       isUndefMask &= Mask[i] < 0;
20062 
20063     if (isUndefMask)
20064       return DAG.getUNDEF(VT);
20065 
20066     if (!SV0.getNode())
20067       SV0 = DAG.getUNDEF(VT);
20068     if (!SV1.getNode())
20069       SV1 = DAG.getUNDEF(VT);
20070 
20071     // Avoid introducing shuffles with illegal mask.
20072     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
20073     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
20074     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
20075     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
20076     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
20077     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
20078     return TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask, DAG);
20079   }
20080 
20081   if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG))
20082     return V;
20083 
20084   return SDValue();
20085 }
20086 
20087 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
20088   SDValue InVal = N->getOperand(0);
20089   EVT VT = N->getValueType(0);
20090 
20091   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
20092   // with a VECTOR_SHUFFLE and possible truncate.
20093   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
20094     SDValue InVec = InVal->getOperand(0);
20095     SDValue EltNo = InVal->getOperand(1);
20096     auto InVecT = InVec.getValueType();
20097     if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
20098       SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
20099       int Elt = C0->getZExtValue();
20100       NewMask[0] = Elt;
20101       // If we have an implict truncate do truncate here as long as it's legal.
20102       // if it's not legal, this should
20103       if (VT.getScalarType() != InVal.getValueType() &&
20104           InVal.getValueType().isScalarInteger() &&
20105           isTypeLegal(VT.getScalarType())) {
20106         SDValue Val =
20107             DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
20108         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
20109       }
20110       if (VT.getScalarType() == InVecT.getScalarType() &&
20111           VT.getVectorNumElements() <= InVecT.getVectorNumElements()) {
20112         SDValue LegalShuffle =
20113           TLI.buildLegalVectorShuffle(InVecT, SDLoc(N), InVec,
20114                                       DAG.getUNDEF(InVecT), NewMask, DAG);
20115         if (LegalShuffle) {
20116           // If the initial vector is the correct size this shuffle is a
20117           // valid result.
20118           if (VT == InVecT)
20119             return LegalShuffle;
20120           // If not we must truncate the vector.
20121           if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
20122             SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N));
20123             EVT SubVT = EVT::getVectorVT(*DAG.getContext(),
20124                                          InVecT.getVectorElementType(),
20125                                          VT.getVectorNumElements());
20126             return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT,
20127                                LegalShuffle, ZeroIdx);
20128           }
20129         }
20130       }
20131     }
20132   }
20133 
20134   return SDValue();
20135 }
20136 
20137 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
20138   EVT VT = N->getValueType(0);
20139   SDValue N0 = N->getOperand(0);
20140   SDValue N1 = N->getOperand(1);
20141   SDValue N2 = N->getOperand(2);
20142   uint64_t InsIdx = N->getConstantOperandVal(2);
20143 
20144   // If inserting an UNDEF, just return the original vector.
20145   if (N1.isUndef())
20146     return N0;
20147 
20148   // If this is an insert of an extracted vector into an undef vector, we can
20149   // just use the input to the extract.
20150   if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
20151       N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
20152     return N1.getOperand(0);
20153 
20154   // If we are inserting a bitcast value into an undef, with the same
20155   // number of elements, just use the bitcast input of the extract.
20156   // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
20157   //        BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
20158   if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
20159       N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
20160       N1.getOperand(0).getOperand(1) == N2 &&
20161       N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
20162           VT.getVectorNumElements() &&
20163       N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
20164           VT.getSizeInBits()) {
20165     return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
20166   }
20167 
20168   // If both N1 and N2 are bitcast values on which insert_subvector
20169   // would makes sense, pull the bitcast through.
20170   // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
20171   //        BITCAST (INSERT_SUBVECTOR N0 N1 N2)
20172   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
20173     SDValue CN0 = N0.getOperand(0);
20174     SDValue CN1 = N1.getOperand(0);
20175     EVT CN0VT = CN0.getValueType();
20176     EVT CN1VT = CN1.getValueType();
20177     if (CN0VT.isVector() && CN1VT.isVector() &&
20178         CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
20179         CN0VT.getVectorNumElements() == VT.getVectorNumElements()) {
20180       SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
20181                                       CN0.getValueType(), CN0, CN1, N2);
20182       return DAG.getBitcast(VT, NewINSERT);
20183     }
20184   }
20185 
20186   // Combine INSERT_SUBVECTORs where we are inserting to the same index.
20187   // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
20188   // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
20189   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
20190       N0.getOperand(1).getValueType() == N1.getValueType() &&
20191       N0.getOperand(2) == N2)
20192     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
20193                        N1, N2);
20194 
20195   // Eliminate an intermediate insert into an undef vector:
20196   // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
20197   // insert_subvector undef, X, N2
20198   if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20199       N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2)))
20200     return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0,
20201                        N1.getOperand(1), N2);
20202 
20203   // Push subvector bitcasts to the output, adjusting the index as we go.
20204   // insert_subvector(bitcast(v), bitcast(s), c1)
20205   // -> bitcast(insert_subvector(v, s, c2))
20206   if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) &&
20207       N1.getOpcode() == ISD::BITCAST) {
20208     SDValue N0Src = peekThroughBitcasts(N0);
20209     SDValue N1Src = peekThroughBitcasts(N1);
20210     EVT N0SrcSVT = N0Src.getValueType().getScalarType();
20211     EVT N1SrcSVT = N1Src.getValueType().getScalarType();
20212     if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) &&
20213         N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) {
20214       EVT NewVT;
20215       SDLoc DL(N);
20216       SDValue NewIdx;
20217       LLVMContext &Ctx = *DAG.getContext();
20218       unsigned NumElts = VT.getVectorNumElements();
20219       unsigned EltSizeInBits = VT.getScalarSizeInBits();
20220       if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) {
20221         unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits();
20222         NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale);
20223         NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL);
20224       } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) {
20225         unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits;
20226         if ((NumElts % Scale) == 0 && (InsIdx % Scale) == 0) {
20227           NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts / Scale);
20228           NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL);
20229         }
20230       }
20231       if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) {
20232         SDValue Res = DAG.getBitcast(NewVT, N0Src);
20233         Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx);
20234         return DAG.getBitcast(VT, Res);
20235       }
20236     }
20237   }
20238 
20239   // Canonicalize insert_subvector dag nodes.
20240   // Example:
20241   // (insert_subvector (insert_subvector A, Idx0), Idx1)
20242   // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
20243   if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
20244       N1.getValueType() == N0.getOperand(1).getValueType()) {
20245     unsigned OtherIdx = N0.getConstantOperandVal(2);
20246     if (InsIdx < OtherIdx) {
20247       // Swap nodes.
20248       SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
20249                                   N0.getOperand(0), N1, N2);
20250       AddToWorklist(NewOp.getNode());
20251       return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
20252                          VT, NewOp, N0.getOperand(1), N0.getOperand(2));
20253     }
20254   }
20255 
20256   // If the input vector is a concatenation, and the insert replaces
20257   // one of the pieces, we can optimize into a single concat_vectors.
20258   if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
20259       N0.getOperand(0).getValueType() == N1.getValueType()) {
20260     unsigned Factor = N1.getValueType().getVectorNumElements();
20261     SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
20262     Ops[InsIdx / Factor] = N1;
20263     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
20264   }
20265 
20266   // Simplify source operands based on insertion.
20267   if (SimplifyDemandedVectorElts(SDValue(N, 0)))
20268     return SDValue(N, 0);
20269 
20270   return SDValue();
20271 }
20272 
20273 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
20274   SDValue N0 = N->getOperand(0);
20275 
20276   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
20277   if (N0->getOpcode() == ISD::FP16_TO_FP)
20278     return N0->getOperand(0);
20279 
20280   return SDValue();
20281 }
20282 
20283 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
20284   SDValue N0 = N->getOperand(0);
20285 
20286   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
20287   if (N0->getOpcode() == ISD::AND) {
20288     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
20289     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
20290       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
20291                          N0.getOperand(0));
20292     }
20293   }
20294 
20295   return SDValue();
20296 }
20297 
20298 SDValue DAGCombiner::visitVECREDUCE(SDNode *N) {
20299   SDValue N0 = N->getOperand(0);
20300   EVT VT = N0.getValueType();
20301   unsigned Opcode = N->getOpcode();
20302 
20303   // VECREDUCE over 1-element vector is just an extract.
20304   if (VT.getVectorNumElements() == 1) {
20305     SDLoc dl(N);
20306     SDValue Res =
20307         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0,
20308                     DAG.getVectorIdxConstant(0, dl));
20309     if (Res.getValueType() != N->getValueType(0))
20310       Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res);
20311     return Res;
20312   }
20313 
20314   // On an boolean vector an and/or reduction is the same as a umin/umax
20315   // reduction. Convert them if the latter is legal while the former isn't.
20316   if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) {
20317     unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND
20318         ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX;
20319     if (!TLI.isOperationLegalOrCustom(Opcode, VT) &&
20320         TLI.isOperationLegalOrCustom(NewOpcode, VT) &&
20321         DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits())
20322       return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0);
20323   }
20324 
20325   return SDValue();
20326 }
20327 
20328 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
20329 /// with the destination vector and a zero vector.
20330 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
20331 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
20332 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
20333   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
20334 
20335   EVT VT = N->getValueType(0);
20336   SDValue LHS = N->getOperand(0);
20337   SDValue RHS = peekThroughBitcasts(N->getOperand(1));
20338   SDLoc DL(N);
20339 
20340   // Make sure we're not running after operation legalization where it
20341   // may have custom lowered the vector shuffles.
20342   if (LegalOperations)
20343     return SDValue();
20344 
20345   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
20346     return SDValue();
20347 
20348   EVT RVT = RHS.getValueType();
20349   unsigned NumElts = RHS.getNumOperands();
20350 
20351   // Attempt to create a valid clear mask, splitting the mask into
20352   // sub elements and checking to see if each is
20353   // all zeros or all ones - suitable for shuffle masking.
20354   auto BuildClearMask = [&](int Split) {
20355     int NumSubElts = NumElts * Split;
20356     int NumSubBits = RVT.getScalarSizeInBits() / Split;
20357 
20358     SmallVector<int, 8> Indices;
20359     for (int i = 0; i != NumSubElts; ++i) {
20360       int EltIdx = i / Split;
20361       int SubIdx = i % Split;
20362       SDValue Elt = RHS.getOperand(EltIdx);
20363       // X & undef --> 0 (not undef). So this lane must be converted to choose
20364       // from the zero constant vector (same as if the element had all 0-bits).
20365       if (Elt.isUndef()) {
20366         Indices.push_back(i + NumSubElts);
20367         continue;
20368       }
20369 
20370       APInt Bits;
20371       if (isa<ConstantSDNode>(Elt))
20372         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
20373       else if (isa<ConstantFPSDNode>(Elt))
20374         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
20375       else
20376         return SDValue();
20377 
20378       // Extract the sub element from the constant bit mask.
20379       if (DAG.getDataLayout().isBigEndian())
20380         Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits);
20381       else
20382         Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits);
20383 
20384       if (Bits.isAllOnesValue())
20385         Indices.push_back(i);
20386       else if (Bits == 0)
20387         Indices.push_back(i + NumSubElts);
20388       else
20389         return SDValue();
20390     }
20391 
20392     // Let's see if the target supports this vector_shuffle.
20393     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
20394     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
20395     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
20396       return SDValue();
20397 
20398     SDValue Zero = DAG.getConstant(0, DL, ClearVT);
20399     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
20400                                                    DAG.getBitcast(ClearVT, LHS),
20401                                                    Zero, Indices));
20402   };
20403 
20404   // Determine maximum split level (byte level masking).
20405   int MaxSplit = 1;
20406   if (RVT.getScalarSizeInBits() % 8 == 0)
20407     MaxSplit = RVT.getScalarSizeInBits() / 8;
20408 
20409   for (int Split = 1; Split <= MaxSplit; ++Split)
20410     if (RVT.getScalarSizeInBits() % Split == 0)
20411       if (SDValue S = BuildClearMask(Split))
20412         return S;
20413 
20414   return SDValue();
20415 }
20416 
20417 /// If a vector binop is performed on splat values, it may be profitable to
20418 /// extract, scalarize, and insert/splat.
20419 static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG) {
20420   SDValue N0 = N->getOperand(0);
20421   SDValue N1 = N->getOperand(1);
20422   unsigned Opcode = N->getOpcode();
20423   EVT VT = N->getValueType(0);
20424   EVT EltVT = VT.getVectorElementType();
20425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20426 
20427   // TODO: Remove/replace the extract cost check? If the elements are available
20428   //       as scalars, then there may be no extract cost. Should we ask if
20429   //       inserting a scalar back into a vector is cheap instead?
20430   int Index0, Index1;
20431   SDValue Src0 = DAG.getSplatSourceVector(N0, Index0);
20432   SDValue Src1 = DAG.getSplatSourceVector(N1, Index1);
20433   if (!Src0 || !Src1 || Index0 != Index1 ||
20434       Src0.getValueType().getVectorElementType() != EltVT ||
20435       Src1.getValueType().getVectorElementType() != EltVT ||
20436       !TLI.isExtractVecEltCheap(VT, Index0) ||
20437       !TLI.isOperationLegalOrCustom(Opcode, EltVT))
20438     return SDValue();
20439 
20440   SDLoc DL(N);
20441   SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL);
20442   SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N0, IndexC);
20443   SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N1, IndexC);
20444   SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags());
20445 
20446   // If all lanes but 1 are undefined, no need to splat the scalar result.
20447   // TODO: Keep track of undefs and use that info in the general case.
20448   if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() &&
20449       count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 &&
20450       count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) {
20451     // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
20452     // build_vec ..undef, (bo X, Y), undef...
20453     SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT));
20454     Ops[Index0] = ScalarBO;
20455     return DAG.getBuildVector(VT, DL, Ops);
20456   }
20457 
20458   // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
20459   SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO);
20460   return DAG.getBuildVector(VT, DL, Ops);
20461 }
20462 
20463 /// Visit a binary vector operation, like ADD.
20464 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
20465   assert(N->getValueType(0).isVector() &&
20466          "SimplifyVBinOp only works on vectors!");
20467 
20468   SDValue LHS = N->getOperand(0);
20469   SDValue RHS = N->getOperand(1);
20470   SDValue Ops[] = {LHS, RHS};
20471   EVT VT = N->getValueType(0);
20472   unsigned Opcode = N->getOpcode();
20473 
20474   // See if we can constant fold the vector operation.
20475   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
20476           Opcode, SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
20477     return Fold;
20478 
20479   // Move unary shuffles with identical masks after a vector binop:
20480   // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
20481   //   --> shuffle (VBinOp A, B), Undef, Mask
20482   // This does not require type legality checks because we are creating the
20483   // same types of operations that are in the original sequence. We do have to
20484   // restrict ops like integer div that have immediate UB (eg, div-by-zero)
20485   // though. This code is adapted from the identical transform in instcombine.
20486   if (Opcode != ISD::UDIV && Opcode != ISD::SDIV &&
20487       Opcode != ISD::UREM && Opcode != ISD::SREM &&
20488       Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) {
20489     auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
20490     auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
20491     if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
20492         LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
20493         (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
20494       SDLoc DL(N);
20495       SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0),
20496                                      RHS.getOperand(0), N->getFlags());
20497       SDValue UndefV = LHS.getOperand(1);
20498       return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
20499     }
20500   }
20501 
20502   // The following pattern is likely to emerge with vector reduction ops. Moving
20503   // the binary operation ahead of insertion may allow using a narrower vector
20504   // instruction that has better performance than the wide version of the op:
20505   // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
20506   if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() &&
20507       RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() &&
20508       LHS.getOperand(2) == RHS.getOperand(2) &&
20509       (LHS.hasOneUse() || RHS.hasOneUse())) {
20510     SDValue X = LHS.getOperand(1);
20511     SDValue Y = RHS.getOperand(1);
20512     SDValue Z = LHS.getOperand(2);
20513     EVT NarrowVT = X.getValueType();
20514     if (NarrowVT == Y.getValueType() &&
20515         TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) {
20516       // (binop undef, undef) may not return undef, so compute that result.
20517       SDLoc DL(N);
20518       SDValue VecC =
20519           DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT));
20520       SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y);
20521       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z);
20522     }
20523   }
20524 
20525   // Make sure all but the first op are undef or constant.
20526   auto ConcatWithConstantOrUndef = [](SDValue Concat) {
20527     return Concat.getOpcode() == ISD::CONCAT_VECTORS &&
20528            std::all_of(std::next(Concat->op_begin()), Concat->op_end(),
20529                      [](const SDValue &Op) {
20530                        return Op.isUndef() ||
20531                               ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
20532                      });
20533   };
20534 
20535   // The following pattern is likely to emerge with vector reduction ops. Moving
20536   // the binary operation ahead of the concat may allow using a narrower vector
20537   // instruction that has better performance than the wide version of the op:
20538   // VBinOp (concat X, undef/constant), (concat Y, undef/constant) -->
20539   //   concat (VBinOp X, Y), VecC
20540   if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) &&
20541       (LHS.hasOneUse() || RHS.hasOneUse())) {
20542     EVT NarrowVT = LHS.getOperand(0).getValueType();
20543     if (NarrowVT == RHS.getOperand(0).getValueType() &&
20544         TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) {
20545       SDLoc DL(N);
20546       unsigned NumOperands = LHS.getNumOperands();
20547       SmallVector<SDValue, 4> ConcatOps;
20548       for (unsigned i = 0; i != NumOperands; ++i) {
20549         // This constant fold for operands 1 and up.
20550         ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i),
20551                                         RHS.getOperand(i)));
20552       }
20553 
20554       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
20555     }
20556   }
20557 
20558   if (SDValue V = scalarizeBinOpOfSplats(N, DAG))
20559     return V;
20560 
20561   return SDValue();
20562 }
20563 
20564 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
20565                                     SDValue N2) {
20566   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
20567 
20568   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
20569                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
20570 
20571   // If we got a simplified select_cc node back from SimplifySelectCC, then
20572   // break it down into a new SETCC node, and a new SELECT node, and then return
20573   // the SELECT node, since we were called with a SELECT node.
20574   if (SCC.getNode()) {
20575     // Check to see if we got a select_cc back (to turn into setcc/select).
20576     // Otherwise, just return whatever node we got back, like fabs.
20577     if (SCC.getOpcode() == ISD::SELECT_CC) {
20578       const SDNodeFlags Flags = N0.getNode()->getFlags();
20579       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
20580                                   N0.getValueType(),
20581                                   SCC.getOperand(0), SCC.getOperand(1),
20582                                   SCC.getOperand(4), Flags);
20583       AddToWorklist(SETCC.getNode());
20584       SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
20585                                          SCC.getOperand(2), SCC.getOperand(3));
20586       SelectNode->setFlags(Flags);
20587       return SelectNode;
20588     }
20589 
20590     return SCC;
20591   }
20592   return SDValue();
20593 }
20594 
20595 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
20596 /// being selected between, see if we can simplify the select.  Callers of this
20597 /// should assume that TheSelect is deleted if this returns true.  As such, they
20598 /// should return the appropriate thing (e.g. the node) back to the top-level of
20599 /// the DAG combiner loop to avoid it being looked at.
20600 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
20601                                     SDValue RHS) {
20602   // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
20603   // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
20604   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
20605     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
20606       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
20607       SDValue Sqrt = RHS;
20608       ISD::CondCode CC;
20609       SDValue CmpLHS;
20610       const ConstantFPSDNode *Zero = nullptr;
20611 
20612       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
20613         CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
20614         CmpLHS = TheSelect->getOperand(0);
20615         Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
20616       } else {
20617         // SELECT or VSELECT
20618         SDValue Cmp = TheSelect->getOperand(0);
20619         if (Cmp.getOpcode() == ISD::SETCC) {
20620           CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
20621           CmpLHS = Cmp.getOperand(0);
20622           Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
20623         }
20624       }
20625       if (Zero && Zero->isZero() &&
20626           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
20627           CC == ISD::SETULT || CC == ISD::SETLT)) {
20628         // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
20629         CombineTo(TheSelect, Sqrt);
20630         return true;
20631       }
20632     }
20633   }
20634   // Cannot simplify select with vector condition
20635   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
20636 
20637   // If this is a select from two identical things, try to pull the operation
20638   // through the select.
20639   if (LHS.getOpcode() != RHS.getOpcode() ||
20640       !LHS.hasOneUse() || !RHS.hasOneUse())
20641     return false;
20642 
20643   // If this is a load and the token chain is identical, replace the select
20644   // of two loads with a load through a select of the address to load from.
20645   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
20646   // constants have been dropped into the constant pool.
20647   if (LHS.getOpcode() == ISD::LOAD) {
20648     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
20649     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
20650 
20651     // Token chains must be identical.
20652     if (LHS.getOperand(0) != RHS.getOperand(0) ||
20653         // Do not let this transformation reduce the number of volatile loads.
20654         // Be conservative for atomics for the moment
20655         // TODO: This does appear to be legal for unordered atomics (see D66309)
20656         !LLD->isSimple() || !RLD->isSimple() ||
20657         // FIXME: If either is a pre/post inc/dec load,
20658         // we'd need to split out the address adjustment.
20659         LLD->isIndexed() || RLD->isIndexed() ||
20660         // If this is an EXTLOAD, the VT's must match.
20661         LLD->getMemoryVT() != RLD->getMemoryVT() ||
20662         // If this is an EXTLOAD, the kind of extension must match.
20663         (LLD->getExtensionType() != RLD->getExtensionType() &&
20664          // The only exception is if one of the extensions is anyext.
20665          LLD->getExtensionType() != ISD::EXTLOAD &&
20666          RLD->getExtensionType() != ISD::EXTLOAD) ||
20667         // FIXME: this discards src value information.  This is
20668         // over-conservative. It would be beneficial to be able to remember
20669         // both potential memory locations.  Since we are discarding
20670         // src value info, don't do the transformation if the memory
20671         // locations are not in the default address space.
20672         LLD->getPointerInfo().getAddrSpace() != 0 ||
20673         RLD->getPointerInfo().getAddrSpace() != 0 ||
20674         // We can't produce a CMOV of a TargetFrameIndex since we won't
20675         // generate the address generation required.
20676         LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
20677         RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
20678         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
20679                                       LLD->getBasePtr().getValueType()))
20680       return false;
20681 
20682     // The loads must not depend on one another.
20683     if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD))
20684       return false;
20685 
20686     // Check that the select condition doesn't reach either load.  If so,
20687     // folding this will induce a cycle into the DAG.  If not, this is safe to
20688     // xform, so create a select of the addresses.
20689 
20690     SmallPtrSet<const SDNode *, 32> Visited;
20691     SmallVector<const SDNode *, 16> Worklist;
20692 
20693     // Always fail if LLD and RLD are not independent. TheSelect is a
20694     // predecessor to all Nodes in question so we need not search past it.
20695 
20696     Visited.insert(TheSelect);
20697     Worklist.push_back(LLD);
20698     Worklist.push_back(RLD);
20699 
20700     if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) ||
20701         SDNode::hasPredecessorHelper(RLD, Visited, Worklist))
20702       return false;
20703 
20704     SDValue Addr;
20705     if (TheSelect->getOpcode() == ISD::SELECT) {
20706       // We cannot do this optimization if any pair of {RLD, LLD} is a
20707       // predecessor to {RLD, LLD, CondNode}. As we've already compared the
20708       // Loads, we only need to check if CondNode is a successor to one of the
20709       // loads. We can further avoid this if there's no use of their chain
20710       // value.
20711       SDNode *CondNode = TheSelect->getOperand(0).getNode();
20712       Worklist.push_back(CondNode);
20713 
20714       if ((LLD->hasAnyUseOfValue(1) &&
20715            SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
20716           (RLD->hasAnyUseOfValue(1) &&
20717            SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
20718         return false;
20719 
20720       Addr = DAG.getSelect(SDLoc(TheSelect),
20721                            LLD->getBasePtr().getValueType(),
20722                            TheSelect->getOperand(0), LLD->getBasePtr(),
20723                            RLD->getBasePtr());
20724     } else {  // Otherwise SELECT_CC
20725       // We cannot do this optimization if any pair of {RLD, LLD} is a
20726       // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
20727       // the Loads, we only need to check if CondLHS/CondRHS is a successor to
20728       // one of the loads. We can further avoid this if there's no use of their
20729       // chain value.
20730 
20731       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
20732       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
20733       Worklist.push_back(CondLHS);
20734       Worklist.push_back(CondRHS);
20735 
20736       if ((LLD->hasAnyUseOfValue(1) &&
20737            SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
20738           (RLD->hasAnyUseOfValue(1) &&
20739            SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
20740         return false;
20741 
20742       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
20743                          LLD->getBasePtr().getValueType(),
20744                          TheSelect->getOperand(0),
20745                          TheSelect->getOperand(1),
20746                          LLD->getBasePtr(), RLD->getBasePtr(),
20747                          TheSelect->getOperand(4));
20748     }
20749 
20750     SDValue Load;
20751     // It is safe to replace the two loads if they have different alignments,
20752     // but the new load must be the minimum (most restrictive) alignment of the
20753     // inputs.
20754     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
20755     MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
20756     if (!RLD->isInvariant())
20757       MMOFlags &= ~MachineMemOperand::MOInvariant;
20758     if (!RLD->isDereferenceable())
20759       MMOFlags &= ~MachineMemOperand::MODereferenceable;
20760     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
20761       // FIXME: Discards pointer and AA info.
20762       Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
20763                          LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
20764                          MMOFlags);
20765     } else {
20766       // FIXME: Discards pointer and AA info.
20767       Load = DAG.getExtLoad(
20768           LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
20769                                                   : LLD->getExtensionType(),
20770           SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
20771           MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
20772     }
20773 
20774     // Users of the select now use the result of the load.
20775     CombineTo(TheSelect, Load);
20776 
20777     // Users of the old loads now use the new load's chain.  We know the
20778     // old-load value is dead now.
20779     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
20780     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
20781     return true;
20782   }
20783 
20784   return false;
20785 }
20786 
20787 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
20788 /// bitwise 'and'.
20789 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
20790                                             SDValue N1, SDValue N2, SDValue N3,
20791                                             ISD::CondCode CC) {
20792   // If this is a select where the false operand is zero and the compare is a
20793   // check of the sign bit, see if we can perform the "gzip trick":
20794   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
20795   // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
20796   EVT XType = N0.getValueType();
20797   EVT AType = N2.getValueType();
20798   if (!isNullConstant(N3) || !XType.bitsGE(AType))
20799     return SDValue();
20800 
20801   // If the comparison is testing for a positive value, we have to invert
20802   // the sign bit mask, so only do that transform if the target has a bitwise
20803   // 'and not' instruction (the invert is free).
20804   if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
20805     // (X > -1) ? A : 0
20806     // (X >  0) ? X : 0 <-- This is canonical signed max.
20807     if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
20808       return SDValue();
20809   } else if (CC == ISD::SETLT) {
20810     // (X <  0) ? A : 0
20811     // (X <  1) ? X : 0 <-- This is un-canonicalized signed min.
20812     if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
20813       return SDValue();
20814   } else {
20815     return SDValue();
20816   }
20817 
20818   // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
20819   // constant.
20820   EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
20821   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
20822   if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
20823     unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
20824     if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) {
20825       SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
20826       SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
20827       AddToWorklist(Shift.getNode());
20828 
20829       if (XType.bitsGT(AType)) {
20830         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
20831         AddToWorklist(Shift.getNode());
20832       }
20833 
20834       if (CC == ISD::SETGT)
20835         Shift = DAG.getNOT(DL, Shift, AType);
20836 
20837       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
20838     }
20839   }
20840 
20841   unsigned ShCt = XType.getSizeInBits() - 1;
20842   if (TLI.shouldAvoidTransformToShift(XType, ShCt))
20843     return SDValue();
20844 
20845   SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
20846   SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
20847   AddToWorklist(Shift.getNode());
20848 
20849   if (XType.bitsGT(AType)) {
20850     Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
20851     AddToWorklist(Shift.getNode());
20852   }
20853 
20854   if (CC == ISD::SETGT)
20855     Shift = DAG.getNOT(DL, Shift, AType);
20856 
20857   return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
20858 }
20859 
20860 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
20861 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
20862 /// in it. This may be a win when the constant is not otherwise available
20863 /// because it replaces two constant pool loads with one.
20864 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
20865     const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
20866     ISD::CondCode CC) {
20867   if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType()))
20868     return SDValue();
20869 
20870   // If we are before legalize types, we want the other legalization to happen
20871   // first (for example, to avoid messing with soft float).
20872   auto *TV = dyn_cast<ConstantFPSDNode>(N2);
20873   auto *FV = dyn_cast<ConstantFPSDNode>(N3);
20874   EVT VT = N2.getValueType();
20875   if (!TV || !FV || !TLI.isTypeLegal(VT))
20876     return SDValue();
20877 
20878   // If a constant can be materialized without loads, this does not make sense.
20879   if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal ||
20880       TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) ||
20881       TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize))
20882     return SDValue();
20883 
20884   // If both constants have multiple uses, then we won't need to do an extra
20885   // load. The values are likely around in registers for other users.
20886   if (!TV->hasOneUse() && !FV->hasOneUse())
20887     return SDValue();
20888 
20889   Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()),
20890                        const_cast<ConstantFP*>(TV->getConstantFPValue()) };
20891   Type *FPTy = Elts[0]->getType();
20892   const DataLayout &TD = DAG.getDataLayout();
20893 
20894   // Create a ConstantArray of the two constants.
20895   Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
20896   SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
20897                                       TD.getPrefTypeAlign(FPTy));
20898   Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
20899 
20900   // Get offsets to the 0 and 1 elements of the array, so we can select between
20901   // them.
20902   SDValue Zero = DAG.getIntPtrConstant(0, DL);
20903   unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
20904   SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
20905   SDValue Cond =
20906       DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC);
20907   AddToWorklist(Cond.getNode());
20908   SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero);
20909   AddToWorklist(CstOffset.getNode());
20910   CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset);
20911   AddToWorklist(CPIdx.getNode());
20912   return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
20913                      MachinePointerInfo::getConstantPool(
20914                          DAG.getMachineFunction()), Alignment);
20915 }
20916 
20917 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
20918 /// where 'cond' is the comparison specified by CC.
20919 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
20920                                       SDValue N2, SDValue N3, ISD::CondCode CC,
20921                                       bool NotExtCompare) {
20922   // (x ? y : y) -> y.
20923   if (N2 == N3) return N2;
20924 
20925   EVT CmpOpVT = N0.getValueType();
20926   EVT CmpResVT = getSetCCResultType(CmpOpVT);
20927   EVT VT = N2.getValueType();
20928   auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
20929   auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
20930   auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
20931 
20932   // Determine if the condition we're dealing with is constant.
20933   if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) {
20934     AddToWorklist(SCC.getNode());
20935     if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) {
20936       // fold select_cc true, x, y -> x
20937       // fold select_cc false, x, y -> y
20938       return !(SCCC->isNullValue()) ? N2 : N3;
20939     }
20940   }
20941 
20942   if (SDValue V =
20943           convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC))
20944     return V;
20945 
20946   if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
20947     return V;
20948 
20949   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
20950   // where y is has a single bit set.
20951   // A plaintext description would be, we can turn the SELECT_CC into an AND
20952   // when the condition can be materialized as an all-ones register.  Any
20953   // single bit-test can be materialized as an all-ones register with
20954   // shift-left and shift-right-arith.
20955   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
20956       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
20957     SDValue AndLHS = N0->getOperand(0);
20958     auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
20959     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
20960       // Shift the tested bit over the sign bit.
20961       const APInt &AndMask = ConstAndRHS->getAPIntValue();
20962       unsigned ShCt = AndMask.getBitWidth() - 1;
20963       if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
20964         SDValue ShlAmt =
20965           DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
20966                           getShiftAmountTy(AndLHS.getValueType()));
20967         SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
20968 
20969         // Now arithmetic right shift it all the way over, so the result is
20970         // either all-ones, or zero.
20971         SDValue ShrAmt =
20972           DAG.getConstant(ShCt, SDLoc(Shl),
20973                           getShiftAmountTy(Shl.getValueType()));
20974         SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
20975 
20976         return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
20977       }
20978     }
20979   }
20980 
20981   // fold select C, 16, 0 -> shl C, 4
20982   bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2();
20983   bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2();
20984 
20985   if ((Fold || Swap) &&
20986       TLI.getBooleanContents(CmpOpVT) ==
20987           TargetLowering::ZeroOrOneBooleanContent &&
20988       (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) {
20989 
20990     if (Swap) {
20991       CC = ISD::getSetCCInverse(CC, CmpOpVT);
20992       std::swap(N2C, N3C);
20993     }
20994 
20995     // If the caller doesn't want us to simplify this into a zext of a compare,
20996     // don't do it.
20997     if (NotExtCompare && N2C->isOne())
20998       return SDValue();
20999 
21000     SDValue Temp, SCC;
21001     // zext (setcc n0, n1)
21002     if (LegalTypes) {
21003       SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC);
21004       if (VT.bitsLT(SCC.getValueType()))
21005         Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT);
21006       else
21007         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
21008     } else {
21009       SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
21010       Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
21011     }
21012 
21013     AddToWorklist(SCC.getNode());
21014     AddToWorklist(Temp.getNode());
21015 
21016     if (N2C->isOne())
21017       return Temp;
21018 
21019     unsigned ShCt = N2C->getAPIntValue().logBase2();
21020     if (TLI.shouldAvoidTransformToShift(VT, ShCt))
21021       return SDValue();
21022 
21023     // shl setcc result by log2 n2c
21024     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
21025                        DAG.getConstant(ShCt, SDLoc(Temp),
21026                                        getShiftAmountTy(Temp.getValueType())));
21027   }
21028 
21029   // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
21030   // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
21031   // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
21032   // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
21033   // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
21034   // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
21035   // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
21036   // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
21037   if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
21038     SDValue ValueOnZero = N2;
21039     SDValue Count = N3;
21040     // If the condition is NE instead of E, swap the operands.
21041     if (CC == ISD::SETNE)
21042       std::swap(ValueOnZero, Count);
21043     // Check if the value on zero is a constant equal to the bits in the type.
21044     if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
21045       if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
21046         // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
21047         // legal, combine to just cttz.
21048         if ((Count.getOpcode() == ISD::CTTZ ||
21049              Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
21050             N0 == Count.getOperand(0) &&
21051             (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
21052           return DAG.getNode(ISD::CTTZ, DL, VT, N0);
21053         // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
21054         // legal, combine to just ctlz.
21055         if ((Count.getOpcode() == ISD::CTLZ ||
21056              Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
21057             N0 == Count.getOperand(0) &&
21058             (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
21059           return DAG.getNode(ISD::CTLZ, DL, VT, N0);
21060       }
21061     }
21062   }
21063 
21064   return SDValue();
21065 }
21066 
21067 /// This is a stub for TargetLowering::SimplifySetCC.
21068 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
21069                                    ISD::CondCode Cond, const SDLoc &DL,
21070                                    bool foldBooleans) {
21071   TargetLowering::DAGCombinerInfo
21072     DagCombineInfo(DAG, Level, false, this);
21073   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
21074 }
21075 
21076 /// Given an ISD::SDIV node expressing a divide by constant, return
21077 /// a DAG expression to select that will generate the same value by multiplying
21078 /// by a magic number.
21079 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
21080 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
21081   // when optimising for minimum size, we don't want to expand a div to a mul
21082   // and a shift.
21083   if (DAG.getMachineFunction().getFunction().hasMinSize())
21084     return SDValue();
21085 
21086   SmallVector<SDNode *, 8> Built;
21087   if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) {
21088     for (SDNode *N : Built)
21089       AddToWorklist(N);
21090     return S;
21091   }
21092 
21093   return SDValue();
21094 }
21095 
21096 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
21097 /// DAG expression that will generate the same value by right shifting.
21098 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
21099   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
21100   if (!C)
21101     return SDValue();
21102 
21103   // Avoid division by zero.
21104   if (C->isNullValue())
21105     return SDValue();
21106 
21107   SmallVector<SDNode *, 8> Built;
21108   if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) {
21109     for (SDNode *N : Built)
21110       AddToWorklist(N);
21111     return S;
21112   }
21113 
21114   return SDValue();
21115 }
21116 
21117 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
21118 /// expression that will generate the same value by multiplying by a magic
21119 /// number.
21120 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
21121 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
21122   // when optimising for minimum size, we don't want to expand a div to a mul
21123   // and a shift.
21124   if (DAG.getMachineFunction().getFunction().hasMinSize())
21125     return SDValue();
21126 
21127   SmallVector<SDNode *, 8> Built;
21128   if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) {
21129     for (SDNode *N : Built)
21130       AddToWorklist(N);
21131     return S;
21132   }
21133 
21134   return SDValue();
21135 }
21136 
21137 /// Determines the LogBase2 value for a non-null input value using the
21138 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
21139 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
21140   EVT VT = V.getValueType();
21141   unsigned EltBits = VT.getScalarSizeInBits();
21142   SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
21143   SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
21144   SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
21145   return LogBase2;
21146 }
21147 
21148 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
21149 /// For the reciprocal, we need to find the zero of the function:
21150 ///   F(X) = A X - 1 [which has a zero at X = 1/A]
21151 ///     =>
21152 ///   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
21153 ///     does not require additional intermediate precision]
21154 /// For the last iteration, put numerator N into it to gain more precision:
21155 ///   Result = N X_i + X_i (N - N A X_i)
21156 SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op,
21157                                       SDNodeFlags Flags) {
21158   if (LegalDAG)
21159     return SDValue();
21160 
21161   // TODO: Handle half and/or extended types?
21162   EVT VT = Op.getValueType();
21163   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
21164     return SDValue();
21165 
21166   // If estimates are explicitly disabled for this function, we're done.
21167   MachineFunction &MF = DAG.getMachineFunction();
21168   int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
21169   if (Enabled == TLI.ReciprocalEstimate::Disabled)
21170     return SDValue();
21171 
21172   // Estimates may be explicitly enabled for this type with a custom number of
21173   // refinement steps.
21174   int Iterations = TLI.getDivRefinementSteps(VT, MF);
21175   if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
21176     AddToWorklist(Est.getNode());
21177 
21178     SDLoc DL(Op);
21179     if (Iterations) {
21180       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
21181 
21182       // Newton iterations: Est = Est + Est (N - Arg * Est)
21183       // If this is the last iteration, also multiply by the numerator.
21184       for (int i = 0; i < Iterations; ++i) {
21185         SDValue MulEst = Est;
21186 
21187         if (i == Iterations - 1) {
21188           MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags);
21189           AddToWorklist(MulEst.getNode());
21190         }
21191 
21192         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags);
21193         AddToWorklist(NewEst.getNode());
21194 
21195         NewEst = DAG.getNode(ISD::FSUB, DL, VT,
21196                              (i == Iterations - 1 ? N : FPOne), NewEst, Flags);
21197         AddToWorklist(NewEst.getNode());
21198 
21199         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
21200         AddToWorklist(NewEst.getNode());
21201 
21202         Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags);
21203         AddToWorklist(Est.getNode());
21204       }
21205     } else {
21206       // If no iterations are available, multiply with N.
21207       Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags);
21208       AddToWorklist(Est.getNode());
21209     }
21210 
21211     return Est;
21212   }
21213 
21214   return SDValue();
21215 }
21216 
21217 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
21218 /// For the reciprocal sqrt, we need to find the zero of the function:
21219 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
21220 ///     =>
21221 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
21222 /// As a result, we precompute A/2 prior to the iteration loop.
21223 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
21224                                          unsigned Iterations,
21225                                          SDNodeFlags Flags, bool Reciprocal) {
21226   EVT VT = Arg.getValueType();
21227   SDLoc DL(Arg);
21228   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
21229 
21230   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
21231   // this entire sequence requires only one FP constant.
21232   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
21233   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
21234 
21235   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
21236   for (unsigned i = 0; i < Iterations; ++i) {
21237     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
21238     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
21239     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
21240     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
21241   }
21242 
21243   // If non-reciprocal square root is requested, multiply the result by Arg.
21244   if (!Reciprocal)
21245     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
21246 
21247   return Est;
21248 }
21249 
21250 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
21251 /// For the reciprocal sqrt, we need to find the zero of the function:
21252 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
21253 ///     =>
21254 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
21255 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
21256                                          unsigned Iterations,
21257                                          SDNodeFlags Flags, bool Reciprocal) {
21258   EVT VT = Arg.getValueType();
21259   SDLoc DL(Arg);
21260   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
21261   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
21262 
21263   // This routine must enter the loop below to work correctly
21264   // when (Reciprocal == false).
21265   assert(Iterations > 0);
21266 
21267   // Newton iterations for reciprocal square root:
21268   // E = (E * -0.5) * ((A * E) * E + -3.0)
21269   for (unsigned i = 0; i < Iterations; ++i) {
21270     SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
21271     SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
21272     SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
21273 
21274     // When calculating a square root at the last iteration build:
21275     // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
21276     // (notice a common subexpression)
21277     SDValue LHS;
21278     if (Reciprocal || (i + 1) < Iterations) {
21279       // RSQRT: LHS = (E * -0.5)
21280       LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
21281     } else {
21282       // SQRT: LHS = (A * E) * -0.5
21283       LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
21284     }
21285 
21286     Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
21287   }
21288 
21289   return Est;
21290 }
21291 
21292 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
21293 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
21294 /// Op can be zero.
21295 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
21296                                            bool Reciprocal) {
21297   if (LegalDAG)
21298     return SDValue();
21299 
21300   // TODO: Handle half and/or extended types?
21301   EVT VT = Op.getValueType();
21302   if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
21303     return SDValue();
21304 
21305   // If estimates are explicitly disabled for this function, we're done.
21306   MachineFunction &MF = DAG.getMachineFunction();
21307   int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
21308   if (Enabled == TLI.ReciprocalEstimate::Disabled)
21309     return SDValue();
21310 
21311   // Estimates may be explicitly enabled for this type with a custom number of
21312   // refinement steps.
21313   int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
21314 
21315   bool UseOneConstNR = false;
21316   if (SDValue Est =
21317       TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
21318                           Reciprocal)) {
21319     AddToWorklist(Est.getNode());
21320 
21321     if (Iterations) {
21322       Est = UseOneConstNR
21323             ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
21324             : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
21325 
21326       if (!Reciprocal) {
21327         // The estimate is now completely wrong if the input was exactly 0.0 or
21328         // possibly a denormal. Force the answer to 0.0 for those cases.
21329         SDLoc DL(Op);
21330         EVT CCVT = getSetCCResultType(VT);
21331         ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
21332         DenormalMode DenormMode = DAG.getDenormalMode(VT);
21333         if (DenormMode.Input == DenormalMode::IEEE) {
21334           // This is specifically a check for the handling of denormal inputs,
21335           // not the result.
21336 
21337           // fabs(X) < SmallestNormal ? 0.0 : Est
21338           const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
21339           APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
21340           SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
21341           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
21342           SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
21343           SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
21344           Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est);
21345         } else {
21346           // X == 0.0 ? 0.0 : Est
21347           SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
21348           SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
21349           Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est);
21350         }
21351       }
21352     }
21353     return Est;
21354   }
21355 
21356   return SDValue();
21357 }
21358 
21359 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
21360   return buildSqrtEstimateImpl(Op, Flags, true);
21361 }
21362 
21363 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
21364   return buildSqrtEstimateImpl(Op, Flags, false);
21365 }
21366 
21367 /// Return true if there is any possibility that the two addresses overlap.
21368 bool DAGCombiner::isAlias(SDNode *Op0, SDNode *Op1) const {
21369 
21370   struct MemUseCharacteristics {
21371     bool IsVolatile;
21372     bool IsAtomic;
21373     SDValue BasePtr;
21374     int64_t Offset;
21375     Optional<int64_t> NumBytes;
21376     MachineMemOperand *MMO;
21377   };
21378 
21379   auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics {
21380     if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) {
21381       int64_t Offset = 0;
21382       if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset()))
21383         Offset = (LSN->getAddressingMode() == ISD::PRE_INC)
21384                      ? C->getSExtValue()
21385                      : (LSN->getAddressingMode() == ISD::PRE_DEC)
21386                            ? -1 * C->getSExtValue()
21387                            : 0;
21388       uint64_t Size =
21389           MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize());
21390       return {LSN->isVolatile(), LSN->isAtomic(), LSN->getBasePtr(),
21391               Offset /*base offset*/,
21392               Optional<int64_t>(Size),
21393               LSN->getMemOperand()};
21394     }
21395     if (const auto *LN = cast<LifetimeSDNode>(N))
21396       return {false /*isVolatile*/, /*isAtomic*/ false, LN->getOperand(1),
21397               (LN->hasOffset()) ? LN->getOffset() : 0,
21398               (LN->hasOffset()) ? Optional<int64_t>(LN->getSize())
21399                                 : Optional<int64_t>(),
21400               (MachineMemOperand *)nullptr};
21401     // Default.
21402     return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(),
21403             (int64_t)0 /*offset*/,
21404             Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr};
21405   };
21406 
21407   MemUseCharacteristics MUC0 = getCharacteristics(Op0),
21408                         MUC1 = getCharacteristics(Op1);
21409 
21410   // If they are to the same address, then they must be aliases.
21411   if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr &&
21412       MUC0.Offset == MUC1.Offset)
21413     return true;
21414 
21415   // If they are both volatile then they cannot be reordered.
21416   if (MUC0.IsVolatile && MUC1.IsVolatile)
21417     return true;
21418 
21419   // Be conservative about atomics for the moment
21420   // TODO: This is way overconservative for unordered atomics (see D66309)
21421   if (MUC0.IsAtomic && MUC1.IsAtomic)
21422     return true;
21423 
21424   if (MUC0.MMO && MUC1.MMO) {
21425     if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
21426         (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
21427       return false;
21428   }
21429 
21430   // Try to prove that there is aliasing, or that there is no aliasing. Either
21431   // way, we can return now. If nothing can be proved, proceed with more tests.
21432   bool IsAlias;
21433   if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes,
21434                                        DAG, IsAlias))
21435     return IsAlias;
21436 
21437   // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
21438   // either are not known.
21439   if (!MUC0.MMO || !MUC1.MMO)
21440     return true;
21441 
21442   // If one operation reads from invariant memory, and the other may store, they
21443   // cannot alias. These should really be checking the equivalent of mayWrite,
21444   // but it only matters for memory nodes other than load /store.
21445   if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
21446       (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
21447     return false;
21448 
21449   // If we know required SrcValue1 and SrcValue2 have relatively large
21450   // alignment compared to the size and offset of the access, we may be able
21451   // to prove they do not alias. This check is conservative for now to catch
21452   // cases created by splitting vector types, it only works when the offsets are
21453   // multiples of the size of the data.
21454   int64_t SrcValOffset0 = MUC0.MMO->getOffset();
21455   int64_t SrcValOffset1 = MUC1.MMO->getOffset();
21456   Align OrigAlignment0 = MUC0.MMO->getBaseAlign();
21457   Align OrigAlignment1 = MUC1.MMO->getBaseAlign();
21458   auto &Size0 = MUC0.NumBytes;
21459   auto &Size1 = MUC1.NumBytes;
21460   if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
21461       Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 &&
21462       OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 &&
21463       SrcValOffset1 % *Size1 == 0) {
21464     int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value();
21465     int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value();
21466 
21467     // There is no overlap between these relatively aligned accesses of
21468     // similar size. Return no alias.
21469     if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0)
21470       return false;
21471   }
21472 
21473   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
21474                    ? CombinerGlobalAA
21475                    : DAG.getSubtarget().useAA();
21476 #ifndef NDEBUG
21477   if (CombinerAAOnlyFunc.getNumOccurrences() &&
21478       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
21479     UseAA = false;
21480 #endif
21481 
21482   if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() &&
21483       Size0.hasValue() && Size1.hasValue()) {
21484     // Use alias analysis information.
21485     int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
21486     int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset;
21487     int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset;
21488     AliasResult AAResult = AA->alias(
21489         MemoryLocation(MUC0.MMO->getValue(), Overlap0,
21490                        UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()),
21491         MemoryLocation(MUC1.MMO->getValue(), Overlap1,
21492                        UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes()));
21493     if (AAResult == NoAlias)
21494       return false;
21495   }
21496 
21497   // Otherwise we have to assume they alias.
21498   return true;
21499 }
21500 
21501 /// Walk up chain skipping non-aliasing memory nodes,
21502 /// looking for aliasing nodes and adding them to the Aliases vector.
21503 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
21504                                    SmallVectorImpl<SDValue> &Aliases) {
21505   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
21506   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
21507 
21508   // Get alias information for node.
21509   // TODO: relax aliasing for unordered atomics (see D66309)
21510   const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple();
21511 
21512   // Starting off.
21513   Chains.push_back(OriginalChain);
21514   unsigned Depth = 0;
21515 
21516   // Attempt to improve chain by a single step
21517   std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool {
21518     switch (C.getOpcode()) {
21519     case ISD::EntryToken:
21520       // No need to mark EntryToken.
21521       C = SDValue();
21522       return true;
21523     case ISD::LOAD:
21524     case ISD::STORE: {
21525       // Get alias information for C.
21526       // TODO: Relax aliasing for unordered atomics (see D66309)
21527       bool IsOpLoad = isa<LoadSDNode>(C.getNode()) &&
21528                       cast<LSBaseSDNode>(C.getNode())->isSimple();
21529       if ((IsLoad && IsOpLoad) || !isAlias(N, C.getNode())) {
21530         // Look further up the chain.
21531         C = C.getOperand(0);
21532         return true;
21533       }
21534       // Alias, so stop here.
21535       return false;
21536     }
21537 
21538     case ISD::CopyFromReg:
21539       // Always forward past past CopyFromReg.
21540       C = C.getOperand(0);
21541       return true;
21542 
21543     case ISD::LIFETIME_START:
21544     case ISD::LIFETIME_END: {
21545       // We can forward past any lifetime start/end that can be proven not to
21546       // alias the memory access.
21547       if (!isAlias(N, C.getNode())) {
21548         // Look further up the chain.
21549         C = C.getOperand(0);
21550         return true;
21551       }
21552       return false;
21553     }
21554     default:
21555       return false;
21556     }
21557   };
21558 
21559   // Look at each chain and determine if it is an alias.  If so, add it to the
21560   // aliases list.  If not, then continue up the chain looking for the next
21561   // candidate.
21562   while (!Chains.empty()) {
21563     SDValue Chain = Chains.pop_back_val();
21564 
21565     // Don't bother if we've seen Chain before.
21566     if (!Visited.insert(Chain.getNode()).second)
21567       continue;
21568 
21569     // For TokenFactor nodes, look at each operand and only continue up the
21570     // chain until we reach the depth limit.
21571     //
21572     // FIXME: The depth check could be made to return the last non-aliasing
21573     // chain we found before we hit a tokenfactor rather than the original
21574     // chain.
21575     if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
21576       Aliases.clear();
21577       Aliases.push_back(OriginalChain);
21578       return;
21579     }
21580 
21581     if (Chain.getOpcode() == ISD::TokenFactor) {
21582       // We have to check each of the operands of the token factor for "small"
21583       // token factors, so we queue them up.  Adding the operands to the queue
21584       // (stack) in reverse order maintains the original order and increases the
21585       // likelihood that getNode will find a matching token factor (CSE.)
21586       if (Chain.getNumOperands() > 16) {
21587         Aliases.push_back(Chain);
21588         continue;
21589       }
21590       for (unsigned n = Chain.getNumOperands(); n;)
21591         Chains.push_back(Chain.getOperand(--n));
21592       ++Depth;
21593       continue;
21594     }
21595     // Everything else
21596     if (ImproveChain(Chain)) {
21597       // Updated Chain Found, Consider new chain if one exists.
21598       if (Chain.getNode())
21599         Chains.push_back(Chain);
21600       ++Depth;
21601       continue;
21602     }
21603     // No Improved Chain Possible, treat as Alias.
21604     Aliases.push_back(Chain);
21605   }
21606 }
21607 
21608 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
21609 /// (aliasing node.)
21610 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
21611   if (OptLevel == CodeGenOpt::None)
21612     return OldChain;
21613 
21614   // Ops for replacing token factor.
21615   SmallVector<SDValue, 8> Aliases;
21616 
21617   // Accumulate all the aliases to this node.
21618   GatherAllAliases(N, OldChain, Aliases);
21619 
21620   // If no operands then chain to entry token.
21621   if (Aliases.size() == 0)
21622     return DAG.getEntryNode();
21623 
21624   // If a single operand then chain to it.  We don't need to revisit it.
21625   if (Aliases.size() == 1)
21626     return Aliases[0];
21627 
21628   // Construct a custom tailored token factor.
21629   return DAG.getTokenFactor(SDLoc(N), Aliases);
21630 }
21631 
21632 namespace {
21633 // TODO: Replace with with std::monostate when we move to C++17.
21634 struct UnitT { } Unit;
21635 bool operator==(const UnitT &, const UnitT &) { return true; }
21636 bool operator!=(const UnitT &, const UnitT &) { return false; }
21637 } // namespace
21638 
21639 // This function tries to collect a bunch of potentially interesting
21640 // nodes to improve the chains of, all at once. This might seem
21641 // redundant, as this function gets called when visiting every store
21642 // node, so why not let the work be done on each store as it's visited?
21643 //
21644 // I believe this is mainly important because MergeConsecutiveStores
21645 // is unable to deal with merging stores of different sizes, so unless
21646 // we improve the chains of all the potential candidates up-front
21647 // before running MergeConsecutiveStores, it might only see some of
21648 // the nodes that will eventually be candidates, and then not be able
21649 // to go from a partially-merged state to the desired final
21650 // fully-merged state.
21651 
21652 bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) {
21653   SmallVector<StoreSDNode *, 8> ChainedStores;
21654   StoreSDNode *STChain = St;
21655   // Intervals records which offsets from BaseIndex have been covered. In
21656   // the common case, every store writes to the immediately previous address
21657   // space and thus merged with the previous interval at insertion time.
21658 
21659   using IMap =
21660       llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>;
21661   IMap::Allocator A;
21662   IMap Intervals(A);
21663 
21664   // This holds the base pointer, index, and the offset in bytes from the base
21665   // pointer.
21666   const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
21667 
21668   // We must have a base and an offset.
21669   if (!BasePtr.getBase().getNode())
21670     return false;
21671 
21672   // Do not handle stores to undef base pointers.
21673   if (BasePtr.getBase().isUndef())
21674     return false;
21675 
21676   // BaseIndexOffset assumes that offsets are fixed-size, which
21677   // is not valid for scalable vectors where the offsets are
21678   // scaled by `vscale`, so bail out early.
21679   if (St->getMemoryVT().isScalableVector())
21680     return false;
21681 
21682   // Add ST's interval.
21683   Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit);
21684 
21685   while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) {
21686     // If the chain has more than one use, then we can't reorder the mem ops.
21687     if (!SDValue(Chain, 0)->hasOneUse())
21688       break;
21689     // TODO: Relax for unordered atomics (see D66309)
21690     if (!Chain->isSimple() || Chain->isIndexed())
21691       break;
21692 
21693     // Find the base pointer and offset for this memory node.
21694     const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG);
21695     // Check that the base pointer is the same as the original one.
21696     int64_t Offset;
21697     if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset))
21698       break;
21699     int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8;
21700     // Make sure we don't overlap with other intervals by checking the ones to
21701     // the left or right before inserting.
21702     auto I = Intervals.find(Offset);
21703     // If there's a next interval, we should end before it.
21704     if (I != Intervals.end() && I.start() < (Offset + Length))
21705       break;
21706     // If there's a previous interval, we should start after it.
21707     if (I != Intervals.begin() && (--I).stop() <= Offset)
21708       break;
21709     Intervals.insert(Offset, Offset + Length, Unit);
21710 
21711     ChainedStores.push_back(Chain);
21712     STChain = Chain;
21713   }
21714 
21715   // If we didn't find a chained store, exit.
21716   if (ChainedStores.size() == 0)
21717     return false;
21718 
21719   // Improve all chained stores (St and ChainedStores members) starting from
21720   // where the store chain ended and return single TokenFactor.
21721   SDValue NewChain = STChain->getChain();
21722   SmallVector<SDValue, 8> TFOps;
21723   for (unsigned I = ChainedStores.size(); I;) {
21724     StoreSDNode *S = ChainedStores[--I];
21725     SDValue BetterChain = FindBetterChain(S, NewChain);
21726     S = cast<StoreSDNode>(DAG.UpdateNodeOperands(
21727         S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3)));
21728     TFOps.push_back(SDValue(S, 0));
21729     ChainedStores[I] = S;
21730   }
21731 
21732   // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
21733   SDValue BetterChain = FindBetterChain(St, NewChain);
21734   SDValue NewST;
21735   if (St->isTruncatingStore())
21736     NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(),
21737                               St->getBasePtr(), St->getMemoryVT(),
21738                               St->getMemOperand());
21739   else
21740     NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(),
21741                          St->getBasePtr(), St->getMemOperand());
21742 
21743   TFOps.push_back(NewST);
21744 
21745   // If we improved every element of TFOps, then we've lost the dependence on
21746   // NewChain to successors of St and we need to add it back to TFOps. Do so at
21747   // the beginning to keep relative order consistent with FindBetterChains.
21748   auto hasImprovedChain = [&](SDValue ST) -> bool {
21749     return ST->getOperand(0) != NewChain;
21750   };
21751   bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain);
21752   if (AddNewChain)
21753     TFOps.insert(TFOps.begin(), NewChain);
21754 
21755   SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps);
21756   CombineTo(St, TF);
21757 
21758   // Add TF and its operands to the worklist.
21759   AddToWorklist(TF.getNode());
21760   for (const SDValue &Op : TF->ops())
21761     AddToWorklist(Op.getNode());
21762   AddToWorklist(STChain);
21763   return true;
21764 }
21765 
21766 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
21767   if (OptLevel == CodeGenOpt::None)
21768     return false;
21769 
21770   const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
21771 
21772   // We must have a base and an offset.
21773   if (!BasePtr.getBase().getNode())
21774     return false;
21775 
21776   // Do not handle stores to undef base pointers.
21777   if (BasePtr.getBase().isUndef())
21778     return false;
21779 
21780   // Directly improve a chain of disjoint stores starting at St.
21781   if (parallelizeChainedStores(St))
21782     return true;
21783 
21784   // Improve St's Chain..
21785   SDValue BetterChain = FindBetterChain(St, St->getChain());
21786   if (St->getChain() != BetterChain) {
21787     replaceStoreChain(St, BetterChain);
21788     return true;
21789   }
21790   return false;
21791 }
21792 
21793 /// This is the entry point for the file.
21794 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
21795                            CodeGenOpt::Level OptLevel) {
21796   /// This is the main entry point to this class.
21797   DAGCombiner(*this, AA, OptLevel).Run(Level);
21798 }
21799