LLVM 23.0.0git
DAGCombiner.cpp
Go to the documentation of this file.
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/APSInt.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/Statistic.h"
52#include "llvm/IR/Attributes.h"
53#include "llvm/IR/Constant.h"
54#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Metadata.h"
63#include "llvm/Support/Debug.h"
71#include <algorithm>
72#include <cassert>
73#include <cstdint>
74#include <functional>
75#include <iterator>
76#include <optional>
77#include <string>
78#include <tuple>
79#include <utility>
80#include <variant>
81
82#include "MatchContext.h"
83#include "SDNodeDbgValue.h"
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88#define DEBUG_TYPE "dagcombine"
89
90STATISTIC(NodesCombined , "Number of dag nodes combined");
91STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
92STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
93STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
94STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
95STATISTIC(SlicedLoads, "Number of load sliced");
96STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
97
98DEBUG_COUNTER(DAGCombineCounter, "dagcombine",
99 "Controls whether a DAG combine is performed for a node");
100
101static cl::opt<bool>
102CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
103 cl::desc("Enable DAG combiner's use of IR alias analysis"));
104
105static cl::opt<bool>
106UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
107 cl::desc("Enable DAG combiner's use of TBAA"));
108
109#ifndef NDEBUG
111CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
112 cl::desc("Only use DAG-combiner alias analysis in this"
113 " function"));
114#endif
115
116/// Hidden option to stress test load slicing, i.e., when this option
117/// is enabled, load slicing bypasses most of its profitability guards.
118static cl::opt<bool>
119StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
120 cl::desc("Bypass the profitability model of load slicing"),
121 cl::init(false));
122
123static cl::opt<bool>
124 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
125 cl::desc("DAG combiner may split indexing from loads"));
126
127static cl::opt<bool>
128 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
129 cl::desc("DAG combiner enable merging multiple stores "
130 "into a wider store"));
131
133 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
134 cl::desc("Limit the number of operands to inline for Token Factors"));
135
137 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
138 cl::desc("Limit the number of times for the same StoreNode and RootNode "
139 "to bail out in store merging dependence check"));
140
142 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
143 cl::desc("DAG combiner enable reducing the width of load/op/store "
144 "sequence"));
146 "combiner-reduce-load-op-store-width-force-narrowing-profitable",
147 cl::Hidden, cl::init(false),
148 cl::desc("DAG combiner force override the narrowing profitable check when "
149 "reducing the width of load/op/store sequences"));
150
152 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
153 cl::desc("DAG combiner enable load/<replace bytes>/store with "
154 "a narrower store"));
155
157 "combiner-topological-sorting", cl::Hidden, cl::init(false),
158 cl::desc("DAG combiner nodes consistently processed in topological order"));
159
160static cl::opt<bool> DisableCombines("combiner-disabled", cl::Hidden,
161 cl::init(false),
162 cl::desc("Disable the DAG combiner"));
163
164namespace {
165
166 class DAGCombiner {
167 SelectionDAG &DAG;
168 const TargetLowering &TLI;
169 const SelectionDAGTargetInfo *STI;
171 CodeGenOptLevel OptLevel;
172 bool LegalDAG = false;
173 bool LegalOperations = false;
174 bool LegalTypes = false;
175 bool ForCodeSize;
176 bool DisableGenericCombines;
177
178 /// Worklist of all of the nodes that need to be simplified.
179 ///
180 /// This must behave as a stack -- new nodes to process are pushed onto the
181 /// back and when processing we pop off of the back.
182 ///
183 /// The worklist will not contain duplicates but may contain null entries
184 /// due to nodes being deleted from the underlying DAG. For fast lookup and
185 /// deduplication, the index of the node in this vector is stored in the
186 /// node in SDNode::CombinerWorklistIndex.
188
189 /// This records all nodes attempted to be added to the worklist since we
190 /// considered a new worklist entry. As we keep do not add duplicate nodes
191 /// in the worklist, this is different from the tail of the worklist.
193
194 /// Map from candidate StoreNode to the pair of RootNode and count.
195 /// The count is used to track how many times we have seen the StoreNode
196 /// with the same RootNode bail out in dependence check. If we have seen
197 /// the bail out for the same pair many times over a limit, we won't
198 /// consider the StoreNode with the same RootNode as store merging
199 /// candidate again.
201
202 // BatchAA - Used for DAG load/store alias analysis.
203 BatchAAResults *BatchAA;
204
205 /// This caches all chains that have already been processed in
206 /// DAGCombiner::getStoreMergeCandidates() and found to have no mergeable
207 /// stores candidates.
208 SmallPtrSet<SDNode *, 4> ChainsWithoutMergeableStores;
209
210 /// When an instruction is simplified, add all users of the instruction to
211 /// the work lists because they might get more simplified now.
212 void AddUsersToWorklist(SDNode *N) {
213 for (SDNode *Node : N->users())
214 AddToWorklist(Node);
215 }
216
217 /// Convenient shorthand to add a node and all of its user to the worklist.
218 void AddToWorklistWithUsers(SDNode *N) {
219 AddUsersToWorklist(N);
220 AddToWorklist(N);
221 }
222
223 // Prune potentially dangling nodes. This is called after
224 // any visit to a node, but should also be called during a visit after any
225 // failed combine which may have created a DAG node.
226 void clearAddedDanglingWorklistEntries() {
227 // Check any nodes added to the worklist to see if they are prunable.
228 while (!PruningList.empty()) {
229 auto *N = PruningList.pop_back_val();
230 if (N->use_empty())
231 recursivelyDeleteUnusedNodes(N);
232 }
233 }
234
235 SDNode *getNextWorklistEntry() {
236 // Before we do any work, remove nodes that are not in use.
237 clearAddedDanglingWorklistEntries();
238 SDNode *N = nullptr;
239 // The Worklist holds the SDNodes in order, but it may contain null
240 // entries.
241 while (!N && !Worklist.empty()) {
242 N = Worklist.pop_back_val();
243 }
244
245 if (N) {
246 assert(N->getCombinerWorklistIndex() >= 0 &&
247 "Found a worklist entry without a corresponding map entry!");
248 // Set to -2 to indicate that we combined the node.
249 N->setCombinerWorklistIndex(-2);
250 }
251 return N;
252 }
253
254 /// Call the node-specific routine that folds each particular type of node.
255 SDValue visit(SDNode *N);
256
257 public:
258 DAGCombiner(SelectionDAG &D, BatchAAResults *BatchAA, CodeGenOptLevel OL)
259 : DAG(D), TLI(D.getTargetLoweringInfo()),
260 STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL),
261 BatchAA(BatchAA) {
262 ForCodeSize = DAG.shouldOptForSize();
263 DisableGenericCombines =
264 DisableCombines || (STI && STI->disableGenericCombines(OptLevel));
265 }
266
267 void ConsiderForPruning(SDNode *N) {
268 // Mark this for potential pruning.
269 PruningList.insert(N);
270 }
271
272 /// Add to the worklist making sure its instance is at the back (next to be
273 /// processed.)
274 void AddToWorklist(SDNode *N, bool IsCandidateForPruning = true,
275 bool SkipIfCombinedBefore = false) {
276 assert(N->getOpcode() != ISD::DELETED_NODE &&
277 "Deleted Node added to Worklist");
278
279 // Skip handle nodes as they can't usefully be combined and confuse the
280 // zero-use deletion strategy.
281 if (N->getOpcode() == ISD::HANDLENODE)
282 return;
283
284 if (SkipIfCombinedBefore && N->getCombinerWorklistIndex() == -2)
285 return;
286
287 if (IsCandidateForPruning)
288 ConsiderForPruning(N);
289
290 if (N->getCombinerWorklistIndex() < 0) {
291 N->setCombinerWorklistIndex(Worklist.size());
292 Worklist.push_back(N);
293 }
294 }
295
296 /// Remove all instances of N from the worklist.
297 void removeFromWorklist(SDNode *N) {
298 PruningList.remove(N);
299 StoreRootCountMap.erase(N);
300
301 int WorklistIndex = N->getCombinerWorklistIndex();
302 // If not in the worklist, the index might be -1 or -2 (was combined
303 // before). As the node gets deleted anyway, there's no need to update
304 // the index.
305 if (WorklistIndex < 0)
306 return; // Not in the worklist.
307
308 // Null out the entry rather than erasing it to avoid a linear operation.
309 Worklist[WorklistIndex] = nullptr;
310 N->setCombinerWorklistIndex(-1);
311 }
312
313 void deleteAndRecombine(SDNode *N);
314 bool recursivelyDeleteUnusedNodes(SDNode *N);
315
316 /// Replaces all uses of the results of one DAG node with new values.
317 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
318 bool AddTo = true);
319
320 /// Replaces all uses of the results of one DAG node with new values.
321 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
322 return CombineTo(N, &Res, 1, AddTo);
323 }
324
325 /// Replaces all uses of the results of one DAG node with new values.
326 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
327 bool AddTo = true) {
328 SDValue To[] = { Res0, Res1 };
329 return CombineTo(N, To, 2, AddTo);
330 }
331
332 SDValue CombineTo(SDNode *N, SmallVectorImpl<SDValue> *To,
333 bool AddTo = true) {
334 return CombineTo(N, To->data(), To->size(), AddTo);
335 }
336
337 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
338
339 private:
340 /// Check the specified integer node value to see if it can be simplified or
341 /// if things it uses can be simplified by bit propagation.
342 /// If so, return true.
343 bool SimplifyDemandedBits(SDValue Op) {
344 unsigned BitWidth = Op.getScalarValueSizeInBits();
345 APInt DemandedBits = APInt::getAllOnes(BitWidth);
346 return SimplifyDemandedBits(Op, DemandedBits);
347 }
348
349 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
350 EVT VT = Op.getValueType();
351 APInt DemandedElts = VT.isFixedLengthVector()
353 : APInt(1, 1);
354 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, false);
355 }
356
357 /// Check the specified vector node value to see if it can be simplified or
358 /// if things it uses can be simplified as it only uses some of the
359 /// elements. If so, return true.
360 bool SimplifyDemandedVectorElts(SDValue Op) {
361 // TODO: For now just pretend it cannot be simplified.
362 if (Op.getValueType().isScalableVector())
363 return false;
364
365 unsigned NumElts = Op.getValueType().getVectorNumElements();
366 APInt DemandedElts = APInt::getAllOnes(NumElts);
367 return SimplifyDemandedVectorElts(Op, DemandedElts);
368 }
369
370 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
371 const APInt &DemandedElts,
372 bool AssumeSingleUse = false);
373 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
374 bool AssumeSingleUse = false);
375
376 bool CombineToPreIndexedLoadStore(SDNode *N);
377 bool CombineToPostIndexedLoadStore(SDNode *N);
378 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
379 bool SliceUpLoad(SDNode *N);
380
381 // Looks up the chain to find a unique (unaliased) store feeding the passed
382 // load. If no such store is found, returns a nullptr.
383 // Note: This will look past a CALLSEQ_START if the load is chained to it so
384 // so that it can find stack stores for byval params.
385 StoreSDNode *getUniqueStoreFeeding(LoadSDNode *LD, int64_t &Offset);
386 // Scalars have size 0 to distinguish from singleton vectors.
387 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
388 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
389 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
390
391 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
392 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
393 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
394 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
395 SDValue PromoteIntBinOp(SDValue Op);
396 SDValue PromoteIntShiftOp(SDValue Op);
397 SDValue PromoteExtend(SDValue Op);
398 bool PromoteLoad(SDValue Op);
399
400 SDValue foldShiftToAvg(SDNode *N, const SDLoc &DL);
401 // Fold `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`
402 SDValue foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT);
403
404 SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
405 SDValue RHS, SDValue True, SDValue False,
406 ISD::CondCode CC);
407
408 /// Call the node-specific routine that knows how to fold each
409 /// particular type of node. If that doesn't do anything, try the
410 /// target-specific DAG combines.
411 SDValue combine(SDNode *N);
412
413 // Visitation implementation - Implement dag node combining for different
414 // node types. The semantics are as follows:
415 // Return Value:
416 // SDValue.getNode() == 0 - No change was made
417 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
418 // otherwise - N should be replaced by the returned Operand.
419 //
420 SDValue visitTokenFactor(SDNode *N);
421 SDValue visitMERGE_VALUES(SDNode *N);
422 SDValue visitADD(SDNode *N);
423 SDValue visitADDLike(SDNode *N);
424 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1,
425 SDNode *LocReference);
426 SDValue visitPTRADD(SDNode *N);
427 SDValue visitSUB(SDNode *N);
428 SDValue visitADDSAT(SDNode *N);
429 SDValue visitSUBSAT(SDNode *N);
430 SDValue visitADDC(SDNode *N);
431 SDValue visitADDO(SDNode *N);
432 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
433 SDValue visitSUBC(SDNode *N);
434 SDValue visitSUBO(SDNode *N);
435 SDValue visitADDE(SDNode *N);
436 SDValue visitUADDO_CARRY(SDNode *N);
437 SDValue visitSADDO_CARRY(SDNode *N);
438 SDValue visitUADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
439 SDNode *N);
440 SDValue visitSADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
441 SDNode *N);
442 SDValue visitSUBE(SDNode *N);
443 SDValue visitUSUBO_CARRY(SDNode *N);
444 SDValue visitSSUBO_CARRY(SDNode *N);
445 SDValue visitMUL(SDNode *N);
446 SDValue visitMULFIX(SDNode *N);
447 SDValue useDivRem(SDNode *N);
448 SDValue visitSDIV(SDNode *N);
449 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
450 SDValue visitUDIV(SDNode *N);
451 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
452 SDValue visitREM(SDNode *N);
453 SDValue visitMULHU(SDNode *N);
454 SDValue visitMULHS(SDNode *N);
455 SDValue visitAVG(SDNode *N);
456 SDValue visitABD(SDNode *N);
457 SDValue visitSMUL_LOHI(SDNode *N);
458 SDValue visitUMUL_LOHI(SDNode *N);
459 SDValue visitMULO(SDNode *N);
460 SDValue visitIMINMAX(SDNode *N);
461 SDValue visitAND(SDNode *N);
462 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
463 SDValue visitOR(SDNode *N);
464 SDValue visitORLike(SDValue N0, SDValue N1, const SDLoc &DL);
465 SDValue visitXOR(SDNode *N);
466 SDValue SimplifyVCastOp(SDNode *N, const SDLoc &DL);
467 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
468 SDValue visitSHL(SDNode *N);
469 SDValue visitSRA(SDNode *N);
470 SDValue visitSRL(SDNode *N);
471 SDValue visitFunnelShift(SDNode *N);
472 SDValue visitSHLSAT(SDNode *N);
473 SDValue visitRotate(SDNode *N);
474 SDValue visitABS(SDNode *N);
475 SDValue visitABS_MIN_POISON(SDNode *N);
476 SDValue visitCLMUL(SDNode *N);
477 SDValue visitPEXT(SDNode *N);
478 SDValue visitPDEP(SDNode *N);
479 SDValue visitBSWAP(SDNode *N);
480 SDValue visitBITREVERSE(SDNode *N);
481 SDValue visitCTLZ(SDNode *N);
482 SDValue visitCTLZ_ZERO_POISON(SDNode *N);
483 SDValue visitCTTZ(SDNode *N);
484 SDValue visitCTTZ_ZERO_POISON(SDNode *N);
485 SDValue visitCTPOP(SDNode *N);
486 SDValue visitSELECT(SDNode *N);
487 SDValue visitVSELECT(SDNode *N);
488 SDValue visitVP_SELECT(SDNode *N);
489 SDValue visitSELECT_CC(SDNode *N);
490 SDValue visitSETCC(SDNode *N);
491 SDValue visitSETCCCARRY(SDNode *N);
492 SDValue visitSIGN_EXTEND(SDNode *N);
493 SDValue visitZERO_EXTEND(SDNode *N);
494 SDValue visitANY_EXTEND(SDNode *N);
495 SDValue visitAssertExt(SDNode *N);
496 SDValue visitAssertAlign(SDNode *N);
497 SDValue visitIS_FPCLASS(SDNode *N);
498 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
499 SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
500 SDValue visitTRUNCATE(SDNode *N);
501 SDValue visitTRUNCATE_USAT_U(SDNode *N);
502 SDValue visitBITCAST(SDNode *N);
503 SDValue visitFREEZE(SDNode *N);
504 SDValue visitBUILD_PAIR(SDNode *N);
505 SDValue visitFADD(SDNode *N);
506 SDValue visitSTRICT_FADD(SDNode *N);
507 SDValue visitFSUB(SDNode *N);
508 SDValue visitFMUL(SDNode *N);
509 SDValue visitFMA(SDNode *N);
510 SDValue visitFMAD(SDNode *N);
511 SDValue visitFMULADD(SDNode *N);
512 SDValue visitFDIV(SDNode *N);
513 SDValue visitFREM(SDNode *N);
514 SDValue visitFSQRT(SDNode *N);
515 SDValue visitFCOPYSIGN(SDNode *N);
516 SDValue visitFPOW(SDNode *N);
517 SDValue visitFCANONICALIZE(SDNode *N);
518 SDValue visitSINT_TO_FP(SDNode *N);
519 SDValue visitUINT_TO_FP(SDNode *N);
520 SDValue visitFP_TO_SINT(SDNode *N);
521 SDValue visitFP_TO_UINT(SDNode *N);
522 SDValue visitXROUND(SDNode *N);
523 SDValue visitFP_ROUND(SDNode *N);
524 SDValue visitFP_EXTEND(SDNode *N);
525 SDValue visitFNEG(SDNode *N);
526 SDValue visitFABS(SDNode *N);
527 SDValue visitFCEIL(SDNode *N);
528 SDValue visitFTRUNC(SDNode *N);
529 SDValue visitFFREXP(SDNode *N);
530 SDValue visitFFLOOR(SDNode *N);
531 SDValue visitFMinMax(SDNode *N);
532 SDValue visitBRCOND(SDNode *N);
533 SDValue visitBR_CC(SDNode *N);
534 SDValue visitLOAD(SDNode *N);
535
536 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
537 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
538 SDValue replaceStoreOfInsertLoad(StoreSDNode *ST);
539
540 bool refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(SDNode *N);
541 SDValue combineStoreConcatTruncVector(StoreSDNode *N);
542 SDValue visitSTORE(SDNode *N);
543 SDValue visitATOMIC_STORE(SDNode *N);
544 SDValue visitLIFETIME_END(SDNode *N);
545 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
546 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
547 SDValue visitBUILD_VECTOR(SDNode *N);
548 SDValue visitCONCAT_VECTORS(SDNode *N);
549 SDValue visitVECTOR_INTERLEAVE(SDNode *N);
550 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
551 SDValue visitVECTOR_SHUFFLE(SDNode *N);
552 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
553 SDValue visitINSERT_SUBVECTOR(SDNode *N);
554 SDValue visitVECTOR_COMPRESS(SDNode *N);
555 SDValue visitMLOAD(SDNode *N);
556 SDValue visitMSTORE(SDNode *N);
557 SDValue visitMGATHER(SDNode *N);
558 SDValue visitMSCATTER(SDNode *N);
559 SDValue visitMHISTOGRAM(SDNode *N);
560 SDValue visitPARTIAL_REDUCE_MLA(SDNode *N);
561 SDValue visitVPGATHER(SDNode *N);
562 SDValue visitVPSCATTER(SDNode *N);
563 SDValue visitVP_STRIDED_LOAD(SDNode *N);
564 SDValue visitVP_STRIDED_STORE(SDNode *N);
565 SDValue visitFP_TO_FP16(SDNode *N);
566 SDValue visitFP16_TO_FP(SDNode *N);
567 SDValue visitFP_TO_BF16(SDNode *N);
568 SDValue visitBF16_TO_FP(SDNode *N);
569 SDValue visitVECREDUCE(SDNode *N);
570 SDValue visitVPOp(SDNode *N);
571 SDValue visitGET_FPENV_MEM(SDNode *N);
572 SDValue visitSET_FPENV_MEM(SDNode *N);
573
574 SDValue visitFADDForFMACombine(SDNode *N);
575 SDValue visitFSUBForFMACombine(SDNode *N);
576 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
577
578 SDValue XformToShuffleWithZero(SDNode *N);
579 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
580 const SDLoc &DL,
581 SDNode *N,
582 SDValue N0,
583 SDValue N1);
584 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
585 SDValue N1, SDNodeFlags Flags);
586 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
587 SDValue N1, SDNodeFlags Flags);
588 SDValue reassociateReduction(unsigned RedOpc, unsigned Opc, const SDLoc &DL,
589 EVT VT, SDValue N0, SDValue N1,
590 SDNodeFlags Flags = SDNodeFlags());
591
592 SDValue visitShiftByConstant(SDNode *N);
593
594 SDValue foldSelectOfConstants(SDNode *N);
595 SDValue foldVSelectOfConstants(SDNode *N);
596 SDValue foldBinOpIntoSelect(SDNode *BO);
597 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
598 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
599 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
600 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
601 SDValue N2, SDValue N3, ISD::CondCode CC,
602 bool NotExtCompare = false);
603 SDValue convertSelectOfFPConstantsToLoadOffset(
604 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
605 ISD::CondCode CC);
606 SDValue foldSignChangeInBitcast(SDNode *N);
607 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
608 SDValue N2, SDValue N3, ISD::CondCode CC);
609 SDValue foldSelectOfBinops(SDNode *N);
610 SDValue foldSextSetcc(SDNode *N);
611 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
612 const SDLoc &DL);
613 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL);
614 SDValue foldABSToABD(SDNode *N, const SDLoc &DL);
615 SDValue foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
616 SDValue False, ISD::CondCode CC, const SDLoc &DL);
617 SDValue foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
618 SDValue False, ISD::CondCode CC, const SDLoc &DL);
619 SDValue unfoldMaskedMerge(SDNode *N);
620 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
621 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
622 const SDLoc &DL, bool foldBooleans);
623 SDValue rebuildSetCC(SDValue N);
624
625 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
626 SDValue &CC, bool MatchStrict = false) const;
627 bool isOneUseSetCC(SDValue N) const;
628
629 SDValue foldAddToAvg(SDNode *N, const SDLoc &DL);
630 SDValue foldSubToAvg(SDNode *N, const SDLoc &DL);
631
632 SDValue foldCTLZToCTLS(SDValue Src, const SDLoc &DL);
633
634 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
635 unsigned HiOp);
636 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
637 SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
638 const TargetLowering &TLI);
639 SDValue foldPartialReduceMLAMulOp(SDNode *N);
640 SDValue foldPartialReduceAdd(SDNode *N);
641
642 SDValue CombineExtLoad(SDNode *N);
643 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
644 SDValue combineRepeatedFPDivisors(SDNode *N);
645 SDValue combineFMulOrFDivWithIntPow2(SDNode *N);
646 SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf);
647 SDValue mergeInsertEltWithShuffle(SDNode *N, unsigned InsIndex);
648 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
649 SDValue combineInsertEltToLoad(SDNode *N, unsigned InsIndex);
650 SDValue foldExtractSubvectorFromConcatVectors(EVT VT, SDValue V,
651 uint64_t ExtIdx,
652 const SDLoc &DL);
653 SDValue BuildSDIV(SDNode *N);
654 SDValue BuildSDIVPow2(SDNode *N);
655 SDValue BuildUDIV(SDNode *N);
656 SDValue BuildSREMPow2(SDNode *N);
657 SDValue buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N);
658 SDValue BuildLogBase2(SDValue V, const SDLoc &DL,
659 bool KnownNeverZero = false,
660 bool InexpensiveOnly = false,
661 std::optional<EVT> OutVT = std::nullopt);
662 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
663 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
664 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
665 SDValue buildSqrtEstimateImpl(SDValue Op, bool Recip, SDNodeFlags Flags);
666 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
667 bool Reciprocal);
668 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
669 bool Reciprocal);
670 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
671 bool DemandHighBits = true);
672 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
673 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
674 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
675 bool HasPos, unsigned PosOpcode,
676 unsigned NegOpcode, const SDLoc &DL);
677 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
678 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
679 bool HasPos, unsigned PosOpcode,
680 unsigned NegOpcode, const SDLoc &DL);
681 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
682 bool FromAdd);
683 SDValue MatchLoadCombine(SDNode *N);
684 SDValue mergeTruncStores(StoreSDNode *N);
685 SDValue reduceLoadWidth(SDNode *N);
686 SDValue ReduceLoadOpStoreWidth(SDNode *N);
687 SDValue splitMergedValStore(StoreSDNode *ST);
688 SDValue TransformFPLoadStorePair(SDNode *N);
689 SDValue convertBuildVecExtToExt(SDNode *N);
690 SDValue convertBuildVecZextToBuildVecWithZeros(SDNode *N);
691 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
692 SDValue reduceBuildVecTruncToBitCast(SDNode *N);
693 SDValue reduceBuildVecToShuffle(SDNode *N);
694 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
695 ArrayRef<int> VectorMask, SDValue VecIn1,
696 SDValue VecIn2, unsigned LeftIdx,
697 bool DidSplitVec);
698 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
699
700 /// Walk up chain skipping non-aliasing memory nodes,
701 /// looking for aliasing nodes and adding them to the Aliases vector.
702 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
703 SmallVectorImpl<SDValue> &Aliases);
704
705 /// Return true if there is any possibility that the two addresses overlap.
706 bool mayAlias(SDNode *Op0, SDNode *Op1) const;
707
708 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
709 /// chain (aliasing node.)
710 SDValue FindBetterChain(SDNode *N, SDValue Chain);
711
712 /// Try to replace a store and any possibly adjacent stores on
713 /// consecutive chains with better chains. Return true only if St is
714 /// replaced.
715 ///
716 /// Notice that other chains may still be replaced even if the function
717 /// returns false.
718 bool findBetterNeighborChains(StoreSDNode *St);
719
720 // Helper for findBetterNeighborChains. Walk up store chain add additional
721 // chained stores that do not overlap and can be parallelized.
722 bool parallelizeChainedStores(StoreSDNode *St);
723
724 /// Holds a pointer to an LSBaseSDNode as well as information on where it
725 /// is located in a sequence of memory operations connected by a chain.
726 struct MemOpLink {
727 // Ptr to the mem node.
728 LSBaseSDNode *MemNode;
729
730 // Offset from the base ptr.
731 int64_t OffsetFromBase;
732
733 MemOpLink(LSBaseSDNode *N, int64_t Offset)
734 : MemNode(N), OffsetFromBase(Offset) {}
735 };
736
737 // Classify the origin of a stored value.
738 enum class StoreSource { Unknown, Constant, Extract, Load };
739 StoreSource getStoreSource(SDValue StoreVal) {
740 switch (StoreVal.getOpcode()) {
741 case ISD::Constant:
742 case ISD::ConstantFP:
743 return StoreSource::Constant;
747 return StoreSource::Constant;
748 return StoreSource::Unknown;
751 return StoreSource::Extract;
752 case ISD::LOAD:
753 return StoreSource::Load;
754 default:
755 return StoreSource::Unknown;
756 }
757 }
758
759 /// This is a helper function for visitMUL to check the profitability
760 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
761 /// MulNode is the original multiply, AddNode is (add x, c1),
762 /// and ConstNode is c2.
763 bool isMulAddWithConstProfitable(SDNode *MulNode, SDValue AddNode,
764 SDValue ConstNode);
765
766 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
767 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
768 /// the type of the loaded value to be extended.
769 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
770 EVT LoadResultTy, EVT &ExtVT);
771
772 /// Helper function to calculate whether the given Load/Store can have its
773 /// width reduced to ExtVT.
774 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
775 EVT &MemVT, unsigned ShAmt = 0);
776
777 /// Used by BackwardsPropagateMask to find suitable loads.
778 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
779 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
780 ConstantSDNode *Mask, SDNode *&NodeToMask);
781 /// Attempt to propagate a given AND node back to load leaves so that they
782 /// can be combined into narrow loads.
783 bool BackwardsPropagateMask(SDNode *N);
784
785 /// Helper function for mergeConsecutiveStores which merges the component
786 /// store chains.
787 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
788 unsigned NumStores);
789
790 /// Helper function for mergeConsecutiveStores which checks if all the store
791 /// nodes have the same underlying object. We can still reuse the first
792 /// store's pointer info if all the stores are from the same object.
793 bool hasSameUnderlyingObj(ArrayRef<MemOpLink> StoreNodes);
794
795 /// This is a helper function for mergeConsecutiveStores. When the source
796 /// elements of the consecutive stores are all constants or all extracted
797 /// vector elements, try to merge them into one larger store introducing
798 /// bitcasts if necessary. \return True if a merged store was created.
799 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
800 EVT MemVT, unsigned NumStores,
801 bool IsConstantSrc, bool UseVector,
802 bool UseTrunc);
803
804 /// This is a helper function for mergeConsecutiveStores. Stores that
805 /// potentially may be merged with St are placed in StoreNodes. On success,
806 /// returns a chain predecessor to all store candidates.
807 SDNode *getStoreMergeCandidates(StoreSDNode *St,
808 SmallVectorImpl<MemOpLink> &StoreNodes);
809
810 /// Helper function for mergeConsecutiveStores. Checks if candidate stores
811 /// have indirect dependency through their operands. RootNode is the
812 /// predecessor to all stores calculated by getStoreMergeCandidates and is
813 /// used to prune the dependency check. \return True if safe to merge.
814 bool checkMergeStoreCandidatesForDependencies(
815 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
816 SDNode *RootNode);
817
818 /// Helper function for tryStoreMergeOfLoads. Checks if the load/store
819 /// chain has a call in it. \return True if a call is found.
820 bool hasCallInLdStChain(StoreSDNode *St, LoadSDNode *Ld);
821
822 /// This is a helper function for mergeConsecutiveStores. Given a list of
823 /// store candidates, find the first N that are consecutive in memory.
824 /// Returns 0 if there are not at least 2 consecutive stores to try merging.
825 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
826 int64_t ElementSizeBytes) const;
827
828 /// This is a helper function for mergeConsecutiveStores. It is used for
829 /// store chains that are composed entirely of constant values.
830 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
831 unsigned NumConsecutiveStores,
832 EVT MemVT, SDNode *Root, bool AllowVectors);
833
834 /// This is a helper function for mergeConsecutiveStores. It is used for
835 /// store chains that are composed entirely of extracted vector elements.
836 /// When extracting multiple vector elements, try to store them in one
837 /// vector store rather than a sequence of scalar stores.
838 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
839 unsigned NumConsecutiveStores, EVT MemVT,
840 SDNode *Root);
841
842 /// This is a helper function for mergeConsecutiveStores. It is used for
843 /// store chains that are composed entirely of loaded values.
844 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
845 unsigned NumConsecutiveStores, EVT MemVT,
846 SDNode *Root, bool AllowVectors,
847 bool IsNonTemporalStore, bool IsNonTemporalLoad);
848
849 /// Merge consecutive store operations into a wide store.
850 /// This optimization uses wide integers or vectors when possible.
851 /// \return true if stores were merged.
852 bool mergeConsecutiveStores(StoreSDNode *St);
853
854 /// Try to transform a truncation where C is a constant:
855 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
856 ///
857 /// \p N needs to be a truncation and its first operand an AND. Other
858 /// requirements are checked by the function (e.g. that trunc is
859 /// single-use) and if missed an empty SDValue is returned.
860 SDValue distributeTruncateThroughAnd(SDNode *N);
861
862 /// Helper function to determine whether the target supports operation
863 /// given by \p Opcode for type \p VT, that is, whether the operation
864 /// is legal or custom before legalizing operations, and whether is
865 /// legal (but not custom) after legalization.
866 bool hasOperation(unsigned Opcode, EVT VT) {
867 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
868 }
869
870 bool hasUMin(EVT VT) const {
871 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
872 return (LK.first == TargetLoweringBase::TypeLegal ||
874 TLI.isOperationLegalOrCustom(ISD::UMIN, LK.second);
875 }
876
877 public:
878 /// Runs the dag combiner on all nodes in the work list
879 void Run(CombineLevel AtLevel);
880
881 SelectionDAG &getDAG() const { return DAG; }
882
883 /// Convenience wrapper around TargetLowering::getShiftAmountTy.
884 EVT getShiftAmountTy(EVT LHSTy) {
885 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout());
886 }
887
888 /// This method returns true if we are running before type legalization or
889 /// if the specified VT is legal.
890 bool isTypeLegal(const EVT &VT) {
891 if (!LegalTypes) return true;
892 return TLI.isTypeLegal(VT);
893 }
894
895 /// Convenience wrapper around TargetLowering::getSetCCResultType
896 EVT getSetCCResultType(EVT VT) const {
897 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
898 }
899
900 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
901 SDValue OrigLoad, SDValue ExtLoad,
902 ISD::NodeType ExtType);
903 };
904
905/// This class is a DAGUpdateListener that removes any deleted
906/// nodes from the worklist.
907class WorklistRemover : public SelectionDAG::DAGUpdateListener {
908 DAGCombiner &DC;
909
910public:
911 explicit WorklistRemover(DAGCombiner &dc)
912 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
913
914 void NodeDeleted(SDNode *N, SDNode *E) override {
915 DC.removeFromWorklist(N);
916 }
917};
918
919class WorklistInserter : public SelectionDAG::DAGUpdateListener {
920 DAGCombiner &DC;
921
922public:
923 explicit WorklistInserter(DAGCombiner &dc)
924 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
925
926 // FIXME: Ideally we could add N to the worklist, but this causes exponential
927 // compile time costs in large DAGs, e.g. Halide.
928 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
929};
930
931} // end anonymous namespace
932
933//===----------------------------------------------------------------------===//
934// TargetLowering::DAGCombinerInfo implementation
935//===----------------------------------------------------------------------===//
936
938 ((DAGCombiner*)DC)->AddToWorklist(N);
939}
940
942CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
943 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
944}
945
947CombineTo(SDNode *N, SDValue Res, bool AddTo) {
948 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
949}
950
952CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
953 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
954}
955
958 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
959}
960
963 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
964}
965
966//===----------------------------------------------------------------------===//
967// Helper Functions
968//===----------------------------------------------------------------------===//
969
970void DAGCombiner::deleteAndRecombine(SDNode *N) {
971 removeFromWorklist(N);
972
973 // If the operands of this node are only used by the node, they will now be
974 // dead. Make sure to re-visit them and recursively delete dead nodes.
975 for (const SDValue &Op : N->ops())
976 // For an operand generating multiple values, one of the values may
977 // become dead allowing further simplification (e.g. split index
978 // arithmetic from an indexed load).
979 if (Op->hasOneUse() || Op->getNumValues() > 1)
980 AddToWorklist(Op.getNode());
981
982 DAG.DeleteNode(N);
983}
984
985// APInts must be the same size for most operations, this helper
986// function zero extends the shorter of the pair so that they match.
987// We provide an Offset so that we can create bitwidths that won't overflow.
988static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
989 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
990 LHS = LHS.zext(Bits);
991 RHS = RHS.zext(Bits);
992}
993
994// Return true if this node is a setcc, or is a select_cc
995// that selects between the target values used for true and false, making it
996// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
997// the appropriate nodes based on the type of node we are checking. This
998// simplifies life a bit for the callers.
999bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
1000 SDValue &CC, bool MatchStrict) const {
1001 if (N.getOpcode() == ISD::SETCC) {
1002 LHS = N.getOperand(0);
1003 RHS = N.getOperand(1);
1004 CC = N.getOperand(2);
1005 return true;
1006 }
1007
1008 if (MatchStrict &&
1009 (N.getOpcode() == ISD::STRICT_FSETCC ||
1010 N.getOpcode() == ISD::STRICT_FSETCCS)) {
1011 LHS = N.getOperand(1);
1012 RHS = N.getOperand(2);
1013 CC = N.getOperand(3);
1014 return true;
1015 }
1016
1017 if (N.getOpcode() != ISD::SELECT_CC || !TLI.isConstTrueVal(N.getOperand(2)) ||
1018 !TLI.isConstFalseVal(N.getOperand(3)))
1019 return false;
1020
1021 if (TLI.getBooleanContents(N.getValueType()) ==
1023 return false;
1024
1025 LHS = N.getOperand(0);
1026 RHS = N.getOperand(1);
1027 CC = N.getOperand(4);
1028 return true;
1029}
1030
1031/// Return true if this is a SetCC-equivalent operation with only one use.
1032/// If this is true, it allows the users to invert the operation for free when
1033/// it is profitable to do so.
1034bool DAGCombiner::isOneUseSetCC(SDValue N) const {
1035 SDValue N0, N1, N2;
1036 if (isSetCCEquivalent(N, N0, N1, N2) && N->hasOneUse())
1037 return true;
1038 return false;
1039}
1040
1042 if (!ScalarTy.isSimple())
1043 return false;
1044
1045 uint64_t MaskForTy = 0ULL;
1046 switch (ScalarTy.getSimpleVT().SimpleTy) {
1047 case MVT::i8:
1048 MaskForTy = 0xFFULL;
1049 break;
1050 case MVT::i16:
1051 MaskForTy = 0xFFFFULL;
1052 break;
1053 case MVT::i32:
1054 MaskForTy = 0xFFFFFFFFULL;
1055 break;
1056 default:
1057 return false;
1058 break;
1059 }
1060
1061 APInt Val;
1062 if (ISD::isConstantSplatVector(N, Val))
1063 return Val.getLimitedValue() == MaskForTy;
1064
1065 return false;
1066}
1067
1068// Determines if it is a constant integer or a splat/build vector of constant
1069// integers (and undefs).
1070// Do not permit build vector implicit truncation unless AllowTruncation is set.
1071static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false,
1072 bool AllowTruncation = false) {
1074 return !(Const->isOpaque() && NoOpaques);
1075 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
1076 return false;
1077 unsigned BitWidth = N.getScalarValueSizeInBits();
1078 for (const SDValue &Op : N->op_values()) {
1079 if (Op.isUndef())
1080 continue;
1082 if (!Const || (Const->isOpaque() && NoOpaques))
1083 return false;
1084 // When AllowTruncation is true, allow constants that have been promoted
1085 // during type legalization as long as the value fits in the target type.
1086 if ((AllowTruncation &&
1087 Const->getAPIntValue().getActiveBits() > BitWidth) ||
1088 (!AllowTruncation && Const->getAPIntValue().getBitWidth() != BitWidth))
1089 return false;
1090 }
1091 return true;
1092}
1093
1094// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1095// undef's.
1096static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
1097 if (V.getOpcode() != ISD::BUILD_VECTOR)
1098 return false;
1099 return isConstantOrConstantVector(V, NoOpaques) ||
1101}
1102
1103// Determine if this an indexed load with an opaque target constant index.
1104static bool canSplitIdx(LoadSDNode *LD) {
1105 return MaySplitLoadIndex &&
1106 (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
1107 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
1108}
1109
1110bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
1111 const SDLoc &DL,
1112 SDNode *N,
1113 SDValue N0,
1114 SDValue N1) {
1115 // Currently this only tries to ensure we don't undo the GEP splits done by
1116 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1117 // we check if the following transformation would be problematic:
1118 // (load/store (add, (add, x, offset1), offset2)) ->
1119 // (load/store (add, x, offset1+offset2)).
1120
1121 // (load/store (add, (add, x, y), offset2)) ->
1122 // (load/store (add, (add, x, offset2), y)).
1123
1124 if (!N0.isAnyAdd())
1125 return false;
1126
1127 // Check for vscale addressing modes.
1128 // (load/store (add/sub (add x, y), vscale))
1129 // (load/store (add/sub (add x, y), (lsl vscale, C)))
1130 // (load/store (add/sub (add x, y), (mul vscale, C)))
1131 if ((N1.getOpcode() == ISD::VSCALE ||
1132 ((N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::MUL) &&
1133 N1.getOperand(0).getOpcode() == ISD::VSCALE &&
1135 N1.getValueType().getFixedSizeInBits() <= 64) {
1136 int64_t ScalableOffset = N1.getOpcode() == ISD::VSCALE
1137 ? N1.getConstantOperandVal(0)
1138 : (N1.getOperand(0).getConstantOperandVal(0) *
1139 (N1.getOpcode() == ISD::SHL
1140 ? (1LL << N1.getConstantOperandVal(1))
1141 : N1.getConstantOperandVal(1)));
1142 if (Opc == ISD::SUB)
1143 ScalableOffset = -ScalableOffset;
1144 if (all_of(N->users(), [&](SDNode *Node) {
1145 if (auto *LoadStore = dyn_cast<MemSDNode>(Node);
1146 LoadStore && LoadStore->hasUniqueMemOperand() &&
1147 LoadStore->getBasePtr().getNode() == N) {
1148 TargetLoweringBase::AddrMode AM;
1149 AM.HasBaseReg = true;
1150 AM.ScalableOffset = ScalableOffset;
1151 EVT VT = LoadStore->getMemoryVT();
1152 unsigned AS = LoadStore->getAddressSpace();
1153 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1154 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy,
1155 AS);
1156 }
1157 return false;
1158 }))
1159 return true;
1160 }
1161
1162 if (Opc != ISD::ADD && Opc != ISD::PTRADD)
1163 return false;
1164
1165 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1166 if (!C2)
1167 return false;
1168
1169 const APInt &C2APIntVal = C2->getAPIntValue();
1170 if (C2APIntVal.getSignificantBits() > 64)
1171 return false;
1172
1173 if (auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1174 if (N0.hasOneUse())
1175 return false;
1176
1177 const APInt &C1APIntVal = C1->getAPIntValue();
1178 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1179 if (CombinedValueIntVal.getSignificantBits() > 64)
1180 return false;
1181 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1182
1183 for (SDNode *Node : N->users()) {
1184 if (auto *LoadStore = dyn_cast<MemSDNode>(Node)) {
1185 if (!LoadStore->hasUniqueMemOperand())
1186 continue;
1187 // Is x[offset2] already not a legal addressing mode? If so then
1188 // reassociating the constants breaks nothing (we test offset2 because
1189 // that's the one we hope to fold into the load or store).
1190 TargetLoweringBase::AddrMode AM;
1191 AM.HasBaseReg = true;
1192 AM.BaseOffs = C2APIntVal.getSExtValue();
1193 EVT VT = LoadStore->getMemoryVT();
1194 unsigned AS = LoadStore->getAddressSpace();
1195 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1196 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1197 continue;
1198
1199 // Would x[offset1+offset2] still be a legal addressing mode?
1200 AM.BaseOffs = CombinedValue;
1201 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1202 return true;
1203 }
1204 }
1205 } else {
1206 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N0.getOperand(1)))
1207 if (GA->getOpcode() == ISD::GlobalAddress && TLI.isOffsetFoldingLegal(GA))
1208 return false;
1209
1210 for (SDNode *Node : N->users()) {
1211 auto *LoadStore = dyn_cast<MemSDNode>(Node);
1212 if (!LoadStore || !LoadStore->hasUniqueMemOperand())
1213 return false;
1214
1215 // Is x[offset2] a legal addressing mode? If so then
1216 // reassociating the constants breaks address pattern
1217 TargetLoweringBase::AddrMode AM;
1218 AM.HasBaseReg = true;
1219 AM.BaseOffs = C2APIntVal.getSExtValue();
1220 EVT VT = LoadStore->getMemoryVT();
1221 unsigned AS = LoadStore->getAddressSpace();
1222 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1223 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1224 return false;
1225 }
1226 return true;
1227 }
1228
1229 return false;
1230}
1231
1232/// Helper for DAGCombiner::reassociateOps. Try to reassociate (Opc N0, N1) if
1233/// \p N0 is the same kind of operation as \p Opc.
1234SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1235 SDValue N0, SDValue N1,
1236 SDNodeFlags Flags) {
1237 EVT VT = N0.getValueType();
1238
1239 if (N0.getOpcode() != Opc)
1240 return SDValue();
1241
1242 SDValue N00 = N0.getOperand(0);
1243 SDValue N01 = N0.getOperand(1);
1244
1246 SDNodeFlags NewFlags;
1247 if (N0.getOpcode() == ISD::ADD && N0->getFlags().hasNoUnsignedWrap() &&
1248 Flags.hasNoUnsignedWrap())
1249 NewFlags |= SDNodeFlags::NoUnsignedWrap;
1250
1252 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1253 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1})) {
1254 NewFlags.setDisjoint(Flags.hasDisjoint() &&
1255 N0->getFlags().hasDisjoint());
1256 return DAG.getNode(Opc, DL, VT, N00, OpNode, NewFlags);
1257 }
1258 return SDValue();
1259 }
1260 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1261 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1262 // iff (op x, c1) has one use
1263 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, NewFlags);
1264 return DAG.getNode(Opc, DL, VT, OpNode, N01, NewFlags);
1265 }
1266 }
1267
1268 // Check for repeated operand logic simplifications.
1269 if (Opc == ISD::AND || Opc == ISD::OR) {
1270 // (N00 & N01) & N00 --> N00 & N01
1271 // (N00 & N01) & N01 --> N00 & N01
1272 // (N00 | N01) | N00 --> N00 | N01
1273 // (N00 | N01) | N01 --> N00 | N01
1274 if (N1 == N00 || N1 == N01)
1275 return N0;
1276 }
1277 if (Opc == ISD::XOR) {
1278 // (N00 ^ N01) ^ N00 --> N01
1279 if (N1 == N00)
1280 return N01;
1281 // (N00 ^ N01) ^ N01 --> N00
1282 if (N1 == N01)
1283 return N00;
1284 }
1285
1286 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1287 if (N1 != N01) {
1288 // Reassociate if (op N00, N1) already exist
1289 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N00, N1})) {
1290 // if Op (Op N00, N1), N01 already exist
1291 // we need to stop reassciate to avoid dead loop
1292 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N01}))
1293 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N01);
1294 }
1295 }
1296
1297 if (N1 != N00) {
1298 // Reassociate if (op N01, N1) already exist
1299 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N01, N1})) {
1300 // if Op (Op N01, N1), N00 already exist
1301 // we need to stop reassciate to avoid dead loop
1302 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N00}))
1303 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N00);
1304 }
1305 }
1306
1307 // Reassociate the operands from (OR/AND (OR/AND(N00, N001)), N1) to (OR/AND
1308 // (OR/AND(N00, N1)), N01) when N00 and N1 are comparisons with the same
1309 // predicate or to (OR/AND (OR/AND(N1, N01)), N00) when N01 and N1 are
1310 // comparisons with the same predicate. This enables optimizations as the
1311 // following one:
1312 // CMP(A,C)||CMP(B,C) => CMP(MIN/MAX(A,B), C)
1313 // CMP(A,C)&&CMP(B,C) => CMP(MIN/MAX(A,B), C)
1314 if (Opc == ISD::AND || Opc == ISD::OR) {
1315 if (N1->getOpcode() == ISD::SETCC && N00->getOpcode() == ISD::SETCC &&
1316 N01->getOpcode() == ISD::SETCC) {
1317 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
1318 ISD::CondCode CC00 = cast<CondCodeSDNode>(N00.getOperand(2))->get();
1319 ISD::CondCode CC01 = cast<CondCodeSDNode>(N01.getOperand(2))->get();
1320 if (CC1 == CC00 && CC1 != CC01) {
1321 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, Flags);
1322 return DAG.getNode(Opc, DL, VT, OpNode, N01, Flags);
1323 }
1324 if (CC1 == CC01 && CC1 != CC00) {
1325 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N01, N1, Flags);
1326 return DAG.getNode(Opc, DL, VT, OpNode, N00, Flags);
1327 }
1328 }
1329 }
1330 }
1331
1332 return SDValue();
1333}
1334
1335/// Try to reassociate commutative (Opc N0, N1) if either \p N0 or \p N1 is the
1336/// same kind of operation as \p Opc.
1337SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
1338 SDValue N1, SDNodeFlags Flags) {
1339 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
1340
1341 // Floating-point reassociation is not allowed without loose FP math.
1342 if (N0.getValueType().isFloatingPoint() ||
1344 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1345 return SDValue();
1346
1347 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1, Flags))
1348 return Combined;
1349 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0, Flags))
1350 return Combined;
1351 return SDValue();
1352}
1353
1354// Try to fold Opc(vecreduce(x), vecreduce(y)) -> vecreduce(Opc(x, y))
1355// Note that we only expect Flags to be passed from FP operations. For integer
1356// operations they need to be dropped.
1357SDValue DAGCombiner::reassociateReduction(unsigned RedOpc, unsigned Opc,
1358 const SDLoc &DL, EVT VT, SDValue N0,
1359 SDValue N1, SDNodeFlags Flags) {
1360 if (N0.getOpcode() == RedOpc && N1.getOpcode() == RedOpc &&
1361 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1362 N0->hasOneUse() && N1->hasOneUse() &&
1364 TLI.shouldReassociateReduction(RedOpc, N0.getOperand(0).getValueType())) {
1365 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
1366 return DAG.getNode(RedOpc, DL, VT,
1367 DAG.getNode(Opc, DL, N0.getOperand(0).getValueType(),
1368 N0.getOperand(0), N1.getOperand(0)));
1369 }
1370
1371 // Reassociate op(op(vecreduce(a), b), op(vecreduce(c), d)) into
1372 // op(vecreduce(op(a, c)), op(b, d)), to combine the reductions into a
1373 // single node.
1374 SDValue A, B, C, D, RedA, RedB;
1375 if (sd_match(N0,
1377 Opc, m_Value(RedA, m_OneUse(m_UnaryOp(RedOpc, m_Value(A)))),
1378 m_Value(B, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1379 sd_match(N1,
1381 Opc, m_Value(RedB, m_OneUse(m_UnaryOp(RedOpc, m_Value(C)))),
1382 m_Value(D, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1383 A.getValueType() == C.getValueType() &&
1384 hasOperation(Opc, A.getValueType()) &&
1385 TLI.shouldReassociateReduction(RedOpc, VT)) {
1386 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1387 (!N0->getFlags().hasAllowReassociation() ||
1389 !RedA->getFlags().hasAllowReassociation() ||
1390 !RedB->getFlags().hasAllowReassociation()))
1391 return SDValue();
1392 SelectionDAG::FlagInserter FlagsInserter(
1393 DAG, Flags & N0->getFlags() & N1->getFlags() & RedA->getFlags() &
1394 RedB->getFlags());
1395 SDValue Op = DAG.getNode(Opc, DL, A.getValueType(), A, C);
1396 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1397 SDValue Op2 = DAG.getNode(Opc, DL, VT, B, D);
1398 return DAG.getNode(Opc, DL, VT, Red, Op2);
1399 }
1400
1401 // Reassociate a reduction chain so two reductions become adjacent and the
1402 // folds above can merge them:
1403 // op(vecreduce(X), op(vecreduce(Y), Z))
1404 // -> op(vecreduce(op(X, Y)), Z)
1405 // Applied to fixpoint by the combiner worklist, this collapses an
1406 // arbitrarily long chain of reductions (such as the left-leaning chain SLP
1407 // emits) into a single reduction.
1408 auto FoldReductionChain = [&](SDValue Red0, SDValue Chain) -> SDValue {
1409 SDValue X, Y, Z, RedY;
1410 if (!sd_match(Red0, m_OneUse(m_UnaryOp(RedOpc, m_Value(X)))) ||
1411 !sd_match(
1412 Chain,
1414 Opc, m_Value(RedY, m_OneUse(m_UnaryOp(RedOpc, m_Value(Y)))),
1415 m_Value(Z, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) ||
1416 X.getValueType() != Y.getValueType() ||
1417 !hasOperation(Opc, X.getValueType()) ||
1418 !TLI.shouldReassociateReduction(RedOpc, VT))
1419 return SDValue();
1420 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1421 (!Chain->getFlags().hasAllowReassociation() ||
1422 !Red0->getFlags().hasAllowReassociation() ||
1423 !RedY->getFlags().hasAllowReassociation()))
1424 return SDValue();
1425 SelectionDAG::FlagInserter FlagsInserter(
1426 DAG, Flags & Chain->getFlags() & Red0->getFlags() & RedY->getFlags());
1427 SDValue Op = DAG.getNode(Opc, DL, X.getValueType(), X, Y);
1428 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1429 return DAG.getNode(Opc, DL, VT, Red, Z);
1430 };
1431 if (SDValue V = FoldReductionChain(N0, N1))
1432 return V;
1433 if (SDValue V = FoldReductionChain(N1, N0))
1434 return V;
1435
1436 return SDValue();
1437}
1438
1439SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1440 bool AddTo) {
1441 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1442 ++NodesCombined;
1443 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1444 To[0].dump(&DAG);
1445 dbgs() << " and " << NumTo - 1 << " other values\n");
1446 for (unsigned i = 0, e = NumTo; i != e; ++i)
1447 assert((!To[i].getNode() ||
1448 N->getValueType(i) == To[i].getValueType()) &&
1449 "Cannot combine value to value of different type!");
1450
1451 WorklistRemover DeadNodes(*this);
1452 DAG.ReplaceAllUsesWith(N, To);
1453 if (AddTo) {
1454 // Push the new nodes and any users onto the worklist
1455 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1456 if (To[i].getNode())
1457 AddToWorklistWithUsers(To[i].getNode());
1458 }
1459 }
1460
1461 // Finally, if the node is now dead, remove it from the graph. The node
1462 // may not be dead if the replacement process recursively simplified to
1463 // something else needing this node.
1464 if (N->use_empty())
1465 deleteAndRecombine(N);
1466 return SDValue(N, 0);
1467}
1468
1469void DAGCombiner::
1470CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1471 // Replace the old value with the new one.
1472 ++NodesCombined;
1473 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.dump(&DAG);
1474 dbgs() << "\nWith: "; TLO.New.dump(&DAG); dbgs() << '\n');
1475
1476 // Replace all uses.
1477 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1478
1479 // Push the new node and any (possibly new) users onto the worklist.
1480 AddToWorklistWithUsers(TLO.New.getNode());
1481
1482 // Finally, if the node is now dead, remove it from the graph.
1483 recursivelyDeleteUnusedNodes(TLO.Old.getNode());
1484}
1485
1486/// Check the specified integer node value to see if it can be simplified or if
1487/// things it uses can be simplified by bit propagation. If so, return true.
1488bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1489 const APInt &DemandedElts,
1490 bool AssumeSingleUse) {
1491 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1492 KnownBits Known;
1493 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1494 AssumeSingleUse))
1495 return false;
1496
1497 // Revisit the node.
1498 AddToWorklist(Op.getNode());
1499
1500 CommitTargetLoweringOpt(TLO);
1501 return true;
1502}
1503
1504/// Check the specified vector node value to see if it can be simplified or
1505/// if things it uses can be simplified as it only uses some of the elements.
1506/// If so, return true.
1507bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1508 const APInt &DemandedElts,
1509 bool AssumeSingleUse) {
1510 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1511 APInt KnownUndef, KnownZero;
1512 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1513 TLO, 0, AssumeSingleUse))
1514 return false;
1515
1516 // Revisit the node.
1517 AddToWorklist(Op.getNode());
1518
1519 CommitTargetLoweringOpt(TLO);
1520 return true;
1521}
1522
1523void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1524 SDLoc DL(Load);
1525 EVT VT = Load->getValueType(0);
1526 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1527
1528 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1529 Trunc.dump(&DAG); dbgs() << '\n');
1530
1531 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1532 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1533
1534 AddToWorklist(Trunc.getNode());
1535 recursivelyDeleteUnusedNodes(Load);
1536}
1537
1538SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1539 Replace = false;
1540 SDLoc DL(Op);
1541 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1542 LoadSDNode *LD = cast<LoadSDNode>(Op);
1543 EVT MemVT = LD->getMemoryVT();
1545 : LD->getExtensionType();
1546 Replace = true;
1547 return DAG.getExtLoad(ExtType, DL, PVT,
1548 LD->getChain(), LD->getBasePtr(),
1549 MemVT, LD->getMemOperand());
1550 }
1551
1552 unsigned Opc = Op.getOpcode();
1553 switch (Opc) {
1554 default: break;
1555 case ISD::AssertSext:
1556 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1557 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1558 break;
1559 case ISD::AssertZext:
1560 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1561 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1562 break;
1563 case ISD::Constant: {
1564 unsigned ExtOpc =
1565 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1566 return DAG.getNode(ExtOpc, DL, PVT, Op);
1567 }
1568 }
1569
1570 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1571 return SDValue();
1572 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1573}
1574
1575SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1577 return SDValue();
1578 EVT OldVT = Op.getValueType();
1579 SDLoc DL(Op);
1580 bool Replace = false;
1581 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1582 if (!NewOp.getNode())
1583 return SDValue();
1584 AddToWorklist(NewOp.getNode());
1585
1586 if (Replace)
1587 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1588 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1589 DAG.getValueType(OldVT));
1590}
1591
1592SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1593 EVT OldVT = Op.getValueType();
1594 SDLoc DL(Op);
1595 bool Replace = false;
1596 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1597 if (!NewOp.getNode())
1598 return SDValue();
1599 AddToWorklist(NewOp.getNode());
1600
1601 if (Replace)
1602 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1603 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1604}
1605
1606/// Promote the specified integer binary operation if the target indicates it is
1607/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1608/// i32 since i16 instructions are longer.
1609SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1610 if (!LegalOperations)
1611 return SDValue();
1612
1613 EVT VT = Op.getValueType();
1614 if (VT.isVector() || !VT.isInteger())
1615 return SDValue();
1616
1617 // If operation type is 'undesirable', e.g. i16 on x86, consider
1618 // promoting it.
1619 unsigned Opc = Op.getOpcode();
1620 if (TLI.isTypeDesirableForOp(Opc, VT))
1621 return SDValue();
1622
1623 EVT PVT = VT;
1624 // Consult target whether it is a good idea to promote this operation and
1625 // what's the right type to promote it to.
1626 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1627 assert(PVT != VT && "Don't know what type to promote to!");
1628
1629 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1630
1631 bool Replace0 = false;
1632 SDValue N0 = Op.getOperand(0);
1633 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1634
1635 bool Replace1 = false;
1636 SDValue N1 = Op.getOperand(1);
1637 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1638 SDLoc DL(Op);
1639
1640 SDValue RV =
1641 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1642
1643 // We are always replacing N0/N1's use in N and only need additional
1644 // replacements if there are additional uses.
1645 // Note: We are checking uses of the *nodes* (SDNode) rather than values
1646 // (SDValue) here because the node may reference multiple values
1647 // (for example, the chain value of a load node).
1648 Replace0 &= !N0->hasOneUse();
1649 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1650
1651 // Combine Op here so it is preserved past replacements.
1652 CombineTo(Op.getNode(), RV);
1653
1654 // If operands have a use ordering, make sure we deal with
1655 // predecessor first.
1656 if (Replace0 && Replace1 && N0->isPredecessorOf(N1.getNode())) {
1657 std::swap(N0, N1);
1658 std::swap(NN0, NN1);
1659 }
1660
1661 if (Replace0) {
1662 AddToWorklist(NN0.getNode());
1663 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1664 }
1665 if (Replace1) {
1666 AddToWorklist(NN1.getNode());
1667 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1668 }
1669 return Op;
1670 }
1671 return SDValue();
1672}
1673
1674/// Promote the specified integer shift operation if the target indicates it is
1675/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1676/// i32 since i16 instructions are longer.
1677SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1678 if (!LegalOperations)
1679 return SDValue();
1680
1681 EVT VT = Op.getValueType();
1682 if (VT.isVector() || !VT.isInteger())
1683 return SDValue();
1684
1685 // If operation type is 'undesirable', e.g. i16 on x86, consider
1686 // promoting it.
1687 unsigned Opc = Op.getOpcode();
1688 if (TLI.isTypeDesirableForOp(Opc, VT))
1689 return SDValue();
1690
1691 EVT PVT = VT;
1692 // Consult target whether it is a good idea to promote this operation and
1693 // what's the right type to promote it to.
1694 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1695 assert(PVT != VT && "Don't know what type to promote to!");
1696
1697 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1698
1699 SDNodeFlags TruncFlags;
1700 bool Replace = false;
1701 SDValue N0 = Op.getOperand(0);
1702 if (Opc == ISD::SRA) {
1703 N0 = SExtPromoteOperand(N0, PVT);
1704 } else if (Opc == ISD::SRL) {
1705 N0 = ZExtPromoteOperand(N0, PVT);
1706 } else {
1707 if (Op->getFlags().hasNoUnsignedWrap()) {
1708 N0 = ZExtPromoteOperand(N0, PVT);
1709 TruncFlags = SDNodeFlags::NoUnsignedWrap;
1710 } else if (Op->getFlags().hasNoSignedWrap()) {
1711 N0 = SExtPromoteOperand(N0, PVT);
1712 TruncFlags = SDNodeFlags::NoSignedWrap;
1713 } else {
1714 N0 = PromoteOperand(N0, PVT, Replace);
1715 }
1716 }
1717
1718 if (!N0.getNode())
1719 return SDValue();
1720
1721 SDLoc DL(Op);
1722 SDValue N1 = Op.getOperand(1);
1723 SDValue RV = DAG.getNode(ISD::TRUNCATE, DL, VT,
1724 DAG.getNode(Opc, DL, PVT, N0, N1), TruncFlags);
1725
1726 if (Replace)
1727 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1728
1729 // Deal with Op being deleted.
1730 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1731 return RV;
1732 }
1733 return SDValue();
1734}
1735
1736SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1737 if (!LegalOperations)
1738 return SDValue();
1739
1740 EVT VT = Op.getValueType();
1741 if (VT.isVector() || !VT.isInteger())
1742 return SDValue();
1743
1744 // If operation type is 'undesirable', e.g. i16 on x86, consider
1745 // promoting it.
1746 unsigned Opc = Op.getOpcode();
1747 if (TLI.isTypeDesirableForOp(Opc, VT))
1748 return SDValue();
1749
1750 EVT PVT = VT;
1751 // Consult target whether it is a good idea to promote this operation and
1752 // what's the right type to promote it to.
1753 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1754 assert(PVT != VT && "Don't know what type to promote to!");
1755 // fold (aext (aext x)) -> (aext x)
1756 // fold (aext (zext x)) -> (zext x)
1757 // fold (aext (sext x)) -> (sext x)
1758 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1759 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1760 }
1761 return SDValue();
1762}
1763
1764bool DAGCombiner::PromoteLoad(SDValue Op) {
1765 if (!LegalOperations)
1766 return false;
1767
1768 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1769 return false;
1770
1771 EVT VT = Op.getValueType();
1772 if (VT.isVector() || !VT.isInteger())
1773 return false;
1774
1775 // If operation type is 'undesirable', e.g. i16 on x86, consider
1776 // promoting it.
1777 unsigned Opc = Op.getOpcode();
1778 if (TLI.isTypeDesirableForOp(Opc, VT))
1779 return false;
1780
1781 EVT PVT = VT;
1782 // Consult target whether it is a good idea to promote this operation and
1783 // what's the right type to promote it to.
1784 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1785 assert(PVT != VT && "Don't know what type to promote to!");
1786
1787 SDLoc DL(Op);
1788 SDNode *N = Op.getNode();
1789 LoadSDNode *LD = cast<LoadSDNode>(N);
1790 EVT MemVT = LD->getMemoryVT();
1792 : LD->getExtensionType();
1793 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1794 LD->getChain(), LD->getBasePtr(),
1795 MemVT, LD->getMemOperand());
1796 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1797
1798 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1799 Result.dump(&DAG); dbgs() << '\n');
1800
1801 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1802 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1803
1804 AddToWorklist(Result.getNode());
1805 recursivelyDeleteUnusedNodes(N);
1806 return true;
1807 }
1808
1809 return false;
1810}
1811
1812/// Recursively delete a node which has no uses and any operands for
1813/// which it is the only use.
1814///
1815/// Note that this both deletes the nodes and removes them from the worklist.
1816/// It also adds any nodes who have had a user deleted to the worklist as they
1817/// may now have only one use and subject to other combines.
1818bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1819 if (!N->use_empty())
1820 return false;
1821
1822 SmallSetVector<SDNode *, 16> Nodes;
1823 Nodes.insert(N);
1824 do {
1825 N = Nodes.pop_back_val();
1826 if (!N)
1827 continue;
1828
1829 if (N->use_empty()) {
1830 for (const SDValue &ChildN : N->op_values())
1831 Nodes.insert(ChildN.getNode());
1832
1833 removeFromWorklist(N);
1834 DAG.DeleteNode(N);
1835 } else {
1836 AddToWorklist(N);
1837 }
1838 } while (!Nodes.empty());
1839 return true;
1840}
1841
1842//===----------------------------------------------------------------------===//
1843// Main DAG Combiner implementation
1844//===----------------------------------------------------------------------===//
1845
1846void DAGCombiner::Run(CombineLevel AtLevel) {
1847 // set the instance variables, so that the various visit routines may use it.
1848 Level = AtLevel;
1849 LegalDAG = Level >= AfterLegalizeDAG;
1850 LegalOperations = Level >= AfterLegalizeVectorOps;
1851 LegalTypes = Level >= AfterLegalizeTypes;
1852
1853 bool UseTopologicalSorting = EnableTopologicalSorting.getNumOccurrences() > 0
1855 : TLI.useTopologicalSorting();
1856
1857 WorklistInserter AddNodes(*this);
1858
1859 if (UseTopologicalSorting)
1861
1862 // Add all the dag nodes to the worklist.
1863 //
1864 // Note: All nodes are not added to PruningList here, this is because the only
1865 // nodes which can be deleted are those which have no uses and all other nodes
1866 // which would otherwise be added to the worklist by the first call to
1867 // getNextWorklistEntry are already present in it.
1868 if (UseTopologicalSorting) {
1869 for (SDNode &Node : reverse(DAG.allnodes()))
1870 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1871 } else {
1872 for (SDNode &Node : DAG.allnodes())
1873 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1874 }
1875
1876 // Create a dummy node (which is not added to allnodes), that adds a reference
1877 // to the root node, preventing it from being deleted, and tracking any
1878 // changes of the root.
1879 HandleSDNode Dummy(DAG.getRoot());
1880
1881 // While we have a valid worklist entry node, try to combine it.
1882 while (SDNode *N = getNextWorklistEntry()) {
1883 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1884 // N is deleted from the DAG, since they too may now be dead or may have a
1885 // reduced number of uses, allowing other xforms.
1886 if (recursivelyDeleteUnusedNodes(N))
1887 continue;
1888
1889 WorklistRemover DeadNodes(*this);
1890
1891 // If this combine is running after legalizing the DAG, re-legalize any
1892 // nodes pulled off the worklist.
1893 if (LegalDAG) {
1894 SmallSetVector<SDNode *, 16> UpdatedNodes;
1895 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1896
1897 for (SDNode *LN : UpdatedNodes)
1898 AddToWorklistWithUsers(LN);
1899
1900 if (!NIsValid)
1901 continue;
1902 }
1903
1904 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1905
1906 // Add any operands of the new node which have not yet been combined to the
1907 // worklist as well. getNextWorklistEntry flags nodes that have been
1908 // combined before. Because the worklist uniques things already, this won't
1909 // repeatedly process the same operand.
1910 for (const SDValue &ChildN : N->op_values())
1911 AddToWorklist(ChildN.getNode(), /*IsCandidateForPruning=*/true,
1912 /*SkipIfCombinedBefore=*/true);
1913
1914 SDValue RV = combine(N);
1915
1916 if (!RV.getNode())
1917 continue;
1918
1919 ++NodesCombined;
1920
1921 // Invalidate cached info.
1922 ChainsWithoutMergeableStores.clear();
1923
1924 // If we get back the same node we passed in, rather than a new node or
1925 // zero, we know that the node must have defined multiple values and
1926 // CombineTo was used. Since CombineTo takes care of the worklist
1927 // mechanics for us, we have no work to do in this case.
1928 if (RV.getNode() == N)
1929 continue;
1930
1931 assert(N->getOpcode() != ISD::DELETED_NODE &&
1932 RV.getOpcode() != ISD::DELETED_NODE &&
1933 "Node was deleted but visit returned new node!");
1934
1935 LLVM_DEBUG(dbgs() << " ... into: "; RV.dump(&DAG));
1936
1937 if (N->getNumValues() == RV->getNumValues())
1938 DAG.ReplaceAllUsesWith(N, RV.getNode());
1939 else {
1940 assert(N->getValueType(0) == RV.getValueType() &&
1941 N->getNumValues() == 1 && "Type mismatch");
1942 DAG.ReplaceAllUsesWith(N, &RV);
1943 }
1944
1945 // Push the new node and any users onto the worklist. Omit this if the
1946 // new node is the EntryToken (e.g. if a store managed to get optimized
1947 // out), because re-visiting the EntryToken and its users will not uncover
1948 // any additional opportunities, but there may be a large number of such
1949 // users, potentially causing compile time explosion.
1950 if (RV.getOpcode() != ISD::EntryToken)
1951 AddToWorklistWithUsers(RV.getNode());
1952
1953 // Finally, if the node is now dead, remove it from the graph. The node
1954 // may not be dead if the replacement process recursively simplified to
1955 // something else needing this node. This will also take care of adding any
1956 // operands which have lost a user to the worklist.
1957 recursivelyDeleteUnusedNodes(N);
1958 }
1959
1960 // If the root changed (e.g. it was a dead load, update the root).
1961 DAG.setRoot(Dummy.getValue());
1962 DAG.RemoveDeadNodes();
1963}
1964
1965SDValue DAGCombiner::visit(SDNode *N) {
1966 // clang-format off
1967 switch (N->getOpcode()) {
1968 default: break;
1969 case ISD::TokenFactor: return visitTokenFactor(N);
1970 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1971 case ISD::ADD: return visitADD(N);
1972 case ISD::PTRADD: return visitPTRADD(N);
1973 case ISD::SUB: return visitSUB(N);
1974 case ISD::SADDSAT:
1975 case ISD::UADDSAT: return visitADDSAT(N);
1976 case ISD::SSUBSAT:
1977 case ISD::USUBSAT: return visitSUBSAT(N);
1978 case ISD::ADDC: return visitADDC(N);
1979 case ISD::SADDO:
1980 case ISD::UADDO: return visitADDO(N);
1981 case ISD::SUBC: return visitSUBC(N);
1982 case ISD::SSUBO:
1983 case ISD::USUBO: return visitSUBO(N);
1984 case ISD::ADDE: return visitADDE(N);
1985 case ISD::UADDO_CARRY: return visitUADDO_CARRY(N);
1986 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
1987 case ISD::SUBE: return visitSUBE(N);
1988 case ISD::USUBO_CARRY: return visitUSUBO_CARRY(N);
1989 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
1990 case ISD::SMULFIX:
1991 case ISD::SMULFIXSAT:
1992 case ISD::UMULFIX:
1993 case ISD::UMULFIXSAT: return visitMULFIX(N);
1994 case ISD::MUL: return visitMUL(N);
1995 case ISD::SDIV: return visitSDIV(N);
1996 case ISD::UDIV: return visitUDIV(N);
1997 case ISD::SREM:
1998 case ISD::UREM: return visitREM(N);
1999 case ISD::MULHU: return visitMULHU(N);
2000 case ISD::MULHS: return visitMULHS(N);
2001 case ISD::AVGFLOORS:
2002 case ISD::AVGFLOORU:
2003 case ISD::AVGCEILS:
2004 case ISD::AVGCEILU: return visitAVG(N);
2005 case ISD::ABDS:
2006 case ISD::ABDU: return visitABD(N);
2007 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
2008 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
2009 case ISD::SMULO:
2010 case ISD::UMULO: return visitMULO(N);
2011 case ISD::SMIN:
2012 case ISD::SMAX:
2013 case ISD::UMIN:
2014 case ISD::UMAX: return visitIMINMAX(N);
2015 case ISD::AND: return visitAND(N);
2016 case ISD::OR: return visitOR(N);
2017 case ISD::XOR: return visitXOR(N);
2018 case ISD::SHL: return visitSHL(N);
2019 case ISD::SRA: return visitSRA(N);
2020 case ISD::SRL: return visitSRL(N);
2021 case ISD::ROTR:
2022 case ISD::ROTL: return visitRotate(N);
2023 case ISD::FSHL:
2024 case ISD::FSHR: return visitFunnelShift(N);
2025 case ISD::SSHLSAT:
2026 case ISD::USHLSAT: return visitSHLSAT(N);
2027 case ISD::ABS: return visitABS(N);
2028 case ISD::ABS_MIN_POISON: return visitABS_MIN_POISON(N);
2029 case ISD::CLMUL:
2030 case ISD::CLMULR:
2031 case ISD::CLMULH: return visitCLMUL(N);
2032 case ISD::PEXT: return visitPEXT(N);
2033 case ISD::PDEP: return visitPDEP(N);
2034 case ISD::BSWAP: return visitBSWAP(N);
2035 case ISD::BITREVERSE: return visitBITREVERSE(N);
2036 case ISD::CTLZ: return visitCTLZ(N);
2037 case ISD::CTLZ_ZERO_POISON: return visitCTLZ_ZERO_POISON(N);
2038 case ISD::CTTZ: return visitCTTZ(N);
2039 case ISD::CTTZ_ZERO_POISON: return visitCTTZ_ZERO_POISON(N);
2040 case ISD::CTPOP: return visitCTPOP(N);
2041 case ISD::SELECT: return visitSELECT(N);
2042 case ISD::VSELECT: return visitVSELECT(N);
2043 case ISD::SELECT_CC: return visitSELECT_CC(N);
2044 case ISD::SETCC: return visitSETCC(N);
2045 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
2046 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
2047 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
2048 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
2049 case ISD::AssertSext:
2050 case ISD::AssertZext: return visitAssertExt(N);
2051 case ISD::AssertAlign: return visitAssertAlign(N);
2052 case ISD::IS_FPCLASS: return visitIS_FPCLASS(N);
2053 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
2056 case ISD::ANY_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
2057 case ISD::TRUNCATE: return visitTRUNCATE(N);
2058 case ISD::TRUNCATE_USAT_U: return visitTRUNCATE_USAT_U(N);
2059 case ISD::BITCAST: return visitBITCAST(N);
2060 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
2061 case ISD::FADD: return visitFADD(N);
2062 case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
2063 case ISD::FSUB: return visitFSUB(N);
2064 case ISD::FMUL: return visitFMUL(N);
2065 case ISD::FMA: return visitFMA(N);
2066 case ISD::FMAD: return visitFMAD(N);
2067 case ISD::FMULADD: return visitFMULADD(N);
2068 case ISD::FDIV: return visitFDIV(N);
2069 case ISD::FREM: return visitFREM(N);
2070 case ISD::FSQRT: return visitFSQRT(N);
2071 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
2072 case ISD::FPOW: return visitFPOW(N);
2073 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
2074 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
2075 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
2076 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
2077 case ISD::LROUND:
2078 case ISD::LLROUND:
2079 case ISD::LRINT:
2080 case ISD::LLRINT: return visitXROUND(N);
2081 case ISD::FP_ROUND: return visitFP_ROUND(N);
2082 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
2083 case ISD::FNEG: return visitFNEG(N);
2084 case ISD::FABS: return visitFABS(N);
2085 case ISD::FFLOOR: return visitFFLOOR(N);
2086 case ISD::FMINNUM:
2087 case ISD::FMAXNUM:
2088 case ISD::FMINIMUM:
2089 case ISD::FMAXIMUM:
2090 case ISD::FMINIMUMNUM:
2091 case ISD::FMAXIMUMNUM: return visitFMinMax(N);
2092 case ISD::FCEIL: return visitFCEIL(N);
2093 case ISD::FTRUNC: return visitFTRUNC(N);
2094 case ISD::FFREXP: return visitFFREXP(N);
2095 case ISD::BRCOND: return visitBRCOND(N);
2096 case ISD::BR_CC: return visitBR_CC(N);
2097 case ISD::LOAD: return visitLOAD(N);
2098 case ISD::STORE: return visitSTORE(N);
2099 case ISD::ATOMIC_STORE: return visitATOMIC_STORE(N);
2100 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
2101 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
2102 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
2103 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
2104 case ISD::VECTOR_INTERLEAVE: return visitVECTOR_INTERLEAVE(N);
2105 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
2106 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
2107 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
2108 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
2109 case ISD::MGATHER: return visitMGATHER(N);
2110 case ISD::MLOAD: return visitMLOAD(N);
2111 case ISD::MSCATTER: return visitMSCATTER(N);
2112 case ISD::MSTORE: return visitMSTORE(N);
2113 case ISD::EXPERIMENTAL_VECTOR_HISTOGRAM: return visitMHISTOGRAM(N);
2118 return visitPARTIAL_REDUCE_MLA(N);
2119 case ISD::VECTOR_COMPRESS: return visitVECTOR_COMPRESS(N);
2120 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
2121 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
2122 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
2123 case ISD::FP_TO_BF16: return visitFP_TO_BF16(N);
2124 case ISD::BF16_TO_FP: return visitBF16_TO_FP(N);
2125 case ISD::FREEZE: return visitFREEZE(N);
2126 case ISD::GET_FPENV_MEM: return visitGET_FPENV_MEM(N);
2127 case ISD::SET_FPENV_MEM: return visitSET_FPENV_MEM(N);
2128 case ISD::FCANONICALIZE: return visitFCANONICALIZE(N);
2131 case ISD::VECREDUCE_ADD:
2132 case ISD::VECREDUCE_MUL:
2133 case ISD::VECREDUCE_AND:
2134 case ISD::VECREDUCE_OR:
2135 case ISD::VECREDUCE_XOR:
2143 case ISD::VECREDUCE_FMINIMUM: return visitVECREDUCE(N);
2144#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
2145#include "llvm/IR/VPIntrinsics.def"
2146 return visitVPOp(N);
2147 }
2148 // clang-format on
2149 return SDValue();
2150}
2151
2152SDValue DAGCombiner::combine(SDNode *N) {
2153 if (!DebugCounter::shouldExecute(DAGCombineCounter))
2154 return SDValue();
2155
2156 SDValue RV;
2157 if (!DisableGenericCombines)
2158 RV = visit(N);
2159
2160 // If nothing happened, try a target-specific DAG combine.
2161 if (!RV.getNode()) {
2162 assert(N->getOpcode() != ISD::DELETED_NODE &&
2163 "Node was deleted but visit returned NULL!");
2164
2165 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
2166 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
2167
2168 // Expose the DAG combiner to the target combiner impls.
2169 TargetLowering::DAGCombinerInfo
2170 DagCombineInfo(DAG, Level, false, this);
2171
2172 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
2173 }
2174 }
2175
2176 // If nothing happened still, try promoting the operation.
2177 if (!RV.getNode()) {
2178 switch (N->getOpcode()) {
2179 default: break;
2180 case ISD::ADD:
2181 case ISD::SUB:
2182 case ISD::MUL:
2183 case ISD::AND:
2184 case ISD::OR:
2185 case ISD::XOR:
2186 RV = PromoteIntBinOp(SDValue(N, 0));
2187 break;
2188 case ISD::SHL:
2189 case ISD::SRA:
2190 case ISD::SRL:
2191 RV = PromoteIntShiftOp(SDValue(N, 0));
2192 break;
2193 case ISD::SIGN_EXTEND:
2194 case ISD::ZERO_EXTEND:
2195 case ISD::ANY_EXTEND:
2196 RV = PromoteExtend(SDValue(N, 0));
2197 break;
2198 case ISD::LOAD:
2199 if (PromoteLoad(SDValue(N, 0)))
2200 RV = SDValue(N, 0);
2201 break;
2202 }
2203 }
2204
2205 // If N is a commutative binary node, try to eliminate it if the commuted
2206 // version is already present in the DAG.
2207 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode())) {
2208 SDValue N0 = N->getOperand(0);
2209 SDValue N1 = N->getOperand(1);
2210
2211 // Constant operands are canonicalized to RHS.
2212 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
2213 SDValue Ops[] = {N1, N0};
2214 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
2215 N->getFlags());
2216 if (CSENode)
2217 return SDValue(CSENode, 0);
2218 }
2219 }
2220
2221 return RV;
2222}
2223
2224/// Given a node, return its input chain if it has one, otherwise return a null
2225/// sd operand.
2227 if (unsigned NumOps = N->getNumOperands()) {
2228 if (N->getOperand(0).getValueType() == MVT::Other)
2229 return N->getOperand(0);
2230 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
2231 return N->getOperand(NumOps-1);
2232 for (unsigned i = 1; i < NumOps-1; ++i)
2233 if (N->getOperand(i).getValueType() == MVT::Other)
2234 return N->getOperand(i);
2235 }
2236 return SDValue();
2237}
2238
2239SDValue DAGCombiner::visitFCANONICALIZE(SDNode *N) {
2240 SDValue Operand = N->getOperand(0);
2241 EVT VT = Operand.getValueType();
2242 SDLoc dl(N);
2243
2244 // Canonicalize undef to quiet NaN.
2245 if (Operand.isUndef()) {
2246 APFloat CanonicalQNaN = APFloat::getQNaN(VT.getFltSemantics());
2247 return DAG.getConstantFP(CanonicalQNaN, dl, VT);
2248 }
2249 return SDValue();
2250}
2251
2252SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
2253 // If N has two operands, where one has an input chain equal to the other,
2254 // the 'other' chain is redundant.
2255 if (N->getNumOperands() == 2) {
2256 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
2257 return N->getOperand(0);
2258 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
2259 return N->getOperand(1);
2260 }
2261
2262 // Don't simplify token factors if optnone.
2263 if (OptLevel == CodeGenOptLevel::None)
2264 return SDValue();
2265
2266 // Don't simplify the token factor if the node itself has too many operands.
2267 if (N->getNumOperands() > TokenFactorInlineLimit)
2268 return SDValue();
2269
2270 // If the sole user is a token factor, we should make sure we have a
2271 // chance to merge them together. This prevents TF chains from inhibiting
2272 // optimizations.
2273 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TokenFactor)
2274 AddToWorklist(*(N->user_begin()));
2275
2276 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
2277 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
2278 SmallPtrSet<SDNode*, 16> SeenOps;
2279 bool Changed = false; // If we should replace this token factor.
2280
2281 // Start out with this token factor.
2282 TFs.push_back(N);
2283
2284 // Iterate through token factors. The TFs grows when new token factors are
2285 // encountered.
2286 for (unsigned i = 0; i < TFs.size(); ++i) {
2287 // Limit number of nodes to inline, to avoid quadratic compile times.
2288 // We have to add the outstanding Token Factors to Ops, otherwise we might
2289 // drop Ops from the resulting Token Factors.
2290 if (Ops.size() > TokenFactorInlineLimit) {
2291 for (unsigned j = i; j < TFs.size(); j++)
2292 Ops.emplace_back(TFs[j], 0);
2293 // Drop unprocessed Token Factors from TFs, so we do not add them to the
2294 // combiner worklist later.
2295 TFs.resize(i);
2296 break;
2297 }
2298
2299 SDNode *TF = TFs[i];
2300 // Check each of the operands.
2301 for (const SDValue &Op : TF->op_values()) {
2302 switch (Op.getOpcode()) {
2303 case ISD::EntryToken:
2304 // Entry tokens don't need to be added to the list. They are
2305 // redundant.
2306 Changed = true;
2307 break;
2308
2309 case ISD::TokenFactor:
2310 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
2311 // Queue up for processing.
2312 TFs.push_back(Op.getNode());
2313 Changed = true;
2314 break;
2315 }
2316 [[fallthrough]];
2317
2318 default:
2319 // Only add if it isn't already in the list.
2320 if (SeenOps.insert(Op.getNode()).second)
2321 Ops.push_back(Op);
2322 else
2323 Changed = true;
2324 break;
2325 }
2326 }
2327 }
2328
2329 // Re-visit inlined Token Factors, to clean them up in case they have been
2330 // removed. Skip the first Token Factor, as this is the current node.
2331 for (unsigned i = 1, e = TFs.size(); i < e; i++)
2332 AddToWorklist(TFs[i]);
2333
2334 // Remove Nodes that are chained to another node in the list. Do so
2335 // by walking up chains breath-first stopping when we've seen
2336 // another operand. In general we must climb to the EntryNode, but we can exit
2337 // early if we find all remaining work is associated with just one operand as
2338 // no further pruning is possible.
2339
2340 // List of nodes to search through and original Ops from which they originate.
2342 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
2343 SmallPtrSet<SDNode *, 16> SeenChains;
2344 bool DidPruneOps = false;
2345
2346 unsigned NumLeftToConsider = 0;
2347 for (const SDValue &Op : Ops) {
2348 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
2349 OpWorkCount.push_back(1);
2350 }
2351
2352 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
2353 // If this is an Op, we can remove the op from the list. Remark any
2354 // search associated with it as from the current OpNumber.
2355 if (SeenOps.contains(Op)) {
2356 Changed = true;
2357 DidPruneOps = true;
2358 unsigned OrigOpNumber = 0;
2359 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
2360 OrigOpNumber++;
2361 assert((OrigOpNumber != Ops.size()) &&
2362 "expected to find TokenFactor Operand");
2363 // Re-mark worklist from OrigOpNumber to OpNumber
2364 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
2365 if (Worklist[i].second == OrigOpNumber) {
2366 Worklist[i].second = OpNumber;
2367 }
2368 }
2369 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
2370 OpWorkCount[OrigOpNumber] = 0;
2371 NumLeftToConsider--;
2372 }
2373 // Add if it's a new chain
2374 if (SeenChains.insert(Op).second) {
2375 OpWorkCount[OpNumber]++;
2376 Worklist.push_back(std::make_pair(Op, OpNumber));
2377 }
2378 };
2379
2380 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
2381 // We need at least be consider at least 2 Ops to prune.
2382 if (NumLeftToConsider <= 1)
2383 break;
2384 auto CurNode = Worklist[i].first;
2385 auto CurOpNumber = Worklist[i].second;
2386 assert((OpWorkCount[CurOpNumber] > 0) &&
2387 "Node should not appear in worklist");
2388 switch (CurNode->getOpcode()) {
2389 case ISD::EntryToken:
2390 // Hitting EntryToken is the only way for the search to terminate without
2391 // hitting
2392 // another operand's search. Prevent us from marking this operand
2393 // considered.
2394 NumLeftToConsider++;
2395 break;
2396 case ISD::TokenFactor:
2397 for (const SDValue &Op : CurNode->op_values())
2398 AddToWorklist(i, Op.getNode(), CurOpNumber);
2399 break;
2401 case ISD::LIFETIME_END:
2402 case ISD::CopyFromReg:
2403 case ISD::CopyToReg:
2404 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
2405 break;
2406 default:
2407 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
2408 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
2409 break;
2410 }
2411 OpWorkCount[CurOpNumber]--;
2412 if (OpWorkCount[CurOpNumber] == 0)
2413 NumLeftToConsider--;
2414 }
2415
2416 // If we've changed things around then replace token factor.
2417 if (Changed) {
2419 if (Ops.empty()) {
2420 // The entry token is the only possible outcome.
2421 Result = DAG.getEntryNode();
2422 } else {
2423 if (DidPruneOps) {
2424 SmallVector<SDValue, 8> PrunedOps;
2425 //
2426 for (const SDValue &Op : Ops) {
2427 if (SeenChains.count(Op.getNode()) == 0)
2428 PrunedOps.push_back(Op);
2429 }
2430 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2431 } else {
2432 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2433 }
2434 }
2435 return Result;
2436 }
2437 return SDValue();
2438}
2439
2440/// MERGE_VALUES can always be eliminated.
2441SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2442 WorklistRemover DeadNodes(*this);
2443 // Replacing results may cause a different MERGE_VALUES to suddenly
2444 // be CSE'd with N, and carry its uses with it. Iterate until no
2445 // uses remain, to ensure that the node can be safely deleted.
2446 // First add the users of this node to the work list so that they
2447 // can be tried again once they have new operands.
2448 AddUsersToWorklist(N);
2449 do {
2450 // Do as a single replacement to avoid rewalking use lists.
2452 DAG.ReplaceAllUsesWith(N, Ops.data());
2453 } while (!N->use_empty());
2454 deleteAndRecombine(N);
2455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2456}
2457
2458/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2459/// ConstantSDNode pointer else nullptr.
2462 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2463}
2464
2465// isTruncateOf - If N is a truncate of some other value, return true, record
2466// the value being truncated in Op and which of Op's bits are zero/one in Known.
2467// This function computes KnownBits to avoid a duplicated call to
2468// computeKnownBits in the caller.
2470 KnownBits &Known) {
2471 if (N->getOpcode() == ISD::TRUNCATE) {
2472 Op = N->getOperand(0);
2473 Known = DAG.computeKnownBits(Op);
2474 if (N->getFlags().hasNoUnsignedWrap())
2475 Known.Zero.setBitsFrom(N.getScalarValueSizeInBits());
2476 return true;
2477 }
2478
2479 if (N.getValueType().getScalarType() != MVT::i1 ||
2480 !sd_match(
2482 return false;
2483
2484 Known = DAG.computeKnownBits(Op);
2485 return (Known.Zero | 1).isAllOnes();
2486}
2487
2488/// Return true if 'Use' is a load or a store that uses N as its base pointer
2489/// and that N may be folded in the load / store addressing mode.
2491 const TargetLowering &TLI) {
2492 EVT VT;
2493 unsigned AS;
2494
2495 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2496 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2497 return false;
2498 VT = LD->getMemoryVT();
2499 AS = LD->getAddressSpace();
2500 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2501 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2502 return false;
2503 VT = ST->getMemoryVT();
2504 AS = ST->getAddressSpace();
2506 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2507 return false;
2508 VT = LD->getMemoryVT();
2509 AS = LD->getAddressSpace();
2511 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2512 return false;
2513 VT = ST->getMemoryVT();
2514 AS = ST->getAddressSpace();
2515 } else {
2516 return false;
2517 }
2518
2520 if (N->isAnyAdd()) {
2521 AM.HasBaseReg = true;
2523 if (Offset)
2524 // [reg +/- imm]
2525 AM.BaseOffs = Offset->getSExtValue();
2526 else
2527 // [reg +/- reg]
2528 AM.Scale = 1;
2529 } else if (N->getOpcode() == ISD::SUB) {
2530 AM.HasBaseReg = true;
2532 if (Offset)
2533 // [reg +/- imm]
2534 AM.BaseOffs = -Offset->getSExtValue();
2535 else
2536 // [reg +/- reg]
2537 AM.Scale = 1;
2538 } else {
2539 return false;
2540 }
2541
2542 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2543 VT.getTypeForEVT(*DAG.getContext()), AS);
2544}
2545
2546/// This inverts a canonicalization in IR that replaces a variable select arm
2547/// with an identity constant. Codegen improves if we re-use the variable
2548/// operand rather than load a constant. This can also be converted into a
2549/// masked vector operation if the target supports it.
2551 bool ShouldCommuteOperands) {
2552 SDValue N0 = N->getOperand(0);
2553 SDValue N1 = N->getOperand(1);
2554
2555 // Match a select as operand 1. The identity constant that we are looking for
2556 // is only valid as operand 1 of a non-commutative binop.
2557 if (ShouldCommuteOperands)
2558 std::swap(N0, N1);
2559
2560 SDValue Cond, TVal, FVal;
2562 m_Value(FVal)))))
2563 return SDValue();
2564
2565 // We can't hoist all instructions because of immediate UB (not speculatable).
2566 // For example div/rem by zero.
2568 return SDValue();
2569
2570 unsigned SelOpcode = N1.getOpcode();
2571 unsigned Opcode = N->getOpcode();
2572 EVT VT = N->getValueType(0);
2573 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2574
2575 // This transform increases uses of N0, so freeze it to be safe.
2576 // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
2577 unsigned OpNo = ShouldCommuteOperands ? 0 : 1;
2578 if (DAG.isIdentityElement(Opcode, N->getFlags(), TVal, OpNo) &&
2579 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2580 FVal)) {
2581 SDValue F0 = DAG.getFreeze(N0);
2582 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
2583 return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
2584 }
2585 // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
2586 if (DAG.isIdentityElement(Opcode, N->getFlags(), FVal, OpNo) &&
2587 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2588 TVal)) {
2589 SDValue F0 = DAG.getFreeze(N0);
2590 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
2591 return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
2592 }
2593
2594 return SDValue();
2595}
2596
2597SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2599 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
2600 "Unexpected binary operator");
2601
2602 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
2603 return Sel;
2604
2605 if (TLI.isCommutativeBinOp(BO->getOpcode()))
2606 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
2607 return Sel;
2608
2609 // Don't do this unless the old select is going away. We want to eliminate the
2610 // binary operator, not replace a binop with a select.
2611 // TODO: Handle ISD::SELECT_CC.
2612 unsigned SelOpNo = 0;
2613 SDValue Sel = BO->getOperand(0);
2614 auto BinOpcode = BO->getOpcode();
2615 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2616 SelOpNo = 1;
2617 Sel = BO->getOperand(1);
2618
2619 // Peek through trunc to shift amount type.
2620 if ((BinOpcode == ISD::SHL || BinOpcode == ISD::SRA ||
2621 BinOpcode == ISD::SRL) && Sel.hasOneUse()) {
2622 // This is valid when the truncated bits of x are already zero.
2623 SDValue Op;
2624 KnownBits Known;
2625 if (isTruncateOf(DAG, Sel, Op, Known) &&
2626 Known.countMaxActiveBits() < Sel.getScalarValueSizeInBits())
2627 Sel = Op;
2628 }
2629 }
2630
2631 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2632 return SDValue();
2633
2634 SDValue CT = Sel.getOperand(1);
2635 if (!isConstantOrConstantVector(CT, true) &&
2637 return SDValue();
2638
2639 SDValue CF = Sel.getOperand(2);
2640 if (!isConstantOrConstantVector(CF, true) &&
2642 return SDValue();
2643
2644 // Bail out if any constants are opaque because we can't constant fold those.
2645 // The exception is "and" and "or" with either 0 or -1 in which case we can
2646 // propagate non constant operands into select. I.e.:
2647 // and (select Cond, 0, -1), X --> select Cond, 0, X
2648 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2649 bool CanFoldNonConst =
2650 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2653
2654 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2655 if (!CanFoldNonConst &&
2656 !isConstantOrConstantVector(CBO, true) &&
2658 return SDValue();
2659
2660 SDLoc DL(Sel);
2661 SDValue NewCT, NewCF;
2662 EVT VT = BO->getValueType(0);
2663
2664 if (CanFoldNonConst) {
2665 // If CBO is an opaque constant, we can't rely on getNode to constant fold.
2666 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CT)) ||
2667 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CT)))
2668 NewCT = CT;
2669 else
2670 NewCT = CBO;
2671
2672 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CF)) ||
2673 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CF)))
2674 NewCF = CF;
2675 else
2676 NewCF = CBO;
2677 } else {
2678 // We have a select-of-constants followed by a binary operator with a
2679 // constant. Eliminate the binop by pulling the constant math into the
2680 // select. Example: add (select Cond, CT, CF), CBO --> select Cond, CT +
2681 // CBO, CF + CBO
2682 NewCT = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CT})
2683 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CT, CBO});
2684 if (!NewCT)
2685 return SDValue();
2686
2687 NewCF = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CF})
2688 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CF, CBO});
2689 if (!NewCF)
2690 return SDValue();
2691 }
2692
2693 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF, BO->getFlags());
2694}
2695
2697 SelectionDAG &DAG) {
2698 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2699 "Expecting add or sub");
2700
2701 // Match a constant operand and a zext operand for the math instruction:
2702 // add Z, C
2703 // sub C, Z
2704 bool IsAdd = N->getOpcode() == ISD::ADD;
2705 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2706 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2707 auto *CN = dyn_cast<ConstantSDNode>(C);
2708 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2709 return SDValue();
2710
2711 // Match the zext operand as a setcc of a boolean.
2712 if (Z.getOperand(0).getValueType() != MVT::i1)
2713 return SDValue();
2714
2715 // Match the compare as: setcc (X & 1), 0, eq.
2716 if (!sd_match(Z.getOperand(0), m_SetCC(m_And(m_Value(), m_One()), m_Zero(),
2718 return SDValue();
2719
2720 // We are adding/subtracting a constant and an inverted low bit. Turn that
2721 // into a subtract/add of the low bit with incremented/decremented constant:
2722 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2723 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2724 EVT VT = C.getValueType();
2725 SDValue LowBit = DAG.getZExtOrTrunc(Z.getOperand(0).getOperand(0), DL, VT);
2726 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT)
2727 : DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2728 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2729}
2730
2731// Attempt to form avgceil(A, B) from (A | B) - ((A ^ B) >> 1)
2732SDValue DAGCombiner::foldSubToAvg(SDNode *N, const SDLoc &DL) {
2733 SDValue N0 = N->getOperand(0);
2734 EVT VT = N0.getValueType();
2735 SDValue A, B;
2736
2737 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
2739 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2740 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
2741 }
2742 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
2744 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2745 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
2746 }
2747 return SDValue();
2748}
2749
2750/// Try to fold a pointer arithmetic node.
2751/// This needs to be done separately from normal addition, because pointer
2752/// addition is not commutative.
2753SDValue DAGCombiner::visitPTRADD(SDNode *N) {
2754 SDValue N0 = N->getOperand(0);
2755 SDValue N1 = N->getOperand(1);
2756 EVT PtrVT = N0.getValueType();
2757 EVT IntVT = N1.getValueType();
2758 SDLoc DL(N);
2759
2760 // This is already ensured by an assert in SelectionDAG::getNode(). Several
2761 // combines here depend on this assumption.
2762 assert(PtrVT == IntVT &&
2763 "PTRADD with different operand types is not supported");
2764
2765 // fold (ptradd x, 0) -> x
2766 if (isNullConstant(N1))
2767 return N0;
2768
2769 // fold (ptradd 0, x) -> x
2770 if (PtrVT == IntVT && isNullConstant(N0))
2771 return N1;
2772
2773 if (N0.getOpcode() == ISD::PTRADD &&
2774 !reassociationCanBreakAddressingModePattern(ISD::PTRADD, DL, N, N0, N1)) {
2775 SDValue X = N0.getOperand(0);
2776 SDValue Y = N0.getOperand(1);
2777 SDValue Z = N1;
2778 bool N0OneUse = N0.hasOneUse();
2779 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2780 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2781
2782 // (ptradd (ptradd x, y), z) -> (ptradd x, (add y, z)) if:
2783 // * y is a constant and (ptradd x, y) has one use; or
2784 // * y and z are both constants.
2785 if ((YIsConstant && N0OneUse) || (YIsConstant && ZIsConstant)) {
2786 // If both additions in the original were NUW, the new ones are as well.
2787 SDNodeFlags Flags =
2788 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2789 SDValue Add = DAG.getNode(ISD::ADD, DL, IntVT, {Y, Z}, Flags);
2790 AddToWorklist(Add.getNode());
2791 // We can't set InBounds even if both original ptradds were InBounds and
2792 // NUW: SDAG usually represents pointers as integers, therefore, the
2793 // matched pattern behaves as if it had implicit casts:
2794 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds x, y))), z)
2795 // The outer inbounds ptradd might therefore rely on a provenance that x
2796 // does not have.
2797 return DAG.getMemBasePlusOffset(X, Add, DL, Flags);
2798 }
2799 }
2800
2801 // The following combines can turn in-bounds pointer arithmetic out of bounds.
2802 // That is problematic for settings like AArch64's CPA, which checks that
2803 // intermediate results of pointer arithmetic remain in bounds. The target
2804 // therefore needs to opt-in to enable them.
2806 DAG.getMachineFunction().getFunction(), PtrVT))
2807 return SDValue();
2808
2809 if (N0.getOpcode() == ISD::PTRADD && isa<ConstantSDNode>(N1)) {
2810 // Fold (ptradd (ptradd GA, v), c) -> (ptradd (ptradd GA, c) v) with
2811 // global address GA and constant c, such that c can be folded into GA.
2812 // TODO: Support constant vector splats.
2813 SDValue GAValue = N0.getOperand(0);
2814 if (const GlobalAddressSDNode *GA =
2816 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2817 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2818 // If both additions in the original were NUW, reassociation preserves
2819 // that.
2820 SDNodeFlags Flags =
2821 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2822 // We can't set InBounds even if both original ptradds were InBounds and
2823 // NUW: SDAG usually represents pointers as integers, therefore, the
2824 // matched pattern behaves as if it had implicit casts:
2825 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds GA, v))), c)
2826 // The outer inbounds ptradd might therefore rely on a provenance that
2827 // GA does not have.
2828 SDValue Inner = DAG.getMemBasePlusOffset(GAValue, N1, DL, Flags);
2829 AddToWorklist(Inner.getNode());
2830 return DAG.getMemBasePlusOffset(Inner, N0.getOperand(1), DL, Flags);
2831 }
2832 }
2833 }
2834
2835 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse()) {
2836 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if z is a constant,
2837 // y is not, and (add y, z) is used only once.
2838 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if y is a constant,
2839 // z is not, and (add y, z) is used only once.
2840 // The goal is to move constant offsets to the outermost ptradd, to create
2841 // more opportunities to fold offsets into memory instructions.
2842 // Together with the another combine above, this also implements
2843 // (ptradd (ptradd x, y), z) -> (ptradd (ptradd x, z), y)).
2844 SDValue X = N0;
2845 SDValue Y = N1.getOperand(0);
2846 SDValue Z = N1.getOperand(1);
2847 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2848 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2849
2850 // If both additions in the original were NUW, reassociation preserves that.
2851 SDNodeFlags CommonFlags = N->getFlags() & N1->getFlags();
2852 SDNodeFlags ReassocFlags = CommonFlags & SDNodeFlags::NoUnsignedWrap;
2853 if (CommonFlags.hasNoUnsignedWrap()) {
2854 // If both operations are NUW and the PTRADD is inbounds, the offests are
2855 // both non-negative, so the reassociated PTRADDs are also inbounds.
2856 ReassocFlags |= N->getFlags() & SDNodeFlags::InBounds;
2857 }
2858
2859 if (ZIsConstant != YIsConstant) {
2860 if (YIsConstant)
2861 std::swap(Y, Z);
2862 SDValue Inner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
2863 AddToWorklist(Inner.getNode());
2864 return DAG.getMemBasePlusOffset(Inner, Z, DL, ReassocFlags);
2865 }
2866 }
2867
2868 // Transform (ptradd a, b) -> (or disjoint a, b) if it is equivalent and if
2869 // that transformation can't block an offset folding at any use of the ptradd.
2870 // This should be done late, after legalization, so that it doesn't block
2871 // other ptradd combines that could enable more offset folding.
2872 if (LegalOperations && DAG.haveNoCommonBitsSet(N0, N1)) {
2873 bool TransformCannotBreakAddrMode = none_of(N->users(), [&](SDNode *User) {
2874 return canFoldInAddressingMode(N, User, DAG, TLI);
2875 });
2876
2877 if (TransformCannotBreakAddrMode)
2878 return DAG.getNode(ISD::OR, DL, PtrVT, N0, N1, SDNodeFlags::Disjoint);
2879 }
2880
2881 return SDValue();
2882}
2883
2884/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2885/// a shift and add with a different constant.
2887 SelectionDAG &DAG) {
2888 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2889 "Expecting add or sub");
2890
2891 // We need a constant operand for the add/sub, and the other operand is a
2892 // logical shift right: add (srl), C or sub C, (srl).
2893 bool IsAdd = N->getOpcode() == ISD::ADD;
2894 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2895 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2896 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2897 ShiftOp.getOpcode() != ISD::SRL)
2898 return SDValue();
2899
2900 // The shift must be of a 'not' value.
2901 SDValue Not = ShiftOp.getOperand(0);
2902 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2903 return SDValue();
2904
2905 // The shift must be moving the sign bit to the least-significant-bit.
2906 EVT VT = ShiftOp.getValueType();
2907 SDValue ShAmt = ShiftOp.getOperand(1);
2908 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2909 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2910 return SDValue();
2911
2912 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2913 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2914 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2915 if (SDValue NewC = DAG.FoldConstantArithmetic(
2916 IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2917 {ConstantOp, DAG.getConstant(1, DL, VT)})) {
2918 SDValue NewShift = DAG.getNode(IsAdd ? ISD::SRA : ISD::SRL, DL, VT,
2919 Not.getOperand(0), ShAmt);
2920 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2921 }
2922
2923 return SDValue();
2924}
2925
2926static bool
2928 return (isBitwiseNot(Op0) && Op0.getOperand(0) == Op1) ||
2929 (isBitwiseNot(Op1) && Op1.getOperand(0) == Op0);
2930}
2931
2932/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2933/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2934/// are no common bits set in the operands).
2935SDValue DAGCombiner::visitADDLike(SDNode *N) {
2936 SDValue N0 = N->getOperand(0);
2937 SDValue N1 = N->getOperand(1);
2938 EVT VT = N0.getValueType();
2939 SDLoc DL(N);
2940
2941 // fold (add x, undef) -> undef
2942 if (N0.isUndef())
2943 return N0;
2944 if (N1.isUndef())
2945 return N1;
2946
2947 // fold (add c1, c2) -> c1+c2
2948 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
2949 return C;
2950
2951 // canonicalize constant to RHS
2954 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2955
2956 if (areBitwiseNotOfEachother(N0, N1))
2957 return DAG.getConstant(APInt::getAllOnes(VT.getScalarSizeInBits()), DL, VT);
2958
2959 // fold vector ops
2960 if (VT.isVector()) {
2961 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
2962 return FoldedVOp;
2963
2964 // fold (add x, 0) -> x, vector edition
2966 return N0;
2967 }
2968
2969 // fold (add x, 0) -> x
2970 if (isNullConstant(N1))
2971 return N0;
2972
2973 if (N0.getOpcode() == ISD::SUB) {
2974 SDValue N00 = N0.getOperand(0);
2975 SDValue N01 = N0.getOperand(1);
2976
2977 // fold ((A-c1)+c2) -> (A+(c2-c1))
2978 if (SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N01}))
2979 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2980
2981 // fold ((c1-A)+c2) -> (c1+c2)-A
2982 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N00}))
2983 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2984 }
2985
2986 // add (sext i1 X), 1 -> zext (not i1 X)
2987 // We don't transform this pattern:
2988 // add (zext i1 X), -1 -> sext (not i1 X)
2989 // because most (?) targets generate better code for the zext form.
2990 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2991 isOneOrOneSplat(N1)) {
2992 SDValue X = N0.getOperand(0);
2993 if ((!LegalOperations ||
2994 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2996 X.getScalarValueSizeInBits() == 1) {
2997 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
2998 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
2999 }
3000 }
3001
3002 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1))
3003 // iff (or x, c0) is equivalent to (add x, c0).
3004 // Fold (add (xor x, c0), c1) -> (add x, (c0 + c1))
3005 // iff (xor x, c0) is equivalent to (add x, c0).
3006 if (DAG.isADDLike(N0)) {
3007 SDValue N01 = N0.getOperand(1);
3008 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N01}))
3009 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add);
3010 }
3011
3012 if (SDValue NewSel = foldBinOpIntoSelect(N))
3013 return NewSel;
3014
3015 // reassociate add
3016 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N, N0, N1)) {
3017 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
3018 return RADD;
3019
3020 // (X + Y) + X --> Y + (X + X)
3021 SDValue X, Y, InnerAdd;
3022 if (sd_match(
3023 N, m_Add(m_OneUse(m_Value(InnerAdd, m_Add(m_Value(X), m_Value(Y)))),
3024 m_Deferred(X)))) {
3025 if (X != Y) {
3026 // Redistribute shared NUW flag.
3027 // TODO: If NSW+NUW occurs on both adds, that can be redistributed too.
3028 SDNodeFlags NewFlags =
3029 N->getFlags() & InnerAdd->getFlags() & SDNodeFlags::NoUnsignedWrap;
3030 SDValue X2 = DAG.getNode(ISD::ADD, DL, VT, X, X, NewFlags);
3031 return DAG.getNode(ISD::ADD, DL, VT, Y, X2, NewFlags);
3032 }
3033 }
3034
3035 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
3036 // equivalent to (add x, c).
3037 // Reassociate (add (xor x, c), y) -> (add add(x, y), c)) if (xor x, c) is
3038 // equivalent to (add x, c).
3039 // Do this optimization only when adding c does not introduce instructions
3040 // for adding carries.
3041 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
3042 if (DAG.isADDLike(N0) && N0.hasOneUse() &&
3043 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
3044 // If N0's type does not split or is a sign mask, it does not introduce
3045 // add carry.
3046 auto TyActn = TLI.getTypeAction(*DAG.getContext(), N0.getValueType());
3047 bool NoAddCarry = TyActn == TargetLoweringBase::TypeLegal ||
3050 if (NoAddCarry)
3051 return DAG.getNode(
3052 ISD::ADD, DL, VT,
3053 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
3054 N0.getOperand(1));
3055 }
3056 return SDValue();
3057 };
3058 if (SDValue Add = ReassociateAddOr(N0, N1))
3059 return Add;
3060 if (SDValue Add = ReassociateAddOr(N1, N0))
3061 return Add;
3062
3063 // Fold add(vecreduce(x), vecreduce(y)) -> vecreduce(add(x, y))
3064 if (SDValue SD =
3065 reassociateReduction(ISD::VECREDUCE_ADD, ISD::ADD, DL, VT, N0, N1))
3066 return SD;
3067 }
3068
3069 SDValue A, B, C, D;
3070
3071 // fold ((0-A) + B) -> B-A
3072 if (sd_match(N0, m_Neg(m_Value(A))))
3073 return DAG.getNode(ISD::SUB, DL, VT, N1, A);
3074
3075 // fold (A + (0-B)) -> A-B
3076 if (sd_match(N1, m_Neg(m_Value(B))))
3077 return DAG.getNode(ISD::SUB, DL, VT, N0, B);
3078
3079 // fold (A+(B-A)) -> B
3080 if (sd_match(N1, m_Sub(m_Value(B), m_Specific(N0))))
3081 return B;
3082
3083 // fold ((B-A)+A) -> B
3084 if (sd_match(N0, m_Sub(m_Value(B), m_Specific(N1))))
3085 return B;
3086
3087 // fold ((A-B)+(C-A)) -> (C-B)
3088 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3090 return DAG.getNode(ISD::SUB, DL, VT, C, B);
3091
3092 // fold ((A-B)+(B-C)) -> (A-C)
3093 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3095 return DAG.getNode(ISD::SUB, DL, VT, A, C);
3096
3097 // fold (A+(B-(A+C))) to (B-C)
3098 // fold (A+(B-(C+A))) to (B-C)
3099 if (sd_match(N1, m_Sub(m_Value(B), m_Add(m_Specific(N0), m_Value(C)))))
3100 return DAG.getNode(ISD::SUB, DL, VT, B, C);
3101
3102 // fold (A+((B-A)+or-C)) to (B+or-C)
3103 if (sd_match(N1,
3105 m_Sub(m_Sub(m_Value(B), m_Specific(N0)), m_Value(C)))))
3106 return DAG.getNode(N1.getOpcode(), DL, VT, B, C);
3107
3108 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
3109 if (sd_match(N0, m_OneUse(m_Sub(m_Value(A), m_Value(B)))) &&
3110 sd_match(N1, m_OneUse(m_Sub(m_Value(C), m_Value(D)))) &&
3112 return DAG.getNode(ISD::SUB, DL, VT,
3113 DAG.getNode(ISD::ADD, SDLoc(N0), VT, A, C),
3114 DAG.getNode(ISD::ADD, SDLoc(N1), VT, B, D));
3115
3116 // fold (add (umax X, C), -C) --> (usubsat X, C)
3117 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
3118 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
3119 return (!Max && !Op) ||
3120 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
3121 };
3122 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
3123 /*AllowUndefs*/ true))
3124 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
3125 N0.getOperand(1));
3126 }
3127
3129 return SDValue(N, 0);
3130
3131 if (isOneOrOneSplat(N1)) {
3132 // fold (add (xor a, -1), 1) -> (sub 0, a)
3133 if (isBitwiseNot(N0))
3134 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
3135 N0.getOperand(0));
3136
3137 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
3138 if (N0.getOpcode() == ISD::ADD) {
3139 SDValue A, Xor;
3140
3141 if (isBitwiseNot(N0.getOperand(0))) {
3142 A = N0.getOperand(1);
3143 Xor = N0.getOperand(0);
3144 } else if (isBitwiseNot(N0.getOperand(1))) {
3145 A = N0.getOperand(0);
3146 Xor = N0.getOperand(1);
3147 }
3148
3149 if (Xor)
3150 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
3151 }
3152
3153 // Look for:
3154 // add (add x, y), 1
3155 // And if the target does not like this form then turn into:
3156 // sub y, (xor x, -1)
3157 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3158 N0.hasOneUse() &&
3159 // Limit this to after legalization if the add has wrap flags
3160 (Level >= AfterLegalizeDAG || (!N->getFlags().hasNoUnsignedWrap() &&
3161 !N->getFlags().hasNoSignedWrap()))) {
3162 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3163 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
3164 }
3165 }
3166
3167 // (x - y) + -1 -> add (xor y, -1), x
3168 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
3169 isAllOnesOrAllOnesSplat(N1, /*AllowUndefs=*/true)) {
3170 SDValue Not = DAG.getNOT(DL, N0.getOperand(1), VT);
3171 return DAG.getNode(ISD::ADD, DL, VT, Not, N0.getOperand(0));
3172 }
3173
3174 // Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB).
3175 // This can help if the inner add has multiple uses.
3176 APInt CM, CA;
3177 if (ConstantSDNode *CB = dyn_cast<ConstantSDNode>(N1)) {
3178 if (VT.getScalarSizeInBits() <= 64) {
3180 m_ConstInt(CM)))) &&
3182 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3183 SDNodeFlags Flags;
3184 // If all the inputs are nuw, the outputs can be nuw. If all the input
3185 // are _also_ nsw the outputs can be too.
3186 if (N->getFlags().hasNoUnsignedWrap() &&
3187 N0->getFlags().hasNoUnsignedWrap() &&
3190 if (N->getFlags().hasNoSignedWrap() &&
3191 N0->getFlags().hasNoSignedWrap() &&
3194 }
3195 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3196 DAG.getConstant(CM, DL, VT), Flags);
3197 return DAG.getNode(
3198 ISD::ADD, DL, VT, Mul,
3199 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3200 }
3201 // Also look in case there is an intermediate add.
3202 if (sd_match(N0, m_OneUse(m_Add(
3204 m_ConstInt(CM))),
3205 m_Value(B)))) &&
3207 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3208 SDNodeFlags Flags;
3209 // If all the inputs are nuw, the outputs can be nuw. If all the input
3210 // are _also_ nsw the outputs can be too.
3211 SDValue OMul =
3212 N0.getOperand(0) == B ? N0.getOperand(1) : N0.getOperand(0);
3213 if (N->getFlags().hasNoUnsignedWrap() &&
3214 N0->getFlags().hasNoUnsignedWrap() &&
3215 OMul->getFlags().hasNoUnsignedWrap() &&
3216 OMul.getOperand(0)->getFlags().hasNoUnsignedWrap()) {
3218 if (N->getFlags().hasNoSignedWrap() &&
3219 N0->getFlags().hasNoSignedWrap() &&
3220 OMul->getFlags().hasNoSignedWrap() &&
3221 OMul.getOperand(0)->getFlags().hasNoSignedWrap())
3223 }
3224 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3225 DAG.getConstant(CM, DL, VT), Flags);
3226 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N1), VT, Mul, B, Flags);
3227 return DAG.getNode(
3228 ISD::ADD, DL, VT, Add,
3229 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3230 }
3231 }
3232 }
3233
3234 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
3235 return Combined;
3236
3237 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
3238 return Combined;
3239
3240 return SDValue();
3241}
3242
3243// Attempt to form avgfloor(A, B) from (A & B) + ((A ^ B) >> 1)
3244// Attempt to form avgfloor(A, B) from ((A >> 1) + (B >> 1)) + (A & B & 1)
3245// Attempt to form avgceil(A, B) from ((A >> 1) + (B >> 1)) + ((A | B) & 1)
3246SDValue DAGCombiner::foldAddToAvg(SDNode *N, const SDLoc &DL) {
3247 SDValue N0 = N->getOperand(0);
3248 EVT VT = N0.getValueType();
3249 SDValue A, B;
3250
3251 if ((!LegalOperations || hasOperation(ISD::AVGFLOORU, VT)) &&
3252 (sd_match(N,
3254 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3257 m_Srl(m_Deferred(A), m_One()),
3258 m_Srl(m_Deferred(B), m_One()))))) {
3259 return DAG.getNode(ISD::AVGFLOORU, DL, VT, A, B);
3260 }
3261 if ((!LegalOperations || hasOperation(ISD::AVGFLOORS, VT)) &&
3262 (sd_match(N,
3264 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3267 m_Sra(m_Deferred(A), m_One()),
3268 m_Sra(m_Deferred(B), m_One()))))) {
3269 return DAG.getNode(ISD::AVGFLOORS, DL, VT, A, B);
3270 }
3271
3272 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
3273 sd_match(N,
3275 m_Srl(m_Deferred(A), m_One()),
3276 m_Srl(m_Deferred(B), m_One())))) {
3277 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
3278 }
3279 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
3280 sd_match(N,
3282 m_Sra(m_Deferred(A), m_One()),
3283 m_Sra(m_Deferred(B), m_One())))) {
3284 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
3285 }
3286
3287 return SDValue();
3288}
3289
3290SDValue DAGCombiner::visitADD(SDNode *N) {
3291 SDValue N0 = N->getOperand(0);
3292 SDValue N1 = N->getOperand(1);
3293 EVT VT = N0.getValueType();
3294 SDLoc DL(N);
3295
3296 if (SDValue Combined = visitADDLike(N))
3297 return Combined;
3298
3299 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
3300 return V;
3301
3302 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
3303 return V;
3304
3305 if (SDValue V = MatchRotate(N0, N1, SDLoc(N), /*FromAdd=*/true))
3306 return V;
3307
3308 // Try to match AVGFLOOR fixedwidth pattern
3309 if (SDValue V = foldAddToAvg(N, DL))
3310 return V;
3311
3312 // fold (a+b) -> (a|b) iff a and b share no bits.
3313 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
3314 DAG.haveNoCommonBitsSet(N0, N1))
3315 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
3316
3317 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
3318 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
3319 const APInt &C0 = N0->getConstantOperandAPInt(0);
3320 const APInt &C1 = N1->getConstantOperandAPInt(0);
3321 return DAG.getVScale(DL, VT, C0 + C1);
3322 }
3323
3324 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
3325 if (N0.getOpcode() == ISD::ADD &&
3326 N0.getOperand(1).getOpcode() == ISD::VSCALE &&
3327 N1.getOpcode() == ISD::VSCALE) {
3328 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3329 const APInt &VS1 = N1->getConstantOperandAPInt(0);
3330 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
3331 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
3332 }
3333
3334 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
3335 if (N0.getOpcode() == ISD::STEP_VECTOR &&
3336 N1.getOpcode() == ISD::STEP_VECTOR) {
3337 const APInt &C0 = N0->getConstantOperandAPInt(0);
3338 const APInt &C1 = N1->getConstantOperandAPInt(0);
3339 APInt NewStep = C0 + C1;
3340 return DAG.getStepVector(DL, VT, NewStep);
3341 }
3342
3343 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
3344 if (N0.getOpcode() == ISD::ADD &&
3346 N1.getOpcode() == ISD::STEP_VECTOR) {
3347 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3348 const APInt &SV1 = N1->getConstantOperandAPInt(0);
3349 APInt NewStep = SV0 + SV1;
3350 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
3351 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
3352 }
3353
3354 return SDValue();
3355}
3356
3357SDValue DAGCombiner::visitADDSAT(SDNode *N) {
3358 unsigned Opcode = N->getOpcode();
3359 SDValue N0 = N->getOperand(0);
3360 SDValue N1 = N->getOperand(1);
3361 EVT VT = N0.getValueType();
3362 bool IsSigned = Opcode == ISD::SADDSAT;
3363 SDLoc DL(N);
3364
3365 // fold (add_sat x, undef) -> -1
3366 if (N0.isUndef() || N1.isUndef())
3367 return DAG.getAllOnesConstant(DL, VT);
3368
3369 // fold (add_sat c1, c2) -> c3
3370 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
3371 return C;
3372
3373 // canonicalize constant to RHS
3376 return DAG.getNode(Opcode, DL, VT, N1, N0);
3377
3378 // fold vector ops
3379 if (VT.isVector()) {
3380 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
3381 return FoldedVOp;
3382
3383 // fold (add_sat x, 0) -> x, vector edition
3385 return N0;
3386 }
3387
3388 // fold (add_sat x, 0) -> x
3389 if (isNullConstant(N1))
3390 return N0;
3391
3392 // If it cannot overflow, transform into an add.
3393 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3394 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
3395
3396 return SDValue();
3397}
3398
3400 bool ForceCarryReconstruction = false) {
3401 bool Masked = false;
3402
3403 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
3404 while (true) {
3405 if (ForceCarryReconstruction && V.getValueType() == MVT::i1)
3406 return V;
3407
3408 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
3409 V = V.getOperand(0);
3410 continue;
3411 }
3412
3413 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
3414 if (ForceCarryReconstruction)
3415 return V;
3416
3417 Masked = true;
3418 V = V.getOperand(0);
3419 continue;
3420 }
3421
3422 break;
3423 }
3424
3425 // If this is not a carry, return.
3426 if (V.getResNo() != 1)
3427 return SDValue();
3428
3429 if (V.getOpcode() != ISD::UADDO_CARRY && V.getOpcode() != ISD::USUBO_CARRY &&
3430 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
3431 return SDValue();
3432
3433 EVT VT = V->getValueType(0);
3434 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
3435 return SDValue();
3436
3437 // If the result is masked, then no matter what kind of bool it is we can
3438 // return. If it isn't, then we need to make sure the bool type is either 0 or
3439 // 1 and not other values.
3440 if (Masked ||
3441 TLI.getBooleanContents(V.getValueType()) ==
3443 return V;
3444
3445 return SDValue();
3446}
3447
3448/// Given the operands of an add/sub operation, see if the 2nd operand is a
3449/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
3450/// the opcode and bypass the mask operation.
3451static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
3452 SelectionDAG &DAG, const SDLoc &DL) {
3453 if (N1.getOpcode() == ISD::ZERO_EXTEND)
3454 N1 = N1.getOperand(0);
3455
3456 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
3457 return SDValue();
3458
3459 EVT VT = N0.getValueType();
3460 SDValue N10 = N1.getOperand(0);
3461 if (N10.getValueType() != VT && N10.getOpcode() == ISD::TRUNCATE)
3462 N10 = N10.getOperand(0);
3463
3464 if (N10.getValueType() != VT)
3465 return SDValue();
3466
3467 if (DAG.ComputeNumSignBits(N10) != VT.getScalarSizeInBits())
3468 return SDValue();
3469
3470 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
3471 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
3472 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N10);
3473}
3474
3475/// Helper for doing combines based on N0 and N1 being added to each other.
3476SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
3477 SDNode *LocReference) {
3478 EVT VT = N0.getValueType();
3479 SDLoc DL(LocReference);
3480
3481 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
3482 SDValue Y, N;
3483 if (sd_match(N1, m_Shl(m_Neg(m_Value(Y)), m_Value(N))))
3484 return DAG.getNode(ISD::SUB, DL, VT, N0,
3485 DAG.getNode(ISD::SHL, DL, VT, Y, N));
3486
3487 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
3488 return V;
3489
3490 // Look for:
3491 // add (add x, 1), y
3492 // And if the target does not like this form then turn into:
3493 // sub y, (xor x, -1)
3494 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3495 N0.hasOneUse() && isOneOrOneSplat(N0.getOperand(1)) &&
3496 // Limit this to after legalization if the add has wrap flags
3497 (Level >= AfterLegalizeDAG || (!N0->getFlags().hasNoUnsignedWrap() &&
3498 !N0->getFlags().hasNoSignedWrap()))) {
3499 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3500 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
3501 }
3502
3503 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse()) {
3504 // Hoist one-use subtraction by non-opaque constant:
3505 // (x - C) + y -> (x + y) - C
3506 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3507 if (isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3508 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
3509 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
3510 }
3511 // Hoist one-use subtraction from non-opaque constant:
3512 // (C - x) + y -> (y - x) + C
3513 if (isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3514 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
3515 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
3516 }
3517 }
3518
3519 // add (mul x, C), x -> mul x, C+1
3520 if (N0.getOpcode() == ISD::MUL && N0.getOperand(0) == N1 &&
3521 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true) &&
3522 N0.hasOneUse()) {
3523 SDValue NewC = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
3524 DAG.getConstant(1, DL, VT));
3525 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), NewC);
3526 }
3527
3528 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
3529 // rather than 'add 0/-1' (the zext should get folded).
3530 // add (sext i1 Y), X --> sub X, (zext i1 Y)
3531 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
3532 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
3534 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
3535 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
3536 }
3537
3538 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
3539 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3540 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3541 if (TN->getVT() == MVT::i1) {
3542 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3543 DAG.getConstant(1, DL, VT));
3544 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
3545 }
3546 }
3547
3548 // (add X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3549 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1)) &&
3550 N1.getResNo() == 0)
3551 return DAG.getNode(ISD::UADDO_CARRY, DL, N1->getVTList(),
3552 N0, N1.getOperand(0), N1.getOperand(2));
3553
3554 // (add X, Carry) -> (uaddo_carry X, 0, Carry)
3556 if (SDValue Carry = getAsCarry(TLI, N1))
3557 return DAG.getNode(ISD::UADDO_CARRY, DL,
3558 DAG.getVTList(VT, Carry.getValueType()), N0,
3559 DAG.getConstant(0, DL, VT), Carry);
3560
3561 return SDValue();
3562}
3563
3564SDValue DAGCombiner::visitADDC(SDNode *N) {
3565 SDValue N0 = N->getOperand(0);
3566 SDValue N1 = N->getOperand(1);
3567 EVT VT = N0.getValueType();
3568 SDLoc DL(N);
3569
3570 // If the flag result is dead, turn this into an ADD.
3571 if (!N->hasAnyUseOfValue(1))
3572 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3573 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3574
3575 // canonicalize constant to RHS.
3576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3578 if (N0C && !N1C)
3579 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
3580
3581 // fold (addc x, 0) -> x + no carry out
3582 if (isNullConstant(N1))
3583 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
3584 DL, MVT::Glue));
3585
3586 // If it cannot overflow, transform into an add.
3588 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3589 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3590
3591 return SDValue();
3592}
3593
3594/**
3595 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
3596 * then the flip also occurs if computing the inverse is the same cost.
3597 * This function returns an empty SDValue in case it cannot flip the boolean
3598 * without increasing the cost of the computation. If you want to flip a boolean
3599 * no matter what, use DAG.getLogicalNOT.
3600 */
3602 const TargetLowering &TLI,
3603 bool Force) {
3604 if (Force && isa<ConstantSDNode>(V))
3605 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3606
3607 if (V.getOpcode() != ISD::XOR)
3608 return SDValue();
3609
3610 if (DAG.isBoolConstant(V.getOperand(1)) == true)
3611 return V.getOperand(0);
3612 if (Force && isConstOrConstSplat(V.getOperand(1), false))
3613 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3614 return SDValue();
3615}
3616
3617SDValue DAGCombiner::visitADDO(SDNode *N) {
3618 SDValue N0 = N->getOperand(0);
3619 SDValue N1 = N->getOperand(1);
3620 EVT VT = N0.getValueType();
3621 bool IsSigned = (ISD::SADDO == N->getOpcode());
3622
3623 EVT CarryVT = N->getValueType(1);
3624 SDLoc DL(N);
3625
3626 // If the flag result is dead, turn this into an ADD.
3627 if (!N->hasAnyUseOfValue(1))
3628 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3629 DAG.getUNDEF(CarryVT));
3630
3631 // canonicalize constant to RHS.
3634 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
3635
3636 // fold (addo x, 0) -> x + no carry out
3637 if (isNullOrNullSplat(N1))
3638 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3639
3640 // If it cannot overflow, transform into an add.
3641 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3642 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3643 DAG.getConstant(0, DL, CarryVT));
3644
3645 if (IsSigned) {
3646 // fold (saddo (xor a, -1), 1) -> (ssub 0, a).
3647 if (isBitwiseNot(N0) && isOneOrOneSplat(N1))
3648 return DAG.getNode(ISD::SSUBO, DL, N->getVTList(),
3649 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3650 } else {
3651 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
3652 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
3653 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
3654 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3655 return CombineTo(
3656 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3657 }
3658
3659 if (SDValue Combined = visitUADDOLike(N0, N1, N))
3660 return Combined;
3661
3662 if (SDValue Combined = visitUADDOLike(N1, N0, N))
3663 return Combined;
3664 }
3665
3666 return SDValue();
3667}
3668
3669SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
3670 EVT VT = N0.getValueType();
3671 if (VT.isVector())
3672 return SDValue();
3673
3674 // (uaddo X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3675 // If Y + 1 cannot overflow.
3676 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1))) {
3677 SDValue Y = N1.getOperand(0);
3678 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
3680 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0, Y,
3681 N1.getOperand(2));
3682 }
3683
3684 // (uaddo X, Carry) -> (uaddo_carry X, 0, Carry)
3686 if (SDValue Carry = getAsCarry(TLI, N1))
3687 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0,
3688 DAG.getConstant(0, SDLoc(N), VT), Carry);
3689
3690 return SDValue();
3691}
3692
3693SDValue DAGCombiner::visitADDE(SDNode *N) {
3694 SDValue N0 = N->getOperand(0);
3695 SDValue N1 = N->getOperand(1);
3696 SDValue CarryIn = N->getOperand(2);
3697
3698 // canonicalize constant to RHS
3699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3701 if (N0C && !N1C)
3702 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
3703 N1, N0, CarryIn);
3704
3705 // fold (adde x, y, false) -> (addc x, y)
3706 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3707 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
3708
3709 return SDValue();
3710}
3711
3712SDValue DAGCombiner::visitUADDO_CARRY(SDNode *N) {
3713 SDValue N0 = N->getOperand(0);
3714 SDValue N1 = N->getOperand(1);
3715 SDValue CarryIn = N->getOperand(2);
3716 SDLoc DL(N);
3717
3718 // canonicalize constant to RHS
3719 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3720 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3721 if (N0C && !N1C)
3722 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
3723
3724 // fold (uaddo_carry x, y, false) -> (uaddo x, y)
3725 if (isNullConstant(CarryIn)) {
3726 if (!LegalOperations ||
3727 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
3728 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
3729 }
3730
3731 // fold (uaddo_carry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
3732 if (isNullConstant(N0) && isNullConstant(N1)) {
3733 EVT VT = N0.getValueType();
3734 EVT CarryVT = CarryIn.getValueType();
3735 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
3736 AddToWorklist(CarryExt.getNode());
3737 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
3738 DAG.getConstant(1, DL, VT)),
3739 DAG.getConstant(0, DL, CarryVT));
3740 }
3741
3742 if (SDValue Combined = visitUADDO_CARRYLike(N0, N1, CarryIn, N))
3743 return Combined;
3744
3745 if (SDValue Combined = visitUADDO_CARRYLike(N1, N0, CarryIn, N))
3746 return Combined;
3747
3748 // We want to avoid useless duplication.
3749 // TODO: This is done automatically for binary operations. As UADDO_CARRY is
3750 // not a binary operation, this is not really possible to leverage this
3751 // existing mechanism for it. However, if more operations require the same
3752 // deduplication logic, then it may be worth generalize.
3753 SDValue Ops[] = {N1, N0, CarryIn};
3754 SDNode *CSENode =
3755 DAG.getNodeIfExists(ISD::UADDO_CARRY, N->getVTList(), Ops, N->getFlags());
3756 if (CSENode)
3757 return SDValue(CSENode, 0);
3758
3759 return SDValue();
3760}
3761
3762/**
3763 * If we are facing some sort of diamond carry propagation pattern try to
3764 * break it up to generate something like:
3765 * (uaddo_carry X, 0, (uaddo_carry A, B, Z):Carry)
3766 *
3767 * The end result is usually an increase in operation required, but because the
3768 * carry is now linearized, other transforms can kick in and optimize the DAG.
3769 *
3770 * Patterns typically look something like
3771 * (uaddo A, B)
3772 * / \
3773 * Carry Sum
3774 * | \
3775 * | (uaddo_carry *, 0, Z)
3776 * | /
3777 * \ Carry
3778 * | /
3779 * (uaddo_carry X, *, *)
3780 *
3781 * But numerous variation exist. Our goal is to identify A, B, X and Z and
3782 * produce a combine with a single path for carry propagation.
3783 */
3785 SelectionDAG &DAG, SDValue X,
3786 SDValue Carry0, SDValue Carry1,
3787 SDNode *N) {
3788 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
3789 return SDValue();
3790 if (Carry1.getOpcode() != ISD::UADDO)
3791 return SDValue();
3792
3793 SDValue Z;
3794
3795 /**
3796 * First look for a suitable Z. It will present itself in the form of
3797 * (uaddo_carry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
3798 */
3799 if (Carry0.getOpcode() == ISD::UADDO_CARRY &&
3800 isNullConstant(Carry0.getOperand(1))) {
3801 Z = Carry0.getOperand(2);
3802 } else if (Carry0.getOpcode() == ISD::UADDO &&
3803 isOneConstant(Carry0.getOperand(1))) {
3804 EVT VT = Carry0->getValueType(1);
3805 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
3806 } else {
3807 // We couldn't find a suitable Z.
3808 return SDValue();
3809 }
3810
3811
3812 auto cancelDiamond = [&](SDValue A,SDValue B) {
3813 SDLoc DL(N);
3814 SDValue NewY =
3815 DAG.getNode(ISD::UADDO_CARRY, DL, Carry0->getVTList(), A, B, Z);
3816 Combiner.AddToWorklist(NewY.getNode());
3817 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), X,
3818 DAG.getConstant(0, DL, X.getValueType()),
3819 NewY.getValue(1));
3820 };
3821
3822 /**
3823 * (uaddo A, B)
3824 * |
3825 * Sum
3826 * |
3827 * (uaddo_carry *, 0, Z)
3828 */
3829 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3830 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3831 }
3832
3833 /**
3834 * (uaddo_carry A, 0, Z)
3835 * |
3836 * Sum
3837 * |
3838 * (uaddo *, B)
3839 */
3840 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3841 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3842 }
3843
3844 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3845 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3846 }
3847
3848 return SDValue();
3849}
3850
3851// If we are facing some sort of diamond carry/borrow in/out pattern try to
3852// match patterns like:
3853//
3854// (uaddo A, B) CarryIn
3855// | \ |
3856// | \ |
3857// PartialSum PartialCarryOutX /
3858// | | /
3859// | ____|____________/
3860// | / |
3861// (uaddo *, *) \________
3862// | \ \
3863// | \ |
3864// | PartialCarryOutY |
3865// | \ |
3866// | \ /
3867// AddCarrySum | ______/
3868// | /
3869// CarryOut = (or *, *)
3870//
3871// And generate UADDO_CARRY (or USUBO_CARRY) with two result values:
3872//
3873// {AddCarrySum, CarryOut} = (uaddo_carry A, B, CarryIn)
3874//
3875// Our goal is to identify A, B, and CarryIn and produce UADDO_CARRY/USUBO_CARRY
3876// with a single path for carry/borrow out propagation.
3878 SDValue N0, SDValue N1, SDNode *N) {
3879 SDValue Carry0 = getAsCarry(TLI, N0);
3880 if (!Carry0)
3881 return SDValue();
3882 SDValue Carry1 = getAsCarry(TLI, N1);
3883 if (!Carry1)
3884 return SDValue();
3885
3886 unsigned Opcode = Carry0.getOpcode();
3887 if (Opcode != Carry1.getOpcode())
3888 return SDValue();
3889 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3890 return SDValue();
3891 // Guarantee identical type of CarryOut
3892 EVT CarryOutType = N->getValueType(0);
3893 if (CarryOutType != Carry0.getValue(1).getValueType() ||
3894 CarryOutType != Carry1.getValue(1).getValueType())
3895 return SDValue();
3896
3897 // Canonicalize the add/sub of A and B (the top node in the above ASCII art)
3898 // as Carry0 and the add/sub of the carry in as Carry1 (the middle node).
3899 if (Carry1.getNode()->isOperandOf(Carry0.getNode()))
3900 std::swap(Carry0, Carry1);
3901
3902 // Check if nodes are connected in expected way.
3903 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3904 Carry1.getOperand(1) != Carry0.getValue(0))
3905 return SDValue();
3906
3907 // The carry in value must be on the righthand side for subtraction.
3908 unsigned CarryInOperandNum =
3909 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3910 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3911 return SDValue();
3912 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3913
3914 unsigned NewOp = Opcode == ISD::UADDO ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
3915 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3916 return SDValue();
3917
3918 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3919 CarryIn = getAsCarry(TLI, CarryIn, true);
3920 if (!CarryIn)
3921 return SDValue();
3922
3923 SDLoc DL(N);
3924 CarryIn = DAG.getBoolExtOrTrunc(CarryIn, DL, Carry1->getValueType(1),
3925 Carry1->getValueType(0));
3926 SDValue Merged =
3927 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3928 Carry0.getOperand(1), CarryIn);
3929
3930 // Please note that because we have proven that the result of the UADDO/USUBO
3931 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3932 // therefore prove that if the first UADDO/USUBO overflows, the second
3933 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3934 // maximum value.
3935 //
3936 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3937 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3938 //
3939 // This is important because it means that OR and XOR can be used to merge
3940 // carry flags; and that AND can return a constant zero.
3941 //
3942 // TODO: match other operations that can merge flags (ADD, etc)
3943 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3944 if (N->getOpcode() == ISD::AND)
3945 return DAG.getConstant(0, DL, CarryOutType);
3946 return Merged.getValue(1);
3947}
3948
3949// Reconstruct a subtract-with-borrow chain from its canonicalized icmp form:
3950// carry_out = or(icmp ult A, B, and(icmp eq A, B, carry_in))
3951// InstCombine folds usub.with.overflow chains into this, losing the
3952// USUBO_CARRY that lowers to sbb/sbcs.
3954 const TargetLowering &TLI) {
3955 SDValue A, B, CarryIn;
3960 m_Value(CarryIn)))))
3961 return SDValue();
3962
3963 EVT IntVT = A.getValueType();
3964 // Skip vectors: USUBO_CARRY on a vector type has no legalization path and
3965 // would crash.
3966 if (IntVT.isVector() || !TLI.isOperationLegalOrCustom(
3968 *DAG.getContext(), IntVT)))
3969 return SDValue();
3970
3971 SDLoc DL(N);
3972 SDVTList VTs = DAG.getVTList(IntVT, N->getValueType(0));
3973 return DAG.getNode(ISD::USUBO_CARRY, DL, VTs, A, B, CarryIn).getValue(1);
3974}
3975
3976SDValue DAGCombiner::visitUADDO_CARRYLike(SDValue N0, SDValue N1,
3977 SDValue CarryIn, SDNode *N) {
3978 // fold (uaddo_carry (xor a, -1), b, c) -> (usubo_carry b, a, !c) and flip
3979 // carry.
3980 if (isBitwiseNot(N0))
3981 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3982 SDLoc DL(N);
3983 SDValue Sub = DAG.getNode(ISD::USUBO_CARRY, DL, N->getVTList(), N1,
3984 N0.getOperand(0), NotC);
3985 return CombineTo(
3986 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3987 }
3988
3989 // Iff the flag result is dead:
3990 // (uaddo_carry (add|uaddo X, Y), 0, Carry) -> (uaddo_carry X, Y, Carry)
3991 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3992 // or the dependency between the instructions.
3993 if ((N0.getOpcode() == ISD::ADD ||
3994 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3995 N0.getValue(1) != CarryIn)) &&
3996 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3997 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(),
3998 N0.getOperand(0), N0.getOperand(1), CarryIn);
3999
4000 /**
4001 * When one of the uaddo_carry argument is itself a carry, we may be facing
4002 * a diamond carry propagation. In which case we try to transform the DAG
4003 * to ensure linear carry propagation if that is possible.
4004 */
4005 if (auto Y = getAsCarry(TLI, N1)) {
4006 // Because both are carries, Y and Z can be swapped.
4007 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
4008 return R;
4009 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
4010 return R;
4011 }
4012
4013 return SDValue();
4014}
4015
4016SDValue DAGCombiner::visitSADDO_CARRYLike(SDValue N0, SDValue N1,
4017 SDValue CarryIn, SDNode *N) {
4018 // fold (saddo_carry (xor a, -1), b, c) -> (ssubo_carry b, a, !c)
4019 if (isBitwiseNot(N0)) {
4020 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true))
4021 return DAG.getNode(ISD::SSUBO_CARRY, SDLoc(N), N->getVTList(), N1,
4022 N0.getOperand(0), NotC);
4023 }
4024
4025 return SDValue();
4026}
4027
4028SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
4029 SDValue N0 = N->getOperand(0);
4030 SDValue N1 = N->getOperand(1);
4031 SDValue CarryIn = N->getOperand(2);
4032 SDLoc DL(N);
4033
4034 // canonicalize constant to RHS
4035 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4036 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4037 if (N0C && !N1C)
4038 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
4039
4040 // fold (saddo_carry x, y, false) -> (saddo x, y)
4041 if (isNullConstant(CarryIn)) {
4042 if (!LegalOperations ||
4043 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
4044 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
4045 }
4046
4047 if (SDValue Combined = visitSADDO_CARRYLike(N0, N1, CarryIn, N))
4048 return Combined;
4049
4050 if (SDValue Combined = visitSADDO_CARRYLike(N1, N0, CarryIn, N))
4051 return Combined;
4052
4053 return SDValue();
4054}
4055
4056// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
4057// clamp/truncation if necessary.
4059 SDValue RHS, SelectionDAG &DAG,
4060 const SDLoc &DL) {
4061 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
4062 "Illegal truncation");
4063
4064 if (DstVT == SrcVT)
4065 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4066
4067 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
4068 // clamping RHS.
4070 DstVT.getScalarSizeInBits());
4071 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
4072 return SDValue();
4073
4074 SDValue SatLimit =
4076 DstVT.getScalarSizeInBits()),
4077 DL, SrcVT);
4078 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
4079 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
4080 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
4081 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4082}
4083
4084// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
4085// usubsat(a,b), optionally as a truncated type.
4086SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL) {
4087 if (N->getOpcode() != ISD::SUB ||
4088 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
4089 return SDValue();
4090
4091 EVT SubVT = N->getValueType(0);
4092 SDValue Op0 = N->getOperand(0);
4093 SDValue Op1 = N->getOperand(1);
4094
4095 // Try to find umax(a,b) - b or a - umin(a,b) patterns
4096 // they may be converted to usubsat(a,b).
4097 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4098 SDValue MaxLHS = Op0.getOperand(0);
4099 SDValue MaxRHS = Op0.getOperand(1);
4100 if (MaxLHS == Op1)
4101 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, DL);
4102 if (MaxRHS == Op1)
4103 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, DL);
4104 }
4105
4106 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
4107 SDValue MinLHS = Op1.getOperand(0);
4108 SDValue MinRHS = Op1.getOperand(1);
4109 if (MinLHS == Op0)
4110 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, DL);
4111 if (MinRHS == Op0)
4112 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, DL);
4113 }
4114
4115 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
4116 if (Op1.getOpcode() == ISD::TRUNCATE &&
4117 Op1.getOperand(0).getOpcode() == ISD::UMIN &&
4118 Op1.getOperand(0).hasOneUse()) {
4119 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
4120 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
4121 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
4122 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
4123 DAG, DL);
4124 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
4125 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
4126 DAG, DL);
4127 }
4128
4129 return SDValue();
4130}
4131
4132// Refinement of DAG/Type Legalisation (promotion) when CTLZ is used for
4133// counting leading ones. Broadly, it replaces the substraction with a left
4134// shift.
4135//
4136// * DAG Legalisation Pattern:
4137//
4138// (sub (ctlz (zeroextend (not Src)))
4139// BitWidthDiff)
4140//
4141// if BitWidthDiff == BitWidth(Node) - BitWidth(Src)
4142// -->
4143//
4144// (ctlz_zero_poison (not (shl (anyextend Src)
4145// BitWidthDiff)))
4146//
4147// * Type Legalisation Pattern:
4148//
4149// (sub (ctlz (and (xor Src XorMask)
4150// AndMask))
4151// BitWidthDiff)
4152//
4153// if AndMask has only trailing ones
4154// and MaskBitWidth(AndMask) == BitWidth(Node) - BitWidthDiff
4155// and XorMask has more trailing ones than AndMask
4156// -->
4157//
4158// (ctlz_zero_poison (not (shl Src BitWidthDiff)))
4159template <class MatchContextClass>
4161 const SDLoc DL(N);
4162 SDValue N0 = N->getOperand(0);
4163 EVT VT = N0.getValueType();
4164 unsigned BitWidth = VT.getScalarSizeInBits();
4165
4166 MatchContextClass Matcher(DAG, DAG.getTargetLoweringInfo(), N);
4167
4168 APInt AndMask;
4169 APInt XorMask;
4170 uint64_t BitWidthDiff;
4171
4172 SDValue CtlzOp;
4173 SDValue Src;
4174
4175 if (!sd_context_match(
4176 N, Matcher, m_Sub(m_Ctlz(m_Value(CtlzOp)), m_ConstInt(BitWidthDiff))))
4177 return SDValue();
4178
4179 if (sd_context_match(CtlzOp, Matcher, m_ZExt(m_Not(m_Value(Src))))) {
4180 // DAG Legalisation Pattern:
4181 // (sub (ctlz (zero_extend (not Op)) BitWidthDiff))
4182 if ((BitWidth - Src.getValueType().getScalarSizeInBits()) != BitWidthDiff)
4183 return SDValue();
4184
4185 Src = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Src);
4186 } else if (sd_context_match(CtlzOp, Matcher,
4187 m_And(m_Xor(m_Value(Src), m_ConstInt(XorMask)),
4188 m_ConstInt(AndMask)))) {
4189 // Type Legalisation Pattern:
4190 // (sub (ctlz (and (xor Op XorMask) AndMask)) BitWidthDiff)
4191 if (BitWidthDiff >= BitWidth)
4192 return SDValue();
4193 unsigned AndMaskWidth = BitWidth - BitWidthDiff;
4194 if (!(AndMask.isMask(AndMaskWidth) && XorMask.countr_one() >= AndMaskWidth))
4195 return SDValue();
4196 } else
4197 return SDValue();
4198
4199 SDValue ShiftConst = DAG.getShiftAmountConstant(BitWidthDiff, VT, DL);
4200 SDValue LShift = Matcher.getNode(ISD::SHL, DL, VT, Src, ShiftConst);
4201 SDValue Not =
4202 Matcher.getNode(ISD::XOR, DL, VT, LShift, DAG.getAllOnesConstant(DL, VT));
4203
4204 return Matcher.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, Not);
4205}
4206
4207// Fold sub(x, mul(divrem(x,y)[0], y)) to divrem(x, y)[1]
4209 const SDLoc &DL) {
4210 assert(N->getOpcode() == ISD::SUB && "Node must be a SUB");
4211 SDValue Sub0 = N->getOperand(0);
4212 SDValue Sub1 = N->getOperand(1);
4213
4214 auto CheckAndFoldMulCase = [&](SDValue DivRem, SDValue MaybeY) -> SDValue {
4215 if ((DivRem.getOpcode() == ISD::SDIVREM ||
4216 DivRem.getOpcode() == ISD::UDIVREM) &&
4217 DivRem.getResNo() == 0 && DivRem.getOperand(0) == Sub0 &&
4218 DivRem.getOperand(1) == MaybeY) {
4219 return SDValue(DivRem.getNode(), 1);
4220 }
4221 return SDValue();
4222 };
4223
4224 if (Sub1.getOpcode() == ISD::MUL) {
4225 // (sub x, (mul divrem(x,y)[0], y))
4226 SDValue Mul0 = Sub1.getOperand(0);
4227 SDValue Mul1 = Sub1.getOperand(1);
4228
4229 if (SDValue Res = CheckAndFoldMulCase(Mul0, Mul1))
4230 return Res;
4231
4232 if (SDValue Res = CheckAndFoldMulCase(Mul1, Mul0))
4233 return Res;
4234
4235 } else if (Sub1.getOpcode() == ISD::SHL) {
4236 // Handle (sub x, (shl divrem(x,y)[0], C)) where y = 1 << C
4237 SDValue Shl0 = Sub1.getOperand(0);
4238 SDValue Shl1 = Sub1.getOperand(1);
4239 // Check if Shl0 is divrem(x, Y)[0]
4240 if ((Shl0.getOpcode() == ISD::SDIVREM ||
4241 Shl0.getOpcode() == ISD::UDIVREM) &&
4242 Shl0.getResNo() == 0 && Shl0.getOperand(0) == Sub0) {
4243
4244 SDValue Divisor = Shl0.getOperand(1);
4245
4246 ConstantSDNode *DivC = isConstOrConstSplat(Divisor);
4248 if (!DivC || !ShC)
4249 return SDValue();
4250
4251 if (DivC->getAPIntValue().isPowerOf2() &&
4252 DivC->getAPIntValue().logBase2() == ShC->getAPIntValue())
4253 return SDValue(Shl0.getNode(), 1);
4254 }
4255 }
4256 return SDValue();
4257}
4258
4259// Since it may not be valid to emit a fold to zero for vector initializers
4260// check if we can before folding.
4261static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
4262 SelectionDAG &DAG, bool LegalOperations) {
4263 if (!VT.isVector())
4264 return DAG.getConstant(0, DL, VT);
4265 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
4266 return DAG.getConstant(0, DL, VT);
4267 return SDValue();
4268}
4269
4270SDValue DAGCombiner::visitSUB(SDNode *N) {
4271 SDValue N0 = N->getOperand(0);
4272 SDValue N1 = N->getOperand(1);
4273 EVT VT = N0.getValueType();
4274 unsigned BitWidth = VT.getScalarSizeInBits();
4275 SDLoc DL(N);
4276
4278 return V;
4279
4280 // fold (sub x, x) -> 0
4281 if (N0 == N1)
4282 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4283
4284 // fold (sub c1, c2) -> c3
4285 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
4286 return C;
4287
4288 // fold vector ops
4289 if (VT.isVector()) {
4290 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4291 return FoldedVOp;
4292
4293 // fold (sub x, 0) -> x, vector edition
4295 return N0;
4296 }
4297
4298 // (sub x, ([v]select (ult x, y), 0, y)) -> (umin x, (sub x, y))
4299 // (sub x, ([v]select (uge x, y), y, 0)) -> (umin x, (sub x, y))
4300 if (N1.hasOneUse() && hasUMin(VT)) {
4301 SDValue Y;
4302 auto MS0 = m_Specific(N0);
4303 auto MVY = m_Value(Y);
4304 auto MZ = m_Zero();
4305 auto MCC1 = m_SpecificCondCode(ISD::SETULT);
4306 auto MCC2 = m_SpecificCondCode(ISD::SETUGE);
4307
4308 if (sd_match(N1, m_SelectCCLike(MS0, MVY, MZ, m_Deferred(Y), MCC1)) ||
4309 sd_match(N1, m_SelectCCLike(MS0, MVY, m_Deferred(Y), MZ, MCC2)) ||
4310 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC1), MZ, m_Deferred(Y))) ||
4311 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC2), m_Deferred(Y), MZ)))
4312
4313 return DAG.getNode(ISD::UMIN, DL, VT, N0,
4314 DAG.getNode(ISD::SUB, DL, VT, N0, Y));
4315 }
4316
4317 if (SDValue NewSel = foldBinOpIntoSelect(N))
4318 return NewSel;
4319
4320 // fold (sub x, c) -> (add x, -c)
4321 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4322 return DAG.getNode(ISD::ADD, DL, VT, N0,
4323 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4324
4325 if (isNullOrNullSplat(N0)) {
4326 // Right-shifting everything out but the sign bit followed by negation is
4327 // the same as flipping arithmetic/logical shift type without the negation:
4328 // -(X >>u 31) -> (X >>s 31)
4329 // -(X >>s 31) -> (X >>u 31)
4330 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
4331 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
4332 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
4333 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
4334 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
4335 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
4336 }
4337 }
4338
4339 // 0 - X --> 0 if the sub is NUW.
4340 if (N->getFlags().hasNoUnsignedWrap())
4341 return N0;
4342
4344 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
4345 // N1 must be 0 because negating the minimum signed value is undefined.
4346 if (N->getFlags().hasNoSignedWrap())
4347 return N0;
4348
4349 // 0 - X --> X if X is 0 or the minimum signed value.
4350 return N1;
4351 }
4352
4353 // Convert 0 - abs(x).
4354 if (ISD::isAbsOpcode(N1.getOpcode()) && N1.hasOneUse() &&
4355 !TLI.isOperationLegalOrCustom(N1.getOpcode(), VT))
4356 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
4357 return Result;
4358
4359 // Similar to the previous rule, but this time targeting an expanded abs.
4360 // (sub 0, (max X, (sub 0, X))) --> (min X, (sub 0, X))
4361 // as well as
4362 // (sub 0, (min X, (sub 0, X))) --> (max X, (sub 0, X))
4363 // Note that these two are applicable to both signed and unsigned min/max.
4364 SDValue X;
4365 SDValue S0;
4366 auto NegPat = m_Value(S0, m_Neg(m_Deferred(X)));
4367 if (sd_match(N1, m_OneUse(m_AnyOf(m_SMax(m_Value(X), NegPat),
4368 m_UMax(m_Value(X), NegPat),
4369 m_SMin(m_Value(X), NegPat),
4370 m_UMin(m_Value(X), NegPat))))) {
4371 unsigned NewOpc = ISD::getInverseMinMaxOpcode(N1->getOpcode());
4372 if (hasOperation(NewOpc, VT))
4373 return DAG.getNode(NewOpc, DL, VT, X, S0);
4374 }
4375
4376 // Fold neg(splat(neg(x)) -> splat(x)
4377 if (VT.isVector()) {
4378 SDValue N1S = DAG.getSplatValue(N1, true);
4379 if (N1S && N1S.getOpcode() == ISD::SUB &&
4380 isNullConstant(N1S.getOperand(0)))
4381 return DAG.getSplat(VT, DL, N1S.getOperand(1));
4382 }
4383
4384 // sub 0, (and x, 1) --> SIGN_EXTEND_INREG x, i1
4385 if (N1.getOpcode() == ISD::AND && N1.hasOneUse() &&
4386 isOneOrOneSplat(N1->getOperand(1))) {
4387 EVT ExtVT = VT.changeElementType(*DAG.getContext(), MVT::i1);
4390 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N1->getOperand(0),
4391 DAG.getValueType(ExtVT));
4392 }
4393 }
4394 }
4395
4396 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
4398 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4399
4400 // fold (A - (0-B)) -> A+B
4401 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
4402 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
4403
4404 // fold A-(A-B) -> B
4405 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
4406 return N1.getOperand(1);
4407
4408 // fold (A+B)-A -> B
4409 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
4410 return N0.getOperand(1);
4411
4412 // fold (A+B)-B -> A
4413 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
4414 return N0.getOperand(0);
4415
4416 // fold (A+C1)-C2 -> A+(C1-C2)
4417 if (N0.getOpcode() == ISD::ADD) {
4418 SDValue N01 = N0.getOperand(1);
4419 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N01, N1}))
4420 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
4421 }
4422
4423 // fold C2-(A+C1) -> (C2-C1)-A
4424 if (N1.getOpcode() == ISD::ADD) {
4425 SDValue N11 = N1.getOperand(1);
4426 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}))
4427 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
4428 }
4429
4430 // fold (A-C1)-C2 -> A-(C1+C2)
4431 if (N0.getOpcode() == ISD::SUB) {
4432 SDValue N01 = N0.getOperand(1);
4433 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N01, N1}))
4434 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
4435 }
4436
4437 // fold (c1-A)-c2 -> (c1-c2)-A
4438 if (N0.getOpcode() == ISD::SUB) {
4439 SDValue N00 = N0.getOperand(0);
4440 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N00, N1}))
4441 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
4442 }
4443
4444 SDValue A, B, C;
4445
4446 // fold ((A+(B+C))-B) -> A+C
4447 if (sd_match(N0, m_Add(m_Value(A), m_Add(m_Specific(N1), m_Value(C)))))
4448 return DAG.getNode(ISD::ADD, DL, VT, A, C);
4449
4450 // fold ((A+(B-C))-B) -> A-C
4451 if (sd_match(N0, m_Add(m_Value(A), m_Sub(m_Specific(N1), m_Value(C)))))
4452 return DAG.getNode(ISD::SUB, DL, VT, A, C);
4453
4454 // fold ((A-(B-C))-C) -> A-B
4455 if (sd_match(N0, m_Sub(m_Value(A), m_Sub(m_Value(B), m_Specific(N1)))))
4456 return DAG.getNode(ISD::SUB, DL, VT, A, B);
4457
4458 // fold (A-(B-C)) -> A+(C-B)
4459 if (sd_match(N1, m_OneUse(m_Sub(m_Value(B), m_Value(C)))))
4460 return DAG.getNode(ISD::ADD, DL, VT, N0,
4461 DAG.getNode(ISD::SUB, DL, VT, C, B));
4462
4463 // A - (A & B) -> A & (~B)
4464 if (sd_match(N1, m_And(m_Specific(N0), m_Value(B))) &&
4465 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true)))
4466 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getNOT(DL, B, VT));
4467
4468 // fold (A - (-B * C)) -> (A + (B * C))
4469 if (sd_match(N1, m_OneUse(m_Mul(m_Neg(m_Value(B)), m_Value(C)))))
4470 return DAG.getNode(ISD::ADD, DL, VT, N0,
4471 DAG.getNode(ISD::MUL, DL, VT, B, C));
4472
4473 // If either operand of a sub is undef, the result is undef
4474 if (N0.isUndef())
4475 return N0;
4476 if (N1.isUndef())
4477 return N1;
4478
4479 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
4480 return V;
4481
4482 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
4483 return V;
4484
4485 // Try to match AVGCEIL fixedwidth pattern
4486 if (SDValue V = foldSubToAvg(N, DL))
4487 return V;
4488
4489 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, DL))
4490 return V;
4491
4492 if (SDValue V = foldSubToUSubSat(VT, N, DL))
4493 return V;
4494
4495 if (SDValue V = foldRemainderIdiom(N, DAG, DL))
4496 return V;
4497
4498 // (A - B) - 1 -> add (xor B, -1), A
4500 m_One(/*AllowUndefs=*/true))))
4501 return DAG.getNode(ISD::ADD, DL, VT, A, DAG.getNOT(DL, B, VT));
4502
4503 // Look for:
4504 // sub y, (xor x, -1)
4505 // And if the target does not like this form then turn into:
4506 // add (add x, y), 1
4507 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
4508 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
4509 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
4510 }
4511
4512 // Hoist one-use addition by non-opaque constant:
4513 // (x + C) - y -> (x - y) + C
4514 if (!reassociationCanBreakAddressingModePattern(ISD::SUB, DL, N, N0, N1) &&
4515 N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
4516 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4517 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4518 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
4519 }
4520 // y - (x + C) -> (y - x) - C
4521 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse() &&
4522 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
4523 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
4524 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
4525 }
4526 // (x - C) - y -> (x - y) - C
4527 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
4528 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4529 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4530 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4531 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
4532 }
4533 // (C - x) - y -> C - (x + y)
4534 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4535 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
4536 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
4537 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
4538 }
4539
4540 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
4541 // rather than 'sub 0/1' (the sext should get folded).
4542 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
4543 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
4544 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
4545 TLI.getBooleanContents(VT) ==
4547 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
4548 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
4549 }
4550
4551 // fold B = sra (A, size(A)-1); sub (xor (A, B), B) -> (abs A)
4552 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
4554 sd_match(N0, m_Xor(m_Specific(A), m_Specific(N1))))
4555 return DAG.getNode(ISD::ABS, DL, VT, A);
4556
4557 // If the relocation model supports it, consider symbol offsets.
4558 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
4559 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
4560 // fold (sub Sym+c1, Sym+c2) -> c1-c2
4561 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
4562 if (GA->getGlobal() == GB->getGlobal())
4563 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
4564 DL, VT);
4565 }
4566
4567 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
4568 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
4569 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
4570 if (TN->getVT() == MVT::i1) {
4571 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
4572 DAG.getConstant(1, DL, VT));
4573 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
4574 }
4575 }
4576
4577 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
4578 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
4579 if (N1.getOpcode() == ISD::VSCALE && N1.hasOneUse()) {
4580 const APInt &IntVal = N1.getConstantOperandAPInt(0);
4581 if (!IntVal.isPowerOf2() ||
4582 hasOperation(ISD::MUL, N1.getOperand(0).getValueType()))
4583 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
4584 }
4585
4586 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
4587 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
4588 APInt NewStep = -N1.getConstantOperandAPInt(0);
4589 return DAG.getNode(ISD::ADD, DL, VT, N0,
4590 DAG.getStepVector(DL, VT, NewStep));
4591 }
4592
4593 // Prefer an add for more folding potential and possibly better codegen:
4594 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
4595 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
4596 SDValue ShAmt = N1.getOperand(1);
4597 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
4598 if (ShAmtC && ShAmtC->getAPIntValue() == (BitWidth - 1)) {
4599 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
4600 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
4601 }
4602 }
4603
4604 // As with the previous fold, prefer add for more folding potential.
4605 // Subtracting SMIN/0 is the same as adding SMIN/0:
4606 // N0 - (X << BW-1) --> N0 + (X << BW-1)
4607 if (N1.getOpcode() == ISD::SHL) {
4608 ConstantSDNode *ShlC = isConstOrConstSplat(N1.getOperand(1));
4609 if (ShlC && ShlC->getAPIntValue() == (BitWidth - 1))
4610 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
4611 }
4612
4613 // (sub (usubo_carry X, 0, Carry), Y) -> (usubo_carry X, Y, Carry)
4614 if (N0.getOpcode() == ISD::USUBO_CARRY && isNullConstant(N0.getOperand(1)) &&
4615 N0.getResNo() == 0 && N0.hasOneUse())
4616 return DAG.getNode(ISD::USUBO_CARRY, DL, N0->getVTList(),
4617 N0.getOperand(0), N1, N0.getOperand(2));
4618
4620 // (sub Carry, X) -> (uaddo_carry (sub 0, X), 0, Carry)
4621 if (SDValue Carry = getAsCarry(TLI, N0)) {
4622 SDValue X = N1;
4623 SDValue Zero = DAG.getConstant(0, DL, VT);
4624 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
4625 return DAG.getNode(ISD::UADDO_CARRY, DL,
4626 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
4627 Carry);
4628 }
4629 }
4630
4631 if (ConstantSDNode *C0 = isConstOrConstSplat(N0)) {
4632 const APInt &C0Val = C0->getAPIntValue();
4633
4634 // sub nuw C, x --> xor x, C when C is a mask (2^k - 1)
4635 if (N->getFlags().hasNoUnsignedWrap() && C0Val.isMask())
4636 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4637
4638 // If there's no chance of borrowing from adjacent bits, then sub is xor:
4639 // sub C0, X --> xor X, C0
4640 if (!C0->isOpaque()) {
4641 const APInt &MaybeOnes = ~DAG.computeKnownBits(N1).Zero;
4642 if ((C0Val - MaybeOnes) == (C0Val ^ MaybeOnes))
4643 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4644 }
4645 }
4646
4647 // smax(a,b) - smin(a,b) --> abds(a,b)
4648 if ((!LegalOperations || hasOperation(ISD::ABDS, VT)) &&
4649 sd_match(N0, &DAG, m_SMaxLike(m_Value(A), m_Value(B))) &&
4650 sd_match(N1, &DAG, m_SMinLike(m_Specific(A), m_Specific(B))))
4651 return DAG.getNode(ISD::ABDS, DL, VT, A, B);
4652
4653 // smin(a,b) - smax(a,b) --> neg(abds(a,b))
4654 if (hasOperation(ISD::ABDS, VT) &&
4655 sd_match(N0, &DAG, m_SMinLike(m_Value(A), m_Value(B))) &&
4656 sd_match(N1, &DAG, m_SMaxLike(m_Specific(A), m_Specific(B))))
4657 return DAG.getNegative(DAG.getNode(ISD::ABDS, DL, VT, A, B), DL, VT);
4658
4659 // umax(a,b) - umin(a,b) --> abdu(a,b)
4660 if ((!LegalOperations || hasOperation(ISD::ABDU, VT)) &&
4661 sd_match(N0, &DAG, m_UMaxLike(m_Value(A), m_Value(B))) &&
4662 sd_match(N1, &DAG, m_UMinLike(m_Specific(A), m_Specific(B))))
4663 return DAG.getNode(ISD::ABDU, DL, VT, A, B);
4664
4665 // umin(a,b) - umax(a,b) --> neg(abdu(a,b))
4666 if (hasOperation(ISD::ABDU, VT) &&
4667 sd_match(N0, &DAG, m_UMinLike(m_Value(A), m_Value(B))) &&
4668 sd_match(N1, &DAG, m_UMaxLike(m_Specific(A), m_Specific(B))))
4669 return DAG.getNegative(DAG.getNode(ISD::ABDU, DL, VT, A, B), DL, VT);
4670
4671 return SDValue();
4672}
4673
4674SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
4675 unsigned Opcode = N->getOpcode();
4676 SDValue N0 = N->getOperand(0);
4677 SDValue N1 = N->getOperand(1);
4678 EVT VT = N0.getValueType();
4679 bool IsSigned = Opcode == ISD::SSUBSAT;
4680 SDLoc DL(N);
4681
4682 // fold (sub_sat x, undef) -> 0
4683 if (N0.isUndef() || N1.isUndef())
4684 return DAG.getConstant(0, DL, VT);
4685
4686 // fold (sub_sat x, x) -> 0
4687 if (N0 == N1)
4688 return DAG.getConstant(0, DL, VT);
4689
4690 // fold (sub_sat c1, c2) -> c3
4691 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4692 return C;
4693
4694 // fold vector ops
4695 if (VT.isVector()) {
4696 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4697 return FoldedVOp;
4698
4699 // fold (sub_sat x, 0) -> x, vector edition
4701 return N0;
4702 }
4703
4704 // fold (sub_sat x, 0) -> x
4705 if (isNullConstant(N1))
4706 return N0;
4707
4708 // If it cannot overflow, transform into an sub.
4709 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4710 return DAG.getNode(ISD::SUB, DL, VT, N0, N1);
4711
4712 return SDValue();
4713}
4714
4715SDValue DAGCombiner::visitSUBC(SDNode *N) {
4716 SDValue N0 = N->getOperand(0);
4717 SDValue N1 = N->getOperand(1);
4718 EVT VT = N0.getValueType();
4719 SDLoc DL(N);
4720
4721 // If the flag result is dead, turn this into an SUB.
4722 if (!N->hasAnyUseOfValue(1))
4723 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4724 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4725
4726 // fold (subc x, x) -> 0 + no borrow
4727 if (N0 == N1)
4728 return CombineTo(N, DAG.getConstant(0, DL, VT),
4729 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4730
4731 // fold (subc x, 0) -> x + no borrow
4732 if (isNullConstant(N1))
4733 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4734
4735 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4736 if (isAllOnesConstant(N0))
4737 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4738 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4739
4740 return SDValue();
4741}
4742
4743SDValue DAGCombiner::visitSUBO(SDNode *N) {
4744 SDValue N0 = N->getOperand(0);
4745 SDValue N1 = N->getOperand(1);
4746 EVT VT = N0.getValueType();
4747 bool IsSigned = (ISD::SSUBO == N->getOpcode());
4748
4749 EVT CarryVT = N->getValueType(1);
4750 SDLoc DL(N);
4751
4752 // If the flag result is dead, turn this into an SUB.
4753 if (!N->hasAnyUseOfValue(1))
4754 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4755 DAG.getUNDEF(CarryVT));
4756
4757 // fold (subo x, x) -> 0 + no borrow
4758 if (N0 == N1)
4759 return CombineTo(N, DAG.getConstant(0, DL, VT),
4760 DAG.getConstant(0, DL, CarryVT));
4761
4762 // fold (subox, c) -> (addo x, -c)
4763 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4764 if (IsSigned && !N1C->isMinSignedValue())
4765 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
4766 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4767
4768 // fold (subo x, 0) -> x + no borrow
4769 if (isNullOrNullSplat(N1))
4770 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
4771
4772 // If it cannot overflow, transform into an sub.
4773 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4774 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4775 DAG.getConstant(0, DL, CarryVT));
4776
4777 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4778 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
4779 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4780 DAG.getConstant(0, DL, CarryVT));
4781
4782 return SDValue();
4783}
4784
4785SDValue DAGCombiner::visitSUBE(SDNode *N) {
4786 SDValue N0 = N->getOperand(0);
4787 SDValue N1 = N->getOperand(1);
4788 SDValue CarryIn = N->getOperand(2);
4789
4790 // fold (sube x, y, false) -> (subc x, y)
4791 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
4792 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
4793
4794 return SDValue();
4795}
4796
4797SDValue DAGCombiner::visitUSUBO_CARRY(SDNode *N) {
4798 SDValue N0 = N->getOperand(0);
4799 SDValue N1 = N->getOperand(1);
4800 SDValue CarryIn = N->getOperand(2);
4801
4802 // fold (usubo_carry x, y, false) -> (usubo x, y)
4803 if (isNullConstant(CarryIn)) {
4804 if (!LegalOperations ||
4805 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
4806 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
4807 }
4808
4809 // Iff the flag result is dead:
4810 // (usubo_carry (sub X, Y), 0, Carry) -> (usubo_carry X, Y, Carry)
4811 if (N0.getOpcode() == ISD::SUB && isNullConstant(N1) &&
4812 !N->hasAnyUseOfValue(1))
4813 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), N->getVTList(),
4814 N0.getOperand(0), N0.getOperand(1), CarryIn);
4815
4816 return SDValue();
4817}
4818
4819SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
4820 SDValue N0 = N->getOperand(0);
4821 SDValue N1 = N->getOperand(1);
4822 SDValue CarryIn = N->getOperand(2);
4823
4824 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
4825 if (isNullConstant(CarryIn)) {
4826 if (!LegalOperations ||
4827 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
4828 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
4829 }
4830
4831 return SDValue();
4832}
4833
4834// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
4835// UMULFIXSAT here.
4836SDValue DAGCombiner::visitMULFIX(SDNode *N) {
4837 SDValue N0 = N->getOperand(0);
4838 SDValue N1 = N->getOperand(1);
4839 SDValue Scale = N->getOperand(2);
4840 EVT VT = N0.getValueType();
4841
4842 // fold (mulfix x, undef, scale) -> 0
4843 if (N0.isUndef() || N1.isUndef())
4844 return DAG.getConstant(0, SDLoc(N), VT);
4845
4846 // Canonicalize constant to RHS (vector doesn't have to splat)
4849 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
4850
4851 // fold (mulfix x, 0, scale) -> 0
4852 if (isNullConstant(N1))
4853 return DAG.getConstant(0, SDLoc(N), VT);
4854
4855 return SDValue();
4856}
4857
4858SDValue DAGCombiner::visitMUL(SDNode *N) {
4859 SDValue N0 = N->getOperand(0);
4860 SDValue N1 = N->getOperand(1);
4861 EVT VT = N0.getValueType();
4862 unsigned BitWidth = VT.getScalarSizeInBits();
4863 SDLoc DL(N);
4864
4865 // fold (mul x, undef) -> 0
4866 if (N0.isUndef() || N1.isUndef())
4867 return DAG.getConstant(0, DL, VT);
4868
4869 // fold (mul c1, c2) -> c1*c2
4870 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, DL, VT, {N0, N1}))
4871 return C;
4872
4873 // canonicalize constant to RHS (vector doesn't have to splat)
4876 return DAG.getNode(ISD::MUL, DL, VT, N1, N0);
4877
4878 bool N1IsConst = false;
4879 bool N1IsOpaqueConst = false;
4880 APInt ConstValue1;
4881
4882 // fold vector ops
4883 if (VT.isVector()) {
4884 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4885 return FoldedVOp;
4886
4887 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
4888 assert((!N1IsConst || ConstValue1.getBitWidth() == BitWidth) &&
4889 "Splat APInt should be element width");
4890 } else {
4891 N1IsConst = isa<ConstantSDNode>(N1);
4892 if (N1IsConst) {
4893 ConstValue1 = N1->getAsAPIntVal();
4894 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
4895 }
4896 }
4897
4898 // fold (mul x, 0) -> 0
4899 if (N1IsConst && ConstValue1.isZero())
4900 return N1;
4901
4902 // fold (mul x, 1) -> x
4903 if (N1IsConst && ConstValue1.isOne())
4904 return N0;
4905
4906 if (SDValue NewSel = foldBinOpIntoSelect(N))
4907 return NewSel;
4908
4909 // fold (mul x, -1) -> 0-x
4910 if (N1IsConst && ConstValue1.isAllOnes())
4911 return DAG.getNegative(N0, DL, VT);
4912
4913 // fold (mul x, (1 << c)) -> x << c
4914 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4915 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
4916 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
4917 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4918 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4919 SDNodeFlags Flags;
4920 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap());
4921 // Preserve nsw when the shift amount is strictly less than BitWidth - 1,
4922 // i.e. the multiplier is not the signed minimum value.
4923 if (N->getFlags().hasNoSignedWrap() && N1IsConst &&
4924 ConstValue1.logBase2() < BitWidth - 1)
4925 Flags.setNoSignedWrap(true);
4926 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc, Flags);
4927 }
4928 }
4929
4930 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
4931 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
4932 unsigned Log2Val = (-ConstValue1).logBase2();
4933
4934 // FIXME: If the input is something that is easily negated (e.g. a
4935 // single-use add), we should put the negate there.
4936 return DAG.getNode(
4937 ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4938 DAG.getNode(ISD::SHL, DL, VT, N0,
4939 DAG.getShiftAmountConstant(Log2Val, VT, DL)));
4940 }
4941
4942 // Attempt to reuse an existing umul_lohi/smul_lohi node, but only if the
4943 // hi result is in use in case we hit this mid-legalization.
4944 for (unsigned LoHiOpc : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
4945 if (!LegalOperations || TLI.isOperationLegalOrCustom(LoHiOpc, VT)) {
4946 SDVTList LoHiVT = DAG.getVTList(VT, VT);
4947 // TODO: Can we match commutable operands with getNodeIfExists?
4948 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N0, N1}))
4949 if (LoHi->hasAnyUseOfValue(1))
4950 return SDValue(LoHi, 0);
4951 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N1, N0}))
4952 if (LoHi->hasAnyUseOfValue(1))
4953 return SDValue(LoHi, 0);
4954 }
4955 }
4956
4957 // Try to transform:
4958 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
4959 // mul x, (2^N + 1) --> add (shl x, N), x
4960 // mul x, (2^N - 1) --> sub (shl x, N), x
4961 // Examples: x * 33 --> (x << 5) + x
4962 // x * 15 --> (x << 4) - x
4963 // x * -33 --> -((x << 5) + x)
4964 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
4965 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
4966 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
4967 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
4968 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
4969 // x * 0xf800 --> (x << 16) - (x << 11)
4970 // x * -0x8800 --> -((x << 15) + (x << 11))
4971 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
4972 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
4973 // TODO: We could handle more general decomposition of any constant by
4974 // having the target set a limit on number of ops and making a
4975 // callback to determine that sequence (similar to sqrt expansion).
4976 unsigned MathOp = ISD::DELETED_NODE;
4977 APInt MulC = ConstValue1.abs();
4978 // The constant `2` should be treated as (2^0 + 1).
4979 unsigned TZeros = MulC == 2 ? 0 : MulC.countr_zero();
4980 MulC.lshrInPlace(TZeros);
4981 if ((MulC - 1).isPowerOf2())
4982 MathOp = ISD::ADD;
4983 else if ((MulC + 1).isPowerOf2())
4984 MathOp = ISD::SUB;
4985
4986 if (MathOp != ISD::DELETED_NODE) {
4987 unsigned ShAmt =
4988 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
4989 ShAmt += TZeros;
4990 assert(ShAmt < BitWidth &&
4991 "multiply-by-constant generated out of bounds shift");
4992 SDValue Shl =
4993 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
4994 SDValue R =
4995 TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
4996 DAG.getNode(ISD::SHL, DL, VT, N0,
4997 DAG.getConstant(TZeros, DL, VT)))
4998 : DAG.getNode(MathOp, DL, VT, Shl, N0);
4999 if (ConstValue1.isNegative())
5000 R = DAG.getNegative(R, DL, VT);
5001 return R;
5002 }
5003 }
5004
5005 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
5006 {
5007 SDValue X, C1;
5008 if (sd_match(N0, m_Shl(m_Value(X), m_Value(C1))))
5009 if (SDValue C3 = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N1, C1}))
5010 return DAG.getNode(ISD::MUL, DL, VT, X, C3);
5011 }
5012
5013 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
5014 // use.
5015 {
5016 SDValue X, C, Y;
5017 if (sd_match(N,
5020 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, X, Y);
5021 return DAG.getNode(ISD::SHL, DL, VT, Mul, C);
5022 }
5023 }
5024
5025 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
5029 return DAG.getNode(
5030 ISD::ADD, DL, VT,
5031 DAG.getNode(ISD::MUL, SDLoc(N0), VT, N0.getOperand(0), N1),
5032 DAG.getNode(ISD::MUL, SDLoc(N1), VT, N0.getOperand(1), N1));
5033
5034 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
5035 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
5036 ConstantSDNode *NC1 = isConstOrConstSplat(N1);
5037 if (N0.getOpcode() == ISD::VSCALE && NC1) {
5038 const APInt &C0 = N0.getConstantOperandAPInt(0);
5039 const APInt &C1 = NC1->getAPIntValue();
5040 if (!C0.isPowerOf2() || C1.isPowerOf2() ||
5041 hasOperation(ISD::MUL, NC1->getValueType(0)))
5042 return DAG.getVScale(DL, VT, C0 * C1);
5043 }
5044
5045 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5046 APInt MulVal;
5047 if (N0.getOpcode() == ISD::STEP_VECTOR &&
5048 ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
5049 const APInt &C0 = N0.getConstantOperandAPInt(0);
5050 APInt NewStep = C0 * MulVal;
5051 return DAG.getStepVector(DL, VT, NewStep);
5052 }
5053
5054 // Fold Y = sra (X, size(X)-1); mul (or (Y, 1), X) -> (abs X)
5055 SDValue X;
5056 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
5058 m_One()),
5059 m_Deferred(X)))) {
5060 return DAG.getNode(ISD::ABS, DL, VT, X);
5061 }
5062
5063 // Fold ((mul x, 0/undef) -> 0,
5064 // (mul x, 1) -> x) -> x)
5065 // -> and(x, mask)
5066 // We can replace vectors with '0' and '1' factors with a clearing mask.
5067 if (VT.isFixedLengthVector()) {
5068 unsigned NumElts = VT.getVectorNumElements();
5069 SmallBitVector ClearMask;
5070 ClearMask.reserve(NumElts);
5071 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
5072 if (!V || V->isZero()) {
5073 ClearMask.push_back(true);
5074 return true;
5075 }
5076 ClearMask.push_back(false);
5077 return V->isOne();
5078 };
5079 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
5080 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
5081 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
5082 EVT LegalSVT = N1.getOperand(0).getValueType();
5083 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
5084 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
5086 for (unsigned I = 0; I != NumElts; ++I)
5087 if (ClearMask[I])
5088 Mask[I] = Zero;
5089 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
5090 }
5091 }
5092
5093 // reassociate mul
5094 if (SDValue RMUL = reassociateOps(ISD::MUL, DL, N0, N1, N->getFlags()))
5095 return RMUL;
5096
5097 // Fold mul(vecreduce(x), vecreduce(y)) -> vecreduce(mul(x, y))
5098 if (SDValue SD =
5099 reassociateReduction(ISD::VECREDUCE_MUL, ISD::MUL, DL, VT, N0, N1))
5100 return SD;
5101
5102 // Simplify the operands using demanded-bits information.
5104 return SDValue(N, 0);
5105
5106 return SDValue();
5107}
5108
5109/// Return true if divmod libcall is available.
5111 const SelectionDAG &DAG) {
5112 RTLIB::Libcall LC;
5113 EVT NodeType = Node->getValueType(0);
5114 if (!NodeType.isSimple())
5115 return false;
5116 switch (NodeType.getSimpleVT().SimpleTy) {
5117 default: return false; // No libcall for vector types.
5118 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
5119 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
5120 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
5121 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
5122 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
5123 }
5124
5125 return DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported;
5126}
5127
5128/// Issue divrem if both quotient and remainder are needed.
5129SDValue DAGCombiner::useDivRem(SDNode *Node) {
5130 if (Node->use_empty())
5131 return SDValue(); // This is a dead node, leave it alone.
5132
5133 unsigned Opcode = Node->getOpcode();
5134 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
5135 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
5136
5137 // DivMod lib calls can still work on non-legal types if using lib-calls.
5138 EVT VT = Node->getValueType(0);
5139 if (VT.isVector() || !VT.isInteger())
5140 return SDValue();
5141
5142 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
5143 return SDValue();
5144
5145 // If DIVREM is going to get expanded into a libcall,
5146 // but there is no libcall available, then don't combine.
5147 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
5149 return SDValue();
5150
5151 // If div is legal, it's better to do the normal expansion
5152 unsigned OtherOpcode = 0;
5153 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
5154 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
5155 if (TLI.isOperationLegalOrCustom(Opcode, VT))
5156 return SDValue();
5157 } else {
5158 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5159 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
5160 return SDValue();
5161 }
5162
5163 SDValue Op0 = Node->getOperand(0);
5164 SDValue Op1 = Node->getOperand(1);
5165 SDValue combined;
5166 for (SDNode *User : Op0->users()) {
5167 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
5168 User->use_empty())
5169 continue;
5170 // Convert the other matching node(s), too;
5171 // otherwise, the DIVREM may get target-legalized into something
5172 // target-specific that we won't be able to recognize.
5173 unsigned UserOpc = User->getOpcode();
5174 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
5175 User->getOperand(0) == Op0 &&
5176 User->getOperand(1) == Op1) {
5177 if (!combined) {
5178 if (UserOpc == OtherOpcode) {
5179 SDVTList VTs = DAG.getVTList(VT, VT);
5180 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
5181 } else if (UserOpc == DivRemOpc) {
5182 combined = SDValue(User, 0);
5183 } else {
5184 assert(UserOpc == Opcode);
5185 continue;
5186 }
5187 }
5188 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
5189 CombineTo(User, combined);
5190 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
5191 CombineTo(User, combined.getValue(1));
5192 }
5193 }
5194 return combined;
5195}
5196
5198 SDValue N0 = N->getOperand(0);
5199 SDValue N1 = N->getOperand(1);
5200 EVT VT = N->getValueType(0);
5201 SDLoc DL(N);
5202
5203 unsigned Opc = N->getOpcode();
5204 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
5205
5206 // X / undef -> undef
5207 // X % undef -> undef
5208 // X / 0 -> undef
5209 // X % 0 -> undef
5210 // NOTE: This includes vectors where any divisor element is zero/undef.
5211 if (DAG.isUndef(Opc, {N0, N1}))
5212 return DAG.getUNDEF(VT);
5213
5214 // undef / X -> 0
5215 // undef % X -> 0
5216 if (N0.isUndef())
5217 return DAG.getConstant(0, DL, VT);
5218
5219 // 0 / X -> 0
5220 // 0 % X -> 0
5222 if (N0C && N0C->isZero())
5223 return N0;
5224
5225 // X / X -> 1
5226 // X % X -> 0
5227 if (N0 == N1)
5228 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
5229
5230 // X / 1 -> X
5231 // X % 1 -> 0
5232 // If this is a boolean op (single-bit element type), we can't have
5233 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
5234 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
5235 // it's a 1.
5236 if (isOneOrOneSplat(N1) || (VT.getScalarType() == MVT::i1))
5237 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
5238
5239 return SDValue();
5240}
5241
5242SDValue DAGCombiner::visitSDIV(SDNode *N) {
5243 SDValue N0 = N->getOperand(0);
5244 SDValue N1 = N->getOperand(1);
5245 EVT VT = N->getValueType(0);
5246 EVT CCVT = getSetCCResultType(VT);
5247 SDLoc DL(N);
5248
5249 // fold (sdiv c1, c2) -> c1/c2
5250 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
5251 return C;
5252
5253 // fold vector ops
5254 if (VT.isVector())
5255 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5256 return FoldedVOp;
5257
5258 // fold (sdiv X, -1) -> 0-X
5259 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5260 if (N1C && N1C->isAllOnes())
5261 return DAG.getNegative(N0, DL, VT);
5262
5263 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
5264 if (N1C && N1C->isMinSignedValue())
5265 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5266 DAG.getConstant(1, DL, VT),
5267 DAG.getConstant(0, DL, VT));
5268
5269 if (SDValue V = simplifyDivRem(N, DAG))
5270 return V;
5271
5272 if (SDValue NewSel = foldBinOpIntoSelect(N))
5273 return NewSel;
5274
5275 // If we know the sign bits of both operands are zero, strength reduce to a
5276 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
5277 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5278 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
5279
5280 if (SDValue V = visitSDIVLike(N0, N1, N)) {
5281 // If the corresponding remainder node exists, update its users with
5282 // (Dividend - (Quotient * Divisor).
5283 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
5284 { N0, N1 })) {
5285 // If the sdiv has the exact flag we shouldn't propagate it to the
5286 // remainder node.
5287 if (!N->getFlags().hasExact()) {
5288 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5289 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5290 AddToWorklist(Mul.getNode());
5291 AddToWorklist(Sub.getNode());
5292 CombineTo(RemNode, Sub);
5293 }
5294 }
5295 return V;
5296 }
5297
5298 // sdiv, srem -> sdivrem
5299 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5300 // true. Otherwise, we break the simplification logic in visitREM().
5301 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5302 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5303 if (SDValue DivRem = useDivRem(N))
5304 return DivRem;
5305
5306 return SDValue();
5307}
5308
5309static bool isDivisorPowerOfTwo(SDValue Divisor) {
5310 // Helper for determining whether a value is a power-2 constant scalar or a
5311 // vector of such elements.
5312 auto IsPowerOfTwo = [](ConstantSDNode *C) {
5313 if (C->isZero() || C->isOpaque())
5314 return false;
5315 if (C->getAPIntValue().isPowerOf2())
5316 return true;
5317 if (C->getAPIntValue().isNegatedPowerOf2())
5318 return true;
5319 return false;
5320 };
5321
5322 return ISD::matchUnaryPredicate(Divisor, IsPowerOfTwo, /*AllowUndefs=*/false,
5323 /*AllowTruncation=*/true);
5324}
5325
5326SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5327 SDLoc DL(N);
5328 EVT VT = N->getValueType(0);
5329 EVT CCVT = getSetCCResultType(VT);
5330 unsigned BitWidth = VT.getScalarSizeInBits();
5331 unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();
5332
5333 // fold (sdiv X, pow2) -> simple ops after legalize
5334 // FIXME: We check for the exact bit here because the generic lowering gives
5335 // better results in that case. The target-specific lowering should learn how
5336 // to handle exact sdivs efficiently. An exception is made for large bitwidths
5337 // exceeding what the target can natively support, as division expansion was
5338 // skipped in favor of this optimization.
5339 if ((!N->getFlags().hasExact() || BitWidth > MaxLegalDivRemBitWidth) &&
5340 isDivisorPowerOfTwo(N1)) {
5341 // Target-specific implementation of sdiv x, pow2.
5342 if (SDValue Res = BuildSDIVPow2(N))
5343 return Res;
5344
5345 // Create constants that are functions of the shift amount value.
5346 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
5347 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
5348 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
5349 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
5350 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
5351 if (!isConstantOrConstantVector(Inexact))
5352 return SDValue();
5353
5354 // Splat the sign bit into the register
5355 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
5356 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
5357 AddToWorklist(Sign.getNode());
5358
5359 // Add (N0 < 0) ? abs2 - 1 : 0;
5360 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
5361 AddToWorklist(Srl.getNode());
5362 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
5363 AddToWorklist(Add.getNode());
5364 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
5365 AddToWorklist(Sra.getNode());
5366
5367 // Special case: (sdiv X, 1) -> X
5368 // Special Case: (sdiv X, -1) -> 0-X
5369 SDValue One = DAG.getConstant(1, DL, VT);
5371 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
5372 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
5373 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
5374 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
5375
5376 // If dividing by a positive value, we're done. Otherwise, the result must
5377 // be negated.
5378 SDValue Zero = DAG.getConstant(0, DL, VT);
5379 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
5380
5381 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
5382 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
5383 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
5384 return Res;
5385 }
5386
5387 // If integer divide is expensive and we satisfy the requirements, emit an
5388 // alternate sequence. Targets may check function attributes for size/speed
5389 // trade-offs.
5390 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5391 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5392 /*AllowTruncation=*/true) &&
5393 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5394 if (SDValue Op = BuildSDIV(N))
5395 return Op;
5396
5397 return SDValue();
5398}
5399
5400SDValue DAGCombiner::visitUDIV(SDNode *N) {
5401 SDValue N0 = N->getOperand(0);
5402 SDValue N1 = N->getOperand(1);
5403 EVT VT = N->getValueType(0);
5404 EVT CCVT = getSetCCResultType(VT);
5405 SDLoc DL(N);
5406
5407 // fold (udiv c1, c2) -> c1/c2
5408 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
5409 return C;
5410
5411 // fold vector ops
5412 if (VT.isVector())
5413 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5414 return FoldedVOp;
5415
5416 // fold (udiv X, -1) -> select(X == -1, 1, 0)
5417 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5418 if (N1C && N1C->isAllOnes() && CCVT.isVector() == VT.isVector()) {
5419 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5420 DAG.getConstant(1, DL, VT),
5421 DAG.getConstant(0, DL, VT));
5422 }
5423
5424 if (SDValue V = simplifyDivRem(N, DAG))
5425 return V;
5426
5427 if (SDValue NewSel = foldBinOpIntoSelect(N))
5428 return NewSel;
5429
5430 if (SDValue V = visitUDIVLike(N0, N1, N)) {
5431 // If the corresponding remainder node exists, update its users with
5432 // (Dividend - (Quotient * Divisor).
5433 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
5434 { N0, N1 })) {
5435 // If the udiv has the exact flag we shouldn't propagate it to the
5436 // remainder node.
5437 if (!N->getFlags().hasExact()) {
5438 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5439 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5440 AddToWorklist(Mul.getNode());
5441 AddToWorklist(Sub.getNode());
5442 CombineTo(RemNode, Sub);
5443 }
5444 }
5445 return V;
5446 }
5447
5448 // sdiv, srem -> sdivrem
5449 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5450 // true. Otherwise, we break the simplification logic in visitREM().
5451 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5452 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5453 if (SDValue DivRem = useDivRem(N))
5454 return DivRem;
5455
5456 // Simplify the operands using demanded-bits information.
5457 // We don't have demanded bits support for UDIV so this just enables constant
5458 // folding based on known bits.
5460 return SDValue(N, 0);
5461
5462 return SDValue();
5463}
5464
5465SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5466 SDLoc DL(N);
5467 EVT VT = N->getValueType(0);
5468
5469 // fold (udiv x, (1 << c)) -> x >>u c
5470 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5471 /*AllowTruncation=*/true)) {
5472 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5473 AddToWorklist(LogBase2.getNode());
5474
5475 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5476 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
5477 AddToWorklist(Trunc.getNode());
5478 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5479 }
5480 }
5481
5482 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
5483 if (N1.getOpcode() == ISD::SHL) {
5484 SDValue N10 = N1.getOperand(0);
5485 if (isConstantOrConstantVector(N10, /*NoOpaques=*/true,
5486 /*AllowTruncation=*/true)) {
5487 if (SDValue LogBase2 = BuildLogBase2(N10, DL)) {
5488 AddToWorklist(LogBase2.getNode());
5489
5490 EVT ADDVT = N1.getOperand(1).getValueType();
5491 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
5492 AddToWorklist(Trunc.getNode());
5493 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
5494 AddToWorklist(Add.getNode());
5495 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
5496 }
5497 }
5498 }
5499
5500 // fold (udiv x, c) -> alternate
5501 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5502 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5503 /*AllowTruncation=*/true) &&
5504 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5505 if (SDValue Op = BuildUDIV(N))
5506 return Op;
5507
5508 return SDValue();
5509}
5510
5511SDValue DAGCombiner::buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N) {
5512 if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1) &&
5513 !DAG.doesNodeExist(ISD::SDIV, N->getVTList(), {N0, N1})) {
5514 // Target-specific implementation of srem x, pow2.
5515 if (SDValue Res = BuildSREMPow2(N))
5516 return Res;
5517 }
5518 return SDValue();
5519}
5520
5521// handles ISD::SREM and ISD::UREM
5522SDValue DAGCombiner::visitREM(SDNode *N) {
5523 unsigned Opcode = N->getOpcode();
5524 SDValue N0 = N->getOperand(0);
5525 SDValue N1 = N->getOperand(1);
5526 EVT VT = N->getValueType(0);
5527 EVT CCVT = getSetCCResultType(VT);
5528
5529 bool isSigned = (Opcode == ISD::SREM);
5530 SDLoc DL(N);
5531
5532 // fold (rem c1, c2) -> c1%c2
5533 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5534 return C;
5535
5536 // fold (urem X, -1) -> select(FX == -1, 0, FX)
5537 // Freeze the numerator to avoid a miscompile with an undefined value.
5538 if (!isSigned && llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false) &&
5539 CCVT.isVector() == VT.isVector()) {
5540 SDValue F0 = DAG.getFreeze(N0);
5541 SDValue EqualsNeg1 = DAG.getSetCC(DL, CCVT, F0, N1, ISD::SETEQ);
5542 return DAG.getSelect(DL, VT, EqualsNeg1, DAG.getConstant(0, DL, VT), F0);
5543 }
5544
5545 if (SDValue V = simplifyDivRem(N, DAG))
5546 return V;
5547
5548 if (SDValue NewSel = foldBinOpIntoSelect(N))
5549 return NewSel;
5550
5551 if (isSigned) {
5552 // If we know the sign bits of both operands are zero, strength reduce to a
5553 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
5554 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5555 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
5556 } else {
5557 if (DAG.isKnownToBeAPowerOfTwo(N1, /*OrZero=*/true)) {
5558 // fold (urem x, pow2) -> (and x, pow2-1)
5559 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
5560 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
5561 AddToWorklist(Add.getNode());
5562 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
5563 }
5564 }
5565
5566 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5567
5568 // If X/C can be simplified by the division-by-constant logic, lower
5569 // X%C to the equivalent of X-X/C*C.
5570 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
5571 // speculative DIV must not cause a DIVREM conversion. We guard against this
5572 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
5573 // combine will not return a DIVREM. Regardless, checking cheapness here
5574 // makes sense since the simplification results in fatter code.
5575 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
5576 if (isSigned) {
5577 // check if we can build faster implementation for srem
5578 if (SDValue OptimizedRem = buildOptimizedSREM(N0, N1, N))
5579 return OptimizedRem;
5580 }
5581
5582 SDValue OptimizedDiv =
5583 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
5584 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
5585 // If the equivalent Div node also exists, update its users.
5586 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5587 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
5588 { N0, N1 }))
5589 CombineTo(DivNode, OptimizedDiv);
5590 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
5591 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5592 AddToWorklist(OptimizedDiv.getNode());
5593 AddToWorklist(Mul.getNode());
5594 return Sub;
5595 }
5596 }
5597
5598 // sdiv, srem -> sdivrem
5599 if (SDValue DivRem = useDivRem(N))
5600 return DivRem.getValue(1);
5601
5602 // fold urem(urem(A, BCst), Op1Cst) -> urem(A, Op1Cst)
5603 // iff urem(BCst, Op1Cst) == 0
5604 SDValue A;
5605 APInt Op1Cst, BCst;
5606 if (sd_match(N, m_URem(m_URem(m_Value(A), m_ConstInt(BCst)),
5607 m_ConstInt(Op1Cst))) &&
5608 BCst.urem(Op1Cst).isZero()) {
5609 return DAG.getNode(ISD::UREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5610 }
5611
5612 // fold srem(srem(A, BCst), Op1Cst) -> srem(A, Op1Cst)
5613 // iff srem(BCst, Op1Cst) == 0 && Op1Cst != 1
5614 if (sd_match(N, m_SRem(m_SRem(m_Value(A), m_ConstInt(BCst)),
5615 m_ConstInt(Op1Cst))) &&
5616 BCst.srem(Op1Cst).isZero() && !Op1Cst.isAllOnes()) {
5617 return DAG.getNode(ISD::SREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5618 }
5619
5620 return SDValue();
5621}
5622
5623SDValue DAGCombiner::visitMULHS(SDNode *N) {
5624 SDValue N0 = N->getOperand(0);
5625 SDValue N1 = N->getOperand(1);
5626 EVT VT = N->getValueType(0);
5627 SDLoc DL(N);
5628
5629 // fold (mulhs c1, c2)
5630 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
5631 return C;
5632
5633 // canonicalize constant to RHS.
5636 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
5637
5638 if (VT.isVector()) {
5639 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5640 return FoldedVOp;
5641
5642 // fold (mulhs x, 0) -> 0
5643 // do not return N1, because undef node may exist.
5645 return DAG.getConstant(0, DL, VT);
5646 }
5647
5648 // fold (mulhs x, 0) -> 0
5649 if (isNullConstant(N1))
5650 return N1;
5651
5652 // fold (mulhs x, 1) -> (sra x, size(x)-1)
5653 if (isOneConstant(N1))
5654 return DAG.getNode(
5655 ISD::SRA, DL, VT, N0,
5657
5658 // fold (mulhs x, undef) -> 0
5659 if (N0.isUndef() || N1.isUndef())
5660 return DAG.getConstant(0, DL, VT);
5661
5662 // If the type twice as wide is legal, transform the mulhs to a wider multiply
5663 // plus a shift.
5664 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
5665 !VT.isVector()) {
5666 MVT Simple = VT.getSimpleVT();
5667 unsigned SimpleSize = Simple.getSizeInBits();
5668 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5669 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5670 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
5671 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
5672 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5673 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5674 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5675 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5676 }
5677 }
5678
5679 return SDValue();
5680}
5681
5682SDValue DAGCombiner::visitMULHU(SDNode *N) {
5683 SDValue N0 = N->getOperand(0);
5684 SDValue N1 = N->getOperand(1);
5685 EVT VT = N->getValueType(0);
5686 SDLoc DL(N);
5687
5688 // fold (mulhu c1, c2)
5689 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
5690 return C;
5691
5692 // canonicalize constant to RHS.
5695 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
5696
5697 if (VT.isVector()) {
5698 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5699 return FoldedVOp;
5700
5701 // fold (mulhu x, 0) -> 0
5702 // do not return N1, because undef node may exist.
5704 return DAG.getConstant(0, DL, VT);
5705 }
5706
5707 // fold (mulhu x, 0) -> 0
5708 if (isNullConstant(N1))
5709 return N1;
5710
5711 // fold (mulhu x, 1) -> 0
5712 if (isOneConstant(N1))
5713 return DAG.getConstant(0, DL, VT);
5714
5715 // fold (mulhu x, undef) -> 0
5716 if (N0.isUndef() || N1.isUndef())
5717 return DAG.getConstant(0, DL, VT);
5718
5719 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
5720 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5721 /*AllowTruncation=*/true) &&
5722 (!LegalOperations || hasOperation(ISD::SRL, VT))) {
5723 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5724 unsigned NumEltBits = VT.getScalarSizeInBits();
5725 SDValue SRLAmt = DAG.getNode(
5726 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
5727 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5728 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
5729 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5730 }
5731 }
5732
5733 // If the type twice as wide is legal, transform the mulhu to a wider multiply
5734 // plus a shift.
5735 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
5736 !VT.isVector()) {
5737 MVT Simple = VT.getSimpleVT();
5738 unsigned SimpleSize = Simple.getSizeInBits();
5739 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5740 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5741 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
5742 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
5743 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5744 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5745 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5746 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5747 }
5748 }
5749
5750 // Simplify the operands using demanded-bits information.
5751 // We don't have demanded bits support for MULHU so this just enables constant
5752 // folding based on known bits.
5754 return SDValue(N, 0);
5755
5756 return SDValue();
5757}
5758
5759SDValue DAGCombiner::visitAVG(SDNode *N) {
5760 unsigned Opcode = N->getOpcode();
5761 SDValue N0 = N->getOperand(0);
5762 SDValue N1 = N->getOperand(1);
5763 EVT VT = N->getValueType(0);
5764 SDLoc DL(N);
5765 bool IsSigned = Opcode == ISD::AVGCEILS || Opcode == ISD::AVGFLOORS;
5766
5767 // fold (avg c1, c2)
5768 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5769 return C;
5770
5771 // canonicalize constant to RHS.
5774 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5775
5776 if (VT.isVector())
5777 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5778 return FoldedVOp;
5779
5780 // fold (avg x, undef) -> x
5781 if (N0.isUndef())
5782 return N1;
5783 if (N1.isUndef())
5784 return N0;
5785
5786 // fold (avg x, x) --> x
5787 if (N0 == N1 && Level >= AfterLegalizeTypes)
5788 return N0;
5789
5790 // fold (avgfloor x, 0) -> x >> 1
5791 SDValue X, Y;
5793 return DAG.getNode(ISD::SRA, DL, VT, X,
5794 DAG.getShiftAmountConstant(1, VT, DL));
5796 return DAG.getNode(ISD::SRL, DL, VT, X,
5797 DAG.getShiftAmountConstant(1, VT, DL));
5798
5799 // fold avgu(zext(x), zext(y)) -> zext(avgu(x, y))
5800 // fold avgs(sext(x), sext(y)) -> sext(avgs(x, y))
5801 if (!IsSigned &&
5802 sd_match(N, m_BinOp(Opcode, m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
5803 X.getValueType() == Y.getValueType() &&
5804 hasOperation(Opcode, X.getValueType())) {
5805 SDValue AvgU = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5806 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, AvgU);
5807 }
5808 if (IsSigned &&
5809 sd_match(N, m_BinOp(Opcode, m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
5810 X.getValueType() == Y.getValueType() &&
5811 hasOperation(Opcode, X.getValueType())) {
5812 SDValue AvgS = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5813 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, AvgS);
5814 }
5815
5816 // Fold avgflooru(x,y) -> avgceilu(x,y-1) iff y != 0
5817 // Fold avgflooru(x,y) -> avgceilu(x-1,y) iff x != 0
5818 // Check if avgflooru isn't legal/custom but avgceilu is.
5819 if (Opcode == ISD::AVGFLOORU && !hasOperation(ISD::AVGFLOORU, VT) &&
5820 (!LegalOperations || hasOperation(ISD::AVGCEILU, VT))) {
5821 if (DAG.isKnownNeverZero(N1))
5822 return DAG.getNode(
5823 ISD::AVGCEILU, DL, VT, N0,
5824 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getAllOnesConstant(DL, VT)));
5825 if (DAG.isKnownNeverZero(N0))
5826 return DAG.getNode(
5827 ISD::AVGCEILU, DL, VT, N1,
5828 DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getAllOnesConstant(DL, VT)));
5829 }
5830
5831 // Fold avgfloor((add nw x,y), 1) -> avgceil(x,y)
5832 // Fold avgfloor((add nw x,1), y) -> avgceil(x,y)
5833 if ((Opcode == ISD::AVGFLOORU && hasOperation(ISD::AVGCEILU, VT)) ||
5834 (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGCEILS, VT))) {
5835 SDValue Add;
5836 if (sd_match(N,
5837 m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_Value(Y))),
5838 m_One())) ||
5839 sd_match(N, m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_One())),
5840 m_Value(Y)))) {
5841
5842 if (IsSigned && Add->getFlags().hasNoSignedWrap())
5843 return DAG.getNode(ISD::AVGCEILS, DL, VT, X, Y);
5844
5845 if (!IsSigned && Add->getFlags().hasNoUnsignedWrap())
5846 return DAG.getNode(ISD::AVGCEILU, DL, VT, X, Y);
5847 }
5848 }
5849
5850 // Fold avgfloors(x,y) -> avgflooru(x,y) if both x and y are non-negative
5851 if (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGFLOORU, VT)) {
5852 if (DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5853 return DAG.getNode(ISD::AVGFLOORU, DL, VT, N0, N1);
5854 }
5855
5856 return SDValue();
5857}
5858
5859SDValue DAGCombiner::visitABD(SDNode *N) {
5860 unsigned Opcode = N->getOpcode();
5861 SDValue N0 = N->getOperand(0);
5862 SDValue N1 = N->getOperand(1);
5863 EVT VT = N->getValueType(0);
5864 SDLoc DL(N);
5865
5866 // fold (abd c1, c2)
5867 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5868 return C;
5869
5870 // canonicalize constant to RHS.
5873 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5874
5875 if (VT.isVector())
5876 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5877 return FoldedVOp;
5878
5879 // fold (abd x, undef) -> 0
5880 if (N0.isUndef() || N1.isUndef())
5881 return DAG.getConstant(0, DL, VT);
5882
5883 // fold (abd x, x) -> 0
5884 if (N0 == N1)
5885 return DAG.getConstant(0, DL, VT);
5886
5887 SDValue X, Y;
5888
5889 // fold (abds x, 0) -> abs x
5891 (!LegalOperations || hasOperation(ISD::ABS, VT)))
5892 return DAG.getNode(ISD::ABS, DL, VT, X);
5893
5894 // fold (abdu x, 0) -> x
5896 return X;
5897
5898 // fold (abds x, y) -> (abdu x, y) iff both args are known positive
5899 if (Opcode == ISD::ABDS && hasOperation(ISD::ABDU, VT) &&
5900 DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5901 return DAG.getNode(ISD::ABDU, DL, VT, N1, N0);
5902
5903 // fold (abd? (?ext x), (?ext y)) -> (zext (abd? x, y))
5906 EVT SmallVT = X.getScalarValueSizeInBits() > Y.getScalarValueSizeInBits()
5907 ? X.getValueType()
5908 : Y.getValueType();
5909 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5910 SDValue ExtedX = DAG.getExtOrTrunc(X, SDLoc(X), SmallVT, N0->getOpcode());
5911 SDValue ExtedY = DAG.getExtOrTrunc(Y, SDLoc(Y), SmallVT, N0->getOpcode());
5912 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {ExtedX, ExtedY});
5913 SDValue ZExted = DAG.getZExtOrTrunc(SmallABD, DL, VT);
5914 return ZExted;
5915 }
5916 }
5917
5918 // fold (abd? (?ext ty:x), small_const:c) -> (zext (abd? x, c))
5921 EVT SmallVT = X.getValueType();
5922 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5923 uint64_t Bits = SmallVT.getScalarSizeInBits();
5924 unsigned RelevantBits =
5925 (Opcode == ISD::ABDS) ? DAG.ComputeMaxSignificantBits(Y)
5927 bool TruncatingYIsCheap = TLI.isTruncateFree(Y, SmallVT) ||
5929 Y,
5930 [&](auto *C) {
5931 const APInt &YConst = C->getAsAPIntVal();
5932 return (Opcode == ISD::ABDS)
5933 ? YConst.isSignedIntN(Bits)
5934 : YConst.isIntN(Bits);
5935 },
5936 /*AllowUndefs=*/true);
5937
5938 if (RelevantBits <= Bits && TruncatingYIsCheap) {
5939 SDValue NewY = DAG.getNode(ISD::TRUNCATE, SDLoc(Y), SmallVT, Y);
5940 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {X, NewY});
5941 return DAG.getZExtOrTrunc(SmallABD, DL, VT);
5942 }
5943 }
5944 }
5945
5946 return SDValue();
5947}
5948
5949/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
5950/// give the opcodes for the two computations that are being performed. Return
5951/// true if a simplification was made.
5952SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
5953 unsigned HiOp) {
5954 // If the high half is not needed, just compute the low half.
5955 bool HiExists = N->hasAnyUseOfValue(1);
5956 if (!HiExists && (!LegalOperations ||
5957 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
5958 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5959 return CombineTo(N, Res, Res);
5960 }
5961
5962 // If the low half is not needed, just compute the high half.
5963 bool LoExists = N->hasAnyUseOfValue(0);
5964 if (!LoExists && (!LegalOperations ||
5965 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
5966 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
5967 return CombineTo(N, Res, Res);
5968 }
5969
5970 // If both halves are used, return as it is.
5971 if (LoExists && HiExists)
5972 return SDValue();
5973
5974 // If the two computed results can be simplified separately, separate them.
5975 if (LoExists) {
5976 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5977 AddToWorklist(Lo.getNode());
5978 SDValue LoOpt = combine(Lo.getNode());
5979 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
5980 (!LegalOperations ||
5981 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
5982 return CombineTo(N, LoOpt, LoOpt);
5983 }
5984
5985 if (HiExists) {
5986 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
5987 AddToWorklist(Hi.getNode());
5988 SDValue HiOpt = combine(Hi.getNode());
5989 if (HiOpt.getNode() && HiOpt != Hi &&
5990 (!LegalOperations ||
5991 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
5992 return CombineTo(N, HiOpt, HiOpt);
5993 }
5994
5995 return SDValue();
5996}
5997
5998SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
5999 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
6000 return Res;
6001
6002 SDValue N0 = N->getOperand(0);
6003 SDValue N1 = N->getOperand(1);
6004 EVT VT = N->getValueType(0);
6005 SDLoc DL(N);
6006
6007 // Constant fold.
6009 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N0, N1);
6010
6011 // canonicalize constant to RHS (vector doesn't have to splat)
6014 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N1, N0);
6015
6016 // If the type is twice as wide is legal, transform the mulhu to a wider
6017 // multiply plus a shift.
6018 if (VT.isSimple() && !VT.isVector()) {
6019 MVT Simple = VT.getSimpleVT();
6020 unsigned SimpleSize = Simple.getSizeInBits();
6021 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6022 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6023 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
6024 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
6025 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6026 // Compute the high part as N1.
6027 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6028 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6029 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6030 // Compute the low part as N0.
6031 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6032 return CombineTo(N, Lo, Hi);
6033 }
6034 }
6035
6036 return SDValue();
6037}
6038
6039SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
6040 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
6041 return Res;
6042
6043 SDValue N0 = N->getOperand(0);
6044 SDValue N1 = N->getOperand(1);
6045 EVT VT = N->getValueType(0);
6046 SDLoc DL(N);
6047
6048 // Constant fold.
6050 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N0, N1);
6051
6052 // canonicalize constant to RHS (vector doesn't have to splat)
6055 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N1, N0);
6056
6057 // (umul_lohi N0, 0) -> (0, 0)
6058 if (isNullConstant(N1)) {
6059 SDValue Zero = DAG.getConstant(0, DL, VT);
6060 return CombineTo(N, Zero, Zero);
6061 }
6062
6063 // (umul_lohi N0, 1) -> (N0, 0)
6064 if (isOneConstant(N1)) {
6065 SDValue Zero = DAG.getConstant(0, DL, VT);
6066 return CombineTo(N, N0, Zero);
6067 }
6068
6069 // If the type is twice as wide is legal, transform the mulhu to a wider
6070 // multiply plus a shift.
6071 if (VT.isSimple() && !VT.isVector()) {
6072 MVT Simple = VT.getSimpleVT();
6073 unsigned SimpleSize = Simple.getSizeInBits();
6074 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6075 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6076 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
6077 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
6078 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6079 // Compute the high part as N1.
6080 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6081 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6082 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6083 // Compute the low part as N0.
6084 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6085 return CombineTo(N, Lo, Hi);
6086 }
6087 }
6088
6089 return SDValue();
6090}
6091
6092SDValue DAGCombiner::visitMULO(SDNode *N) {
6093 SDValue N0 = N->getOperand(0);
6094 SDValue N1 = N->getOperand(1);
6095 EVT VT = N0.getValueType();
6096 bool IsSigned = (ISD::SMULO == N->getOpcode());
6097
6098 EVT CarryVT = N->getValueType(1);
6099 SDLoc DL(N);
6100
6101 ConstantSDNode *N0C = isConstOrConstSplat(N0);
6102 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6103
6104 // fold operation with constant operands.
6105 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
6106 // multiple results.
6107 if (N0C && N1C) {
6108 bool Overflow;
6109 APInt Result =
6110 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
6111 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
6112 return CombineTo(N, DAG.getConstant(Result, DL, VT),
6113 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
6114 }
6115
6116 // canonicalize constant to RHS.
6119 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
6120
6121 // fold (mulo x, 0) -> 0 + no carry out
6122 if (isNullOrNullSplat(N1))
6123 return CombineTo(N, DAG.getConstant(0, DL, VT),
6124 DAG.getConstant(0, DL, CarryVT));
6125
6126 // (mulo x, 2) -> (addo x, x)
6127 // FIXME: This needs a freeze.
6128 if (N1C && N1C->getAPIntValue() == 2 &&
6129 (!IsSigned || VT.getScalarSizeInBits() > 2))
6130 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
6131 N->getVTList(), N0, N0);
6132
6133 // A 1 bit SMULO overflows if both inputs are 1.
6134 if (IsSigned && VT.getScalarSizeInBits() == 1) {
6135 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
6136 SDValue Cmp = DAG.getSetCC(DL, CarryVT, And,
6137 DAG.getConstant(0, DL, VT), ISD::SETNE);
6138 return CombineTo(N, And, Cmp);
6139 }
6140
6141 // If it cannot overflow, transform into a mul.
6142 if (DAG.willNotOverflowMul(IsSigned, N0, N1))
6143 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
6144 DAG.getConstant(0, DL, CarryVT));
6145 return SDValue();
6146}
6147
6148// Function to calculate whether the Min/Max pair of SDNodes (potentially
6149// swapped around) make a signed saturate pattern, clamping to between a signed
6150// saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
6151// Returns the node being clamped and the bitwidth of the clamp in BW. Should
6152// work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
6153// same as SimplifySelectCC. N0<N1 ? N2 : N3.
6155 SDValue N3, ISD::CondCode CC, unsigned &BW,
6156 bool &Unsigned, SelectionDAG &DAG) {
6157 auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
6158 ISD::CondCode CC) {
6159 // The compare and select operand should be the same or the select operands
6160 // should be truncated versions of the comparison.
6161 if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
6162 return 0;
6163 // The constants need to be the same or a truncated version of each other.
6166 if (!N1C || !N3C)
6167 return 0;
6168 const APInt &C1 = N1C->getAPIntValue().trunc(N1.getScalarValueSizeInBits());
6169 const APInt &C2 = N3C->getAPIntValue().trunc(N3.getScalarValueSizeInBits());
6170 if (C1.getBitWidth() < C2.getBitWidth() || C1 != C2.sext(C1.getBitWidth()))
6171 return 0;
6172 return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
6173 };
6174
6175 // Check the initial value is a SMIN/SMAX equivalent.
6176 unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
6177 if (!Opcode0)
6178 return SDValue();
6179
6180 // We could only need one range check, if the fptosi could never produce
6181 // the upper value.
6182 if (N0.getOpcode() == ISD::FP_TO_SINT && Opcode0 == ISD::SMAX) {
6183 if (isNullOrNullSplat(N3)) {
6184 EVT IntVT = N0.getValueType().getScalarType();
6185 EVT FPVT = N0.getOperand(0).getValueType().getScalarType();
6186 if (FPVT.isSimple()) {
6187 Type *InputTy = FPVT.getTypeForEVT(*DAG.getContext());
6188 const fltSemantics &Semantics = InputTy->getFltSemantics();
6189 uint32_t MinBitWidth =
6190 APFloatBase::semanticsIntSizeInBits(Semantics, /*isSigned*/ true);
6191 if (IntVT.getSizeInBits() >= MinBitWidth) {
6192 Unsigned = true;
6193 BW = PowerOf2Ceil(MinBitWidth);
6194 return N0;
6195 }
6196 }
6197 }
6198 }
6199
6200 SDValue N00, N01, N02, N03;
6201 ISD::CondCode N0CC;
6202 switch (N0.getOpcode()) {
6203 case ISD::SMIN:
6204 case ISD::SMAX:
6205 N00 = N02 = N0.getOperand(0);
6206 N01 = N03 = N0.getOperand(1);
6207 N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
6208 break;
6209 case ISD::SELECT_CC:
6210 N00 = N0.getOperand(0);
6211 N01 = N0.getOperand(1);
6212 N02 = N0.getOperand(2);
6213 N03 = N0.getOperand(3);
6214 N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
6215 break;
6216 case ISD::SELECT:
6217 case ISD::VSELECT:
6218 if (N0.getOperand(0).getOpcode() != ISD::SETCC)
6219 return SDValue();
6220 N00 = N0.getOperand(0).getOperand(0);
6221 N01 = N0.getOperand(0).getOperand(1);
6222 N02 = N0.getOperand(1);
6223 N03 = N0.getOperand(2);
6224 N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
6225 break;
6226 default:
6227 return SDValue();
6228 }
6229
6230 unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
6231 if (!Opcode1 || Opcode0 == Opcode1)
6232 return SDValue();
6233
6234 ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
6235 ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
6236 if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
6237 return SDValue();
6238
6239 const APInt &MinC = MinCOp->getAPIntValue();
6240 const APInt &MaxC = MaxCOp->getAPIntValue();
6241 APInt MinCPlus1 = MinC + 1;
6242 if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
6243 BW = MinCPlus1.exactLogBase2() + 1;
6244 Unsigned = false;
6245 return N02;
6246 }
6247
6248 if (MaxC == 0 && MinC != 0 && MinCPlus1.isPowerOf2()) {
6249 BW = MinCPlus1.exactLogBase2();
6250 Unsigned = true;
6251 return N02;
6252 }
6253
6254 return SDValue();
6255}
6256
6258 SDValue N3, ISD::CondCode CC,
6259 SelectionDAG &DAG) {
6260 unsigned BW;
6261 bool Unsigned;
6262 SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned, DAG);
6263 if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
6264 return SDValue();
6265 EVT FPVT = Fp.getOperand(0).getValueType();
6266 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6267 EVT::getIntegerVT(*DAG.getContext(), BW));
6268 unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
6269 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
6270 return SDValue();
6271 SDLoc DL(Fp);
6272 SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
6273 DAG.getValueType(NewVT.getScalarType()));
6274 return DAG.getExtOrTrunc(!Unsigned, Sat, DL, N2->getValueType(0));
6275}
6276
6278 SDValue N3, ISD::CondCode CC,
6279 SelectionDAG &DAG) {
6280 // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
6281 // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
6282 // be truncated versions of the setcc (N0/N1).
6283 if ((N0 != N2 &&
6284 (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
6285 N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
6286 return SDValue();
6289 if (!N1C || !N3C)
6290 return SDValue();
6291 const APInt &C1 = N1C->getAPIntValue();
6292 const APInt &C3 = N3C->getAPIntValue();
6293 if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
6294 C1 != C3.zext(C1.getBitWidth()))
6295 return SDValue();
6296
6297 unsigned BW = (C1 + 1).exactLogBase2();
6298 EVT FPVT = N0.getOperand(0).getValueType();
6299 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6300 EVT::getIntegerVT(*DAG.getContext(), BW));
6302 FPVT, NewVT))
6303 return SDValue();
6304
6305 SDValue Sat =
6306 DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
6307 DAG.getValueType(NewVT.getScalarType()));
6308 return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
6309}
6310
6311SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
6312 SDValue N0 = N->getOperand(0);
6313 SDValue N1 = N->getOperand(1);
6314 EVT VT = N0.getValueType();
6315 unsigned Opcode = N->getOpcode();
6316 SDLoc DL(N);
6317
6318 // fold operation with constant operands.
6319 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
6320 return C;
6321
6322 // If the operands are the same, this is a no-op.
6323 if (N0 == N1)
6324 return N0;
6325
6326 // canonicalize constant to RHS
6329 return DAG.getNode(Opcode, DL, VT, N1, N0);
6330
6331 // fold vector ops
6332 if (VT.isVector())
6333 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
6334 return FoldedVOp;
6335
6336 // reassociate minmax
6337 if (SDValue RMINMAX = reassociateOps(Opcode, DL, N0, N1, N->getFlags()))
6338 return RMINMAX;
6339
6340 // Fold sign-extension masks using arithmetic shift:
6341 // smax(X, -1) -> or(X, ashr(X, BW-1))
6342 // smin(X, 0) -> and(X, ashr(X, BW-1))
6343 // ashr(X, BW-1) sign-extends the sign bit: 0 for X>=0, -1 for X<0.
6344 // OR with X yields X (non-negative) or -1 (negative) = smax(X,-1).
6345 // AND with X yields 0 (non-negative) or X (negative) = smin(X, 0).
6346 // Both reduce to two instructions vs. a compare+cmov on x86-64.
6347 // Only fold when the target has no native SMAX/SMIN instruction for this
6348 // type (isOperationExpand), the type is legal (not needing splitting),
6349 // the operand is not a min/max chain (preserving target combine patterns
6350 // that fold smax(smin(x,C),D) into a single saturation instruction), and
6351 // for smax(X,-1) the operand is not a sign extension (doubling its use
6352 // count can cause the target to lower the extension less efficiently).
6353 APInt C;
6354 if (TLI.isTypeLegal(VT) &&
6356 sd_match(N1, m_ConstInt(C))) {
6357 if (Opcode == ISD::SMAX && TLI.isOperationExpand(ISD::SMAX, VT) &&
6358 N0.getOpcode() != ISD::SMIN && N0.getOpcode() != ISD::SIGN_EXTEND &&
6359 C.isAllOnes()) {
6360 SDValue ShiftAmt =
6362 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6363 return DAG.getNode(ISD::OR, DL, VT, N0, Shift);
6364 }
6365 if (Opcode == ISD::SMIN && TLI.isOperationExpand(ISD::SMIN, VT) &&
6366 N0.getOpcode() != ISD::SMAX && C.isZero()) {
6367 SDValue ShiftAmt =
6369 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6370 return DAG.getNode(ISD::AND, DL, VT, N0, Shift);
6371 }
6372 }
6373
6374 // If both operands are known to have the same sign (both non-negative or both
6375 // negative), flip between UMIN/UMAX and SMIN/SMAX.
6376 // Only do this if:
6377 // 1. The current op isn't legal and the flipped is.
6378 // 2. The saturation pattern is broken by canonicalization in InstCombine.
6379 bool IsOpIllegal = !TLI.isOperationLegal(Opcode, VT);
6380 bool IsSatBroken = Opcode == ISD::UMIN && N0.getOpcode() == ISD::SMAX;
6381
6382 if (IsSatBroken || IsOpIllegal) {
6383 auto HasKnownSameSign = [&](SDValue A, SDValue B) {
6384 if (A.isUndef() || B.isUndef())
6385 return true;
6386
6387 KnownBits KA = DAG.computeKnownBits(A);
6388 if (!KA.isNonNegative() && !KA.isNegative())
6389 return false;
6390
6391 KnownBits KB = DAG.computeKnownBits(B);
6392 if (KA.isNonNegative())
6393 return KB.isNonNegative();
6394 return KB.isNegative();
6395 };
6396
6397 if (HasKnownSameSign(N0, N1)) {
6398 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
6399 if ((IsSatBroken && IsOpIllegal) || TLI.isOperationLegal(AltOpcode, VT))
6400 return DAG.getNode(AltOpcode, DL, VT, N0, N1);
6401 }
6402 }
6403
6404 if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
6406 N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
6407 return S;
6408 if (Opcode == ISD::UMIN)
6409 if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
6410 return S;
6411
6412 // Fold min/max(vecreduce(x), vecreduce(y)) -> vecreduce(min/max(x, y))
6413 auto ReductionOpcode = [](unsigned Opcode) {
6414 switch (Opcode) {
6415 case ISD::SMIN:
6416 return ISD::VECREDUCE_SMIN;
6417 case ISD::SMAX:
6418 return ISD::VECREDUCE_SMAX;
6419 case ISD::UMIN:
6420 return ISD::VECREDUCE_UMIN;
6421 case ISD::UMAX:
6422 return ISD::VECREDUCE_UMAX;
6423 default:
6424 llvm_unreachable("Unexpected opcode");
6425 }
6426 };
6427 if (SDValue SD = reassociateReduction(ReductionOpcode(Opcode), Opcode,
6428 SDLoc(N), VT, N0, N1))
6429 return SD;
6430
6431 // Fold operation with vscale operands.
6432 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
6433 uint64_t C0 = N0->getConstantOperandVal(0);
6434 uint64_t C1 = N1->getConstantOperandVal(0);
6435 if (Opcode == ISD::UMAX)
6436 return C0 > C1 ? N0 : N1;
6437 else if (Opcode == ISD::UMIN)
6438 return C0 > C1 ? N1 : N0;
6439 }
6440
6441 // If we know the range of vscale, see if we can fold it given a constant.
6442 if (N0.getOpcode() == ISD::VSCALE) {
6443 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
6444 bool ForSigned = (Opcode == ISD::SMAX || Opcode == ISD::SMIN);
6445 ConstantRange Range = DAG.computeConstantRange(N0, ForSigned);
6446
6447 const APInt &C1V = C1->getAPIntValue();
6448 if ((Opcode == ISD::UMAX && Range.getUnsignedMax().ule(C1V)) ||
6449 (Opcode == ISD::UMIN && Range.getUnsignedMin().uge(C1V)) ||
6450 (Opcode == ISD::SMAX && Range.getSignedMax().sle(C1V)) ||
6451 (Opcode == ISD::SMIN && Range.getSignedMin().sge(C1V))) {
6452 return N1;
6453 }
6454 }
6455 }
6456
6457 // Simplify the operands using demanded-bits information.
6459 return SDValue(N, 0);
6460
6461 return SDValue();
6462}
6463
6464/// If this is a bitwise logic instruction and both operands have the same
6465/// opcode, try to sink the other opcode after the logic instruction.
6466SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
6467 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
6468 EVT VT = N0.getValueType();
6469 unsigned LogicOpcode = N->getOpcode();
6470 unsigned HandOpcode = N0.getOpcode();
6471 assert(ISD::isBitwiseLogicOp(LogicOpcode) && "Expected logic opcode");
6472 assert(HandOpcode == N1.getOpcode() && "Bad input!");
6473
6474 // Bail early if none of these transforms apply.
6475 if (N0.getNumOperands() == 0)
6476 return SDValue();
6477
6478 // FIXME: We should check number of uses of the operands to not increase
6479 // the instruction count for all transforms.
6480
6481 // Handle size-changing casts (or sign_extend_inreg).
6482 SDValue X = N0.getOperand(0);
6483 SDValue Y = N1.getOperand(0);
6484 EVT XVT = X.getValueType();
6485 SDLoc DL(N);
6486 if (ISD::isExtOpcode(HandOpcode) || ISD::isExtVecInRegOpcode(HandOpcode) ||
6487 (HandOpcode == ISD::SIGN_EXTEND_INREG &&
6488 N0.getOperand(1) == N1.getOperand(1))) {
6489 // If both operands have other uses, this transform would create extra
6490 // instructions without eliminating anything.
6491 if (!N0.hasOneUse() && !N1.hasOneUse())
6492 return SDValue();
6493 // We need matching integer source types.
6494 if (XVT != Y.getValueType())
6495 return SDValue();
6496 // Don't create an illegal op during or after legalization. Don't ever
6497 // create an unsupported vector op.
6498 if ((VT.isVector() || LegalOperations) &&
6499 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
6500 return SDValue();
6501 // Avoid infinite looping with PromoteIntBinOp.
6502 // TODO: Should we apply desirable/legal constraints to all opcodes?
6503 if ((HandOpcode == ISD::ANY_EXTEND ||
6504 HandOpcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
6505 LegalTypes && !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
6506 return SDValue();
6507 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
6508 SDNodeFlags LogicFlags;
6509 LogicFlags.setDisjoint(N->getFlags().hasDisjoint() &&
6510 ISD::isExtOpcode(HandOpcode));
6511 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y, LogicFlags);
6512 if (HandOpcode == ISD::SIGN_EXTEND_INREG)
6513 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6514 return DAG.getNode(HandOpcode, DL, VT, Logic);
6515 }
6516
6517 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
6518 if (HandOpcode == ISD::TRUNCATE) {
6519 // If both operands have other uses, this transform would create extra
6520 // instructions without eliminating anything.
6521 if (!N0.hasOneUse() && !N1.hasOneUse())
6522 return SDValue();
6523 // We need matching source types.
6524 if (XVT != Y.getValueType())
6525 return SDValue();
6526 // Don't create an illegal op during or after legalization.
6527 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
6528 return SDValue();
6529 // Be extra careful sinking truncate. If it's free, there's no benefit in
6530 // widening a binop. Also, don't create a logic op on an illegal type.
6531 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
6532 return SDValue();
6533 if (!TLI.isTypeLegal(XVT))
6534 return SDValue();
6535 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6536 return DAG.getNode(HandOpcode, DL, VT, Logic);
6537 }
6538
6539 // For binops SHL/SRL/SRA/AND:
6540 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
6541 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
6542 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
6543 N0.getOperand(1) == N1.getOperand(1)) {
6544 // If either operand has other uses, this transform is not an improvement.
6545 if (!N0.hasOneUse() || !N1.hasOneUse())
6546 return SDValue();
6547 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6548 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6549 }
6550
6551 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
6552 if (HandOpcode == ISD::BSWAP) {
6553 // If either operand has other uses, this transform is not an improvement.
6554 if (!N0.hasOneUse() || !N1.hasOneUse())
6555 return SDValue();
6556 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6557 return DAG.getNode(HandOpcode, DL, VT, Logic);
6558 }
6559
6560 // For funnel shifts FSHL/FSHR:
6561 // logic_op (OP x, x1, s), (OP y, y1, s) -->
6562 // --> OP (logic_op x, y), (logic_op, x1, y1), s
6563 if ((HandOpcode == ISD::FSHL || HandOpcode == ISD::FSHR) &&
6564 N0.getOperand(2) == N1.getOperand(2)) {
6565 if (!N0.hasOneUse() || !N1.hasOneUse())
6566 return SDValue();
6567 SDValue X1 = N0.getOperand(1);
6568 SDValue Y1 = N1.getOperand(1);
6569 SDValue S = N0.getOperand(2);
6570 SDValue Logic0 = DAG.getNode(LogicOpcode, DL, VT, X, Y);
6571 SDValue Logic1 = DAG.getNode(LogicOpcode, DL, VT, X1, Y1);
6572 return DAG.getNode(HandOpcode, DL, VT, Logic0, Logic1, S);
6573 }
6574
6575 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
6576 // Only perform this optimization up until type legalization, before
6577 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
6578 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
6579 // we don't want to undo this promotion.
6580 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
6581 // on scalars.
6582 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
6583 Level <= AfterLegalizeTypes) {
6584 // Input types must be integer and the same.
6585 if (XVT.isInteger() && XVT == Y.getValueType() &&
6586 !(VT.isVector() && TLI.isTypeLegal(VT) &&
6587 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
6588 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6589 return DAG.getNode(HandOpcode, DL, VT, Logic);
6590 }
6591 }
6592
6593 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
6594 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
6595 // If both shuffles use the same mask, and both shuffle within a single
6596 // vector, then it is worthwhile to move the swizzle after the operation.
6597 // The type-legalizer generates this pattern when loading illegal
6598 // vector types from memory. In many cases this allows additional shuffle
6599 // optimizations.
6600 // There are other cases where moving the shuffle after the xor/and/or
6601 // is profitable even if shuffles don't perform a swizzle.
6602 // If both shuffles use the same mask, and both shuffles have the same first
6603 // or second operand, then it might still be profitable to move the shuffle
6604 // after the xor/and/or operation.
6605 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
6606 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
6607 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
6608 assert(X.getValueType() == Y.getValueType() &&
6609 "Inputs to shuffles are not the same type");
6610
6611 // Check that both shuffles use the same mask. The masks are known to be of
6612 // the same length because the result vector type is the same.
6613 // Check also that shuffles have only one use to avoid introducing extra
6614 // instructions.
6615 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
6616 !SVN0->getMask().equals(SVN1->getMask()))
6617 return SDValue();
6618
6619 // Don't try to fold this node if it requires introducing a
6620 // build vector of all zeros that might be illegal at this stage.
6621 SDValue ShOp = N0.getOperand(1);
6622 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6623 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6624
6625 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
6626 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
6627 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
6628 N0.getOperand(0), N1.getOperand(0));
6629 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
6630 }
6631
6632 // Don't try to fold this node if it requires introducing a
6633 // build vector of all zeros that might be illegal at this stage.
6634 ShOp = N0.getOperand(0);
6635 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6636 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6637
6638 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
6639 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
6640 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
6641 N1.getOperand(1));
6642 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
6643 }
6644 }
6645
6646 return SDValue();
6647}
6648
6649/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
6650SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
6651 const SDLoc &DL) {
6652 SDValue LL, LR, RL, RR, N0CC, N1CC;
6653 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
6654 !isSetCCEquivalent(N1, RL, RR, N1CC))
6655 return SDValue();
6656
6657 assert(N0.getValueType() == N1.getValueType() &&
6658 "Unexpected operand types for bitwise logic op");
6659 assert(LL.getValueType() == LR.getValueType() &&
6660 RL.getValueType() == RR.getValueType() &&
6661 "Unexpected operand types for setcc");
6662
6663 // If we're here post-legalization or the logic op type is not i1, the logic
6664 // op type must match a setcc result type. Also, all folds require new
6665 // operations on the left and right operands, so those types must match.
6666 EVT VT = N0.getValueType();
6667 EVT OpVT = LL.getValueType();
6668 if (LegalOperations || VT.getScalarType() != MVT::i1)
6669 if (VT != getSetCCResultType(OpVT))
6670 return SDValue();
6671 if (OpVT != RL.getValueType())
6672 return SDValue();
6673
6674 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
6675 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
6676 bool IsInteger = OpVT.isInteger();
6677 if (LR == RR && CC0 == CC1 && IsInteger) {
6678 bool IsZero = isNullOrNullSplat(LR);
6679 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
6680
6681 // All bits clear?
6682 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
6683 // All sign bits clear?
6684 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
6685 // Any bits set?
6686 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
6687 // Any sign bits set?
6688 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
6689
6690 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
6691 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
6692 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
6693 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
6694 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
6695 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
6696 AddToWorklist(Or.getNode());
6697 return DAG.getSetCC(DL, VT, Or, LR, CC1);
6698 }
6699
6700 // All bits set?
6701 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
6702 // All sign bits set?
6703 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
6704 // Any bits clear?
6705 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
6706 // Any sign bits clear?
6707 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
6708
6709 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
6710 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
6711 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
6712 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
6713 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
6714 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
6715 AddToWorklist(And.getNode());
6716 return DAG.getSetCC(DL, VT, And, LR, CC1);
6717 }
6718 }
6719
6720 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
6721 // (or (seteq X, 0), (seteq X, -1)) --> (setult (add X, 1), 2)
6722 if (LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && IsInteger &&
6723 ((IsAnd && CC0 == ISD::SETNE) || (!IsAnd && CC0 == ISD::SETEQ)) &&
6724 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
6725 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
6726 SDValue One = DAG.getConstant(1, DL, OpVT);
6727 SDValue Two = DAG.getConstant(2, DL, OpVT);
6728 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
6729 AddToWorklist(Add.getNode());
6730 return DAG.getSetCC(DL, VT, Add, Two, IsAnd ? ISD::SETUGE : ISD::SETULT);
6731 }
6732
6733 // Try more general transforms if the predicates match and the only user of
6734 // the compares is the 'and' or 'or'.
6735 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
6736 N0.hasOneUse() && N1.hasOneUse()) {
6737 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
6738 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
6739 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
6740 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
6741 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
6742 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
6743 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6744 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
6745 }
6746
6747 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
6748 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
6749 // Match a shared variable operand and 2 non-opaque constant operands.
6750 auto MatchDiffPow2 = [&](ConstantSDNode *C0, ConstantSDNode *C1) {
6751 // The difference of the constants must be a single bit.
6752 const APInt &CMax =
6753 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
6754 const APInt &CMin =
6755 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
6756 return !C0->isOpaque() && !C1->isOpaque() && (CMax - CMin).isPowerOf2();
6757 };
6758 if (LL == RL && ISD::matchBinaryPredicate(LR, RR, MatchDiffPow2)) {
6759 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
6760 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
6761 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
6762 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
6763 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
6764 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
6765 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
6766 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
6767 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6768 return DAG.getSetCC(DL, VT, And, Zero, CC0);
6769 }
6770 }
6771 }
6772
6773 // Canonicalize equivalent operands to LL == RL.
6774 if (LL == RR && LR == RL) {
6776 std::swap(RL, RR);
6777 }
6778
6779 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6780 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6781 if (LL == RL && LR == RR) {
6782 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
6783 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
6784 if (NewCC != ISD::SETCC_INVALID &&
6785 (!LegalOperations ||
6786 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
6787 TLI.isOperationLegal(ISD::SETCC, OpVT))))
6788 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
6789 }
6790
6791 return SDValue();
6792}
6793
6794static bool arebothOperandsNotSNan(SDValue Operand1, SDValue Operand2,
6795 SelectionDAG &DAG) {
6796 return DAG.isKnownNeverSNaN(Operand2) && DAG.isKnownNeverSNaN(Operand1);
6797}
6798
6799static bool arebothOperandsNotNan(SDValue Operand1, SDValue Operand2,
6800 SelectionDAG &DAG) {
6801 return DAG.isKnownNeverNaN(Operand2) && DAG.isKnownNeverNaN(Operand1);
6802}
6803
6804/// Returns an appropriate FP min/max opcode for clamping operations.
6805static unsigned getMinMaxOpcodeForClamp(bool IsMin, SDValue Operand1,
6806 SDValue Operand2, SelectionDAG &DAG,
6807 const TargetLowering &TLI) {
6808 EVT VT = Operand1.getValueType();
6809 unsigned IEEEOp = IsMin ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6810 if (TLI.isOperationLegalOrCustom(IEEEOp, VT) &&
6811 arebothOperandsNotNan(Operand1, Operand2, DAG))
6812 return IEEEOp;
6813 unsigned PreferredOp = IsMin ? ISD::FMINNUM : ISD::FMAXNUM;
6814 if (TLI.isOperationLegalOrCustom(PreferredOp, VT))
6815 return PreferredOp;
6816 return ISD::DELETED_NODE;
6817}
6818
6819// FIXME: use FMINIMUMNUM if possible, such as for RISC-V.
6821 SDValue Operand1, SDValue Operand2, bool SetCCNoNaNs, ISD::CondCode CC,
6822 unsigned OrAndOpcode, SelectionDAG &DAG, bool isFMAXNUMFMINNUM_IEEE,
6823 bool isFMAXNUMFMINNUM) {
6824 // The optimization cannot be applied for all the predicates because
6825 // of the way FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle
6826 // NaNs. For FMINNUM_IEEE/FMAXNUM_IEEE, the optimization cannot be
6827 // applied at all if one of the operands is a signaling NaN.
6828
6829 // It is safe to use FMINNUM_IEEE/FMAXNUM_IEEE if all the operands
6830 // are non NaN values.
6831 if (((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::OR)) ||
6832 ((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::AND))) {
6833 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6834 isFMAXNUMFMINNUM_IEEE
6837 }
6838
6839 if (((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::OR)) ||
6840 ((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::AND))) {
6841 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6842 isFMAXNUMFMINNUM_IEEE
6845 }
6846
6847 // Both FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle quiet
6848 // NaNs in the same way. But, FMINNUM/FMAXNUM and FMINNUM_IEEE/
6849 // FMAXNUM_IEEE handle signaling NaNs differently. If we cannot prove
6850 // that there are not any sNaNs, then the optimization is not valid
6851 // for FMINNUM_IEEE/FMAXNUM_IEEE. In the presence of sNaNs, we apply
6852 // the optimization using FMINNUM/FMAXNUM for the following cases. If
6853 // we can prove that we do not have any sNaNs, then we can do the
6854 // optimization using FMINNUM_IEEE/FMAXNUM_IEEE for the following
6855 // cases.
6856 if (((CC == ISD::SETOLT || CC == ISD::SETOLE) && (OrAndOpcode == ISD::OR)) ||
6857 ((CC == ISD::SETUGT || CC == ISD::SETUGE) && (OrAndOpcode == ISD::AND))) {
6858 return isFMAXNUMFMINNUM ? ISD::FMINNUM
6859 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6860 isFMAXNUMFMINNUM_IEEE
6863 }
6864
6865 if (((CC == ISD::SETOGT || CC == ISD::SETOGE) && (OrAndOpcode == ISD::OR)) ||
6866 ((CC == ISD::SETULT || CC == ISD::SETULE) && (OrAndOpcode == ISD::AND))) {
6867 return isFMAXNUMFMINNUM ? ISD::FMAXNUM
6868 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6869 isFMAXNUMFMINNUM_IEEE
6872 }
6873
6874 return ISD::DELETED_NODE;
6875}
6876
6879 assert(
6880 (LogicOp->getOpcode() == ISD::AND || LogicOp->getOpcode() == ISD::OR) &&
6881 "Invalid Op to combine SETCC with");
6882
6883 // TODO: Search past casts/truncates.
6884 SDValue LHS = LogicOp->getOperand(0);
6885 SDValue RHS = LogicOp->getOperand(1);
6886 if (LHS->getOpcode() != ISD::SETCC || RHS->getOpcode() != ISD::SETCC ||
6887 !LHS->hasOneUse() || !RHS->hasOneUse())
6888 return SDValue();
6889
6890 SDNodeFlags LHSSetCCFlags = LHS->getFlags();
6891 SDNodeFlags RHSSetCCFlags = RHS->getFlags();
6892 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6894 LogicOp, LHS.getNode(), RHS.getNode());
6895
6896 SDValue LHS0 = LHS->getOperand(0);
6897 SDValue RHS0 = RHS->getOperand(0);
6898 SDValue LHS1 = LHS->getOperand(1);
6899 SDValue RHS1 = RHS->getOperand(1);
6900 // TODO: We don't actually need a splat here, for vectors we just need the
6901 // invariants to hold for each element.
6902 auto *LHS1C = isConstOrConstSplat(LHS1);
6903 auto *RHS1C = isConstOrConstSplat(RHS1);
6904 ISD::CondCode CCL = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6905 ISD::CondCode CCR = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6906 EVT VT = LogicOp->getValueType(0);
6907 EVT OpVT = LHS0.getValueType();
6908 SDLoc DL(LogicOp);
6909
6910 // Check if the operands of an and/or operation are comparisons and if they
6911 // compare against the same value. Replace the and/or-cmp-cmp sequence with
6912 // min/max cmp sequence. If LHS1 is equal to RHS1, then the or-cmp-cmp
6913 // sequence will be replaced with min-cmp sequence:
6914 // (LHS0 < LHS1) | (RHS0 < RHS1) -> min(LHS0, RHS0) < LHS1
6915 // and and-cmp-cmp will be replaced with max-cmp sequence:
6916 // (LHS0 < LHS1) & (RHS0 < RHS1) -> max(LHS0, RHS0) < LHS1
6917 // The optimization does not work for `==` or `!=` .
6918 // The two comparisons should have either the same predicate or the
6919 // predicate of one of the comparisons is the opposite of the other one.
6920 bool isFMAXNUMFMINNUM_IEEE = TLI.isOperationLegal(ISD::FMAXNUM_IEEE, OpVT) &&
6922 bool isFMAXNUMFMINNUM = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, OpVT) &&
6924 if (((OpVT.isInteger() && TLI.isOperationLegal(ISD::UMAX, OpVT) &&
6925 TLI.isOperationLegal(ISD::SMAX, OpVT) &&
6926 TLI.isOperationLegal(ISD::UMIN, OpVT) &&
6927 TLI.isOperationLegal(ISD::SMIN, OpVT)) ||
6928 (OpVT.isFloatingPoint() &&
6929 (isFMAXNUMFMINNUM_IEEE || isFMAXNUMFMINNUM))) &&
6931 CCL != ISD::SETFALSE && CCL != ISD::SETO && CCL != ISD::SETUO &&
6932 CCL != ISD::SETTRUE &&
6933 (CCL == CCR || CCL == ISD::getSetCCSwappedOperands(CCR))) {
6934
6935 SDValue CommonValue, Operand1, Operand2;
6937 if (CCL == CCR) {
6938 if (LHS0 == RHS0) {
6939 CommonValue = LHS0;
6940 Operand1 = LHS1;
6941 Operand2 = RHS1;
6943 } else if (LHS1 == RHS1) {
6944 CommonValue = LHS1;
6945 Operand1 = LHS0;
6946 Operand2 = RHS0;
6947 CC = CCL;
6948 }
6949 } else {
6950 assert(CCL == ISD::getSetCCSwappedOperands(CCR) && "Unexpected CC");
6951 if (LHS0 == RHS1) {
6952 CommonValue = LHS0;
6953 Operand1 = LHS1;
6954 Operand2 = RHS0;
6955 CC = CCR;
6956 } else if (RHS0 == LHS1) {
6957 CommonValue = LHS1;
6958 Operand1 = LHS0;
6959 Operand2 = RHS1;
6960 CC = CCL;
6961 }
6962 }
6963
6964 // Don't do this transform for sign bit tests. Let foldLogicOfSetCCs
6965 // handle it using OR/AND.
6966 if (CC == ISD::SETLT && isNullOrNullSplat(CommonValue))
6967 CC = ISD::SETCC_INVALID;
6968 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CommonValue))
6969 CC = ISD::SETCC_INVALID;
6970
6971 if (CC != ISD::SETCC_INVALID) {
6972 unsigned NewOpcode = ISD::DELETED_NODE;
6973 bool IsSigned = isSignedIntSetCC(CC);
6974 if (OpVT.isInteger()) {
6975 bool IsLess = (CC == ISD::SETLE || CC == ISD::SETULE ||
6976 CC == ISD::SETLT || CC == ISD::SETULT);
6977 bool IsOr = (LogicOp->getOpcode() == ISD::OR);
6978 if (IsLess == IsOr)
6979 NewOpcode = IsSigned ? ISD::SMIN : ISD::UMIN;
6980 else
6981 NewOpcode = IsSigned ? ISD::SMAX : ISD::UMAX;
6982 } else if (OpVT.isFloatingPoint())
6984 Operand1, Operand2,
6985 LHSSetCCFlags.hasNoNaNs() && RHSSetCCFlags.hasNoNaNs(), CC,
6986 LogicOp->getOpcode(), DAG, isFMAXNUMFMINNUM_IEEE, isFMAXNUMFMINNUM);
6987
6988 if (NewOpcode != ISD::DELETED_NODE) {
6989 // Propagate fast-math flags from setcc.
6990 SDNodeFlags Flags = LHS->getFlags() & RHS->getFlags();
6991 SDValue MinMaxValue =
6992 DAG.getNode(NewOpcode, DL, OpVT, Operand1, Operand2, Flags);
6993 return DAG.getSetCC(DL, VT, MinMaxValue, CommonValue, CC, /*Chain=*/{},
6994 /*IsSignaling=*/false, Flags);
6995 }
6996 }
6997 }
6998
6999 if (LHS0 == LHS1 && RHS0 == RHS1 && CCL == CCR &&
7000 LHS0.getValueType() == RHS0.getValueType() &&
7001 ((LogicOp->getOpcode() == ISD::AND && CCL == ISD::SETO) ||
7002 (LogicOp->getOpcode() == ISD::OR && CCL == ISD::SETUO)))
7003 return DAG.getSetCC(DL, VT, LHS0, RHS0, CCL);
7004
7005 if (TargetPreference == AndOrSETCCFoldKind::None)
7006 return SDValue();
7007
7008 if (CCL == CCR &&
7009 CCL == (LogicOp->getOpcode() == ISD::AND ? ISD::SETNE : ISD::SETEQ) &&
7010 LHS0 == RHS0 && LHS1C && RHS1C && OpVT.isInteger()) {
7011 const APInt &APLhs = LHS1C->getAPIntValue();
7012 const APInt &APRhs = RHS1C->getAPIntValue();
7013
7014 // Preference is to use ISD::ABS or we already have an ISD::ABS (in which
7015 // case this is just a compare).
7016 if (APLhs == (-APRhs) &&
7017 ((TargetPreference & AndOrSETCCFoldKind::ABS) ||
7018 DAG.doesNodeExist(ISD::ABS, DAG.getVTList(OpVT), {LHS0}))) {
7019 const APInt &C = APLhs.isNegative() ? APRhs : APLhs;
7020 // (icmp eq A, C) | (icmp eq A, -C)
7021 // -> (icmp eq Abs(A), C)
7022 // (icmp ne A, C) & (icmp ne A, -C)
7023 // -> (icmp ne Abs(A), C)
7024 SDValue AbsOp = DAG.getNode(ISD::ABS, DL, OpVT, LHS0);
7025 return DAG.getNode(ISD::SETCC, DL, VT, AbsOp,
7026 DAG.getConstant(C, DL, OpVT), LHS.getOperand(2));
7027 } else if (TargetPreference &
7029
7030 // AndOrSETCCFoldKind::AddAnd:
7031 // A == C0 | A == C1
7032 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7033 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) == 0
7034 // A != C0 & A != C1
7035 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7036 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) != 0
7037
7038 // AndOrSETCCFoldKind::NotAnd:
7039 // A == C0 | A == C1
7040 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7041 // -> ~A & smin(C0, C1) == 0
7042 // A != C0 & A != C1
7043 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7044 // -> ~A & smin(C0, C1) != 0
7045
7046 const APInt &MaxC = APIntOps::smax(APRhs, APLhs);
7047 const APInt &MinC = APIntOps::smin(APRhs, APLhs);
7048 APInt Dif = MaxC - MinC;
7049 if (!Dif.isZero() && Dif.isPowerOf2()) {
7050 if (MaxC.isAllOnes() &&
7051 (TargetPreference & AndOrSETCCFoldKind::NotAnd)) {
7052 SDValue NotOp = DAG.getNOT(DL, LHS0, OpVT);
7053 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, NotOp,
7054 DAG.getConstant(MinC, DL, OpVT));
7055 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7056 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7057 } else if (TargetPreference & AndOrSETCCFoldKind::AddAnd) {
7058
7059 SDValue AddOp = DAG.getNode(ISD::ADD, DL, OpVT, LHS0,
7060 DAG.getConstant(-MinC, DL, OpVT));
7061 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, AddOp,
7062 DAG.getConstant(~Dif, DL, OpVT));
7063 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7064 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7065 }
7066 }
7067 }
7068 }
7069
7070 return SDValue();
7071}
7072
7073// Combine `(select c, (X & 1), 0)` -> `(and (zext c), X)`.
7074// We canonicalize to the `select` form in the middle end, but the `and` form
7075// gets better codegen and all tested targets (arm, x86, riscv)
7077 const SDLoc &DL, SelectionDAG &DAG) {
7078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7079 if (!isNullConstant(F))
7080 return SDValue();
7081
7082 EVT CondVT = Cond.getValueType();
7083 if (TLI.getBooleanContents(CondVT) !=
7085 return SDValue();
7086
7087 if (T.getOpcode() != ISD::AND)
7088 return SDValue();
7089
7090 if (!isOneConstant(T.getOperand(1)))
7091 return SDValue();
7092
7093 EVT OpVT = T.getValueType();
7094
7095 SDValue CondMask =
7096 OpVT == CondVT ? Cond : DAG.getBoolExtOrTrunc(Cond, DL, OpVT, CondVT);
7097 return DAG.getNode(ISD::AND, DL, OpVT, CondMask, T.getOperand(0));
7098}
7099
7100/// This contains all DAGCombine rules which reduce two values combined by
7101/// an And operation to a single value. This makes them reusable in the context
7102/// of visitSELECT(). Rules involving constants are not included as
7103/// visitSELECT() already handles those cases.
7104SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
7105 EVT VT = N1.getValueType();
7106 SDLoc DL(N);
7107
7108 // fold (and x, undef) -> 0
7109 if (N0.isUndef() || N1.isUndef())
7110 return DAG.getConstant(0, DL, VT);
7111
7112 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
7113 return V;
7114
7115 // Canonicalize:
7116 // and(x, add) -> and(add, x)
7117 if (N1.getOpcode() == ISD::ADD)
7118 std::swap(N0, N1);
7119
7120 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
7121 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
7122 VT.isScalarInteger() && VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
7123 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7124 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
7125 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
7126 // immediate for an add, but it is legal if its top c2 bits are set,
7127 // transform the ADD so the immediate doesn't need to be materialized
7128 // in a register.
7129 APInt ADDC = ADDI->getAPIntValue();
7130 APInt SRLC = SRLI->getAPIntValue();
7131 if (ADDC.getSignificantBits() <= 64 && SRLC.ult(VT.getSizeInBits()) &&
7132 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7134 SRLC.getZExtValue());
7135 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
7136 ADDC |= Mask;
7137 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7138 SDLoc DL0(N0);
7139 SDValue NewAdd =
7140 DAG.getNode(ISD::ADD, DL0, VT,
7141 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
7142 CombineTo(N0.getNode(), NewAdd);
7143 // Return N so it doesn't get rechecked!
7144 return SDValue(N, 0);
7145 }
7146 }
7147 }
7148 }
7149 }
7150 }
7151
7152 return SDValue();
7153}
7154
7155bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
7156 EVT LoadResultTy, EVT &ExtVT) {
7157 if (!AndC->getAPIntValue().isMask())
7158 return false;
7159
7160 unsigned ActiveBits = AndC->getAPIntValue().countr_one();
7161
7162 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7163 EVT LoadedVT = LoadN->getMemoryVT();
7164
7165 if (ExtVT == LoadedVT &&
7166 (!LegalOperations ||
7167 TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7168 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))) {
7169 // ZEXTLOAD will match without needing to change the size of the value being
7170 // loaded.
7171 return true;
7172 }
7173
7174 // Do not change the width of a volatile or atomic loads.
7175 if (!LoadN->isSimple())
7176 return false;
7177
7178 // Do not generate loads of non-round integer types since these can
7179 // be expensive (and would be wrong if the type is not byte sized).
7180 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
7181 return false;
7182
7183 if (LegalOperations &&
7184 !TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7185 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))
7186 return false;
7187
7188 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT, /*ByteOffset=*/0))
7189 return false;
7190
7191 return true;
7192}
7193
7194bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
7195 ISD::LoadExtType ExtType, EVT &MemVT,
7196 unsigned ShAmt) {
7197 if (!LDST)
7198 return false;
7199
7200 // Only allow byte offsets.
7201 if (ShAmt % 8)
7202 return false;
7203 const unsigned ByteShAmt = ShAmt / 8;
7204
7205 // Do not generate loads of non-round integer types since these can
7206 // be expensive (and would be wrong if the type is not byte sized).
7207 if (!MemVT.isRound())
7208 return false;
7209
7210 // Don't change the width of a volatile or atomic loads.
7211 if (!LDST->isSimple())
7212 return false;
7213
7214 EVT LdStMemVT = LDST->getMemoryVT();
7215
7216 // Bail out when changing the scalable property, since we can't be sure that
7217 // we're actually narrowing here.
7218 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
7219 return false;
7220
7221 // Verify that we are actually reducing a load width here.
7222 if (LdStMemVT.bitsLT(MemVT))
7223 return false;
7224
7225 // Ensure that this isn't going to produce an unsupported memory access.
7226 if (ShAmt) {
7227 const Align LDSTAlign = LDST->getAlign();
7228 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
7229 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7230 LDST->getAddressSpace(), NarrowAlign,
7231 LDST->getMemOperand()->getFlags()))
7232 return false;
7233 }
7234
7235 // It's not possible to generate a constant of extended or untyped type.
7236 EVT PtrType = LDST->getBasePtr().getValueType();
7237 if (PtrType == MVT::Untyped || PtrType.isExtended())
7238 return false;
7239
7240 if (isa<LoadSDNode>(LDST)) {
7241 LoadSDNode *Load = cast<LoadSDNode>(LDST);
7242 // Don't transform one with multiple uses, this would require adding a new
7243 // load.
7244 if (!SDValue(Load, 0).hasOneUse())
7245 return false;
7246
7247 if (LegalOperations &&
7248 !TLI.isLoadLegal(Load->getValueType(0), MemVT, Load->getAlign(),
7249 Load->getAddressSpace(), ExtType, false))
7250 return false;
7251
7252 // For the transform to be legal, the load must produce only two values
7253 // (the value loaded and the chain). Don't transform a pre-increment
7254 // load, for example, which produces an extra value. Otherwise the
7255 // transformation is not equivalent, and the downstream logic to replace
7256 // uses gets things wrong.
7257 if (Load->getNumValues() > 2)
7258 return false;
7259
7260 // If the load that we're shrinking is an extload and we're not just
7261 // discarding the extension we can't simply shrink the load. Bail.
7262 // TODO: It would be possible to merge the extensions in some cases.
7263 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
7264 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7265 return false;
7266
7267 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT, ByteShAmt))
7268 return false;
7269 } else {
7270 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
7271 StoreSDNode *Store = cast<StoreSDNode>(LDST);
7272 // Can't write outside the original store
7273 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7274 return false;
7275
7276 if (LegalOperations &&
7277 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT,
7278 Store->getAlign(), Store->getAddressSpace()))
7279 return false;
7280 }
7281 return true;
7282}
7283
7284bool DAGCombiner::SearchForAndLoads(SDNode *N,
7285 SmallVectorImpl<LoadSDNode*> &Loads,
7286 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
7287 ConstantSDNode *Mask,
7288 SDNode *&NodeToMask) {
7289 // Recursively search for the operands, looking for loads which can be
7290 // narrowed.
7291 for (SDValue Op : N->op_values()) {
7292 if (Op.getValueType().isVector())
7293 return false;
7294
7295 // Some constants may need fixing up later if they are too large.
7296 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7297 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
7298 "Expected bitwise logic operation");
7299 if (!C->getAPIntValue().isSubsetOf(Mask->getAPIntValue()))
7300 NodesWithConsts.insert(N);
7301 continue;
7302 }
7303
7304 if (!Op.hasOneUse())
7305 return false;
7306
7307 switch(Op.getOpcode()) {
7308 case ISD::LOAD: {
7309 auto *Load = cast<LoadSDNode>(Op);
7310 EVT ExtVT;
7311 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
7312 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
7313
7314 // ZEXTLOAD is already small enough.
7315 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
7316 ExtVT.bitsGE(Load->getMemoryVT()))
7317 continue;
7318
7319 // Use LE to convert equal sized loads to zext.
7320 if (ExtVT.bitsLE(Load->getMemoryVT()))
7321 Loads.push_back(Load);
7322
7323 continue;
7324 }
7325 return false;
7326 }
7327 case ISD::ZERO_EXTEND:
7328 case ISD::AssertZext: {
7329 unsigned ActiveBits = Mask->getAPIntValue().countr_one();
7330 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7331 EVT VT = Op.getOpcode() == ISD::AssertZext ?
7332 cast<VTSDNode>(Op.getOperand(1))->getVT() :
7333 Op.getOperand(0).getValueType();
7334
7335 // We can accept extending nodes if the mask is wider or an equal
7336 // width to the original type.
7337 if (ExtVT.bitsGE(VT))
7338 continue;
7339 break;
7340 }
7341 case ISD::OR:
7342 case ISD::XOR:
7343 case ISD::AND:
7344 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
7345 NodeToMask))
7346 return false;
7347 continue;
7348 }
7349
7350 // Allow one node which will masked along with any loads found.
7351 if (NodeToMask)
7352 return false;
7353
7354 // Also ensure that the node to be masked only produces one data result.
7355 NodeToMask = Op.getNode();
7356 if (NodeToMask->getNumValues() > 1) {
7357 bool HasValue = false;
7358 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
7359 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
7360 if (VT != MVT::Glue && VT != MVT::Other) {
7361 if (HasValue) {
7362 NodeToMask = nullptr;
7363 return false;
7364 }
7365 HasValue = true;
7366 }
7367 }
7368 assert(HasValue && "Node to be masked has no data result?");
7369 }
7370 }
7371 return true;
7372}
7373
7374bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
7375 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
7376 if (!Mask)
7377 return false;
7378
7379 if (!Mask->getAPIntValue().isMask())
7380 return false;
7381
7382 // No need to do anything if the and directly uses a load.
7383 if (isa<LoadSDNode>(N->getOperand(0)))
7384 return false;
7385
7387 SmallPtrSet<SDNode*, 2> NodesWithConsts;
7388 SDNode *FixupNode = nullptr;
7389 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
7390 if (Loads.empty())
7391 return false;
7392
7393 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
7394 SDValue MaskOp = N->getOperand(1);
7395
7396 // If it exists, fixup the single node we allow in the tree that needs
7397 // masking.
7398 if (FixupNode) {
7399 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
7400 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
7401 FixupNode->getValueType(0),
7402 SDValue(FixupNode, 0), MaskOp);
7403 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
7404 if (And.getOpcode() == ISD ::AND)
7405 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
7406 }
7407
7408 // Narrow any constants that need it.
7409 for (auto *LogicN : NodesWithConsts) {
7410 SDValue Op0 = LogicN->getOperand(0);
7411 SDValue Op1 = LogicN->getOperand(1);
7412
7413 // We only need to fix AND if both inputs are constants. And we only need
7414 // to fix one of the constants.
7415 if (LogicN->getOpcode() == ISD::AND &&
7417 continue;
7418
7419 if (isa<ConstantSDNode>(Op0) && LogicN->getOpcode() != ISD::AND)
7420 Op0 =
7421 DAG.getNode(ISD::AND, SDLoc(Op0), Op0.getValueType(), Op0, MaskOp);
7422
7423 if (isa<ConstantSDNode>(Op1))
7424 Op1 =
7425 DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), Op1, MaskOp);
7426
7427 if (isa<ConstantSDNode>(Op0) && !isa<ConstantSDNode>(Op1))
7428 std::swap(Op0, Op1);
7429
7430 DAG.UpdateNodeOperands(LogicN, Op0, Op1);
7431 }
7432
7433 // Create narrow loads.
7434 for (auto *Load : Loads) {
7435 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
7436 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
7437 SDValue(Load, 0), MaskOp);
7438 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
7439 if (And.getOpcode() == ISD ::AND)
7440 And = SDValue(
7441 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
7442 SDValue NewLoad = reduceLoadWidth(And.getNode());
7443 assert(NewLoad &&
7444 "Shouldn't be masking the load if it can't be narrowed");
7445 CombineTo(Load, NewLoad, NewLoad.getValue(1));
7446 }
7447 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
7448 return true;
7449 }
7450 return false;
7451}
7452
7453// Unfold
7454// x & (-1 'logical shift' y)
7455// To
7456// (x 'opposite logical shift' y) 'logical shift' y
7457// if it is better for performance.
7458SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
7459 assert(N->getOpcode() == ISD::AND);
7460
7461 SDValue N0 = N->getOperand(0);
7462 SDValue N1 = N->getOperand(1);
7463
7464 // Do we actually prefer shifts over mask?
7466 return SDValue();
7467
7468 // Try to match (-1 '[outer] logical shift' y)
7469 unsigned OuterShift;
7470 unsigned InnerShift; // The opposite direction to the OuterShift.
7471 SDValue Y; // Shift amount.
7472 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
7473 if (!M.hasOneUse())
7474 return false;
7475 OuterShift = M->getOpcode();
7476 if (OuterShift == ISD::SHL)
7477 InnerShift = ISD::SRL;
7478 else if (OuterShift == ISD::SRL)
7479 InnerShift = ISD::SHL;
7480 else
7481 return false;
7482 if (!isAllOnesConstant(M->getOperand(0)))
7483 return false;
7484 Y = M->getOperand(1);
7485 return true;
7486 };
7487
7488 SDValue X;
7489 if (matchMask(N1))
7490 X = N0;
7491 else if (matchMask(N0))
7492 X = N1;
7493 else
7494 return SDValue();
7495
7496 SDLoc DL(N);
7497 EVT VT = N->getValueType(0);
7498
7499 // tmp = x 'opposite logical shift' y
7500 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
7501 // ret = tmp 'logical shift' y
7502 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
7503
7504 return T1;
7505}
7506
7507/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
7508/// For a target with a bit test, this is expected to become test + set and save
7509/// at least 1 instruction.
7511 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
7512
7513 // Look through an optional extension.
7514 SDValue And0 = And->getOperand(0), And1 = And->getOperand(1);
7515 if (And0.getOpcode() == ISD::ANY_EXTEND && And0.hasOneUse())
7516 And0 = And0.getOperand(0);
7517 if (!isOneConstant(And1) || !And0.hasOneUse())
7518 return SDValue();
7519
7520 SDValue Src = And0;
7521
7522 // Attempt to find a 'not' op.
7523 // TODO: Should we favor test+set even without the 'not' op?
7524 bool FoundNot = false;
7525 if (isBitwiseNot(Src)) {
7526 FoundNot = true;
7527 Src = Src.getOperand(0);
7528
7529 // Look though an optional truncation. The source operand may not be the
7530 // same type as the original 'and', but that is ok because we are masking
7531 // off everything but the low bit.
7532 if (Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse())
7533 Src = Src.getOperand(0);
7534 }
7535
7536 // Match a shift-right by constant.
7537 if (Src.getOpcode() != ISD::SRL || !Src.hasOneUse())
7538 return SDValue();
7539
7540 // This is probably not worthwhile without a supported type.
7541 EVT SrcVT = Src.getValueType();
7542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7543 if (!TLI.isTypeLegal(SrcVT))
7544 return SDValue();
7545
7546 // We might have looked through casts that make this transform invalid.
7547 unsigned BitWidth = SrcVT.getScalarSizeInBits();
7548 SDValue ShiftAmt = Src.getOperand(1);
7549 auto *ShiftAmtC = dyn_cast<ConstantSDNode>(ShiftAmt);
7550 if (!ShiftAmtC || !ShiftAmtC->getAPIntValue().ult(BitWidth))
7551 return SDValue();
7552
7553 // Set source to shift source.
7554 Src = Src.getOperand(0);
7555
7556 // Try again to find a 'not' op.
7557 // TODO: Should we favor test+set even with two 'not' ops?
7558 if (!FoundNot) {
7559 if (!isBitwiseNot(Src))
7560 return SDValue();
7561 Src = Src.getOperand(0);
7562 }
7563
7564 if (!TLI.hasBitTest(Src, ShiftAmt))
7565 return SDValue();
7566
7567 // Turn this into a bit-test pattern using mask op + setcc:
7568 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
7569 // and (srl (not X), C)), 1 --> (and X, 1<<C) == 0
7570 SDLoc DL(And);
7571 SDValue X = DAG.getZExtOrTrunc(Src, DL, SrcVT);
7572 EVT CCVT =
7573 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7574 SDValue Mask = DAG.getConstant(
7575 APInt::getOneBitSet(BitWidth, ShiftAmtC->getZExtValue()), DL, SrcVT);
7576 SDValue NewAnd = DAG.getNode(ISD::AND, DL, SrcVT, X, Mask);
7577 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
7578 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
7579 return DAG.getZExtOrTrunc(Setcc, DL, And->getValueType(0));
7580}
7581
7582/// For targets that support usubsat, match a bit-hack form of that operation
7583/// that ends in 'and' and convert it.
7585 EVT VT = N->getValueType(0);
7586 unsigned BitWidth = VT.getScalarSizeInBits();
7587 APInt SignMask = APInt::getSignMask(BitWidth);
7588
7589 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
7590 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
7591 // xor/add with SMIN (signmask) are logically equivalent.
7592 SDValue X;
7593 if (!sd_match(N, m_And(m_OneUse(m_Xor(m_Value(X), m_SpecificInt(SignMask))),
7595 m_SpecificInt(BitWidth - 1))))) &&
7598 m_SpecificInt(BitWidth - 1))))))
7599 return SDValue();
7600
7601 return DAG.getNode(ISD::USUBSAT, DL, VT, X,
7602 DAG.getConstant(SignMask, DL, VT));
7603}
7604
7605/// Given a bitwise logic operation N with a matching bitwise logic operand,
7606/// fold a pattern where 2 of the source operands are identically shifted
7607/// values. For example:
7608/// ((X0 << Y) | Z) | (X1 << Y) --> ((X0 | X1) << Y) | Z
7610 SelectionDAG &DAG) {
7611 unsigned LogicOpcode = N->getOpcode();
7612 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7613 "Expected bitwise logic operation");
7614
7615 if (!LogicOp.hasOneUse() || !ShiftOp.hasOneUse())
7616 return SDValue();
7617
7618 // Match another bitwise logic op and a shift.
7619 unsigned ShiftOpcode = ShiftOp.getOpcode();
7620 if (LogicOp.getOpcode() != LogicOpcode ||
7621 !(ShiftOpcode == ISD::SHL || ShiftOpcode == ISD::SRL ||
7622 ShiftOpcode == ISD::SRA))
7623 return SDValue();
7624
7625 // Match another shift op inside the first logic operand. Handle both commuted
7626 // possibilities.
7627 // LOGIC (LOGIC (SH X0, Y), Z), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7628 // LOGIC (LOGIC Z, (SH X0, Y)), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7629 SDValue X1 = ShiftOp.getOperand(0);
7630 SDValue Y = ShiftOp.getOperand(1);
7631 SDValue X0, Z;
7632 if (LogicOp.getOperand(0).getOpcode() == ShiftOpcode &&
7633 LogicOp.getOperand(0).getOperand(1) == Y) {
7634 X0 = LogicOp.getOperand(0).getOperand(0);
7635 Z = LogicOp.getOperand(1);
7636 } else if (LogicOp.getOperand(1).getOpcode() == ShiftOpcode &&
7637 LogicOp.getOperand(1).getOperand(1) == Y) {
7638 X0 = LogicOp.getOperand(1).getOperand(0);
7639 Z = LogicOp.getOperand(0);
7640 } else {
7641 return SDValue();
7642 }
7643
7644 EVT VT = N->getValueType(0);
7645 SDLoc DL(N);
7646 SDValue LogicX = DAG.getNode(LogicOpcode, DL, VT, X0, X1);
7647 SDValue NewShift = DAG.getNode(ShiftOpcode, DL, VT, LogicX, Y);
7648 return DAG.getNode(LogicOpcode, DL, VT, NewShift, Z);
7649}
7650
7651/// Given a tree of logic operations with shape like
7652/// (LOGIC (LOGIC (X, Y), LOGIC (Z, Y)))
7653/// try to match and fold shift operations with the same shift amount.
7654/// For example:
7655/// LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W) -->
7656/// --> LOGIC (SH (LOGIC X0, X1), Y), (LOGIC Z, W)
7658 SDValue RightHand, SelectionDAG &DAG) {
7659 unsigned LogicOpcode = N->getOpcode();
7660 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7661 "Expected bitwise logic operation");
7662 if (LeftHand.getOpcode() != LogicOpcode ||
7663 RightHand.getOpcode() != LogicOpcode)
7664 return SDValue();
7665 if (!LeftHand.hasOneUse() || !RightHand.hasOneUse())
7666 return SDValue();
7667
7668 // Try to match one of following patterns:
7669 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W)
7670 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC W, (SH X1, Y))
7671 // Note that foldLogicOfShifts will handle commuted versions of the left hand
7672 // itself.
7673 SDValue CombinedShifts, W;
7674 SDValue R0 = RightHand.getOperand(0);
7675 SDValue R1 = RightHand.getOperand(1);
7676 if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R0, DAG)))
7677 W = R1;
7678 else if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R1, DAG)))
7679 W = R0;
7680 else
7681 return SDValue();
7682
7683 EVT VT = N->getValueType(0);
7684 SDLoc DL(N);
7685 return DAG.getNode(LogicOpcode, DL, VT, CombinedShifts, W);
7686}
7687
7688/// Fold "masked merge" expressions like `(m & x) | (~m & y)` and its DeMorgan
7689/// variant `(~m | x) & (m | y)` into the equivalent `((x ^ y) & m) ^ y)`
7690/// pattern. This is typically a better representation for targets without a
7691/// fused "and-not" operation.
7693 const TargetLowering &TLI, const SDLoc &DL) {
7694 // Note that masked-merge variants using XOR or ADD expressions are
7695 // normalized to OR by InstCombine so we only check for OR or AND.
7696 assert((Node->getOpcode() == ISD::OR || Node->getOpcode() == ISD::AND) &&
7697 "Must be called with ISD::OR or ISD::AND node");
7698
7699 // If the target supports and-not, don't fold this.
7700 if (TLI.hasAndNot(SDValue(Node, 0)))
7701 return SDValue();
7702
7703 SDValue M, X, Y;
7704
7705 if (sd_match(Node,
7707 m_OneUse(m_And(m_Deferred(M), m_Value(X))))) ||
7708 sd_match(Node,
7710 m_OneUse(m_Or(m_Deferred(M), m_Value(Y)))))) {
7711 EVT VT = M.getValueType();
7712 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, Y);
7713 SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor, M);
7714 return DAG.getNode(ISD::XOR, DL, VT, And, Y);
7715 }
7716 return SDValue();
7717}
7718
7719SDValue DAGCombiner::visitAND(SDNode *N) {
7720 SDValue N0 = N->getOperand(0);
7721 SDValue N1 = N->getOperand(1);
7722 EVT VT = N1.getValueType();
7723 SDLoc DL(N);
7724
7725 // x & x --> x
7726 if (N0 == N1)
7727 return N0;
7728
7729 // fold (and c1, c2) -> c1&c2
7730 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N0, N1}))
7731 return C;
7732
7733 // canonicalize constant to RHS
7736 return DAG.getNode(ISD::AND, DL, VT, N1, N0);
7737
7738 if (areBitwiseNotOfEachother(N0, N1))
7739 return DAG.getConstant(APInt::getZero(VT.getScalarSizeInBits()), DL, VT);
7740
7741 // fold vector ops
7742 if (VT.isVector()) {
7743 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
7744 return FoldedVOp;
7745
7746 // fold (and x, 0) -> 0, vector edition
7748 // do not return N1, because undef node may exist in N1
7750 N1.getValueType());
7751
7752 // fold (and x, -1) -> x, vector edition
7754 return N0;
7755
7756 // fold (and buildvector(x,0,-1,w), buildvector(0,y,z,w))
7757 // --> buildvector(0,0,z,w)
7758 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
7759 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7760 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
7761 N0.hasOneUse() && N1.hasOneUse() &&
7762 BV0->getOperand(0).getValueType() ==
7763 BV1->getOperand(0).getValueType()) {
7764 SmallVector<SDValue> MergedOps;
7765 unsigned NumElts = VT.getVectorNumElements();
7766 EVT EltVT = BV0->getOperand(0).getValueType();
7767 for (unsigned I = 0; I != NumElts; ++I) {
7768 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
7769 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
7770 if (C0 && C1)
7771 MergedOps.push_back(DAG.getConstant(
7772 C0->getAPIntValue() & C1->getAPIntValue(), DL, EltVT));
7773 else if (C0 && C0->isZero())
7774 MergedOps.push_back(BV0->getOperand(I));
7775 else if (C1 && C1->isZero())
7776 MergedOps.push_back(BV1->getOperand(I));
7777 else if (C0 && C0->isAllOnes())
7778 MergedOps.push_back(BV1->getOperand(I));
7779 else if (C1 && C1->isAllOnes())
7780 MergedOps.push_back(BV0->getOperand(I));
7781 else if (BV0->getOperand(I) == BV1->getOperand(I))
7782 MergedOps.push_back(BV0->getOperand(I));
7783 else
7784 break;
7785 }
7786 if (MergedOps.size() == NumElts)
7787 return DAG.getBuildVector(VT, DL, MergedOps);
7788 }
7789
7790 // fold (and (masked_load) (splat_vec (x, ...))) to zext_masked_load
7791 bool Frozen = N0.getOpcode() == ISD::FREEZE;
7792 auto *MLoad = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0);
7793 ConstantSDNode *Splat = isConstOrConstSplat(N1, true, true);
7794 if (MLoad && MLoad->getExtensionType() == ISD::EXTLOAD && Splat) {
7795 EVT MemVT = MLoad->getMemoryVT();
7796 if (TLI.isLoadLegal(VT, MemVT, MLoad->getAlign(),
7797 MLoad->getAddressSpace(), ISD::ZEXTLOAD, false)) {
7798 // For this AND to be a zero extension of the masked load the elements
7799 // of the BuildVec must mask the bottom bits of the extended element
7800 // type
7801 if (Splat->getAPIntValue().isMask(MemVT.getScalarSizeInBits())) {
7802 SDValue NewLoad = DAG.getMaskedLoad(
7803 VT, DL, MLoad->getChain(), MLoad->getBasePtr(),
7804 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), MemVT,
7805 MLoad->getMemOperand(), MLoad->getAddressingMode(), ISD::ZEXTLOAD,
7806 MLoad->isExpandingLoad());
7807 CombineTo(N, Frozen ? N0 : NewLoad);
7808 CombineTo(MLoad, NewLoad, NewLoad.getValue(1));
7809 return SDValue(N, 0);
7810 }
7811 }
7812 }
7813 }
7814
7815 // fold (and x, -1) -> x
7816 if (isAllOnesConstant(N1))
7817 return N0;
7818
7819 // if (and x, c) is known to be zero, return 0
7820 unsigned BitWidth = VT.getScalarSizeInBits();
7821 ConstantSDNode *N1C = isConstOrConstSplat(N1);
7823 return DAG.getConstant(0, DL, VT);
7824
7825 if (SDValue R = foldAndOrOfSETCC(N, DAG))
7826 return R;
7827
7828 if (SDValue NewSel = foldBinOpIntoSelect(N))
7829 return NewSel;
7830
7831 // reassociate and
7832 if (SDValue RAND = reassociateOps(ISD::AND, DL, N0, N1, N->getFlags()))
7833 return RAND;
7834
7835 // Fold and(vecreduce(x), vecreduce(y)) -> vecreduce(and(x, y))
7836 if (SDValue SD =
7837 reassociateReduction(ISD::VECREDUCE_AND, ISD::AND, DL, VT, N0, N1))
7838 return SD;
7839
7840 // fold (and (or x, C), D) -> D if (C & D) == D
7841 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
7842 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
7843 };
7844 if (N0.getOpcode() == ISD::OR &&
7845 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
7846 return N1;
7847
7848 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
7849 SDValue N0Op0 = N0.getOperand(0);
7850 EVT SrcVT = N0Op0.getValueType();
7851 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
7852 APInt Mask = ~N1C->getAPIntValue();
7853 Mask = Mask.trunc(SrcBitWidth);
7854
7855 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
7856 if (DAG.MaskedValueIsZero(N0Op0, Mask))
7857 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0Op0);
7858
7859 // fold (and (any_ext V), c) -> (zero_ext (and (trunc V), c)) if profitable.
7860 if (N1C->getAPIntValue().countLeadingZeros() >= (BitWidth - SrcBitWidth) &&
7861 TLI.isTruncateFree(VT, SrcVT) && TLI.isZExtFree(SrcVT, VT) &&
7862 TLI.isTypeDesirableForOp(ISD::AND, SrcVT) &&
7863 TLI.isNarrowingProfitable(N, VT, SrcVT))
7864 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT,
7865 DAG.getNode(ISD::AND, DL, SrcVT, N0Op0,
7866 DAG.getZExtOrTrunc(N1, DL, SrcVT)));
7867 }
7868
7869 // fold (and (ext (and V, c1)), c2) -> (and (ext V), (and c1, (ext c2)))
7870 if (ISD::isExtOpcode(N0.getOpcode())) {
7871 unsigned ExtOpc = N0.getOpcode();
7872 SDValue N0Op0 = N0.getOperand(0);
7873 if (N0Op0.getOpcode() == ISD::AND &&
7874 (ExtOpc != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0Op0, VT)) &&
7875 N0->hasOneUse() && N0Op0->hasOneUse()) {
7876 if (SDValue NewExt = DAG.FoldConstantArithmetic(ExtOpc, DL, VT,
7877 {N0Op0.getOperand(1)})) {
7878 if (SDValue NewMask =
7879 DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N1, NewExt})) {
7880 return DAG.getNode(ISD::AND, DL, VT,
7881 DAG.getNode(ExtOpc, DL, VT, N0Op0.getOperand(0)),
7882 NewMask);
7883 }
7884 }
7885 }
7886 }
7887
7888 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
7889 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
7890 // already be zero by virtue of the width of the base type of the load.
7891 //
7892 // the 'X' node here can either be nothing or an extract_vector_elt to catch
7893 // more cases.
7894 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7896 N0.getOperand(0).getOpcode() == ISD::LOAD &&
7897 N0.getOperand(0).getResNo() == 0) ||
7898 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
7899 auto *Load =
7900 cast<LoadSDNode>((N0.getOpcode() == ISD::LOAD) ? N0 : N0.getOperand(0));
7901
7902 // Get the constant (if applicable) the zero'th operand is being ANDed with.
7903 // This can be a pure constant or a vector splat, in which case we treat the
7904 // vector as a scalar and use the splat value.
7905 APInt Constant = APInt::getZero(1);
7906 if (const ConstantSDNode *C = isConstOrConstSplat(
7907 N1, /*AllowUndefs=*/false, /*AllowTruncation=*/true)) {
7908 Constant = C->getAPIntValue();
7909 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
7910 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
7911 APInt SplatValue, SplatUndef;
7912 unsigned SplatBitSize;
7913 bool HasAnyUndefs;
7914 // Endianness should not matter here. Code below makes sure that we only
7915 // use the result if the SplatBitSize is a multiple of the vector element
7916 // size. And after that we AND all element sized parts of the splat
7917 // together. So the end result should be the same regardless of in which
7918 // order we do those operations.
7919 const bool IsBigEndian = false;
7920 bool IsSplat =
7921 Vector->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7922 HasAnyUndefs, EltBitWidth, IsBigEndian);
7923
7924 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
7925 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
7926 if (IsSplat && (SplatBitSize % EltBitWidth) == 0) {
7927 // Undef bits can contribute to a possible optimisation if set, so
7928 // set them.
7929 SplatValue |= SplatUndef;
7930
7931 // The splat value may be something like "0x00FFFFFF", which means 0 for
7932 // the first vector value and FF for the rest, repeating. We need a mask
7933 // that will apply equally to all members of the vector, so AND all the
7934 // lanes of the constant together.
7935 Constant = APInt::getAllOnes(EltBitWidth);
7936 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
7937 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
7938 }
7939 }
7940
7941 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
7942 // actually legal and isn't going to get expanded, else this is a false
7943 // optimisation.
7944 bool CanZextLoadProfitably = TLI.isLoadLegal(
7945 Load->getValueType(0), Load->getMemoryVT(), Load->getAlign(),
7946 Load->getAddressSpace(), ISD::ZEXTLOAD, false);
7947
7948 // Resize the constant to the same size as the original memory access before
7949 // extension. If it is still the AllOnesValue then this AND is completely
7950 // unneeded.
7951 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
7952
7953 bool B;
7954 switch (Load->getExtensionType()) {
7955 default: B = false; break;
7956 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
7957 case ISD::ZEXTLOAD:
7958 case ISD::NON_EXTLOAD: B = true; break;
7959 }
7960
7961 if (B && Constant.isAllOnes()) {
7962 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
7963 // preserve semantics once we get rid of the AND.
7964 SDValue NewLoad(Load, 0);
7965
7966 // Fold the AND away. NewLoad may get replaced immediately.
7967 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
7968
7969 if (Load->getExtensionType() == ISD::EXTLOAD) {
7970 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
7971 Load->getValueType(0), SDLoc(Load),
7972 Load->getChain(), Load->getBasePtr(),
7973 Load->getOffset(), Load->getMemoryVT(),
7974 Load->getMemOperand());
7975 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
7976 if (Load->getNumValues() == 3) {
7977 // PRE/POST_INC loads have 3 values.
7978 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
7979 NewLoad.getValue(2) };
7980 CombineTo(Load, To, 3, true);
7981 } else {
7982 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
7983 }
7984 }
7985
7986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7987 }
7988 }
7989
7990 // Try to convert a constant mask AND into a shuffle clear mask.
7991 if (VT.isVector())
7992 if (SDValue Shuffle = XformToShuffleWithZero(N))
7993 return Shuffle;
7994
7995 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
7996 return Combined;
7997
7998 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() && N1C &&
8000 SDValue Ext = N0.getOperand(0);
8001 EVT ExtVT = Ext->getValueType(0);
8002 SDValue Extendee = Ext->getOperand(0);
8003
8004 unsigned ScalarWidth = Extendee.getValueType().getScalarSizeInBits();
8005 if (N1C->getAPIntValue().isMask(ScalarWidth) &&
8006 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, ExtVT))) {
8007 // (and (extract_subvector (zext|anyext|sext v) _) iN_mask)
8008 // => (extract_subvector (iN_zeroext v))
8009 SDValue ZeroExtExtendee =
8010 DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Extendee);
8011
8012 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ZeroExtExtendee,
8013 N0.getOperand(1));
8014 }
8015 }
8016
8017 // fold (and (masked_gather x)) -> (zext_masked_gather x)
8018 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
8019 EVT MemVT = GN0->getMemoryVT();
8020 EVT ScalarVT = MemVT.getScalarType();
8021
8022 if (SDValue(GN0, 0).hasOneUse() &&
8023 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
8025 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
8026 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
8027
8028 SDValue ZExtLoad = DAG.getMaskedGather(
8029 DAG.getVTList(VT, MVT::Other), MemVT, DL, Ops, GN0->getMemOperand(),
8030 GN0->getIndexType(), ISD::ZEXTLOAD);
8031
8032 CombineTo(N, ZExtLoad);
8033 AddToWorklist(ZExtLoad.getNode());
8034 // Avoid recheck of N.
8035 return SDValue(N, 0);
8036 }
8037 }
8038
8039 // fold (and (load x), 255) -> (zextload x, i8)
8040 // fold (and (extload x, i16), 255) -> (zextload x, i8)
8041 // fold (and (freeze (load x)), 255) -> (freeze (zextload x, i8))
8042 // fold (and (freeze (extload x, i16)), 255) -> (freeze (zextload x, i8))
8043 if (N1C && !VT.isVector()) {
8044 SDValue Inner = peekThroughFreeze(N0);
8045 if (Inner.getOpcode() == ISD::LOAD)
8046 if (SDValue Res = reduceLoadWidth(N))
8047 return Res;
8048 }
8049
8050 if (LegalTypes) {
8051 // Attempt to propagate the AND back up to the leaves which, if they're
8052 // loads, can be combined to narrow loads and the AND node can be removed.
8053 // Perform after legalization so that extend nodes will already be
8054 // combined into the loads.
8055 if (BackwardsPropagateMask(N))
8056 return SDValue(N, 0);
8057 }
8058
8059 if (SDValue Combined = visitANDLike(N0, N1, N))
8060 return Combined;
8061
8062 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
8063 if (N0.getOpcode() == N1.getOpcode())
8064 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
8065 return V;
8066
8067 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
8068 return R;
8069 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
8070 return R;
8071
8072 // Fold (and X, (bswap (not Y))) -> (and X, (not (bswap Y)))
8073 // Fold (and X, (bitreverse (not Y))) -> (and X, (not (bitreverse Y)))
8074 SDValue X, Y, Z, NotY;
8075 for (unsigned Opc : {ISD::BSWAP, ISD::BITREVERSE})
8076 if (sd_match(N,
8077 m_And(m_Value(X), m_OneUse(m_UnaryOp(Opc, m_Value(NotY))))) &&
8078 sd_match(NotY, m_Not(m_Value(Y))) &&
8079 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8080 return DAG.getNode(ISD::AND, DL, VT, X,
8081 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y), VT));
8082
8083 // Fold (and X, (rot (not Y), Z)) -> (and X, (not (rot Y, Z)))
8084 for (unsigned Opc : {ISD::ROTL, ISD::ROTR})
8085 if (sd_match(N, m_And(m_Value(X),
8086 m_OneUse(m_BinOp(Opc, m_Value(NotY), m_Value(Z))))) &&
8087 sd_match(NotY, m_Not(m_Value(Y))) &&
8088 (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse()))
8089 return DAG.getNode(ISD::AND, DL, VT, X,
8090 DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y, Z), VT));
8091
8092 // Fold (and X, (add (not Y), Z)) -> (and X, (not (sub Y, Z)))
8093 // Fold (and X, (sub (not Y), Z)) -> (and X, (not (add Y, Z)))
8094 if (TLI.hasAndNot(SDValue(N, 0)))
8095 if (SDValue Folded = foldBitwiseOpWithNeg(N, DL, VT))
8096 return Folded;
8097
8098 // Fold (and (srl X, C), 1) -> (srl X, BW-1) for signbit extraction
8099 // If we are shifting down an extended sign bit, see if we can simplify
8100 // this to shifting the MSB directly to expose further simplifications.
8101 // This pattern often appears after sext_inreg legalization.
8102 APInt Amt;
8103 if (sd_match(N, m_And(m_Srl(m_Value(X), m_ConstInt(Amt)), m_One())) &&
8104 Amt.ult(BitWidth - 1) && Amt.uge(BitWidth - DAG.ComputeNumSignBits(X)))
8105 return DAG.getNode(ISD::SRL, DL, VT, X,
8106 DAG.getShiftAmountConstant(BitWidth - 1, VT, DL));
8107
8108 // Masking the negated extension of a boolean is just the zero-extended
8109 // boolean:
8110 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
8111 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
8112 //
8113 // Note: the SimplifyDemandedBits fold below can make an information-losing
8114 // transform, and then we have no way to find this better fold.
8115 if (sd_match(N, m_And(m_Sub(m_Zero(), m_Value(X)), m_One()))) {
8116 if (X.getOpcode() == ISD::ZERO_EXTEND &&
8117 X.getOperand(0).getScalarValueSizeInBits() == 1)
8118 return X;
8119 if (X.getOpcode() == ISD::SIGN_EXTEND &&
8120 X.getOperand(0).getScalarValueSizeInBits() == 1)
8121 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, X.getOperand(0));
8122 }
8123
8124 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
8125 // fold (and (sra)) -> (and (srl)) when possible.
8127 return SDValue(N, 0);
8128
8129 // fold (zext_inreg (extload x)) -> (zextload x)
8130 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
8131 if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
8132 (ISD::isEXTLoad(N0.getNode()) ||
8133 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
8134 auto *LN0 = cast<LoadSDNode>(N0);
8135 EVT MemVT = LN0->getMemoryVT();
8136 // If we zero all the possible extended bits, then we can turn this into
8137 // a zextload if we are running before legalize or the operation is legal.
8138 unsigned ExtBitSize = N1.getScalarValueSizeInBits();
8139 unsigned MemBitSize = MemVT.getScalarSizeInBits();
8140 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
8141 if (DAG.MaskedValueIsZero(N1, ExtBits) &&
8142 ((!LegalOperations && LN0->isSimple()) ||
8143 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
8144 ISD::ZEXTLOAD, false))) {
8145 SDValue ExtLoad =
8146 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
8147 LN0->getBasePtr(), MemVT, LN0->getMemOperand());
8148 AddToWorklist(N);
8149 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8151 }
8152 }
8153
8154 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
8155 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
8156 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8157 N0.getOperand(1), false))
8158 return BSwap;
8159 }
8160
8161 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
8162 return Shifts;
8163
8164 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
8165 return V;
8166
8167 // Recognize the following pattern:
8168 //
8169 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
8170 //
8171 // where bitmask is a mask that clears the upper bits of AndVT. The
8172 // number of bits in bitmask must be a power of two.
8173 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
8174 if (LHS->getOpcode() != ISD::SIGN_EXTEND)
8175 return false;
8176
8177 auto *C = isConstOrConstSplat(RHS, false, true);
8178 if (!C)
8179 return false;
8180
8181 if (!C->getAPIntValue().isMask(
8182 LHS.getOperand(0).getValueType().getScalarSizeInBits()))
8183 return false;
8184
8185 return true;
8186 };
8187
8188 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
8189 if (IsAndZeroExtMask(N0, N1) &&
8190 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)))
8191 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
8192
8193 if (hasOperation(ISD::USUBSAT, VT))
8194 if (SDValue V = foldAndToUsubsat(N, DAG, DL))
8195 return V;
8196
8197 // Postpone until legalization completed to avoid interference with bswap
8198 // folding
8199 if (LegalOperations || VT.isVector())
8200 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
8201 return R;
8202
8203 if (VT.isScalarInteger() && VT != MVT::i1)
8204 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
8205 return R;
8206
8207 return SDValue();
8208}
8209
8210/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
8211SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
8212 bool DemandHighBits) {
8213 if (!LegalOperations)
8214 return SDValue();
8215
8216 EVT VT = N->getValueType(0);
8217 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
8218 return SDValue();
8220 return SDValue();
8221
8222 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
8223 bool LookPassAnd0 = false;
8224 bool LookPassAnd1 = false;
8225 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
8226 std::swap(N0, N1);
8227 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
8228 std::swap(N0, N1);
8229 if (N0.getOpcode() == ISD::AND) {
8230 if (!N0->hasOneUse())
8231 return SDValue();
8232 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8233 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
8234 // This is needed for X86.
8235 if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
8236 N01C->getZExtValue() != 0xFFFF))
8237 return SDValue();
8238 N0 = N0.getOperand(0);
8239 LookPassAnd0 = true;
8240 }
8241
8242 if (N1.getOpcode() == ISD::AND) {
8243 if (!N1->hasOneUse())
8244 return SDValue();
8245 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8246 if (!N11C || N11C->getZExtValue() != 0xFF)
8247 return SDValue();
8248 N1 = N1.getOperand(0);
8249 LookPassAnd1 = true;
8250 }
8251
8252 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
8253 std::swap(N0, N1);
8254 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
8255 return SDValue();
8256 if (!N0->hasOneUse() || !N1->hasOneUse())
8257 return SDValue();
8258
8259 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8260 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8261 if (!N01C || !N11C)
8262 return SDValue();
8263 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
8264 return SDValue();
8265
8266 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
8267 SDValue N00 = N0->getOperand(0);
8268 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
8269 if (!N00->hasOneUse())
8270 return SDValue();
8271 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
8272 if (!N001C || N001C->getZExtValue() != 0xFF)
8273 return SDValue();
8274 N00 = N00.getOperand(0);
8275 LookPassAnd0 = true;
8276 }
8277
8278 SDValue N10 = N1->getOperand(0);
8279 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
8280 if (!N10->hasOneUse())
8281 return SDValue();
8282 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
8283 // Also allow 0xFFFF since the bits will be shifted out. This is needed
8284 // for X86.
8285 if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
8286 N101C->getZExtValue() != 0xFFFF))
8287 return SDValue();
8288 N10 = N10.getOperand(0);
8289 LookPassAnd1 = true;
8290 }
8291
8292 if (N00 != N10)
8293 return SDValue();
8294
8295 // Make sure everything beyond the low halfword gets set to zero since the SRL
8296 // 16 will clear the top bits.
8297 unsigned OpSizeInBits = VT.getSizeInBits();
8298 if (OpSizeInBits > 16) {
8299 // If the left-shift isn't masked out then the only way this is a bswap is
8300 // if all bits beyond the low 8 are 0. In that case the entire pattern
8301 // reduces to a left shift anyway: leave it for other parts of the combiner.
8302 if (DemandHighBits && !LookPassAnd0)
8303 return SDValue();
8304
8305 // However, if the right shift isn't masked out then it might be because
8306 // it's not needed. See if we can spot that too. If the high bits aren't
8307 // demanded, we only need bits 23:16 to be zero. Otherwise, we need all
8308 // upper bits to be zero.
8309 if (!LookPassAnd1) {
8310 unsigned HighBit = DemandHighBits ? OpSizeInBits : 24;
8311 if (!DAG.MaskedValueIsZero(N10,
8312 APInt::getBitsSet(OpSizeInBits, 16, HighBit)))
8313 return SDValue();
8314 }
8315 }
8316
8317 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
8318 if (OpSizeInBits > 16) {
8319 SDLoc DL(N);
8320 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
8321 DAG.getShiftAmountConstant(OpSizeInBits - 16, VT, DL));
8322 }
8323 return Res;
8324}
8325
8326/// Return true if the specified node is an element that makes up a 32-bit
8327/// packed halfword byteswap.
8328/// ((x & 0x000000ff) << 8) |
8329/// ((x & 0x0000ff00) >> 8) |
8330/// ((x & 0x00ff0000) << 8) |
8331/// ((x & 0xff000000) >> 8)
8333 if (!N->hasOneUse())
8334 return false;
8335
8336 unsigned Opc = N.getOpcode();
8337 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
8338 return false;
8339
8340 SDValue N0 = N.getOperand(0);
8341 unsigned Opc0 = N0.getOpcode();
8342 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
8343 return false;
8344
8345 ConstantSDNode *N1C = nullptr;
8346 // SHL or SRL: look upstream for AND mask operand
8347 if (Opc == ISD::AND)
8348 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8349 else if (Opc0 == ISD::AND)
8351 if (!N1C)
8352 return false;
8353
8354 unsigned MaskByteOffset;
8355 switch (N1C->getZExtValue()) {
8356 default:
8357 return false;
8358 case 0xFF: MaskByteOffset = 0; break;
8359 case 0xFF00: MaskByteOffset = 1; break;
8360 case 0xFFFF:
8361 // In case demanded bits didn't clear the bits that will be shifted out.
8362 // This is needed for X86.
8363 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
8364 MaskByteOffset = 1;
8365 break;
8366 }
8367 return false;
8368 case 0xFF0000: MaskByteOffset = 2; break;
8369 case 0xFF000000: MaskByteOffset = 3; break;
8370 }
8371
8372 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
8373 if (Opc == ISD::AND) {
8374 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
8375 // (x >> 8) & 0xff
8376 // (x >> 8) & 0xff0000
8377 if (Opc0 != ISD::SRL)
8378 return false;
8380 if (!C || C->getZExtValue() != 8)
8381 return false;
8382 } else {
8383 // (x << 8) & 0xff00
8384 // (x << 8) & 0xff000000
8385 if (Opc0 != ISD::SHL)
8386 return false;
8388 if (!C || C->getZExtValue() != 8)
8389 return false;
8390 }
8391 } else if (Opc == ISD::SHL) {
8392 // (x & 0xff) << 8
8393 // (x & 0xff0000) << 8
8394 if (MaskByteOffset != 0 && MaskByteOffset != 2)
8395 return false;
8396 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8397 if (!C || C->getZExtValue() != 8)
8398 return false;
8399 } else { // Opc == ISD::SRL
8400 // (x & 0xff00) >> 8
8401 // (x & 0xff000000) >> 8
8402 if (MaskByteOffset != 1 && MaskByteOffset != 3)
8403 return false;
8404 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
8405 if (!C || C->getZExtValue() != 8)
8406 return false;
8407 }
8408
8409 if (Parts[MaskByteOffset])
8410 return false;
8411
8412 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
8413 return true;
8414}
8415
8416// Match 2 elements of a packed halfword bswap.
8418 if (N.getOpcode() == ISD::OR)
8419 return isBSwapHWordElement(N.getOperand(0), Parts) &&
8420 isBSwapHWordElement(N.getOperand(1), Parts);
8421
8422 if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
8423 ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
8424 if (!C || C->getAPIntValue() != 16)
8425 return false;
8426 Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
8427 return true;
8428 }
8429
8430 return false;
8431}
8432
8433// Match this pattern:
8434// (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
8435// And rewrite this to:
8436// (rotr (bswap A), 16)
8438 SelectionDAG &DAG, SDNode *N, SDValue N0,
8439 SDValue N1, EVT VT) {
8440 assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
8441 "MatchBSwapHWordOrAndAnd: expecting i32");
8442 if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
8443 return SDValue();
8444 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
8445 return SDValue();
8446 // TODO: this is too restrictive; lifting this restriction requires more tests
8447 if (!N0->hasOneUse() || !N1->hasOneUse())
8448 return SDValue();
8451 if (!Mask0 || !Mask1)
8452 return SDValue();
8453 if (Mask0->getAPIntValue() != 0xff00ff00 ||
8454 Mask1->getAPIntValue() != 0x00ff00ff)
8455 return SDValue();
8456 SDValue Shift0 = N0.getOperand(0);
8457 SDValue Shift1 = N1.getOperand(0);
8458 if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
8459 return SDValue();
8460 ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
8461 ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
8462 if (!ShiftAmt0 || !ShiftAmt1)
8463 return SDValue();
8464 if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
8465 return SDValue();
8466 if (Shift0.getOperand(0) != Shift1.getOperand(0))
8467 return SDValue();
8468
8469 SDLoc DL(N);
8470 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
8471 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8472 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8473}
8474
8475/// Match a 32-bit packed halfword bswap. That is
8476/// ((x & 0x000000ff) << 8) |
8477/// ((x & 0x0000ff00) >> 8) |
8478/// ((x & 0x00ff0000) << 8) |
8479/// ((x & 0xff000000) >> 8)
8480/// => (rotl (bswap x), 16)
8481SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
8482 if (!LegalOperations)
8483 return SDValue();
8484
8485 EVT VT = N->getValueType(0);
8486 if (VT != MVT::i32)
8487 return SDValue();
8489 return SDValue();
8490
8491 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT))
8492 return BSwap;
8493
8494 // Try again with commuted operands.
8495 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT))
8496 return BSwap;
8497
8498
8499 // Look for either
8500 // (or (bswaphpair), (bswaphpair))
8501 // (or (or (bswaphpair), (and)), (and))
8502 // (or (or (and), (bswaphpair)), (and))
8503 SDNode *Parts[4] = {};
8504
8505 if (isBSwapHWordPair(N0, Parts)) {
8506 // (or (or (and), (and)), (or (and), (and)))
8507 if (!isBSwapHWordPair(N1, Parts))
8508 return SDValue();
8509 } else if (N0.getOpcode() == ISD::OR) {
8510 // (or (or (or (and), (and)), (and)), (and))
8511 if (!isBSwapHWordElement(N1, Parts))
8512 return SDValue();
8513 SDValue N00 = N0.getOperand(0);
8514 SDValue N01 = N0.getOperand(1);
8515 if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
8516 !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
8517 return SDValue();
8518 } else {
8519 return SDValue();
8520 }
8521
8522 // Make sure the parts are all coming from the same node.
8523 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
8524 return SDValue();
8525
8526 SDLoc DL(N);
8527 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
8528 SDValue(Parts[0], 0));
8529
8530 // Result of the bswap should be rotated by 16. If it's not legal, then
8531 // do (x << 16) | (x >> 16).
8532 SDValue ShAmt = DAG.getShiftAmountConstant(16, VT, DL);
8534 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
8536 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
8537 return DAG.getNode(ISD::OR, DL, VT,
8538 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
8539 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
8540}
8541
8542/// This contains all DAGCombine rules which reduce two values combined by
8543/// an Or operation to a single value \see visitANDLike().
8544SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, const SDLoc &DL) {
8545 EVT VT = N1.getValueType();
8546
8547 // fold (or x, undef) -> -1
8548 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
8549 return DAG.getAllOnesConstant(DL, VT);
8550
8551 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
8552 return V;
8553
8554 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
8555 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
8556 // Don't increase # computations.
8557 (N0->hasOneUse() || N1->hasOneUse())) {
8558 // We can only do this xform if we know that bits from X that are set in C2
8559 // but not in C1 are already zero. Likewise for Y.
8560 if (const ConstantSDNode *N0O1C =
8562 if (const ConstantSDNode *N1O1C =
8564 // We can only do this xform if we know that bits from X that are set in
8565 // C2 but not in C1 are already zero. Likewise for Y.
8566 const APInt &LHSMask = N0O1C->getAPIntValue();
8567 const APInt &RHSMask = N1O1C->getAPIntValue();
8568
8569 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
8570 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
8571 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8572 N0.getOperand(0), N1.getOperand(0));
8573 return DAG.getNode(ISD::AND, DL, VT, X,
8574 DAG.getConstant(LHSMask | RHSMask, DL, VT));
8575 }
8576 }
8577 }
8578 }
8579
8580 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
8581 if (N0.getOpcode() == ISD::AND &&
8582 N1.getOpcode() == ISD::AND &&
8583 N0.getOperand(0) == N1.getOperand(0) &&
8584 // Don't increase # computations.
8585 (N0->hasOneUse() || N1->hasOneUse())) {
8586 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
8587 N0.getOperand(1), N1.getOperand(1));
8588 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
8589 }
8590
8591 return SDValue();
8592}
8593
8594/// OR combines for which the commuted variant will be tried as well.
8596 SDNode *N) {
8597 EVT VT = N0.getValueType();
8598 unsigned BW = VT.getScalarSizeInBits();
8599 SDLoc DL(N);
8600
8601 auto peekThroughResize = [](SDValue V) {
8602 if (V->getOpcode() == ISD::ZERO_EXTEND || V->getOpcode() == ISD::TRUNCATE)
8603 return V->getOperand(0);
8604 return V;
8605 };
8606
8607 SDValue N0Resized = peekThroughResize(N0);
8608 if (N0Resized.getOpcode() == ISD::AND) {
8609 SDValue N1Resized = peekThroughResize(N1);
8610 SDValue N00 = N0Resized.getOperand(0);
8611 SDValue N01 = N0Resized.getOperand(1);
8612
8613 // fold or (and x, y), x --> x
8614 if (N00 == N1Resized || N01 == N1Resized)
8615 return N1;
8616
8617 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
8618 // TODO: Set AllowUndefs = true.
8619 if (SDValue NotOperand = getBitwiseNotOperand(N01, N00,
8620 /* AllowUndefs */ false)) {
8621 if (peekThroughResize(NotOperand) == N1Resized)
8622 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N00, DL, VT),
8623 N1);
8624 }
8625
8626 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
8627 if (SDValue NotOperand = getBitwiseNotOperand(N00, N01,
8628 /* AllowUndefs */ false)) {
8629 if (peekThroughResize(NotOperand) == N1Resized)
8630 return DAG.getNode(ISD::OR, DL, VT, DAG.getZExtOrTrunc(N01, DL, VT),
8631 N1);
8632 }
8633 }
8634
8635 SDValue X, Y;
8636
8637 // fold or (xor X, N1), N1 --> or X, N1
8638 if (sd_match(N0, m_Xor(m_Value(X), m_Specific(N1))))
8639 return DAG.getNode(ISD::OR, DL, VT, X, N1);
8640
8641 // fold or (xor x, y), (x and/or y) --> or x, y
8642 if (sd_match(N0, m_Xor(m_Value(X), m_Value(Y))) &&
8643 (sd_match(N1, m_And(m_Specific(X), m_Specific(Y))) ||
8645 return DAG.getNode(ISD::OR, DL, VT, X, Y);
8646
8647 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
8648 return R;
8649
8650 auto peekThroughZext = [](SDValue V) {
8651 if (V->getOpcode() == ISD::ZERO_EXTEND)
8652 return V->getOperand(0);
8653 return V;
8654 };
8655
8656 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::SHL &&
8657 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8658 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
8659 if (N0.getOperand(0) == N1.getOperand(0))
8660 return N0;
8661 // (fshl A, X, Y) | (shl X, Y) --> fshl (A|X), X, Y
8662 if (N0.getOperand(1) == N1.getOperand(0) && N0.hasOneUse() &&
8663 N1.hasOneUse()) {
8664 SDValue A = N0.getOperand(0);
8665 SDValue X = N1.getOperand(0);
8666 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, X);
8667 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, X, N0.getOperand(2));
8668 }
8669 }
8670
8671 if (N0.getOpcode() == ISD::FSHR && N1.getOpcode() == ISD::SRL &&
8672 peekThroughZext(N0.getOperand(2)) == peekThroughZext(N1.getOperand(1))) {
8673 // (fshr ?, X, Y) | (srl X, Y) --> fshr ?, X, Y
8674 if (N0.getOperand(1) == N1.getOperand(0))
8675 return N0;
8676 // (fshr X, B, Y) | (srl X, Y) --> fshr X, (X|B), Y
8677 if (N0.getOperand(0) == N1.getOperand(0) && N0.hasOneUse() &&
8678 N1.hasOneUse()) {
8679 SDValue X = N1.getOperand(0);
8680 SDValue B = N0.getOperand(1);
8681 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, X, B);
8682 return DAG.getNode(ISD::FSHR, DL, VT, X, NewRHS, N0.getOperand(2));
8683 }
8684 }
8685
8686 // (fshl A, B, S0) | (fshr C, D, S1) --> fshl (A|C), (B|D), S0
8687 // iff S0 + S1 == bitwidth(S1)
8688 if (N0.getOpcode() == ISD::FSHL && N1.getOpcode() == ISD::FSHR &&
8689 N0.hasOneUse() && N1.hasOneUse()) {
8690 auto *S0 = dyn_cast<ConstantSDNode>(N0.getOperand(2));
8691 auto *S1 = dyn_cast<ConstantSDNode>(N1.getOperand(2));
8692 if (S0 && S1 && S0->getZExtValue() < BW && S1->getZExtValue() < BW &&
8693 S0->getZExtValue() == (BW - S1->getZExtValue())) {
8694 SDValue A = N0.getOperand(0);
8695 SDValue B = N0.getOperand(1);
8696 SDValue C = N1.getOperand(0);
8697 SDValue D = N1.getOperand(1);
8698 SDValue NewLHS = DAG.getNode(ISD::OR, DL, VT, A, C);
8699 SDValue NewRHS = DAG.getNode(ISD::OR, DL, VT, B, D);
8700 return DAG.getNode(ISD::FSHL, DL, VT, NewLHS, NewRHS, N0.getOperand(2));
8701 }
8702 }
8703
8704 // Attempt to match a legalized build_pair-esque pattern:
8705 // or(shl(aext(Hi),BW/2),zext(Lo))
8706 SDValue Lo, Hi;
8707 if (sd_match(N0,
8709 sd_match(N1, m_ZExt(m_Value(Lo))) &&
8710 Lo.getScalarValueSizeInBits() == (BW / 2) &&
8711 Lo.getValueType() == Hi.getValueType()) {
8712 // Fold build_pair(not(Lo),not(Hi)) -> not(build_pair(Lo,Hi)).
8713 SDValue NotLo, NotHi;
8714 if (sd_match(Lo, m_OneUse(m_Not(m_Value(NotLo)))) &&
8715 sd_match(Hi, m_OneUse(m_Not(m_Value(NotHi))))) {
8716 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotLo);
8717 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NotHi);
8718 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
8719 DAG.getShiftAmountConstant(BW / 2, VT, DL));
8720 return DAG.getNOT(DL, DAG.getNode(ISD::OR, DL, VT, Lo, Hi), VT);
8721 }
8722 }
8723
8724 return SDValue();
8725}
8726
8727SDValue DAGCombiner::visitOR(SDNode *N) {
8728 SDValue N0 = N->getOperand(0);
8729 SDValue N1 = N->getOperand(1);
8730 EVT VT = N1.getValueType();
8731 SDLoc DL(N);
8732
8733 // x | x --> x
8734 if (N0 == N1)
8735 return N0;
8736
8737 // fold (or c1, c2) -> c1|c2
8738 if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, DL, VT, {N0, N1}))
8739 return C;
8740
8741 // canonicalize constant to RHS
8744 return DAG.getNode(ISD::OR, DL, VT, N1, N0);
8745
8746 // fold vector ops
8747 if (VT.isVector()) {
8748 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
8749 return FoldedVOp;
8750
8751 // fold (or x, 0) -> x, vector edition
8753 return N0;
8754
8755 // fold (or x, -1) -> -1, vector edition
8757 // do not return N1, because undef node may exist in N1
8758 return DAG.getAllOnesConstant(DL, N1.getValueType());
8759
8760 // fold (or buildvector(x,0,-1,w), buildvector(0,y,z,w))
8761 // --> buildvector(x,y,-1,w)
8762 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
8763 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8764 if (BV0 && BV1 && !BV0->getSplatValue() && !BV1->getSplatValue() &&
8765 N0.hasOneUse() && N1.hasOneUse() &&
8766 BV0->getOperand(0).getValueType() ==
8767 BV1->getOperand(0).getValueType()) {
8768 SmallVector<SDValue> MergedOps;
8769 unsigned NumElts = VT.getVectorNumElements();
8770 EVT EltVT = BV0->getOperand(0).getValueType();
8771 for (unsigned I = 0; I != NumElts; ++I) {
8772 auto *C0 = dyn_cast<ConstantSDNode>(BV0->getOperand(I));
8773 auto *C1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
8774 if (C0 && C1)
8775 MergedOps.push_back(DAG.getConstant(
8776 C0->getAPIntValue() | C1->getAPIntValue(), DL, EltVT));
8777 else if (C0 && C0->isZero())
8778 MergedOps.push_back(BV1->getOperand(I));
8779 else if (C1 && C1->isZero())
8780 MergedOps.push_back(BV0->getOperand(I));
8781 else if (C0 && C0->isAllOnes())
8782 MergedOps.push_back(BV0->getOperand(I));
8783 else if (C1 && C1->isAllOnes())
8784 MergedOps.push_back(BV1->getOperand(I));
8785 else if (BV0->getOperand(I) == BV1->getOperand(I))
8786 MergedOps.push_back(BV0->getOperand(I));
8787 else
8788 break;
8789 }
8790 if (MergedOps.size() == NumElts)
8791 return DAG.getBuildVector(VT, DL, MergedOps);
8792 }
8793
8794 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
8795 // Do this only if the resulting type / shuffle is legal.
8796 auto *SV0 = dyn_cast<ShuffleVectorSDNode>(N0);
8797 auto *SV1 = dyn_cast<ShuffleVectorSDNode>(N1);
8798 if (SV0 && SV1 && TLI.isTypeLegal(VT)) {
8799 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
8800 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
8801 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
8802 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
8803 // Ensure both shuffles have a zero input.
8804 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
8805 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
8806 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
8807 bool CanFold = true;
8808 int NumElts = VT.getVectorNumElements();
8809 SmallVector<int, 4> Mask(NumElts, -1);
8810
8811 for (int i = 0; i != NumElts; ++i) {
8812 int M0 = SV0->getMaskElt(i);
8813 int M1 = SV1->getMaskElt(i);
8814
8815 // Determine if either index is pointing to a zero vector.
8816 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
8817 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
8818
8819 // If one element is zero and the otherside is undef, keep undef.
8820 // This also handles the case that both are undef.
8821 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0))
8822 continue;
8823
8824 // Make sure only one of the elements is zero.
8825 if (M0Zero == M1Zero) {
8826 CanFold = false;
8827 break;
8828 }
8829
8830 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
8831
8832 // We have a zero and non-zero element. If the non-zero came from
8833 // SV0 make the index a LHS index. If it came from SV1, make it
8834 // a RHS index. We need to mod by NumElts because we don't care
8835 // which operand it came from in the original shuffles.
8836 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
8837 }
8838
8839 if (CanFold) {
8840 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
8841 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
8842 SDValue LegalShuffle =
8843 TLI.buildLegalVectorShuffle(VT, DL, NewLHS, NewRHS, Mask, DAG);
8844 if (LegalShuffle)
8845 return LegalShuffle;
8846 }
8847 }
8848 }
8849 }
8850
8851 // fold (or x, 0) -> x
8852 if (isNullConstant(N1))
8853 return N0;
8854
8855 // fold (or x, -1) -> -1
8856 if (isAllOnesConstant(N1))
8857 return N1;
8858
8859 if (SDValue NewSel = foldBinOpIntoSelect(N))
8860 return NewSel;
8861
8862 // fold (or x, c) -> c iff (x & ~c) == 0
8863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8864 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
8865 return N1;
8866
8867 if (SDValue R = foldAndOrOfSETCC(N, DAG))
8868 return R;
8869
8870 if (SDValue Combined = visitORLike(N0, N1, DL))
8871 return Combined;
8872
8873 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
8874 return Combined;
8875
8876 if (SDValue Combined = combineOrOfSetCCToUSUBOCarry(N, DAG, TLI))
8877 return Combined;
8878
8879 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
8880 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
8881 return BSwap;
8882 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
8883 return BSwap;
8884
8885 // reassociate or
8886 if (SDValue ROR = reassociateOps(ISD::OR, DL, N0, N1, N->getFlags()))
8887 return ROR;
8888
8889 // Fold or(vecreduce(x), vecreduce(y)) -> vecreduce(or(x, y))
8890 if (SDValue SD =
8891 reassociateReduction(ISD::VECREDUCE_OR, ISD::OR, DL, VT, N0, N1))
8892 return SD;
8893
8894 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
8895 // iff (c1 & c2) != 0 or c1/c2 are undef.
8896 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
8897 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
8898 };
8899 if (N0.getOpcode() == ISD::AND && N0->hasOneUse() &&
8900 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
8901 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
8902 {N1, N0.getOperand(1)})) {
8903 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
8904 AddToWorklist(IOR.getNode());
8905 return DAG.getNode(ISD::AND, DL, VT, COR, IOR);
8906 }
8907 }
8908
8909 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
8910 return Combined;
8911 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
8912 return Combined;
8913
8914 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
8915 if (N0.getOpcode() == N1.getOpcode())
8916 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
8917 return V;
8918
8919 // See if this is some rotate idiom.
8920 if (SDValue Rot = MatchRotate(N0, N1, DL, /*FromAdd=*/false))
8921 return Rot;
8922
8923 if (SDValue Load = MatchLoadCombine(N))
8924 return Load;
8925
8926 // Simplify the operands using demanded-bits information.
8928 return SDValue(N, 0);
8929
8930 // If OR can be rewritten into ADD, try combines based on ADD.
8931 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
8932 DAG.isADDLike(SDValue(N, 0)))
8933 if (SDValue Combined = visitADDLike(N))
8934 return Combined;
8935
8936 // Postpone until legalization completed to avoid interference with bswap
8937 // folding
8938 if (LegalOperations || VT.isVector())
8939 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
8940 return R;
8941
8942 if (VT.isScalarInteger() && VT != MVT::i1)
8943 if (SDValue R = foldMaskedMerge(N, DAG, TLI, DL))
8944 return R;
8945
8946 return SDValue();
8947}
8948
8950 SDValue &Mask) {
8951 if (Op.getOpcode() == ISD::AND &&
8952 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
8953 Mask = Op.getOperand(1);
8954 return Op.getOperand(0);
8955 }
8956 return Op;
8957}
8958
8959/// Match "(X shl/srl V1) & V2" where V2 may not be present.
8960static bool matchRotateHalf(const SelectionDAG &DAG, SDValue Op, SDValue &Shift,
8961 SDValue &Mask) {
8962 Op = stripConstantMask(DAG, Op, Mask);
8963 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
8964 Shift = Op;
8965 return true;
8966 }
8967 return false;
8968}
8969
8970/// Helper function for visitOR to extract the needed side of a rotate idiom
8971/// from a shl/srl/mul/udiv. This is meant to handle cases where
8972/// InstCombine merged some outside op with one of the shifts from
8973/// the rotate pattern.
8974/// \returns An empty \c SDValue if the needed shift couldn't be extracted.
8975/// Otherwise, returns an expansion of \p ExtractFrom based on the following
8976/// patterns:
8977///
8978/// (or (add v v) (shrl v bitwidth-1)):
8979/// expands (add v v) -> (shl v 1)
8980///
8981/// (or (mul v c0) (shrl (mul v c1) c2)):
8982/// expands (mul v c0) -> (shl (mul v c1) c3)
8983///
8984/// (or (udiv v c0) (shl (udiv v c1) c2)):
8985/// expands (udiv v c0) -> (shrl (udiv v c1) c3)
8986///
8987/// (or (shl v c0) (shrl (shl v c1) c2)):
8988/// expands (shl v c0) -> (shl (shl v c1) c3)
8989///
8990/// (or (shrl v c0) (shl (shrl v c1) c2)):
8991/// expands (shrl v c0) -> (shrl (shrl v c1) c3)
8992///
8993/// Such that in all cases, c3+c2==bitwidth(op v c1).
8995 SDValue ExtractFrom, SDValue &Mask,
8996 const SDLoc &DL) {
8997 assert(OppShift && ExtractFrom && "Empty SDValue");
8998 if (OppShift.getOpcode() != ISD::SHL && OppShift.getOpcode() != ISD::SRL)
8999 return SDValue();
9000
9001 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
9002
9003 // Value and Type of the shift.
9004 SDValue OppShiftLHS = OppShift.getOperand(0);
9005 EVT ShiftedVT = OppShiftLHS.getValueType();
9006
9007 // Amount of the existing shift.
9008 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
9009
9010 // (add v v) -> (shl v 1)
9011 // TODO: Should this be a general DAG canonicalization?
9012 if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
9013 ExtractFrom.getOpcode() == ISD::ADD &&
9014 ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
9015 ExtractFrom.getOperand(0) == OppShiftLHS &&
9016 OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
9017 return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
9018 DAG.getShiftAmountConstant(1, ShiftedVT, DL));
9019
9020 // Preconditions:
9021 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
9022 //
9023 // Find opcode of the needed shift to be extracted from (op0 v c0).
9024 unsigned Opcode = ISD::DELETED_NODE;
9025 bool IsMulOrDiv = false;
9026 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
9027 // opcode or its arithmetic (mul or udiv) variant.
9028 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
9029 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
9030 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
9031 return false;
9032 Opcode = NeededShift;
9033 return true;
9034 };
9035 // op0 must be either the needed shift opcode or the mul/udiv equivalent
9036 // that the needed shift can be extracted from.
9037 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
9038 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
9039 return SDValue();
9040
9041 // op0 must be the same opcode on both sides, have the same LHS argument,
9042 // and produce the same value type.
9043 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
9044 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
9045 ShiftedVT != ExtractFrom.getValueType())
9046 return SDValue();
9047
9048 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
9049 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
9050 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
9051 ConstantSDNode *ExtractFromCst =
9052 isConstOrConstSplat(ExtractFrom.getOperand(1));
9053 // TODO: We should be able to handle non-uniform constant vectors for these values
9054 // Check that we have constant values.
9055 if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
9056 !OppLHSCst || !OppLHSCst->getAPIntValue() ||
9057 !ExtractFromCst || !ExtractFromCst->getAPIntValue())
9058 return SDValue();
9059
9060 // Compute the shift amount we need to extract to complete the rotate.
9061 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
9062 if (OppShiftCst->getAPIntValue().ugt(VTWidth))
9063 return SDValue();
9064 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
9065 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
9066 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
9067 APInt OppLHSAmt = OppLHSCst->getAPIntValue();
9068 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
9069
9070 // Now try extract the needed shift from the ExtractFrom op and see if the
9071 // result matches up with the existing shift's LHS op.
9072 if (IsMulOrDiv) {
9073 // Op to extract from is a mul or udiv by a constant.
9074 // Check:
9075 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
9076 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
9077 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
9078 NeededShiftAmt.getZExtValue());
9079 APInt ResultAmt;
9080 APInt Rem;
9081 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
9082 if (Rem != 0 || ResultAmt != OppLHSAmt)
9083 return SDValue();
9084 } else {
9085 // Op to extract from is a shift by a constant.
9086 // Check:
9087 // c2 - (bitwidth(op0 v c0) - c1) == c0
9088 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
9089 ExtractFromAmt.getBitWidth()))
9090 return SDValue();
9091 }
9092
9093 // Return the expanded shift op that should allow a rotate to be formed.
9094 EVT ShiftVT = OppShift.getOperand(1).getValueType();
9095 EVT ResVT = ExtractFrom.getValueType();
9096 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
9097 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
9098}
9099
9100// Return true if we can prove that, whenever Neg and Pos are both in the
9101// range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
9102// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
9103//
9104// (or (shift1 X, Neg), (shift2 X, Pos))
9105//
9106// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
9107// in direction shift1 by Neg. The range [0, EltSize) means that we only need
9108// to consider shift amounts with defined behavior.
9109//
9110// The IsRotate flag should be set when the LHS of both shifts is the same.
9111// Otherwise if matching a general funnel shift, it should be clear.
9112static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
9113 SelectionDAG &DAG, bool IsRotate, bool FromAdd) {
9114 const auto &TLI = DAG.getTargetLoweringInfo();
9115 // If EltSize is a power of 2 then:
9116 //
9117 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
9118 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
9119 //
9120 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
9121 // for the stronger condition:
9122 //
9123 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
9124 //
9125 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
9126 // we can just replace Neg with Neg' for the rest of the function.
9127 //
9128 // In other cases we check for the even stronger condition:
9129 //
9130 // Neg == EltSize - Pos [B]
9131 //
9132 // for all Neg and Pos. Note that the (or ...) then invokes undefined
9133 // behavior if Pos == 0 (and consequently Neg == EltSize).
9134 //
9135 // We could actually use [A] whenever EltSize is a power of 2, but the
9136 // only extra cases that it would match are those uninteresting ones
9137 // where Neg and Pos are never in range at the same time. E.g. for
9138 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
9139 // as well as (sub 32, Pos), but:
9140 //
9141 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
9142 //
9143 // always invokes undefined behavior for 32-bit X.
9144 //
9145 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
9146 // This allows us to peek through any operations that only affect Mask's
9147 // un-demanded bits.
9148 //
9149 // NOTE: We can only do this when matching operations which won't modify the
9150 // least Log2(EltSize) significant bits and not a general funnel shift.
9151 unsigned MaskLoBits = 0;
9152 if (IsRotate && !FromAdd && isPowerOf2_64(EltSize)) {
9153 unsigned Bits = Log2_64(EltSize);
9154 unsigned NegBits = Neg.getScalarValueSizeInBits();
9155 if (NegBits >= Bits) {
9156 APInt DemandedBits = APInt::getLowBitsSet(NegBits, Bits);
9157 if (SDValue Inner =
9159 Neg = Inner;
9160 MaskLoBits = Bits;
9161 }
9162 }
9163 }
9164
9165 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
9166 if (Neg.getOpcode() != ISD::SUB)
9167 return false;
9169 if (!NegC)
9170 return false;
9171 SDValue NegOp1 = Neg.getOperand(1);
9172
9173 // On the RHS of [A], if Pos is the result of operation on Pos' that won't
9174 // affect Mask's demanded bits, just replace Pos with Pos'. These operations
9175 // are redundant for the purpose of the equality.
9176 if (MaskLoBits) {
9177 unsigned PosBits = Pos.getScalarValueSizeInBits();
9178 if (PosBits >= MaskLoBits) {
9179 APInt DemandedBits = APInt::getLowBitsSet(PosBits, MaskLoBits);
9180 if (SDValue Inner =
9182 Pos = Inner;
9183 }
9184 }
9185 }
9186
9187 // The condition we need is now:
9188 //
9189 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
9190 //
9191 // If NegOp1 == Pos then we need:
9192 //
9193 // EltSize & Mask == NegC & Mask
9194 //
9195 // (because "x & Mask" is a truncation and distributes through subtraction).
9196 //
9197 // We also need to account for a potential truncation of NegOp1 if the amount
9198 // has already been legalized to a shift amount type.
9199 APInt Width;
9200 if ((Pos == NegOp1) ||
9201 (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
9202 Width = NegC->getAPIntValue();
9203
9204 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
9205 // Then the condition we want to prove becomes:
9206 //
9207 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
9208 //
9209 // which, again because "x & Mask" is a truncation, becomes:
9210 //
9211 // NegC & Mask == (EltSize - PosC) & Mask
9212 // EltSize & Mask == (NegC + PosC) & Mask
9213 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
9214 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
9215 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
9216 else
9217 return false;
9218 } else
9219 return false;
9220
9221 // Now we just need to check that EltSize & Mask == Width & Mask.
9222 if (MaskLoBits)
9223 // EltSize & Mask is 0 since Mask is EltSize - 1.
9224 return Width.getLoBits(MaskLoBits) == 0;
9225 return Width == EltSize;
9226}
9227
9228// A subroutine of MatchRotate used once we have found an OR of two opposite
9229// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
9230// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
9231// former being preferred if supported. InnerPos and InnerNeg are Pos and
9232// Neg with outer conversions stripped away.
9233SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
9234 SDValue Neg, SDValue InnerPos,
9235 SDValue InnerNeg, bool FromAdd,
9236 bool HasPos, unsigned PosOpcode,
9237 unsigned NegOpcode, const SDLoc &DL) {
9238 // fold (or/add (shl x, (*ext y)),
9239 // (srl x, (*ext (sub 32, y)))) ->
9240 // (rotl x, y) or (rotr x, (sub 32, y))
9241 //
9242 // fold (or/add (shl x, (*ext (sub 32, y))),
9243 // (srl x, (*ext y))) ->
9244 // (rotr x, y) or (rotl x, (sub 32, y))
9245 EVT VT = Shifted.getValueType();
9246 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG,
9247 /*IsRotate*/ true, FromAdd))
9248 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
9249 HasPos ? Pos : Neg);
9250
9251 return SDValue();
9252}
9253
9254// A subroutine of MatchRotate used once we have found an OR of two opposite
9255// shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces
9256// to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
9257// former being preferred if supported. InnerPos and InnerNeg are Pos and
9258// Neg with outer conversions stripped away.
9259// TODO: Merge with MatchRotatePosNeg.
9260SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
9261 SDValue Neg, SDValue InnerPos,
9262 SDValue InnerNeg, bool FromAdd,
9263 bool HasPos, unsigned PosOpcode,
9264 unsigned NegOpcode, const SDLoc &DL) {
9265 EVT VT = N0.getValueType();
9266 unsigned EltBits = VT.getScalarSizeInBits();
9267
9268 // fold (or/add (shl x0, (*ext y)),
9269 // (srl x1, (*ext (sub 32, y)))) ->
9270 // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
9271 //
9272 // fold (or/add (shl x0, (*ext (sub 32, y))),
9273 // (srl x1, (*ext y))) ->
9274 // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
9275 if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1,
9276 FromAdd))
9277 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
9278 HasPos ? Pos : Neg);
9279
9280 // Matching the shift+xor cases, we can't easily use the xor'd shift amount
9281 // so for now just use the PosOpcode case if its legal.
9282 // TODO: When can we use the NegOpcode case?
9283 if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
9284 SDValue X;
9285 // fold (or/add (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
9286 // -> (fshl x0, x1, y)
9287 if (sd_match(N1, m_Srl(m_Value(X), m_One())) &&
9288 sd_match(InnerNeg,
9289 m_Xor(m_Specific(InnerPos), m_SpecificInt(EltBits - 1))) &&
9291 return DAG.getNode(ISD::FSHL, DL, VT, N0, X, Pos);
9292 }
9293
9294 // fold (or/add (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
9295 // -> (fshr x0, x1, y)
9296 if (sd_match(N0, m_Shl(m_Value(X), m_One())) &&
9297 sd_match(InnerPos,
9298 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9300 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9301 }
9302
9303 // fold (or/add (shl (add x0, x0), (xor y, 31)), (srl x1, y))
9304 // -> (fshr x0, x1, y)
9305 // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
9306 if (sd_match(N0, m_Add(m_Value(X), m_Deferred(X))) &&
9307 sd_match(InnerPos,
9308 m_Xor(m_Specific(InnerNeg), m_SpecificInt(EltBits - 1))) &&
9310 return DAG.getNode(ISD::FSHR, DL, VT, X, N1, Neg);
9311 }
9312 }
9313
9314 return SDValue();
9315}
9316
9317// MatchRotate - Handle an 'or' or 'add' of two operands. If this is one of the
9318// many idioms for rotate, and if the target supports rotation instructions,
9319// generate a rot[lr]. This also matches funnel shift patterns, similar to
9320// rotation but with different shifted sources.
9321SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
9322 bool FromAdd) {
9323 EVT VT = LHS.getValueType();
9324
9325 // The target must have at least one rotate/funnel flavor.
9326 // We still try to match rotate by constant pre-legalization.
9327 // TODO: Support pre-legalization funnel-shift by constant.
9328 bool HasROTL = hasOperation(ISD::ROTL, VT);
9329 bool HasROTR = hasOperation(ISD::ROTR, VT);
9330 bool HasFSHL = hasOperation(ISD::FSHL, VT);
9331 bool HasFSHR = hasOperation(ISD::FSHR, VT);
9332
9333 // If the type is going to be promoted and the target has enabled custom
9334 // lowering for rotate, allow matching rotate by non-constants. Only allow
9335 // this for scalar types.
9336 if (VT.isScalarInteger() && TLI.getTypeAction(*DAG.getContext(), VT) ==
9340 }
9341
9342 if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9343 return SDValue();
9344
9345 // Check for truncated rotate.
9346 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
9347 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
9348 assert(LHS.getValueType() == RHS.getValueType());
9349 if (SDValue Rot =
9350 MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL, FromAdd))
9351 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
9352 }
9353
9354 // Match "(X shl/srl V1) & V2" where V2 may not be present.
9355 SDValue LHSShift; // The shift.
9356 SDValue LHSMask; // AND value if any.
9357 matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
9358
9359 SDValue RHSShift; // The shift.
9360 SDValue RHSMask; // AND value if any.
9361 matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
9362
9363 // If neither side matched a rotate half, bail
9364 if (!LHSShift && !RHSShift)
9365 return SDValue();
9366
9367 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
9368 // side of the rotate, so try to handle that here. In all cases we need to
9369 // pass the matched shift from the opposite side to compute the opcode and
9370 // needed shift amount to extract. We still want to do this if both sides
9371 // matched a rotate half because one half may be a potential overshift that
9372 // can be broken down (ie if InstCombine merged two shl or srl ops into a
9373 // single one).
9374
9375 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
9376 if (LHSShift)
9377 if (SDValue NewRHSShift =
9378 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
9379 RHSShift = NewRHSShift;
9380 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
9381 if (RHSShift)
9382 if (SDValue NewLHSShift =
9383 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
9384 LHSShift = NewLHSShift;
9385
9386 // If a side is still missing, nothing else we can do.
9387 if (!RHSShift || !LHSShift)
9388 return SDValue();
9389
9390 // At this point we've matched or extracted a shift op on each side.
9391
9392 if (LHSShift.getOpcode() == RHSShift.getOpcode())
9393 return SDValue(); // Shifts must disagree.
9394
9395 // Canonicalize shl to left side in a shl/srl pair.
9396 if (RHSShift.getOpcode() == ISD::SHL) {
9397 std::swap(LHS, RHS);
9398 std::swap(LHSShift, RHSShift);
9399 std::swap(LHSMask, RHSMask);
9400 }
9401
9402 // Something has gone wrong - we've lost the shl/srl pair - bail.
9403 if (LHSShift.getOpcode() != ISD::SHL || RHSShift.getOpcode() != ISD::SRL)
9404 return SDValue();
9405
9406 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9407 SDValue LHSShiftArg = LHSShift.getOperand(0);
9408 SDValue LHSShiftAmt = LHSShift.getOperand(1);
9409 SDValue RHSShiftArg = RHSShift.getOperand(0);
9410 SDValue RHSShiftAmt = RHSShift.getOperand(1);
9411
9412 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
9413 ConstantSDNode *RHS) {
9414 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
9415 };
9416
9417 auto ApplyMasks = [&](SDValue Res) {
9418 // If there is an AND of either shifted operand, apply it to the result.
9419 if (LHSMask.getNode() || RHSMask.getNode()) {
9422
9423 if (LHSMask.getNode()) {
9424 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
9425 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9426 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
9427 }
9428 if (RHSMask.getNode()) {
9429 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
9430 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
9431 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
9432 }
9433
9434 Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
9435 }
9436
9437 return Res;
9438 };
9439
9440 // TODO: Support pre-legalization funnel-shift by constant.
9441 bool IsRotate = LHSShiftArg == RHSShiftArg;
9442 if (!IsRotate && !(HasFSHL || HasFSHR)) {
9443 if (TLI.isTypeLegal(VT) && LHS.hasOneUse() && RHS.hasOneUse() &&
9444 ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9445 // Look for a disguised rotate by constant.
9446 // The common shifted operand X may be hidden inside another 'or'.
9447 SDValue X, Y;
9448 auto matchOr = [&X, &Y](SDValue Or, SDValue CommonOp) {
9449 if (!Or.hasOneUse() || Or.getOpcode() != ISD::OR)
9450 return false;
9451 if (CommonOp == Or.getOperand(0)) {
9452 X = CommonOp;
9453 Y = Or.getOperand(1);
9454 return true;
9455 }
9456 if (CommonOp == Or.getOperand(1)) {
9457 X = CommonOp;
9458 Y = Or.getOperand(0);
9459 return true;
9460 }
9461 return false;
9462 };
9463
9464 SDValue Res;
9465 if (matchOr(LHSShiftArg, RHSShiftArg)) {
9466 // (shl (X | Y), C1) | (srl X, C2) --> (rotl X, C1) | (shl Y, C1)
9467 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9468 SDValue ShlY = DAG.getNode(ISD::SHL, DL, VT, Y, LHSShiftAmt);
9469 Res = DAG.getNode(ISD::OR, DL, VT, RotX, ShlY);
9470 } else if (matchOr(RHSShiftArg, LHSShiftArg)) {
9471 // (shl X, C1) | (srl (X | Y), C2) --> (rotl X, C1) | (srl Y, C2)
9472 SDValue RotX = DAG.getNode(ISD::ROTL, DL, VT, X, LHSShiftAmt);
9473 SDValue SrlY = DAG.getNode(ISD::SRL, DL, VT, Y, RHSShiftAmt);
9474 Res = DAG.getNode(ISD::OR, DL, VT, RotX, SrlY);
9475 } else {
9476 return SDValue();
9477 }
9478
9479 return ApplyMasks(Res);
9480 }
9481
9482 return SDValue(); // Requires funnel shift support.
9483 }
9484
9485 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotl x, C1)
9486 // fold (or/add (shl x, C1), (srl x, C2)) -> (rotr x, C2)
9487 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
9488 // fold (or/add (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
9489 // iff C1+C2 == EltSizeInBits
9490 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
9491 SDValue Res;
9492 if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) {
9493 bool UseROTL = !LegalOperations || HasROTL;
9494 Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
9495 UseROTL ? LHSShiftAmt : RHSShiftAmt);
9496 } else {
9497 bool UseFSHL = !LegalOperations || HasFSHL;
9498 Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
9499 RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt);
9500 }
9501
9502 return ApplyMasks(Res);
9503 }
9504
9505 // Even pre-legalization, we can't easily rotate/funnel-shift by a variable
9506 // shift.
9507 if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
9508 return SDValue();
9509
9510 // If there is a mask here, and we have a variable shift, we can't be sure
9511 // that we're masking out the right stuff.
9512 if (LHSMask.getNode() || RHSMask.getNode())
9513 return SDValue();
9514
9515 // If the shift amount is sign/zext/any-extended just peel it off.
9516 SDValue LExtOp0 = LHSShiftAmt;
9517 SDValue RExtOp0 = RHSShiftAmt;
9518 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9519 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9520 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9521 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
9522 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
9523 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
9524 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
9525 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
9526 LExtOp0 = LHSShiftAmt.getOperand(0);
9527 RExtOp0 = RHSShiftAmt.getOperand(0);
9528 }
9529
9530 if (IsRotate && (HasROTL || HasROTR)) {
9531 if (SDValue TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
9532 LExtOp0, RExtOp0, FromAdd, HasROTL,
9534 return TryL;
9535
9536 if (SDValue TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
9537 RExtOp0, LExtOp0, FromAdd, HasROTR,
9539 return TryR;
9540 }
9541
9542 if (SDValue TryL = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt,
9543 RHSShiftAmt, LExtOp0, RExtOp0, FromAdd,
9544 HasFSHL, ISD::FSHL, ISD::FSHR, DL))
9545 return TryL;
9546
9547 if (SDValue TryR = MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt,
9548 LHSShiftAmt, RExtOp0, LExtOp0, FromAdd,
9549 HasFSHR, ISD::FSHR, ISD::FSHL, DL))
9550 return TryR;
9551
9552 return SDValue();
9553}
9554
9555/// Recursively traverses the expression calculating the origin of the requested
9556/// byte of the given value. Returns std::nullopt if the provider can't be
9557/// calculated.
9558///
9559/// For all the values except the root of the expression, we verify that the
9560/// value has exactly one use and if not then return std::nullopt. This way if
9561/// the origin of the byte is returned it's guaranteed that the values which
9562/// contribute to the byte are not used outside of this expression.
9563
9564/// However, there is a special case when dealing with vector loads -- we allow
9565/// more than one use if the load is a vector type. Since the values that
9566/// contribute to the byte ultimately come from the ExtractVectorElements of the
9567/// Load, we don't care if the Load has uses other than ExtractVectorElements,
9568/// because those operations are independent from the pattern to be combined.
9569/// For vector loads, we simply care that the ByteProviders are adjacent
9570/// positions of the same vector, and their index matches the byte that is being
9571/// provided. This is captured by the \p VectorIndex algorithm. \p VectorIndex
9572/// is the index used in an ExtractVectorElement, and \p StartingIndex is the
9573/// byte position we are trying to provide for the LoadCombine. If these do
9574/// not match, then we can not combine the vector loads. \p Index uses the
9575/// byte position we are trying to provide for and is matched against the
9576/// shl and load size. The \p Index algorithm ensures the requested byte is
9577/// provided for by the pattern, and the pattern does not over provide bytes.
9578///
9579///
9580/// The supported LoadCombine pattern for vector loads is as follows
9581/// or
9582/// / \
9583/// or shl
9584/// / \ |
9585/// or shl zext
9586/// / \ | |
9587/// shl zext zext EVE*
9588/// | | | |
9589/// zext EVE* EVE* LOAD
9590/// | | |
9591/// EVE* LOAD LOAD
9592/// |
9593/// LOAD
9594///
9595/// *ExtractVectorElement
9597
9598static std::optional<SDByteProvider>
9599calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
9600 std::optional<uint64_t> VectorIndex,
9601 unsigned StartingIndex = 0) {
9602
9603 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
9604 if (Depth == 10)
9605 return std::nullopt;
9606
9607 // Only allow multiple uses if the instruction is a vector load (in which
9608 // case we will use the load for every ExtractVectorElement)
9609 if (Depth && !Op.hasOneUse() &&
9610 (Op.getOpcode() != ISD::LOAD || !Op.getValueType().isVector()))
9611 return std::nullopt;
9612
9613 // Fail to combine if we have encountered anything but a LOAD after handling
9614 // an ExtractVectorElement.
9615 if (Op.getOpcode() != ISD::LOAD && VectorIndex.has_value())
9616 return std::nullopt;
9617
9618 unsigned BitWidth = Op.getScalarValueSizeInBits();
9619 if (BitWidth % 8 != 0)
9620 return std::nullopt;
9621 unsigned ByteWidth = BitWidth / 8;
9622 assert(Index < ByteWidth && "invalid index requested");
9623 (void) ByteWidth;
9624
9625 switch (Op.getOpcode()) {
9626 case ISD::OR: {
9627 auto LHS =
9628 calculateByteProvider(Op->getOperand(0), Index, Depth + 1, VectorIndex);
9629 if (!LHS)
9630 return std::nullopt;
9631 auto RHS =
9632 calculateByteProvider(Op->getOperand(1), Index, Depth + 1, VectorIndex);
9633 if (!RHS)
9634 return std::nullopt;
9635
9636 if (LHS->isConstantZero())
9637 return RHS;
9638 if (RHS->isConstantZero())
9639 return LHS;
9640 return std::nullopt;
9641 }
9642 case ISD::SHL: {
9643 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9644 if (!ShiftOp)
9645 return std::nullopt;
9646
9647 uint64_t BitShift = ShiftOp->getZExtValue();
9648
9649 if (BitShift % 8 != 0)
9650 return std::nullopt;
9651 uint64_t ByteShift = BitShift / 8;
9652
9653 // If we are shifting by an amount greater than the index we are trying to
9654 // provide, then do not provide anything. Otherwise, subtract the index by
9655 // the amount we shifted by.
9656 return Index < ByteShift
9658 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
9659 Depth + 1, VectorIndex, Index);
9660 }
9661 case ISD::ANY_EXTEND:
9662 case ISD::SIGN_EXTEND:
9663 case ISD::ZERO_EXTEND: {
9664 SDValue NarrowOp = Op->getOperand(0);
9665 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9666 if (NarrowBitWidth % 8 != 0)
9667 return std::nullopt;
9668 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9669
9670 if (Index >= NarrowByteWidth)
9671 return Op.getOpcode() == ISD::ZERO_EXTEND
9672 ? std::optional<SDByteProvider>(
9674 : std::nullopt;
9675 return calculateByteProvider(NarrowOp, Index, Depth + 1, VectorIndex,
9676 StartingIndex);
9677 }
9678 case ISD::BSWAP:
9679 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
9680 Depth + 1, VectorIndex, StartingIndex);
9682 auto OffsetOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9683 if (!OffsetOp)
9684 return std::nullopt;
9685
9686 VectorIndex = OffsetOp->getZExtValue();
9687
9688 SDValue NarrowOp = Op->getOperand(0);
9689 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
9690 if (NarrowBitWidth % 8 != 0)
9691 return std::nullopt;
9692 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9693 // EXTRACT_VECTOR_ELT can extend the element type to the width of the return
9694 // type, leaving the high bits undefined.
9695 if (Index >= NarrowByteWidth)
9696 return std::nullopt;
9697
9698 // Check to see if the position of the element in the vector corresponds
9699 // with the byte we are trying to provide for. In the case of a vector of
9700 // i8, this simply means the VectorIndex == StartingIndex. For non i8 cases,
9701 // the element will provide a range of bytes. For example, if we have a
9702 // vector of i16s, each element provides two bytes (V[1] provides byte 2 and
9703 // 3).
9704 if (*VectorIndex * NarrowByteWidth > StartingIndex)
9705 return std::nullopt;
9706 if ((*VectorIndex + 1) * NarrowByteWidth <= StartingIndex)
9707 return std::nullopt;
9708
9709 return calculateByteProvider(Op->getOperand(0), Index, Depth + 1,
9710 VectorIndex, StartingIndex);
9711 }
9712 case ISD::LOAD: {
9713 auto L = cast<LoadSDNode>(Op.getNode());
9714 if (!L->isSimple() || L->isIndexed())
9715 return std::nullopt;
9716
9717 unsigned NarrowBitWidth = L->getMemoryVT().getScalarSizeInBits();
9718 if (NarrowBitWidth % 8 != 0)
9719 return std::nullopt;
9720 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
9721
9722 // If the width of the load does not reach byte we are trying to provide for
9723 // and it is not a ZEXTLOAD, then the load does not provide for the byte in
9724 // question
9725 if (Index >= NarrowByteWidth)
9726 return L->getExtensionType() == ISD::ZEXTLOAD
9727 ? std::optional<SDByteProvider>(
9729 : std::nullopt;
9730
9731 unsigned BPVectorIndex = VectorIndex.value_or(0U);
9732 return SDByteProvider::getSrc(L, Index, BPVectorIndex);
9733 }
9734 }
9735
9736 return std::nullopt;
9737}
9738
9739static unsigned littleEndianByteAt(unsigned BW, unsigned i) {
9740 return i;
9741}
9742
9743static unsigned bigEndianByteAt(unsigned BW, unsigned i) {
9744 return BW - i - 1;
9745}
9746
9747// Check if the bytes offsets we are looking at match with either big or
9748// little endian value loaded. Return true for big endian, false for little
9749// endian, and std::nullopt if match failed.
9750static std::optional<bool> isBigEndian(ArrayRef<int64_t> ByteOffsets,
9751 int64_t FirstOffset) {
9752 // The endian can be decided only when it is 2 bytes at least.
9753 unsigned Width = ByteOffsets.size();
9754 if (Width < 2)
9755 return std::nullopt;
9756
9757 bool BigEndian = true, LittleEndian = true;
9758 for (unsigned i = 0; i < Width; i++) {
9759 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
9760 LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i);
9761 BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i);
9762 if (!BigEndian && !LittleEndian)
9763 return std::nullopt;
9764 }
9765
9766 assert((BigEndian != LittleEndian) && "It should be either big endian or"
9767 "little endian");
9768 return BigEndian;
9769}
9770
9771// Look through one layer of truncate or extend.
9773 switch (Value.getOpcode()) {
9774 case ISD::TRUNCATE:
9775 case ISD::ZERO_EXTEND:
9776 case ISD::SIGN_EXTEND:
9777 case ISD::ANY_EXTEND:
9778 return Value.getOperand(0);
9779 }
9780 return SDValue();
9781}
9782
9783/// Match a pattern where a wide type scalar value is stored by several narrow
9784/// stores. Fold it into a single store or a BSWAP and a store if the targets
9785/// supports it.
9786///
9787/// Assuming little endian target:
9788/// i8 *p = ...
9789/// i32 val = ...
9790/// p[0] = (val >> 0) & 0xFF;
9791/// p[1] = (val >> 8) & 0xFF;
9792/// p[2] = (val >> 16) & 0xFF;
9793/// p[3] = (val >> 24) & 0xFF;
9794/// =>
9795/// *((i32)p) = val;
9796///
9797/// i8 *p = ...
9798/// i32 val = ...
9799/// p[0] = (val >> 24) & 0xFF;
9800/// p[1] = (val >> 16) & 0xFF;
9801/// p[2] = (val >> 8) & 0xFF;
9802/// p[3] = (val >> 0) & 0xFF;
9803/// =>
9804/// *((i32)p) = BSWAP(val);
9805SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) {
9806 // The matching looks for "store (trunc x)" patterns that appear early but are
9807 // likely to be replaced by truncating store nodes during combining.
9808 // TODO: If there is evidence that running this later would help, this
9809 // limitation could be removed. Legality checks may need to be added
9810 // for the created store and optional bswap/rotate.
9811 if (LegalOperations || OptLevel == CodeGenOptLevel::None)
9812 return SDValue();
9813
9814 // We only handle merging simple stores of 1-4 bytes.
9815 // TODO: Allow unordered atomics when wider type is legal (see D66309)
9816 EVT MemVT = N->getMemoryVT();
9817 if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) ||
9818 !N->isSimple() || N->isIndexed())
9819 return SDValue();
9820
9821 // Collect all of the stores in the chain, upto the maximum store width (i64).
9822 SDValue Chain = N->getChain();
9824 unsigned NarrowNumBits = MemVT.getScalarSizeInBits();
9825 unsigned MaxWideNumBits = 64;
9826 unsigned MaxStores = MaxWideNumBits / NarrowNumBits;
9827 while (auto *Store = dyn_cast<StoreSDNode>(Chain)) {
9828 // All stores must be the same size to ensure that we are writing all of the
9829 // bytes in the wide value.
9830 // This store should have exactly one use as a chain operand for another
9831 // store in the merging set. If there are other chain uses, then the
9832 // transform may not be safe because order of loads/stores outside of this
9833 // set may not be preserved.
9834 // TODO: We could allow multiple sizes by tracking each stored byte.
9835 if (Store->getMemoryVT() != MemVT || !Store->isSimple() ||
9836 Store->isIndexed() || !Store->hasOneUse())
9837 return SDValue();
9838 Stores.push_back(Store);
9839 Chain = Store->getChain();
9840 if (MaxStores < Stores.size())
9841 return SDValue();
9842 }
9843 // There is no reason to continue if we do not have at least a pair of stores.
9844 if (Stores.size() < 2)
9845 return SDValue();
9846
9847 // Handle simple types only.
9848 LLVMContext &Context = *DAG.getContext();
9849 unsigned NumStores = Stores.size();
9850 unsigned WideNumBits = NumStores * NarrowNumBits;
9851 if (WideNumBits != 16 && WideNumBits != 32 && WideNumBits != 64)
9852 return SDValue();
9853
9854 // Check if all bytes of the source value that we are looking at are stored
9855 // to the same base address. Collect offsets from Base address into OffsetMap.
9856 SDValue SourceValue;
9857 SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX);
9858 int64_t FirstOffset = INT64_MAX;
9859 StoreSDNode *FirstStore = nullptr;
9860 std::optional<BaseIndexOffset> Base;
9861 for (auto *Store : Stores) {
9862 // All the stores store different parts of the CombinedValue. A truncate is
9863 // required to get the partial value.
9864 SDValue Trunc = Store->getValue();
9865 if (Trunc.getOpcode() != ISD::TRUNCATE)
9866 return SDValue();
9867 // Other than the first/last part, a shift operation is required to get the
9868 // offset.
9869 int64_t Offset = 0;
9870 SDValue WideVal = Trunc.getOperand(0);
9871 if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) &&
9872 isa<ConstantSDNode>(WideVal.getOperand(1))) {
9873 // The shift amount must be a constant multiple of the narrow type.
9874 // It is translated to the offset address in the wide source value "y".
9875 //
9876 // x = srl y, ShiftAmtC
9877 // i8 z = trunc x
9878 // store z, ...
9879 uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1);
9880 if (ShiftAmtC % NarrowNumBits != 0)
9881 return SDValue();
9882
9883 // Make sure we aren't reading bits that are shifted in.
9884 if (ShiftAmtC > WideVal.getScalarValueSizeInBits() - NarrowNumBits)
9885 return SDValue();
9886
9887 Offset = ShiftAmtC / NarrowNumBits;
9888 WideVal = WideVal.getOperand(0);
9889 }
9890
9891 // Stores must share the same source value with different offsets.
9892 if (!SourceValue)
9893 SourceValue = WideVal;
9894 else if (SourceValue != WideVal) {
9895 // Truncate and extends can be stripped to see if the values are related.
9896 if (stripTruncAndExt(SourceValue) != WideVal &&
9897 stripTruncAndExt(WideVal) != SourceValue)
9898 return SDValue();
9899
9900 if (WideVal.getScalarValueSizeInBits() >
9901 SourceValue.getScalarValueSizeInBits())
9902 SourceValue = WideVal;
9903
9904 // Give up if the source value type is smaller than the store size.
9905 if (SourceValue.getScalarValueSizeInBits() < WideNumBits)
9906 return SDValue();
9907 }
9908
9909 // Stores must share the same base address.
9910 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
9911 int64_t ByteOffsetFromBase = 0;
9912 if (!Base)
9913 Base = Ptr;
9914 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
9915 return SDValue();
9916
9917 // Remember the first store.
9918 if (ByteOffsetFromBase < FirstOffset) {
9919 FirstStore = Store;
9920 FirstOffset = ByteOffsetFromBase;
9921 }
9922 // Map the offset in the store and the offset in the combined value, and
9923 // early return if it has been set before.
9924 if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX)
9925 return SDValue();
9926 OffsetMap[Offset] = ByteOffsetFromBase;
9927 }
9928
9929 EVT WideVT = EVT::getIntegerVT(Context, WideNumBits);
9930
9931 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
9932 assert(FirstStore && "First store must be set");
9933
9934 // Check that a store of the wide type is both allowed and fast on the target
9935 const DataLayout &Layout = DAG.getDataLayout();
9936 unsigned Fast = 0;
9937 bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT,
9938 *FirstStore->getMemOperand(), &Fast);
9939 if (!Allowed || !Fast)
9940 return SDValue();
9941
9942 // Check if the pieces of the value are going to the expected places in memory
9943 // to merge the stores.
9944 auto checkOffsets = [&](bool MatchLittleEndian) {
9945 if (MatchLittleEndian) {
9946 for (unsigned i = 0; i != NumStores; ++i)
9947 if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset)
9948 return false;
9949 } else { // MatchBigEndian by reversing loop counter.
9950 for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j)
9951 if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset)
9952 return false;
9953 }
9954 return true;
9955 };
9956
9957 // Check if the offsets line up for the native data layout of this target.
9958 bool NeedBswap = false;
9959 bool NeedRotate = false;
9960 if (!checkOffsets(Layout.isLittleEndian())) {
9961 // Special-case: check if byte offsets line up for the opposite endian.
9962 if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian()))
9963 NeedBswap = true;
9964 else if (NumStores == 2 && checkOffsets(Layout.isBigEndian()))
9965 NeedRotate = true;
9966 else
9967 return SDValue();
9968 }
9969
9970 SDLoc DL(N);
9971 if (WideVT != SourceValue.getValueType()) {
9972 assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&
9973 "Unexpected store value to merge");
9974 SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue);
9975 }
9976
9977 // Before legalize we can introduce illegal bswaps/rotates which will be later
9978 // converted to an explicit bswap sequence. This way we end up with a single
9979 // store and byte shuffling instead of several stores and byte shuffling.
9980 if (NeedBswap) {
9981 SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue);
9982 } else if (NeedRotate) {
9983 assert(WideNumBits % 2 == 0 && "Unexpected type for rotate");
9984 SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT);
9985 SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt);
9986 }
9987
9988 SDValue NewStore =
9989 DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(),
9990 FirstStore->getPointerInfo(), FirstStore->getAlign());
9991
9992 // Rely on other DAG combine rules to remove the other individual stores.
9993 DAG.ReplaceAllUsesWith(N, NewStore.getNode());
9994 return NewStore;
9995}
9996
9997/// Match a pattern where a wide type scalar value is loaded by several narrow
9998/// loads and combined by shifts and ors. Fold it into a single load or a load
9999/// and a BSWAP if the targets supports it.
10000///
10001/// Assuming little endian target:
10002/// i8 *a = ...
10003/// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
10004/// =>
10005/// i32 val = *((i32)a)
10006///
10007/// i8 *a = ...
10008/// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
10009/// =>
10010/// i32 val = BSWAP(*((i32)a))
10011///
10012/// TODO: This rule matches complex patterns with OR node roots and doesn't
10013/// interact well with the worklist mechanism. When a part of the pattern is
10014/// updated (e.g. one of the loads) its direct users are put into the worklist,
10015/// but the root node of the pattern which triggers the load combine is not
10016/// necessarily a direct user of the changed node. For example, once the address
10017/// of t28 load is reassociated load combine won't be triggered:
10018/// t25: i32 = add t4, Constant:i32<2>
10019/// t26: i64 = sign_extend t25
10020/// t27: i64 = add t2, t26
10021/// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
10022/// t29: i32 = zero_extend t28
10023/// t32: i32 = shl t29, Constant:i8<8>
10024/// t33: i32 = or t23, t32
10025/// As a possible fix visitLoad can check if the load can be a part of a load
10026/// combine pattern and add corresponding OR roots to the worklist.
10027SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
10028 assert(N->getOpcode() == ISD::OR &&
10029 "Can only match load combining against OR nodes");
10030
10031 // Handles simple types only
10032 EVT VT = N->getValueType(0);
10033 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10034 return SDValue();
10035 unsigned ByteWidth = VT.getSizeInBits() / 8;
10036
10037 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
10038 auto MemoryByteOffset = [&](SDByteProvider P) {
10039 assert(P.hasSrc() && "Must be a memory byte provider");
10040 auto *Load = cast<LoadSDNode>(P.Src.value());
10041
10042 unsigned LoadBitWidth = Load->getMemoryVT().getScalarSizeInBits();
10043
10044 assert(LoadBitWidth % 8 == 0 &&
10045 "can only analyze providers for individual bytes not bit");
10046 unsigned LoadByteWidth = LoadBitWidth / 8;
10047 return IsBigEndianTarget ? bigEndianByteAt(LoadByteWidth, P.DestOffset)
10048 : littleEndianByteAt(LoadByteWidth, P.DestOffset);
10049 };
10050
10051 std::optional<BaseIndexOffset> Base;
10052 SDValue Chain;
10053
10054 SmallPtrSet<LoadSDNode *, 8> Loads;
10055 std::optional<SDByteProvider> FirstByteProvider;
10056 int64_t FirstOffset = INT64_MAX;
10057
10058 // Check if all the bytes of the OR we are looking at are loaded from the same
10059 // base address. Collect bytes offsets from Base address in ByteOffsets.
10060 SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
10061 unsigned ZeroExtendedBytes = 0;
10062 for (int i = ByteWidth - 1; i >= 0; --i) {
10063 auto P =
10064 calculateByteProvider(SDValue(N, 0), i, 0, /*VectorIndex*/ std::nullopt,
10065 /*StartingIndex*/ i);
10066 if (!P)
10067 return SDValue();
10068
10069 if (P->isConstantZero()) {
10070 // It's OK for the N most significant bytes to be 0, we can just
10071 // zero-extend the load.
10072 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
10073 return SDValue();
10074 continue;
10075 }
10076 assert(P->hasSrc() && "provenance should either be memory or zero");
10077 auto *L = cast<LoadSDNode>(P->Src.value());
10078
10079 // All loads must share the same chain
10080 SDValue LChain = L->getChain();
10081 if (!Chain)
10082 Chain = LChain;
10083 else if (Chain != LChain)
10084 return SDValue();
10085
10086 // Loads must share the same base address
10087 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
10088 int64_t ByteOffsetFromBase = 0;
10089
10090 // For vector loads, the expected load combine pattern will have an
10091 // ExtractElement for each index in the vector. While each of these
10092 // ExtractElements will be accessing the same base address as determined
10093 // by the load instruction, the actual bytes they interact with will differ
10094 // due to different ExtractElement indices. To accurately determine the
10095 // byte position of an ExtractElement, we offset the base load ptr with
10096 // the index multiplied by the byte size of each element in the vector.
10097 if (L->getMemoryVT().isVector()) {
10098 unsigned LoadWidthInBit = L->getMemoryVT().getScalarSizeInBits();
10099 if (LoadWidthInBit % 8 != 0)
10100 return SDValue();
10101 unsigned ByteOffsetFromVector = P->SrcOffset * LoadWidthInBit / 8;
10102 Ptr.addToOffset(ByteOffsetFromVector);
10103 }
10104
10105 if (!Base)
10106 Base = Ptr;
10107
10108 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
10109 return SDValue();
10110
10111 // Calculate the offset of the current byte from the base address
10112 ByteOffsetFromBase += MemoryByteOffset(*P);
10113 ByteOffsets[i] = ByteOffsetFromBase;
10114
10115 // Remember the first byte load
10116 if (ByteOffsetFromBase < FirstOffset) {
10117 FirstByteProvider = P;
10118 FirstOffset = ByteOffsetFromBase;
10119 }
10120
10121 Loads.insert(L);
10122 }
10123
10124 assert(!Loads.empty() && "All the bytes of the value must be loaded from "
10125 "memory, so there must be at least one load which produces the value");
10126 assert(Base && "Base address of the accessed memory location must be set");
10127 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
10128
10129 bool NeedsZext = ZeroExtendedBytes > 0;
10130
10131 EVT MemVT =
10132 EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
10133
10134 if (!MemVT.isSimple())
10135 return SDValue();
10136
10137 // Check if the bytes of the OR we are looking at match with either big or
10138 // little endian value load
10139 std::optional<bool> IsBigEndian = isBigEndian(
10140 ArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
10141 if (!IsBigEndian)
10142 return SDValue();
10143
10144 assert(FirstByteProvider && "must be set");
10145
10146 // Ensure that the first byte is loaded from zero offset of the first load.
10147 // So the combined value can be loaded from the first load address.
10148 if (MemoryByteOffset(*FirstByteProvider) != 0)
10149 return SDValue();
10150 auto *FirstLoad = cast<LoadSDNode>(FirstByteProvider->Src.value());
10151
10152 // Before legalization we allow introducing loads that are wider than legal,
10153 // which will later be split into legally sized loads. This enables us to
10154 // combine, for example, i8 loads forming an i64 into an i64 load, which get
10155 // then gets split up into couple of i32 loads on 32 bit targets.
10156 if (LegalOperations &&
10157 !TLI.isLoadLegal(VT, MemVT, FirstLoad->getAlign(),
10158 FirstLoad->getAddressSpace(),
10159 NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, false))
10160 return SDValue();
10161
10162 // The node we are looking at matches with the pattern, check if we can
10163 // replace it with a single (possibly zero-extended) load and bswap + shift if
10164 // needed.
10165
10166 // If the load needs byte swap check if the target supports it
10167 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
10168
10169 // Before legalize we can introduce illegal bswaps which will be later
10170 // converted to an explicit bswap sequence. This way we end up with a single
10171 // load and byte shuffling instead of several loads and byte shuffling.
10172 // We do not introduce illegal bswaps when zero-extending as this tends to
10173 // introduce too many arithmetic instructions.
10174 if (NeedsBswap && (LegalOperations || NeedsZext) &&
10175 !TLI.isOperationLegal(ISD::BSWAP, VT))
10176 return SDValue();
10177
10178 // If we need to bswap and zero extend, we have to insert a shift. Check that
10179 // it is legal.
10180 if (NeedsBswap && NeedsZext && LegalOperations &&
10181 !TLI.isOperationLegal(ISD::SHL, VT))
10182 return SDValue();
10183
10184 // Check that a load of the wide type is both allowed and fast on the target
10185 unsigned Fast = 0;
10186 bool Allowed =
10187 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
10188 *FirstLoad->getMemOperand(), &Fast);
10189 if (!Allowed || !Fast)
10190 return SDValue();
10191
10192 SDValue NewLoad =
10193 DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT,
10194 Chain, FirstLoad->getBasePtr(),
10195 FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign());
10196
10197 // Transfer chain users from old loads to the new load.
10198 for (LoadSDNode *L : Loads)
10199 DAG.makeEquivalentMemoryOrdering(L, NewLoad);
10200
10201 if (!NeedsBswap)
10202 return NewLoad;
10203
10204 SDValue ShiftedLoad =
10205 NeedsZext ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
10206 DAG.getShiftAmountConstant(ZeroExtendedBytes * 8,
10207 VT, SDLoc(N)))
10208 : NewLoad;
10209 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
10210}
10211
10212// If the target has andn, bsl, or a similar bit-select instruction,
10213// we want to unfold masked merge, with canonical pattern of:
10214// | A | |B|
10215// ((x ^ y) & m) ^ y
10216// | D |
10217// Into:
10218// (x & m) | (y & ~m)
10219// If y is a constant, m is not a 'not', and the 'andn' does not work with
10220// immediates, we unfold into a different pattern:
10221// ~(~x & m) & (m | y)
10222// If x is a constant, m is a 'not', and the 'andn' does not work with
10223// immediates, we unfold into a different pattern:
10224// (x | ~m) & ~(~m & ~y)
10225// NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
10226// the very least that breaks andnpd / andnps patterns, and because those
10227// patterns are simplified in IR and shouldn't be created in the DAG
10228SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
10229 assert(N->getOpcode() == ISD::XOR);
10230
10231 // Don't touch 'not' (i.e. where y = -1).
10232 if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
10233 return SDValue();
10234
10235 EVT VT = N->getValueType(0);
10236
10237 // There are 3 commutable operators in the pattern,
10238 // so we have to deal with 8 possible variants of the basic pattern.
10239 SDValue X, Y, M;
10240 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
10241 if (And.getOpcode() != ISD::AND || !And.hasOneUse())
10242 return false;
10243 SDValue Xor = And.getOperand(XorIdx);
10244 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
10245 return false;
10246 SDValue Xor0 = Xor.getOperand(0);
10247 SDValue Xor1 = Xor.getOperand(1);
10248 // Don't touch 'not' (i.e. where y = -1).
10249 if (isAllOnesOrAllOnesSplat(Xor1))
10250 return false;
10251 if (Other == Xor0)
10252 std::swap(Xor0, Xor1);
10253 if (Other != Xor1)
10254 return false;
10255 X = Xor0;
10256 Y = Xor1;
10257 M = And.getOperand(XorIdx ? 0 : 1);
10258 return true;
10259 };
10260
10261 SDValue N0 = N->getOperand(0);
10262 SDValue N1 = N->getOperand(1);
10263 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
10264 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
10265 return SDValue();
10266
10267 // Don't do anything if the mask is constant. This should not be reachable.
10268 // InstCombine should have already unfolded this pattern, and DAGCombiner
10269 // probably shouldn't produce it, too.
10270 if (isa<ConstantSDNode>(M.getNode()))
10271 return SDValue();
10272
10273 // We can transform if the target has AndNot
10274 if (!TLI.hasAndNot(M))
10275 return SDValue();
10276
10277 SDLoc DL(N);
10278
10279 // If Y is a constant, check that 'andn' works with immediates. Unless M is
10280 // a bitwise not that would already allow ANDN to be used.
10281 if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) {
10282 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
10283 // If not, we need to do a bit more work to make sure andn is still used.
10284 SDValue NotX = DAG.getNOT(DL, X, VT);
10285 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
10286 SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
10287 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
10288 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
10289 }
10290
10291 // If X is a constant and M is a bitwise not, check that 'andn' works with
10292 // immediates.
10293 if (!TLI.hasAndNot(X) && isBitwiseNot(M)) {
10294 assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable.");
10295 // If not, we need to do a bit more work to make sure andn is still used.
10296 SDValue NotM = M.getOperand(0);
10297 SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM);
10298 SDValue NotY = DAG.getNOT(DL, Y, VT);
10299 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY);
10300 SDValue NotRHS = DAG.getNOT(DL, RHS, VT);
10301 return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS);
10302 }
10303
10304 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
10305 SDValue NotM = DAG.getNOT(DL, M, VT);
10306 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
10307
10308 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
10309}
10310
10311SDValue DAGCombiner::visitXOR(SDNode *N) {
10312 SDValue N0 = N->getOperand(0);
10313 SDValue N1 = N->getOperand(1);
10314 EVT VT = N0.getValueType();
10315 SDLoc DL(N);
10316
10317 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
10318 if (N0.isUndef() && N1.isUndef())
10319 return DAG.getConstant(0, DL, VT);
10320
10321 // fold (xor x, undef) -> undef
10322 if (N0.isUndef())
10323 return N0;
10324 if (N1.isUndef())
10325 return N1;
10326
10327 // fold (xor c1, c2) -> c1^c2
10328 if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
10329 return C;
10330
10331 // canonicalize constant to RHS
10334 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
10335
10336 // fold vector ops
10337 if (VT.isVector()) {
10338 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
10339 return FoldedVOp;
10340
10341 // fold (xor x, 0) -> x, vector edition
10343 return N0;
10344 }
10345
10346 // fold (xor x, 0) -> x
10347 if (isNullConstant(N1))
10348 return N0;
10349
10350 if (SDValue NewSel = foldBinOpIntoSelect(N))
10351 return NewSel;
10352
10353 // reassociate xor
10354 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
10355 return RXOR;
10356
10357 // Fold xor(vecreduce(x), vecreduce(y)) -> vecreduce(xor(x, y))
10358 if (SDValue SD =
10359 reassociateReduction(ISD::VECREDUCE_XOR, ISD::XOR, DL, VT, N0, N1))
10360 return SD;
10361
10362 // fold (a^b) -> (a|b) iff a and b share no bits.
10363 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
10364 DAG.haveNoCommonBitsSet(N0, N1))
10365 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
10366
10367 // look for 'add-like' folds:
10368 // XOR(N0,MIN_SIGNED_VALUE) == ADD(N0,MIN_SIGNED_VALUE)
10369 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
10371 if (SDValue Combined = visitADDLike(N))
10372 return Combined;
10373
10374 // fold not (setcc x, y, cc) -> setcc x y !cc
10375 // Avoid breaking: and (not(setcc x, y, cc), z) -> andn for vec
10376 unsigned N0Opcode = N0.getOpcode();
10377 SDValue LHS, RHS, CC;
10378 if (TLI.isConstTrueVal(N1) &&
10379 isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/ true) &&
10380 !(VT.isVector() && TLI.hasAndNot(SDValue(N, 0)) && N->hasOneUse() &&
10381 N->use_begin()->getUser()->getOpcode() == ISD::AND)) {
10383 LHS.getValueType());
10384 if (!LegalOperations ||
10385 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
10386 // Propagate fast-math-flags.
10387 SDNodeFlags Flags = N0->getFlags();
10388 switch (N0Opcode) {
10389 default:
10390 llvm_unreachable("Unhandled SetCC Equivalent!");
10391 case ISD::SETCC:
10392 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, SDValue(),
10393 /*IsSignaling=*/false, Flags);
10394 case ISD::SELECT_CC:
10395 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
10396 N0.getOperand(3), NotCC, Flags);
10397 case ISD::STRICT_FSETCC:
10398 case ISD::STRICT_FSETCCS: {
10399 if (N0.hasOneUse()) {
10400 // FIXME Can we handle multiple uses? Could we token factor the chain
10401 // results from the new/old setcc?
10402 SDValue SetCC =
10403 DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, N0.getOperand(0),
10404 N0Opcode == ISD::STRICT_FSETCCS, Flags);
10405 CombineTo(N, SetCC);
10406 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
10407 recursivelyDeleteUnusedNodes(N0.getNode());
10408 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10409 }
10410 break;
10411 }
10412 }
10413 }
10414 }
10415
10416 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
10417 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
10418 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
10419 SDValue V = N0.getOperand(0);
10420 SDLoc DL0(N0);
10421 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
10422 DAG.getConstant(1, DL0, V.getValueType()));
10423 AddToWorklist(V.getNode());
10424 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
10425 }
10426
10427 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
10428 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are setcc
10429 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
10430 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10431 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10432 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
10433 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10434 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10435 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10436 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10437 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10438 }
10439 }
10440 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
10441 // fold (not (and x, y)) -> (or (not x), (not y)) iff x or y are constants
10442 if (isAllOnesConstant(N1) && N0.hasOneUse() &&
10443 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
10444 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
10445 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
10446 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
10447 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
10448 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
10449 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
10450 return DAG.getNode(NewOpcode, DL, VT, N00, N01);
10451 }
10452 }
10453
10454 // fold (not (sub Y, X)) -> (add X, ~Y) if Y is a constant
10455 if (N0.getOpcode() == ISD::SUB && isAllOnesConstant(N1)) {
10456 SDValue Y = N0.getOperand(0);
10457 SDValue X = N0.getOperand(1);
10458
10459 if (auto *YConst = dyn_cast<ConstantSDNode>(Y)) {
10460 APInt NotYValue = ~YConst->getAPIntValue();
10461 SDValue NotY = DAG.getConstant(NotYValue, DL, VT);
10462 return DAG.getNode(ISD::ADD, DL, VT, X, NotY, N->getFlags());
10463 }
10464 }
10465
10466 // fold (not (add X, -1)) -> (neg X)
10467 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && isAllOnesConstant(N1) &&
10469 return DAG.getNegative(N0.getOperand(0), DL, VT);
10470 }
10471
10472 // fold (xor (and x, y), y) -> (and (not x), y)
10473 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
10474 SDValue X = N0.getOperand(0);
10475 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
10476 AddToWorklist(NotX.getNode());
10477 return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
10478 }
10479
10480 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
10481 if (!LegalOperations || hasOperation(ISD::ABS, VT)) {
10482 SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
10483 SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
10484 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
10485 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
10486 SDValue S0 = S.getOperand(0);
10487 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0))
10488 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
10489 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
10490 return DAG.getNode(ISD::ABS, DL, VT, S0);
10491 }
10492 }
10493
10494 // fold (xor x, x) -> 0
10495 if (N0 == N1)
10496 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
10497
10498 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
10499 // Here is a concrete example of this equivalence:
10500 // i16 x == 14
10501 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
10502 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
10503 //
10504 // =>
10505 //
10506 // i16 ~1 == 0b1111111111111110
10507 // i16 rol(~1, 14) == 0b1011111111111111
10508 //
10509 // Some additional tips to help conceptualize this transform:
10510 // - Try to see the operation as placing a single zero in a value of all ones.
10511 // - There exists no value for x which would allow the result to contain zero.
10512 // - Values of x larger than the bitwidth are undefined and do not require a
10513 // consistent result.
10514 // - Pushing the zero left requires shifting one bits in from the right.
10515 // A rotate left of ~1 is a nice way of achieving the desired result.
10516 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
10518 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getSignedConstant(~1, DL, VT),
10519 N0.getOperand(1));
10520 }
10521
10522 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
10523 if (N0Opcode == N1.getOpcode())
10524 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
10525 return V;
10526
10527 if (SDValue R = foldLogicOfShifts(N, N0, N1, DAG))
10528 return R;
10529 if (SDValue R = foldLogicOfShifts(N, N1, N0, DAG))
10530 return R;
10531 if (SDValue R = foldLogicTreeOfShifts(N, N0, N1, DAG))
10532 return R;
10533
10534 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
10535 if (SDValue MM = unfoldMaskedMerge(N))
10536 return MM;
10537
10538 // Simplify the expression using non-local knowledge.
10540 return SDValue(N, 0);
10541
10542 if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
10543 return Combined;
10544
10545 // fold (xor (smin(x, C), C)) -> select (x < C), xor(x, C), 0
10546 // fold (xor (smax(x, C), C)) -> select (x > C), xor(x, C), 0
10547 // fold (xor (umin(x, C), C)) -> select (x < C), xor(x, C), 0
10548 // fold (xor (umax(x, C), C)) -> select (x > C), xor(x, C), 0
10549 SDValue Op0;
10550 if (sd_match(N0, m_OneUse(m_AnyOf(m_SMin(m_Value(Op0), m_Specific(N1)),
10551 m_SMax(m_Value(Op0), m_Specific(N1)),
10552 m_UMin(m_Value(Op0), m_Specific(N1)),
10553 m_UMax(m_Value(Op0), m_Specific(N1)))))) {
10554
10555 if (isa<ConstantSDNode>(N1) ||
10557 // For vectors, only optimize when the constant is zero or all-ones to
10558 // avoid generating more instructions
10559 if (VT.isVector()) {
10560 ConstantSDNode *N1C = isConstOrConstSplat(N1);
10561 if (!N1C || (!N1C->isZero() && !N1C->isAllOnes()))
10562 return SDValue();
10563 }
10564
10565 // Avoid the fold if the minmax operation is legal and select is expensive
10566 if (TLI.isOperationLegal(N0.getOpcode(), VT) &&
10568 return SDValue();
10569
10570 EVT CCVT = getSetCCResultType(VT);
10571 ISD::CondCode CC;
10572 switch (N0.getOpcode()) {
10573 case ISD::SMIN:
10574 CC = ISD::SETLT;
10575 break;
10576 case ISD::SMAX:
10577 CC = ISD::SETGT;
10578 break;
10579 case ISD::UMIN:
10580 CC = ISD::SETULT;
10581 break;
10582 case ISD::UMAX:
10583 CC = ISD::SETUGT;
10584 break;
10585 }
10586 SDValue FN1 = DAG.getFreeze(N1);
10587 SDValue Cmp = DAG.getSetCC(DL, CCVT, Op0, FN1, CC);
10588 SDValue XorXC = DAG.getNode(ISD::XOR, DL, VT, Op0, FN1);
10589 SDValue Zero = DAG.getConstant(0, DL, VT);
10590 return DAG.getSelect(DL, VT, Cmp, XorXC, Zero);
10591 }
10592 }
10593
10594 return SDValue();
10595}
10596
10597/// If we have a shift-by-constant of a bitwise logic op that itself has a
10598/// shift-by-constant operand with identical opcode, we may be able to convert
10599/// that into 2 independent shifts followed by the logic op. This is a
10600/// throughput improvement.
10602 // Match a one-use bitwise logic op.
10603 SDValue LogicOp = Shift->getOperand(0);
10604 if (!LogicOp.hasOneUse())
10605 return SDValue();
10606
10607 unsigned LogicOpcode = LogicOp.getOpcode();
10608 if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
10609 LogicOpcode != ISD::XOR)
10610 return SDValue();
10611
10612 // Find a matching one-use shift by constant.
10613 unsigned ShiftOpcode = Shift->getOpcode();
10614 SDValue C1 = Shift->getOperand(1);
10615 ConstantSDNode *C1Node = isConstOrConstSplat(C1);
10616 assert(C1Node && "Expected a shift with constant operand");
10617 const APInt &C1Val = C1Node->getAPIntValue();
10618 auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
10619 const APInt *&ShiftAmtVal) {
10620 if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
10621 return false;
10622
10623 ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
10624 if (!ShiftCNode)
10625 return false;
10626
10627 // Capture the shifted operand and shift amount value.
10628 ShiftOp = V.getOperand(0);
10629 ShiftAmtVal = &ShiftCNode->getAPIntValue();
10630
10631 // Shift amount types do not have to match their operand type, so check that
10632 // the constants are the same width.
10633 if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
10634 return false;
10635
10636 // The fold is not valid if the sum of the shift values doesn't fit in the
10637 // given shift amount type.
10638 bool Overflow = false;
10639 APInt NewShiftAmt = C1Val.uadd_ov(*ShiftAmtVal, Overflow);
10640 if (Overflow)
10641 return false;
10642
10643 // The fold is not valid if the sum of the shift values exceeds bitwidth.
10644 if (NewShiftAmt.uge(V.getScalarValueSizeInBits()))
10645 return false;
10646
10647 return true;
10648 };
10649
10650 // Logic ops are commutative, so check each operand for a match.
10651 SDValue X, Y;
10652 const APInt *C0Val;
10653 if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
10654 Y = LogicOp.getOperand(1);
10655 else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
10656 Y = LogicOp.getOperand(0);
10657 else
10658 return SDValue();
10659
10660 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
10661 SDLoc DL(Shift);
10662 EVT VT = Shift->getValueType(0);
10663 EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
10664 SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
10665 SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
10666 SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
10667 return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2,
10668 LogicOp->getFlags());
10669}
10670
10671/// Handle transforms common to the three shifts, when the shift amount is a
10672/// constant.
10673/// We are looking for: (shift being one of shl/sra/srl)
10674/// shift (binop X, C0), C1
10675/// And want to transform into:
10676/// binop (shift X, C1), (shift C0, C1)
10677SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
10678 assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
10679
10680 // Do not turn a 'not' into a regular xor.
10681 if (isBitwiseNot(N->getOperand(0)))
10682 return SDValue();
10683
10684 // The inner binop must be one-use, since we want to replace it.
10685 SDValue LHS = N->getOperand(0);
10686 if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
10687 return SDValue();
10688
10689 // Fold shift(bitop(shift(x,c1),y), c2) -> bitop(shift(x,c1+c2),shift(y,c2)).
10690 if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
10691 return R;
10692
10693 // We want to pull some binops through shifts, so that we have (and (shift))
10694 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
10695 // thing happens with address calculations, so it's important to canonicalize
10696 // it.
10697 switch (LHS.getOpcode()) {
10698 default:
10699 return SDValue();
10700 case ISD::OR:
10701 case ISD::XOR:
10702 case ISD::AND:
10703 break;
10704 case ISD::ADD:
10705 if (N->getOpcode() != ISD::SHL)
10706 return SDValue(); // only shl(add) not sr[al](add).
10707 break;
10708 }
10709
10710 // FIXME: disable this unless the input to the binop is a shift by a constant
10711 // or is copy/select. Enable this in other cases when figure out it's exactly
10712 // profitable.
10713 SDValue BinOpLHSVal = LHS.getOperand(0);
10714 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
10715 BinOpLHSVal.getOpcode() == ISD::SRA ||
10716 BinOpLHSVal.getOpcode() == ISD::SRL) &&
10717 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
10718 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
10719 BinOpLHSVal.getOpcode() == ISD::SELECT;
10720
10721 if (!IsShiftByConstant && !IsCopyOrSelect)
10722 return SDValue();
10723
10724 if (IsCopyOrSelect && N->hasOneUse())
10725 return SDValue();
10726
10727 // Attempt to fold the constants, shifting the binop RHS by the shift amount.
10728 SDLoc DL(N);
10729 EVT VT = N->getValueType(0);
10730 if (SDValue NewRHS = DAG.FoldConstantArithmetic(
10731 N->getOpcode(), DL, VT, {LHS.getOperand(1), N->getOperand(1)})) {
10732 SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
10733 N->getOperand(1));
10734 return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
10735 }
10736
10737 return SDValue();
10738}
10739
10740SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
10741 assert(N->getOpcode() == ISD::TRUNCATE);
10742 assert(N->getOperand(0).getOpcode() == ISD::AND);
10743
10744 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
10745 EVT TruncVT = N->getValueType(0);
10746 if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
10747 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
10748 SDValue N01 = N->getOperand(0).getOperand(1);
10749 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
10750 SDLoc DL(N);
10751 SDValue N00 = N->getOperand(0).getOperand(0);
10752 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
10753 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
10754 AddToWorklist(Trunc00.getNode());
10755 AddToWorklist(Trunc01.getNode());
10756 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
10757 }
10758 }
10759
10760 return SDValue();
10761}
10762
10763SDValue DAGCombiner::visitRotate(SDNode *N) {
10764 SDLoc dl(N);
10765 SDValue N0 = N->getOperand(0);
10766 SDValue N1 = N->getOperand(1);
10767 EVT VT = N->getValueType(0);
10768 unsigned Bitsize = VT.getScalarSizeInBits();
10769
10770 // fold (rot x, 0) -> x
10771 if (isNullOrNullSplat(N1))
10772 return N0;
10773
10774 // fold (rot x, c) -> x iff (c % BitSize) == 0
10775 if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
10776 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
10777 if (DAG.MaskedValueIsZero(N1, ModuloMask))
10778 return N0;
10779 }
10780
10781 // fold (rot x, c) -> (rot x, c % BitSize)
10782 bool OutOfRange = false;
10783 auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
10784 OutOfRange |= C->getAPIntValue().uge(Bitsize);
10785 return true;
10786 };
10787 if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
10788 EVT AmtVT = N1.getValueType();
10789 SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
10790 if (SDValue Amt =
10791 DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
10792 return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
10793 }
10794
10795 // rot i16 X, 8 --> bswap X
10796 auto *RotAmtC = isConstOrConstSplat(N1);
10797 if (RotAmtC && RotAmtC->getAPIntValue() == 8 &&
10798 VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT))
10799 return DAG.getNode(ISD::BSWAP, dl, VT, N0);
10800
10801 // Simplify the operands using demanded-bits information.
10803 return SDValue(N, 0);
10804
10805 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
10806 if (N1.getOpcode() == ISD::TRUNCATE &&
10807 N1.getOperand(0).getOpcode() == ISD::AND) {
10808 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
10809 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
10810 }
10811
10812 unsigned NextOp = N0.getOpcode();
10813
10814 // fold (rot* (rot* x, c2), c1)
10815 // -> (rot* x, ((c1 % bitsize) +- (c2 % bitsize) + bitsize) % bitsize)
10816 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
10817 bool C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
10819 if (C1 && C2 && N1.getValueType() == N0.getOperand(1).getValueType()) {
10820 EVT ShiftVT = N1.getValueType();
10821 bool SameSide = (N->getOpcode() == NextOp);
10822 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
10823 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
10824 SDValue Norm1 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10825 {N1, BitsizeC});
10826 SDValue Norm2 = DAG.FoldConstantArithmetic(ISD::UREM, dl, ShiftVT,
10827 {N0.getOperand(1), BitsizeC});
10828 if (Norm1 && Norm2)
10829 if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
10830 CombineOp, dl, ShiftVT, {Norm1, Norm2})) {
10831 CombinedShift = DAG.FoldConstantArithmetic(ISD::ADD, dl, ShiftVT,
10832 {CombinedShift, BitsizeC});
10833 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
10834 ISD::UREM, dl, ShiftVT, {CombinedShift, BitsizeC});
10835 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
10836 CombinedShiftNorm);
10837 }
10838 }
10839 }
10840 return SDValue();
10841}
10842
10843SDValue DAGCombiner::visitSHL(SDNode *N) {
10844 SDValue N0 = N->getOperand(0);
10845 SDValue N1 = N->getOperand(1);
10846 if (SDValue V = DAG.simplifyShift(N0, N1))
10847 return V;
10848
10849 SDLoc DL(N);
10850 EVT VT = N0.getValueType();
10851 EVT ShiftVT = N1.getValueType();
10852 unsigned OpSizeInBits = VT.getScalarSizeInBits();
10853
10854 // fold (shl c1, c2) -> c1<<c2
10855 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N0, N1}))
10856 return C;
10857
10858 // fold vector ops
10859 if (VT.isVector()) {
10860 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
10861 return FoldedVOp;
10862
10863 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
10864 // If setcc produces all-one true value then:
10865 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
10866 if (N1CV && N1CV->isConstant()) {
10867 if (N0.getOpcode() == ISD::AND) {
10868 SDValue N00 = N0->getOperand(0);
10869 SDValue N01 = N0->getOperand(1);
10870 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
10871
10872 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
10875 if (SDValue C =
10876 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N01, N1}))
10877 return DAG.getNode(ISD::AND, DL, VT, N00, C);
10878 }
10879 }
10880 }
10881 }
10882
10883 if (SDValue NewSel = foldBinOpIntoSelect(N))
10884 return NewSel;
10885
10886 // if (shl x, c) is known to be zero, return 0
10887 if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
10888 return DAG.getConstant(0, DL, VT);
10889
10890 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
10891 if (N1.getOpcode() == ISD::TRUNCATE &&
10892 N1.getOperand(0).getOpcode() == ISD::AND) {
10893 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
10894 return DAG.getNode(ISD::SHL, DL, VT, N0, NewOp1);
10895 }
10896
10897 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
10898 if (N0.getOpcode() == ISD::SHL) {
10899 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
10900 ConstantSDNode *RHS) {
10901 APInt c1 = LHS->getAPIntValue();
10902 APInt c2 = RHS->getAPIntValue();
10903 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10904 return (c1 + c2).uge(OpSizeInBits);
10905 };
10906 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
10907 return DAG.getConstant(0, DL, VT);
10908
10909 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
10910 ConstantSDNode *RHS) {
10911 APInt c1 = LHS->getAPIntValue();
10912 APInt c2 = RHS->getAPIntValue();
10913 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10914 return (c1 + c2).ult(OpSizeInBits);
10915 };
10916 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
10917 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
10918 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
10919 }
10920 }
10921
10922 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
10923 // For this to be valid, the second form must not preserve any of the bits
10924 // that are shifted out by the inner shift in the first form. This means
10925 // the outer shift size must be >= the number of bits added by the ext.
10926 // As a corollary, we don't care what kind of ext it is.
10927 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
10928 N0.getOpcode() == ISD::ANY_EXTEND ||
10929 N0.getOpcode() == ISD::SIGN_EXTEND) &&
10930 N0.getOperand(0).getOpcode() == ISD::SHL) {
10931 SDValue N0Op0 = N0.getOperand(0);
10932 SDValue InnerShiftAmt = N0Op0.getOperand(1);
10933 EVT InnerVT = N0Op0.getValueType();
10934 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
10935
10936 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
10937 ConstantSDNode *RHS) {
10938 APInt c1 = LHS->getAPIntValue();
10939 APInt c2 = RHS->getAPIntValue();
10940 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10941 return c2.uge(OpSizeInBits - InnerBitwidth) &&
10942 (c1 + c2).uge(OpSizeInBits);
10943 };
10944 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
10945 /*AllowUndefs*/ false,
10946 /*AllowTypeMismatch*/ true))
10947 return DAG.getConstant(0, DL, VT);
10948
10949 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
10950 ConstantSDNode *RHS) {
10951 APInt c1 = LHS->getAPIntValue();
10952 APInt c2 = RHS->getAPIntValue();
10953 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
10954 return c2.uge(OpSizeInBits - InnerBitwidth) &&
10955 (c1 + c2).ult(OpSizeInBits);
10956 };
10957 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
10958 /*AllowUndefs*/ false,
10959 /*AllowTypeMismatch*/ true)) {
10960 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
10961 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
10962 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
10963 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
10964 }
10965 }
10966
10967 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
10968 // Only fold this if the inner zext has no other uses to avoid increasing
10969 // the total number of instructions.
10970 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
10971 N0.getOperand(0).getOpcode() == ISD::SRL) {
10972 SDValue N0Op0 = N0.getOperand(0);
10973 SDValue InnerShiftAmt = N0Op0.getOperand(1);
10974
10975 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
10976 APInt c1 = LHS->getAPIntValue();
10977 APInt c2 = RHS->getAPIntValue();
10978 zeroExtendToMatch(c1, c2);
10979 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
10980 };
10981 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
10982 /*AllowUndefs*/ false,
10983 /*AllowTypeMismatch*/ true)) {
10984 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
10985 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
10986 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
10987 AddToWorklist(NewSHL.getNode());
10988 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
10989 }
10990 }
10991
10992 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) {
10993 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
10994 ConstantSDNode *RHS) {
10995 const APInt &LHSC = LHS->getAPIntValue();
10996 const APInt &RHSC = RHS->getAPIntValue();
10997 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
10998 LHSC.getZExtValue() <= RHSC.getZExtValue();
10999 };
11000
11001 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
11002 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 >= C2
11003 if (N0->getFlags().hasExact()) {
11004 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11005 /*AllowUndefs*/ false,
11006 /*AllowTypeMismatch*/ true)) {
11007 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11008 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11009 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11010 }
11011 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11012 /*AllowUndefs*/ false,
11013 /*AllowTypeMismatch*/ true)) {
11014 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11015 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11016 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Diff);
11017 }
11018 }
11019
11020 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
11021 // (and (srl x, (sub c1, c2), MASK)
11022 // Only fold this if the inner shift has no other uses -- if it does,
11023 // folding this will increase the total number of instructions.
11024 if (N0.getOpcode() == ISD::SRL &&
11025 (N0.getOperand(1) == N1 || N0.hasOneUse()) &&
11027 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11028 /*AllowUndefs*/ false,
11029 /*AllowTypeMismatch*/ true)) {
11030 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11031 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11032 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11033 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N01);
11034 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, Diff);
11035 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
11036 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11037 }
11038 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11039 /*AllowUndefs*/ false,
11040 /*AllowTypeMismatch*/ true)) {
11041 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11042 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11043 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11044 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, N1);
11045 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11046 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11047 }
11048 }
11049 }
11050
11051 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
11052 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
11053 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
11054 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
11055 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
11056 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
11057 }
11058
11059 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11060 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
11061 // Variant of version done on multiply, except mul by a power of 2 is turned
11062 // into a shift.
11063 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
11064 TLI.isDesirableToCommuteWithShift(N, Level)) {
11065 SDValue N01 = N0.getOperand(1);
11066 if (SDValue Shl1 =
11067 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1})) {
11068 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
11069 AddToWorklist(Shl0.getNode());
11070 SDNodeFlags Flags;
11071 // Preserve the disjoint flag for Or.
11072 if (N0.getOpcode() == ISD::OR && N0->getFlags().hasDisjoint())
11074 return DAG.getNode(N0.getOpcode(), DL, VT, Shl0, Shl1, Flags);
11075 }
11076 }
11077
11078 // fold (shl (sext (add_nsw x, c1)), c2) -> (add (shl (sext x), c2), c1 << c2)
11079 // TODO: Add zext/add_nuw variant with suitable test coverage
11080 // TODO: Should we limit this with isLegalAddImmediate?
11081 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
11082 N0.getOperand(0).getOpcode() == ISD::ADD &&
11083 N0.getOperand(0)->getFlags().hasNoSignedWrap() &&
11084 TLI.isDesirableToCommuteWithShift(N, Level)) {
11085 SDValue Add = N0.getOperand(0);
11086 SDLoc DL(N0);
11087 if (SDValue ExtC = DAG.FoldConstantArithmetic(N0.getOpcode(), DL, VT,
11088 {Add.getOperand(1)})) {
11089 if (SDValue ShlC =
11090 DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {ExtC, N1})) {
11091 SDValue ExtX = DAG.getNode(N0.getOpcode(), DL, VT, Add.getOperand(0));
11092 SDValue ShlX = DAG.getNode(ISD::SHL, DL, VT, ExtX, N1);
11093 return DAG.getNode(ISD::ADD, DL, VT, ShlX, ShlC);
11094 }
11095 }
11096 }
11097
11098 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
11099 if (N0.getOpcode() == ISD::MUL && N0->hasOneUse()) {
11100 SDValue N01 = N0.getOperand(1);
11101 if (SDValue Shl =
11102 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, {N01, N1}))
11103 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), Shl);
11104 }
11105
11106 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11107 if (N1C && !N1C->isOpaque())
11108 if (SDValue NewSHL = visitShiftByConstant(N))
11109 return NewSHL;
11110
11111 // fold (shl X, cttz(Y)) -> (mul (Y & -Y), X) if cttz is unsupported on the
11112 // target.
11113 if (((N1.getOpcode() == ISD::CTTZ &&
11114 VT.getScalarSizeInBits() <= ShiftVT.getScalarSizeInBits()) ||
11116 N1.hasOneUse() && !TLI.isOperationLegalOrCustom(ISD::CTTZ, ShiftVT) &&
11118 SDValue Y = N1.getOperand(0);
11119 SDLoc DL(N);
11120 SDValue NegY = DAG.getNegative(Y, DL, ShiftVT);
11121 SDValue And =
11122 DAG.getZExtOrTrunc(DAG.getNode(ISD::AND, DL, ShiftVT, Y, NegY), DL, VT);
11123 return DAG.getNode(ISD::MUL, DL, VT, And, N0);
11124 }
11125
11127 return SDValue(N, 0);
11128
11129 // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
11130 if (N0.getOpcode() == ISD::VSCALE && N1C) {
11131 const APInt &C0 = N0.getConstantOperandAPInt(0);
11132 const APInt &C1 = N1C->getAPIntValue();
11133 return DAG.getVScale(DL, VT, C0 << C1);
11134 }
11135
11136 SDValue X;
11137 APInt VS0;
11138
11139 // fold (shl (X * vscale(VS0)), C1) -> (X * vscale(VS0 << C1))
11140 if (N1C && sd_match(N0, m_Mul(m_Value(X), m_VScale(m_ConstInt(VS0))))) {
11141 SDNodeFlags Flags;
11142 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
11143 N0->getFlags().hasNoUnsignedWrap());
11144
11145 SDValue VScale = DAG.getVScale(DL, VT, VS0 << N1C->getAPIntValue());
11146 return DAG.getNode(ISD::MUL, DL, VT, X, VScale, Flags);
11147 }
11148
11149 // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)).
11150 APInt ShlVal;
11151 if (N0.getOpcode() == ISD::STEP_VECTOR &&
11152 ISD::isConstantSplatVector(N1.getNode(), ShlVal)) {
11153 const APInt &C0 = N0.getConstantOperandAPInt(0);
11154 if (ShlVal.ult(C0.getBitWidth())) {
11155 APInt NewStep = C0 << ShlVal;
11156 return DAG.getStepVector(DL, VT, NewStep);
11157 }
11158 }
11159
11160 return SDValue();
11161}
11162
11163// Transform a right shift of a multiply into a multiply-high.
11164// Examples:
11165// (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b)
11166// (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b)
11168 const TargetLowering &TLI) {
11169 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
11170 "SRL or SRA node is required here!");
11171
11172 // Check the shift amount. Proceed with the transformation if the shift
11173 // amount is constant.
11174 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
11175 if (!ShiftAmtSrc)
11176 return SDValue();
11177
11178 // The operation feeding into the shift must be a multiply.
11179 SDValue ShiftOperand = N->getOperand(0);
11180 if (ShiftOperand.getOpcode() != ISD::MUL)
11181 return SDValue();
11182
11183 // Both operands must be equivalent extend nodes.
11184 SDValue LeftOp = ShiftOperand.getOperand(0);
11185 SDValue RightOp = ShiftOperand.getOperand(1);
11186
11187 if (LeftOp.getOpcode() != ISD::SIGN_EXTEND &&
11188 LeftOp.getOpcode() != ISD::ZERO_EXTEND)
11189 std::swap(LeftOp, RightOp);
11190
11191 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
11192 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
11193
11194 if (!IsSignExt && !IsZeroExt)
11195 return SDValue();
11196
11197 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
11198 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
11199
11200 // return true if U may use the lower bits of its operands
11201 auto UserOfLowerBits = [NarrowVTSize](SDNode *U) {
11202 if (U->getOpcode() != ISD::SRL && U->getOpcode() != ISD::SRA) {
11203 return true;
11204 }
11205 ConstantSDNode *UShiftAmtSrc = isConstOrConstSplat(U->getOperand(1));
11206 if (!UShiftAmtSrc) {
11207 return true;
11208 }
11209 unsigned UShiftAmt = UShiftAmtSrc->getZExtValue();
11210 return UShiftAmt < NarrowVTSize;
11211 };
11212
11213 // If the lower part of the MUL is also used and MUL_LOHI is supported
11214 // do not introduce the MULH in favor of MUL_LOHI
11215 unsigned MulLoHiOp = IsSignExt ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
11216 if (!ShiftOperand.hasOneUse() &&
11217 TLI.isOperationLegalOrCustom(MulLoHiOp, NarrowVT) &&
11218 llvm::any_of(ShiftOperand->users(), UserOfLowerBits)) {
11219 return SDValue();
11220 }
11221
11222 SDValue MulhRightOp;
11223 if (LeftOp.getOpcode() != RightOp.getOpcode()) {
11224 if (IsZeroExt && ShiftOperand.hasOneUse() &&
11225 DAG.computeKnownBits(RightOp).countMaxActiveBits() <= NarrowVTSize) {
11226 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11227 } else if (IsSignExt && ShiftOperand.hasOneUse() &&
11228 DAG.ComputeMaxSignificantBits(RightOp) <= NarrowVTSize) {
11229 MulhRightOp = DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, RightOp);
11230 } else {
11231 return SDValue();
11232 }
11233 } else {
11234 // Check that the two extend nodes are the same type.
11235 if (NarrowVT != RightOp.getOperand(0).getValueType())
11236 return SDValue();
11237 MulhRightOp = RightOp.getOperand(0);
11238 }
11239
11240 EVT WideVT = LeftOp.getValueType();
11241 // Proceed with the transformation if the wide types match.
11242 assert((WideVT == RightOp.getValueType()) &&
11243 "Cannot have a multiply node with two different operand types.");
11244
11245 // Proceed with the transformation if the wide type is twice as large
11246 // as the narrow type.
11247 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
11248 return SDValue();
11249
11250 // Check the shift amount with the narrow type size.
11251 // Proceed with the transformation if the shift amount is the width
11252 // of the narrow type.
11253 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
11254 if (ShiftAmt != NarrowVTSize)
11255 return SDValue();
11256
11257 // If the operation feeding into the MUL is a sign extend (sext),
11258 // we use mulhs. Othewise, zero extends (zext) use mulhu.
11259 unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU;
11260
11261 // Combine to mulh if mulh is legal/custom for the narrow type on the target
11262 // or if it is a vector type then we could transform to an acceptable type and
11263 // rely on legalization to split/combine the result.
11264 EVT TransformVT = NarrowVT;
11265 if (NarrowVT.isVector()) {
11266 TransformVT = TLI.getLegalTypeToTransformTo(*DAG.getContext(), NarrowVT);
11267 if (TransformVT.getScalarType() != NarrowVT.getScalarType())
11268 return SDValue();
11269 }
11270 if (!TLI.isOperationLegalOrCustom(MulhOpcode, TransformVT))
11271 return SDValue();
11272
11273 SDValue Result =
11274 DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp);
11275 bool IsSigned = N->getOpcode() == ISD::SRA;
11276 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
11277}
11278
11279// fold (bswap (logic_op(bswap(x),y))) -> logic_op(x,bswap(y))
11280// This helper function accept SDNode with opcode ISD::BSWAP and ISD::BITREVERSE
11282 unsigned Opcode = N->getOpcode();
11283 if (Opcode != ISD::BSWAP && Opcode != ISD::BITREVERSE)
11284 return SDValue();
11285
11286 SDValue N0 = N->getOperand(0);
11287 EVT VT = N->getValueType(0);
11288 SDLoc DL(N);
11289 SDValue X, Y;
11290
11291 // If both operands are bswap/bitreverse, ignore the multiuse
11293 m_UnaryOp(Opcode, m_Value(Y))))))
11294 return DAG.getNode(N0.getOpcode(), DL, VT, X, Y);
11295
11296 // Otherwise need to ensure logic_op and bswap/bitreverse(x) have one use.
11298 m_OneUse(m_UnaryOp(Opcode, m_Value(X))), m_Value(Y))))) {
11299 SDValue NewBitReorder = DAG.getNode(Opcode, DL, VT, Y);
11300 return DAG.getNode(N0.getOpcode(), DL, VT, X, NewBitReorder);
11301 }
11302
11303 return SDValue();
11304}
11305
11306SDValue DAGCombiner::visitSRA(SDNode *N) {
11307 SDValue N0 = N->getOperand(0);
11308 SDValue N1 = N->getOperand(1);
11309 if (SDValue V = DAG.simplifyShift(N0, N1))
11310 return V;
11311
11312 SDLoc DL(N);
11313 EVT VT = N0.getValueType();
11314 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11315
11316 // fold (sra c1, c2) -> (sra c1, c2)
11317 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, DL, VT, {N0, N1}))
11318 return C;
11319
11320 // Arithmetic shifting an all-sign-bit value is a no-op.
11321 // fold (sra 0, x) -> 0
11322 // fold (sra -1, x) -> -1
11323 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
11324 return N0;
11325
11326 // fold vector ops
11327 if (VT.isVector())
11328 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11329 return FoldedVOp;
11330
11331 if (SDValue NewSel = foldBinOpIntoSelect(N))
11332 return NewSel;
11333
11334 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11335
11336 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
11337 // clamp (add c1, c2) to max shift.
11338 if (N0.getOpcode() == ISD::SRA) {
11339 EVT ShiftVT = N1.getValueType();
11340 EVT ShiftSVT = ShiftVT.getScalarType();
11341 SmallVector<SDValue, 16> ShiftValues;
11342
11343 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
11344 APInt c1 = LHS->getAPIntValue();
11345 APInt c2 = RHS->getAPIntValue();
11346 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11347 APInt Sum = c1 + c2;
11348 unsigned ShiftSum =
11349 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
11350 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
11351 return true;
11352 };
11353 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
11354 SDValue ShiftValue;
11355 if (N1.getOpcode() == ISD::BUILD_VECTOR)
11356 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
11357 else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
11358 assert(ShiftValues.size() == 1 &&
11359 "Expected matchBinaryPredicate to return one element for "
11360 "SPLAT_VECTORs");
11361 ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]);
11362 } else
11363 ShiftValue = ShiftValues[0];
11364 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
11365 }
11366 }
11367
11368 // fold (sra (xor (sra x, c1), -1), c2) -> (xor (sra x, c3), -1)
11369 // This allows merging two arithmetic shifts even when there's a NOT in
11370 // between.
11371 SDValue X;
11372 APInt C1;
11373 if (N1C && sd_match(N0, m_OneUse(m_Not(
11374 m_OneUse(m_Sra(m_Value(X), m_ConstInt(C1))))))) {
11375 APInt C2 = N1C->getAPIntValue();
11376 zeroExtendToMatch(C1, C2, 1 /* Overflow Bit */);
11377 APInt Sum = C1 + C2;
11378 unsigned ShiftSum = Sum.getLimitedValue(OpSizeInBits - 1);
11379 SDValue NewShift = DAG.getNode(
11380 ISD::SRA, DL, VT, X, DAG.getShiftAmountConstant(ShiftSum, VT, DL));
11381 return DAG.getNOT(DL, NewShift, VT);
11382 }
11383
11384 // fold (sra (shl X, m), (sub result_size, n))
11385 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
11386 // result_size - n != m.
11387 // If truncate is free for the target sext(shl) is likely to result in better
11388 // code.
11389 if (N0.getOpcode() == ISD::SHL && N1C) {
11390 // Get the two constants of the shifts, CN0 = m, CN = n.
11391 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
11392 if (N01C) {
11393 LLVMContext &Ctx = *DAG.getContext();
11394 // Determine what the truncate's result bitsize and type would be.
11395 EVT TruncVT = VT.changeElementType(
11396 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()));
11397
11398 // Determine the residual right-shift amount.
11399 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
11400
11401 // If the shift is not a no-op (in which case this should be just a sign
11402 // extend already), the truncated to type is legal, sign_extend is legal
11403 // on that type, and the truncate to that type is both legal and free,
11404 // perform the transform.
11405 if ((ShiftAmt > 0) &&
11408 TLI.isTruncateFree(VT, TruncVT)) {
11409 SDValue Amt = DAG.getShiftAmountConstant(ShiftAmt, VT, DL);
11410 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
11411 N0.getOperand(0), Amt);
11412 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
11413 Shift);
11414 return DAG.getNode(ISD::SIGN_EXTEND, DL,
11415 N->getValueType(0), Trunc);
11416 }
11417 }
11418 }
11419
11420 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
11421 // sra (add (shl X, N1C), AddC), N1C -->
11422 // sext (add (trunc X to (width - N1C)), AddC')
11423 // sra (sub AddC, (shl X, N1C)), N1C -->
11424 // sext (sub AddC1',(trunc X to (width - N1C)))
11425 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB) && N1C &&
11426 N0.hasOneUse()) {
11427 bool IsAdd = N0.getOpcode() == ISD::ADD;
11428 SDValue Shl = N0.getOperand(IsAdd ? 0 : 1);
11429 if (Shl.getOpcode() == ISD::SHL && Shl.getOperand(1) == N1 &&
11430 Shl.hasOneUse()) {
11431 // TODO: AddC does not need to be a splat.
11432 if (ConstantSDNode *AddC =
11433 isConstOrConstSplat(N0.getOperand(IsAdd ? 1 : 0))) {
11434 // Determine what the truncate's type would be and ask the target if
11435 // that is a free operation.
11436 LLVMContext &Ctx = *DAG.getContext();
11437 unsigned ShiftAmt = N1C->getZExtValue();
11438 EVT TruncVT = VT.changeElementType(
11439 Ctx, EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt));
11440
11441 // TODO: The simple type check probably belongs in the default hook
11442 // implementation and/or target-specific overrides (because
11443 // non-simple types likely require masking when legalized), but
11444 // that restriction may conflict with other transforms.
11445 if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
11446 TLI.isTruncateFree(VT, TruncVT)) {
11447 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
11448 SDValue ShiftC =
11449 DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).trunc(
11450 TruncVT.getScalarSizeInBits()),
11451 DL, TruncVT);
11452 SDValue Add;
11453 if (IsAdd)
11454 Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
11455 else
11456 Add = DAG.getNode(ISD::SUB, DL, TruncVT, ShiftC, Trunc);
11457 return DAG.getSExtOrTrunc(Add, DL, VT);
11458 }
11459 }
11460 }
11461 }
11462
11463 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
11464 if (N1.getOpcode() == ISD::TRUNCATE &&
11465 N1.getOperand(0).getOpcode() == ISD::AND) {
11466 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11467 return DAG.getNode(ISD::SRA, DL, VT, N0, NewOp1);
11468 }
11469
11470 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
11471 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
11472 // if c1 is equal to the number of bits the trunc removes
11473 // TODO - support non-uniform vector shift amounts.
11474 if (N0.getOpcode() == ISD::TRUNCATE &&
11475 (N0.getOperand(0).getOpcode() == ISD::SRL ||
11476 N0.getOperand(0).getOpcode() == ISD::SRA) &&
11477 N0.getOperand(0).hasOneUse() &&
11478 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
11479 SDValue N0Op0 = N0.getOperand(0);
11480 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
11481 EVT LargeVT = N0Op0.getValueType();
11482 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
11483 if (LargeShift->getAPIntValue() == TruncBits) {
11484 EVT LargeShiftVT = getShiftAmountTy(LargeVT);
11485 SDValue Amt = DAG.getZExtOrTrunc(N1, DL, LargeShiftVT);
11486 Amt = DAG.getNode(ISD::ADD, DL, LargeShiftVT, Amt,
11487 DAG.getConstant(TruncBits, DL, LargeShiftVT));
11488 SDValue SRA =
11489 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
11490 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
11491 }
11492 }
11493 }
11494
11495 // fold (sra (add nsw X, C), D) -> (add nsw (sra X, D), C s>> D)
11496 // when C has D trailing zeros (so C s>> D is exact).
11497 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11498 N0->getFlags().hasNoSignedWrap()) {
11499 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11500 const APInt &ShAmt = N1C->getAPIntValue();
11501 const APInt &AddVal = AddC->getAPIntValue();
11502 if (ShAmt.ult(AddVal.countr_zero())) {
11503 SDNodeFlags ShiftFlags = N->getFlags();
11504 SDValue NewSra =
11505 DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11506 SDValue NewC = DAG.getConstant(AddVal.ashr(ShAmt), DL, VT);
11507 SDNodeFlags AddFlags = N0->getFlags();
11508 return DAG.getNode(ISD::ADD, DL, VT, NewSra, NewC, AddFlags);
11509 }
11510 }
11511 }
11512
11513 // Simplify, based on bits shifted out of the LHS.
11515 return SDValue(N, 0);
11516
11517 // If the sign bit is known to be zero, switch this to a SRL.
11518 if (DAG.SignBitIsZero(N0))
11519 return DAG.getNode(ISD::SRL, DL, VT, N0, N1);
11520
11521 if (N1C && !N1C->isOpaque())
11522 if (SDValue NewSRA = visitShiftByConstant(N))
11523 return NewSRA;
11524
11525 // Try to transform this shift into a multiply-high if
11526 // it matches the appropriate pattern detected in combineShiftToMULH.
11527 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
11528 return MULH;
11529
11530 // Attempt to convert a sra of a load into a narrower sign-extending load.
11531 if (SDValue NarrowLoad = reduceLoadWidth(N))
11532 return NarrowLoad;
11533
11534 if (SDValue AVG = foldShiftToAvg(N, DL))
11535 return AVG;
11536
11537 return SDValue();
11538}
11539
11540SDValue DAGCombiner::visitSRL(SDNode *N) {
11541 SDValue N0 = N->getOperand(0);
11542 SDValue N1 = N->getOperand(1);
11543 if (SDValue V = DAG.simplifyShift(N0, N1))
11544 return V;
11545
11546 SDLoc DL(N);
11547 EVT VT = N0.getValueType();
11548 EVT ShiftVT = N1.getValueType();
11549 unsigned OpSizeInBits = VT.getScalarSizeInBits();
11550
11551 // fold (srl c1, c2) -> c1 >>u c2
11552 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, DL, VT, {N0, N1}))
11553 return C;
11554
11555 // fold vector ops
11556 if (VT.isVector())
11557 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
11558 return FoldedVOp;
11559
11560 if (SDValue NewSel = foldBinOpIntoSelect(N))
11561 return NewSel;
11562
11563 // if (srl x, c) is known to be zero, return 0
11564 ConstantSDNode *N1C = isConstOrConstSplat(N1);
11565 if (N1C &&
11566 DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
11567 return DAG.getConstant(0, DL, VT);
11568
11569 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
11570 if (N0.getOpcode() == ISD::SRL) {
11571 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
11572 ConstantSDNode *RHS) {
11573 APInt c1 = LHS->getAPIntValue();
11574 APInt c2 = RHS->getAPIntValue();
11575 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11576 return (c1 + c2).uge(OpSizeInBits);
11577 };
11578 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
11579 return DAG.getConstant(0, DL, VT);
11580
11581 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
11582 ConstantSDNode *RHS) {
11583 APInt c1 = LHS->getAPIntValue();
11584 APInt c2 = RHS->getAPIntValue();
11585 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
11586 return (c1 + c2).ult(OpSizeInBits);
11587 };
11588 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
11589 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
11590 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
11591 }
11592 }
11593
11594 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
11595 N0.getOperand(0).getOpcode() == ISD::SRL) {
11596 SDValue InnerShift = N0.getOperand(0);
11597 // TODO - support non-uniform vector shift amounts.
11598 if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
11599 uint64_t c1 = N001C->getZExtValue();
11600 uint64_t c2 = N1C->getZExtValue();
11601 EVT InnerShiftVT = InnerShift.getValueType();
11602 EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
11603 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
11604 // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
11605 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
11606 if (c1 + OpSizeInBits == InnerShiftSize) {
11607 if (c1 + c2 >= InnerShiftSize)
11608 return DAG.getConstant(0, DL, VT);
11609 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11610 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11611 InnerShift.getOperand(0), NewShiftAmt);
11612 return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
11613 }
11614 // In the more general case, we can clear the high bits after the shift:
11615 // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
11616 if (N0.hasOneUse() && InnerShift.hasOneUse() &&
11617 c1 + c2 < InnerShiftSize) {
11618 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
11619 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
11620 InnerShift.getOperand(0), NewShiftAmt);
11621 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
11622 OpSizeInBits - c2),
11623 DL, InnerShiftVT);
11624 SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
11625 return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
11626 }
11627 }
11628 }
11629
11630 if (N0.getOpcode() == ISD::SHL) {
11631 // fold (srl (shl nuw x, c), c) -> x
11632 if (N0.getOperand(1) == N1 && N0->getFlags().hasNoUnsignedWrap())
11633 return N0.getOperand(0);
11634
11635 // fold (srl (shl x, c1), c2) -> (and (shl x, (sub c1, c2), MASK) or
11636 // (and (srl x, (sub c2, c1), MASK)
11637 if ((N0.getOperand(1) == N1 || N0->hasOneUse()) &&
11639 auto MatchShiftAmount = [OpSizeInBits](ConstantSDNode *LHS,
11640 ConstantSDNode *RHS) {
11641 const APInt &LHSC = LHS->getAPIntValue();
11642 const APInt &RHSC = RHS->getAPIntValue();
11643 return LHSC.ult(OpSizeInBits) && RHSC.ult(OpSizeInBits) &&
11644 LHSC.getZExtValue() <= RHSC.getZExtValue();
11645 };
11646 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchShiftAmount,
11647 /*AllowUndefs*/ false,
11648 /*AllowTypeMismatch*/ true)) {
11649 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11650 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N01, N1);
11651 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11652 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N01);
11653 Mask = DAG.getNode(ISD::SHL, DL, VT, Mask, Diff);
11654 SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Diff);
11655 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11656 }
11657 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchShiftAmount,
11658 /*AllowUndefs*/ false,
11659 /*AllowTypeMismatch*/ true)) {
11660 SDValue N01 = DAG.getZExtOrTrunc(N0.getOperand(1), DL, ShiftVT);
11661 SDValue Diff = DAG.getNode(ISD::SUB, DL, ShiftVT, N1, N01);
11662 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
11663 Mask = DAG.getNode(ISD::SRL, DL, VT, Mask, N1);
11664 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Diff);
11665 return DAG.getNode(ISD::AND, DL, VT, Shift, Mask);
11666 }
11667 }
11668 }
11669
11670 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
11671 // TODO - support non-uniform vector shift amounts.
11672 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
11673 // Shifting in all undef bits?
11674 EVT SmallVT = N0.getOperand(0).getValueType();
11675 unsigned BitSize = SmallVT.getScalarSizeInBits();
11676 if (N1C->getAPIntValue().uge(BitSize))
11677 return DAG.getUNDEF(VT);
11678
11679 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
11680 uint64_t ShiftAmt = N1C->getZExtValue();
11681 SDLoc DL0(N0);
11682 SDValue SmallShift =
11683 DAG.getNode(ISD::SRL, DL0, SmallVT, N0.getOperand(0),
11684 DAG.getShiftAmountConstant(ShiftAmt, SmallVT, DL0));
11685 AddToWorklist(SmallShift.getNode());
11686 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
11687 return DAG.getNode(ISD::AND, DL, VT,
11688 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
11689 DAG.getConstant(Mask, DL, VT));
11690 }
11691 }
11692
11693 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
11694 // bit, which is unmodified by sra.
11695 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
11696 if (N0.getOpcode() == ISD::SRA)
11697 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
11698 }
11699
11700 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit), and x has a power
11701 // of two bitwidth. The "5" represents (log2 (bitwidth x)).
11702 if (N1C && N0.getOpcode() == ISD::CTLZ &&
11703 isPowerOf2_32(OpSizeInBits) &&
11704 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
11705 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
11706
11707 // If any of the input bits are KnownOne, then the input couldn't be all
11708 // zeros, thus the result of the srl will always be zero.
11709 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
11710
11711 // If all of the bits input the to ctlz node are known to be zero, then
11712 // the result of the ctlz is "32" and the result of the shift is one.
11713 APInt UnknownBits = ~Known.Zero;
11714 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
11715
11716 // Otherwise, check to see if there is exactly one bit input to the ctlz.
11717 if (UnknownBits.isPowerOf2()) {
11718 // Okay, we know that only that the single bit specified by UnknownBits
11719 // could be set on input to the CTLZ node. If this bit is set, the SRL
11720 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
11721 // to an SRL/XOR pair, which is likely to simplify more.
11722 unsigned ShAmt = UnknownBits.countr_zero();
11723 SDValue Op = N0.getOperand(0);
11724
11725 if (ShAmt) {
11726 SDLoc DL(N0);
11727 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
11728 DAG.getShiftAmountConstant(ShAmt, VT, DL));
11729 AddToWorklist(Op.getNode());
11730 }
11731 return DAG.getNode(ISD::XOR, DL, VT, Op, DAG.getConstant(1, DL, VT));
11732 }
11733 }
11734
11735 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
11736 if (N1.getOpcode() == ISD::TRUNCATE &&
11737 N1.getOperand(0).getOpcode() == ISD::AND) {
11738 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
11739 return DAG.getNode(ISD::SRL, DL, VT, N0, NewOp1);
11740 }
11741
11742 // fold (srl (logic_op x, (shl (zext y), c1)), c1)
11743 // -> (logic_op (srl x, c1), (zext y))
11744 // c1 <= leadingzeros(zext(y))
11745 // TODO: Replace c1 with valuetracking?
11746 SDValue X, ZExtY;
11747 if (sd_match(
11748 N0,
11750 m_Value(X),
11752 m_Specific(N1))))))) {
11753 unsigned NumLeadingZeros = ZExtY.getScalarValueSizeInBits() -
11755 if (N1C && N1C->getZExtValue() <= NumLeadingZeros)
11756 return DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
11757 DAG.getNode(ISD::SRL, SDLoc(N0), VT, X, N1), ZExtY);
11758 }
11759
11760 // fold (srl (bitcast (build_vector e1, ..., eN)), (N-1) * eltsize)
11761 // -> (zext eN)
11762 if (N1C && VT.isScalarInteger() && DAG.getDataLayout().isLittleEndian()) {
11764 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
11765 EVT BVVT = BV.getValueType();
11766 unsigned EltSizeInBits = BVVT.getScalarSizeInBits();
11767 unsigned NumElts = BVVT.getVectorNumElements();
11768 if (N1C->getZExtValue() == (NumElts - 1) * EltSizeInBits) {
11769 SDValue LastElt = BV.getOperand(NumElts - 1);
11770 assert(LastElt.getScalarValueSizeInBits() >= EltSizeInBits &&
11771 "Expected BUILD_VECTOR operand as wide as element type");
11772 LastElt = DAG.getBitcast(LastElt.getValueType().changeTypeToInteger(),
11773 LastElt);
11774 SDValue Ext = DAG.getZExtOrTrunc(LastElt, DL, VT);
11775 APInt Mask = APInt::getLowBitsSet(VT.getSizeInBits(), EltSizeInBits);
11776 return DAG.getNode(ISD::AND, DL, VT, Ext,
11777 DAG.getConstant(Mask, DL, VT));
11778 }
11779 }
11780 }
11781
11782 // fold (srl (add nuw X, C), D) -> (add nuw (srl X, D), C u>> D)
11783 // when C has D trailing zeros (so C >> D is exact).
11784 if (N1C && N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
11785 N0->getFlags().hasNoUnsignedWrap()) {
11786 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
11787 const APInt &ShAmt = N1C->getAPIntValue();
11788 const APInt &AddVal = AddC->getAPIntValue();
11789 if (ShAmt.ult(AddVal.countr_zero())) {
11790 SDNodeFlags ShiftFlags = N->getFlags();
11791 SDValue NewSrl =
11792 DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1, ShiftFlags);
11793 SDValue NewC = DAG.getConstant(AddVal.lshr(ShAmt), DL, VT);
11794 SDNodeFlags AddFlags = N0->getFlags();
11795 return DAG.getNode(ISD::ADD, DL, VT, NewSrl, NewC, AddFlags);
11796 }
11797 }
11798 }
11799
11800 // fold operands of srl based on knowledge that the low bits are not
11801 // demanded.
11803 return SDValue(N, 0);
11804
11805 if (N1C && !N1C->isOpaque())
11806 if (SDValue NewSRL = visitShiftByConstant(N))
11807 return NewSRL;
11808
11809 // Attempt to convert a srl of a load into a narrower zero-extending load.
11810 if (SDValue NarrowLoad = reduceLoadWidth(N))
11811 return NarrowLoad;
11812
11813 // Here is a common situation. We want to optimize:
11814 //
11815 // %a = ...
11816 // %b = and i32 %a, 2
11817 // %c = srl i32 %b, 1
11818 // brcond i32 %c ...
11819 //
11820 // into
11821 //
11822 // %a = ...
11823 // %b = and %a, 2
11824 // %c = setcc eq %b, 0
11825 // brcond %c ...
11826 //
11827 // However when after the source operand of SRL is optimized into AND, the SRL
11828 // itself may not be optimized further. Look for it and add the BRCOND into
11829 // the worklist.
11830 //
11831 // The also tends to happen for binary operations when SimplifyDemandedBits
11832 // is involved.
11833 //
11834 // FIXME: This is unecessary if we process the DAG in topological order,
11835 // which we plan to do. This workaround can be removed once the DAG is
11836 // processed in topological order.
11837 if (N->hasOneUse()) {
11838 SDNode *User = *N->user_begin();
11839
11840 // Look pass the truncate.
11841 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse())
11842 User = *User->user_begin();
11843
11844 if (User->getOpcode() == ISD::BRCOND || User->getOpcode() == ISD::AND ||
11845 User->getOpcode() == ISD::OR || User->getOpcode() == ISD::XOR)
11846 AddToWorklist(User);
11847 }
11848
11849 // Try to transform this shift into a multiply-high if
11850 // it matches the appropriate pattern detected in combineShiftToMULH.
11851 if (SDValue MULH = combineShiftToMULH(N, DL, DAG, TLI))
11852 return MULH;
11853
11854 if (SDValue AVG = foldShiftToAvg(N, DL))
11855 return AVG;
11856
11857 SDValue Y;
11858 if (VT.getScalarSizeInBits() % 2 == 0 && N1C) {
11859 // Fold clmul(zext(x), zext(y)) >> (BW - 1 | BW) -> clmul(r|h)(x, y).
11860 unsigned HalfBW = VT.getScalarSizeInBits() / 2;
11861 if (sd_match(N0, m_Clmul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
11862 X.getScalarValueSizeInBits() == HalfBW &&
11863 Y.getScalarValueSizeInBits() == HalfBW) {
11864 if (N1C->getZExtValue() == HalfBW - 1 &&
11865 (!LegalOperations ||
11866 TLI.isOperationLegalOrCustom(ISD::CLMULR, X.getValueType())))
11867 return DAG.getNode(
11868 ISD::ZERO_EXTEND, DL, VT,
11869 DAG.getNode(ISD::CLMULR, DL, X.getValueType(), X, Y));
11870 if (N1C->getZExtValue() == HalfBW &&
11871 (!LegalOperations ||
11872 TLI.isOperationLegalOrCustom(ISD::CLMULH, X.getValueType())))
11873 return DAG.getNode(
11874 ISD::ZERO_EXTEND, DL, VT,
11875 DAG.getNode(ISD::CLMULH, DL, X.getValueType(), X, Y));
11876 }
11877 }
11878
11879 // Fold bitreverse(clmul(bitreverse(x), bitreverse(y))) >> 1 ->
11880 // clmulh(x, y).
11881 if (N1C && N1C->getZExtValue() == 1 &&
11883 m_BitReverse(m_Value(Y))))))
11884 return DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
11885
11886 return SDValue();
11887}
11888
11889SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
11890 EVT VT = N->getValueType(0);
11891 SDValue N0 = N->getOperand(0);
11892 SDValue N1 = N->getOperand(1);
11893 SDValue N2 = N->getOperand(2);
11894 bool IsFSHL = N->getOpcode() == ISD::FSHL;
11895 unsigned BitWidth = VT.getScalarSizeInBits();
11896 SDLoc DL(N);
11897
11898 // fold (fshl/fshr C0, C1, C2) -> C3
11899 if (SDValue C =
11900 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
11901 return C;
11902
11903 // fold (fshl N0, N1, 0) -> N0
11904 // fold (fshr N0, N1, 0) -> N1
11906 if (DAG.MaskedValueIsZero(
11907 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
11908 return IsFSHL ? N0 : N1;
11909
11910 auto IsUndefOrZero = [](SDValue V) {
11911 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
11912 };
11913
11914 // TODO - support non-uniform vector shift amounts.
11915 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
11916 EVT ShAmtTy = N2.getValueType();
11917
11918 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
11919 if (Cst->getAPIntValue().uge(BitWidth)) {
11920 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
11921 return DAG.getNode(N->getOpcode(), DL, VT, N0, N1,
11922 DAG.getConstant(RotAmt, DL, ShAmtTy));
11923 }
11924
11925 unsigned ShAmt = Cst->getZExtValue();
11926 if (ShAmt == 0)
11927 return IsFSHL ? N0 : N1;
11928
11929 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
11930 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
11931 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
11932 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
11933 if (IsUndefOrZero(N0))
11934 return DAG.getNode(
11935 ISD::SRL, DL, VT, N1,
11936 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, DL, ShAmtTy));
11937 if (IsUndefOrZero(N1))
11938 return DAG.getNode(
11939 ISD::SHL, DL, VT, N0,
11940 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, DL, ShAmtTy));
11941
11942 // fold fshl(N0, N1, c) -> x and fshr(N0, N1, c) -> x
11943 // where N0 is any node that contributes "x >> C0" to the result:
11944 // lshr(x, C0) | fshr(_, x, C0) | fshl(_, x, C1)
11945 // and N1 is any node that contributes "x << C1" to the result:
11946 // shl(x, C1) | fshl(x, _, C1) | fshr(x, _, C0)
11947 // with C0 = IsFSHL ? amnt : BW-amnt, C1 = BW - C0
11948
11949 // ShAmt == 0 was handled above; uge(BitWidth) was reduced via modulo above.
11950 assert(ShAmt >= 1 && ShAmt < BitWidth &&
11951 "ShAmt must be in [1, BW-1] for the identity fold to be valid");
11952 SDValue Val;
11953 unsigned C0Expected = IsFSHL ? ShAmt : BitWidth - ShAmt;
11954 unsigned C1Expected = IsFSHL ? BitWidth - ShAmt : ShAmt;
11955
11956 if ((sd_match(N0, m_Srl(m_Value(Val), m_SpecificInt(C0Expected))) ||
11958 m_SpecificInt(C0Expected))) ||
11960 m_SpecificInt(C1Expected)))) &&
11961 (sd_match(N1, m_Shl(m_Specific(Val), m_SpecificInt(C1Expected))) ||
11963 m_SpecificInt(C1Expected))) ||
11965 m_SpecificInt(C0Expected)))))
11966 return Val;
11967
11968 // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
11969 // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
11970 // TODO - bigendian support once we have test coverage.
11971 // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
11972 // TODO - permit LHS EXTLOAD if extensions are shifted out.
11973 if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
11974 !DAG.getDataLayout().isBigEndian()) {
11975 auto *LHS = dyn_cast<LoadSDNode>(N0);
11976 auto *RHS = dyn_cast<LoadSDNode>(N1);
11977 if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
11978 LHS->getAddressSpace() == RHS->getAddressSpace() &&
11979 (LHS->hasNUsesOfValue(1, 0) || RHS->hasNUsesOfValue(1, 0)) &&
11981 if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
11982 SDLoc DL(RHS);
11983 uint64_t PtrOff =
11984 IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
11985 Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff);
11986 unsigned Fast = 0;
11987 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
11988 RHS->getAddressSpace(), NewAlign,
11989 RHS->getMemOperand()->getFlags(), &Fast) &&
11990 Fast) {
11991 SDValue NewPtr = DAG.getMemBasePlusOffset(
11992 RHS->getBasePtr(), TypeSize::getFixed(PtrOff), DL);
11993 AddToWorklist(NewPtr.getNode());
11994 SDValue Load = DAG.getLoad(
11995 VT, DL, RHS->getChain(), NewPtr,
11996 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11997 RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
11998 DAG.makeEquivalentMemoryOrdering(LHS, Load.getValue(1));
11999 DAG.makeEquivalentMemoryOrdering(RHS, Load.getValue(1));
12000 return Load;
12001 }
12002 }
12003 }
12004 }
12005 }
12006
12007 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
12008 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
12009 // iff We know the shift amount is in range.
12010 // TODO: when is it worth doing SUB(BW, N2) as well?
12011 if (isPowerOf2_32(BitWidth)) {
12012 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
12013 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
12014 return DAG.getNode(ISD::SRL, DL, VT, N1, N2);
12015 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
12016 return DAG.getNode(ISD::SHL, DL, VT, N0, N2);
12017 }
12018
12019 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
12020 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
12021 // TODO: Investigate flipping this rotate if only one is legal.
12022 // If funnel shift is legal as well we might be better off avoiding
12023 // non-constant (BW - N2).
12024 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
12025 if (N0 == N1 && hasOperation(RotOpc, VT))
12026 return DAG.getNode(RotOpc, DL, VT, N0, N2);
12027
12028 // Simplify, based on bits shifted out of N0/N1.
12030 return SDValue(N, 0);
12031
12032 return SDValue();
12033}
12034
12035SDValue DAGCombiner::visitSHLSAT(SDNode *N) {
12036 SDValue N0 = N->getOperand(0);
12037 SDValue N1 = N->getOperand(1);
12038 if (SDValue V = DAG.simplifyShift(N0, N1))
12039 return V;
12040
12041 SDLoc DL(N);
12042 EVT VT = N0.getValueType();
12043
12044 // fold (*shlsat c1, c2) -> c1<<c2
12045 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
12046 return C;
12047
12048 ConstantSDNode *N1C = isConstOrConstSplat(N1);
12049
12050 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) {
12051 // fold (sshlsat x, c) -> (shl x, c)
12052 if (N->getOpcode() == ISD::SSHLSAT && N1C &&
12053 N1C->getAPIntValue().ult(DAG.ComputeNumSignBits(N0)))
12054 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
12055
12056 // fold (ushlsat x, c) -> (shl x, c)
12057 if (N->getOpcode() == ISD::USHLSAT && N1C &&
12058 N1C->getAPIntValue().ule(
12060 return DAG.getNode(ISD::SHL, DL, VT, N0, N1);
12061 }
12062
12063 return SDValue();
12064}
12065
12066// Given a ABS node, detect the following patterns:
12067// (ABS (SUB (EXTEND a), (EXTEND b))).
12068// (TRUNC (ABS (SUB (EXTEND a), (EXTEND b)))).
12069// Generates UABD/SABD instruction.
12070SDValue DAGCombiner::foldABSToABD(SDNode *N, const SDLoc &DL) {
12071 EVT SrcVT = N->getValueType(0);
12072
12073 if (N->getOpcode() == ISD::TRUNCATE)
12074 N = N->getOperand(0).getNode();
12075
12076 EVT VT = N->getValueType(0);
12077 SDValue Op0, Op1;
12078
12079 if (!sd_match(N, m_Abs(m_AnyOf(m_Sub(m_Value(Op0), m_Value(Op1)),
12080 m_Add(m_Value(Op0), m_Value(Op1))))))
12081 return SDValue();
12082
12083 SDValue AbsOp0 = N->getOperand(0);
12084 bool IsAdd = AbsOp0.getOpcode() == ISD::ADD;
12085 // Make sure (abs B) is positive.
12086 if (IsAdd) {
12087 // Elements of Op1 must be constant and != VT.minSignedValue() (or undef)
12088 auto IsNotMinSignedInt = [VT](ConstantSDNode *C) {
12089 if (C == nullptr)
12090 return true;
12091 return !C->getAPIntValue()
12092 .trunc(VT.getScalarSizeInBits())
12093 .isMinSignedValue();
12094 };
12095
12096 if (!ISD::matchUnaryPredicate(Op1, IsNotMinSignedInt, /*AllowUndefs=*/true,
12097 /*AllowTruncation=*/true))
12098 return SDValue();
12099 }
12100
12101 unsigned Opc0 = Op0.getOpcode();
12102
12103 // Check if the operands of the sub are (zero|sign)-extended, otherwise
12104 // fallback to ValueTracking.
12105 if (Opc0 != Op1.getOpcode() ||
12106 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND &&
12107 Opc0 != ISD::SIGN_EXTEND_INREG)) {
12108
12109 auto CreateZextedAbd = [&](unsigned AbdOpc) {
12110 if (IsAdd)
12111 Op1 = DAG.getNegative(Op1, SDLoc(Op1), VT);
12112 SDValue ABD = DAG.getNode(AbdOpc, DL, VT, Op0, Op1);
12113 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12114 };
12115
12116 // fold (abs (sub nsw x, y)) -> abds(x, y)
12117 // fold (abs (add nsw x, -y)) -> abds(x, y)
12118 bool AbsOpWillNSW =
12119 AbsOp0->getFlags().hasNoSignedWrap() ||
12120 (IsAdd ? DAG.willNotOverflowAdd(/*IsSigned=*/true, Op0, Op1)
12121 : DAG.willNotOverflowSub(/*IsSigned=*/true, Op0, Op1));
12122
12123 // Don't fold this for unsupported types as we lose the NSW handling.
12124 if (hasOperation(ISD::ABDS, VT) && TLI.preferABDSToABSWithNSW(VT) &&
12125 AbsOpWillNSW)
12126 return CreateZextedAbd(ISD::ABDS);
12127
12128 // fold (abs (sub x, y)) -> abdu(x, y)
12129 bool Op1SignBitIsOne = DAG.computeKnownBits(Op1).isNegative();
12130 bool AbsOpWillNUW = !IsAdd && DAG.SignBitIsZero(Op0) && Op1SignBitIsOne;
12131
12132 if (hasOperation(ISD::ABDU, VT) && AbsOpWillNUW)
12133 return CreateZextedAbd(ISD::ABDU);
12134
12135 return SDValue();
12136 }
12137
12138 // The IsAdd case explicitly checks for const/bv-of-const. This implies either
12139 // (Opc0 != Op1.getOpcode() || Opc0 is not in {zext/sext/sign_ext_inreg}. This
12140 // implies it was alrady handled by the above if statement.
12141 assert(!IsAdd && "Unexpected abs(add(x,y)) pattern");
12142
12143 EVT VT0, VT1;
12144 if (Opc0 == ISD::SIGN_EXTEND_INREG) {
12145 VT0 = cast<VTSDNode>(Op0.getOperand(1))->getVT();
12146 VT1 = cast<VTSDNode>(Op1.getOperand(1))->getVT();
12147 } else {
12148 VT0 = Op0.getOperand(0).getValueType();
12149 VT1 = Op1.getOperand(0).getValueType();
12150 }
12151 unsigned ABDOpcode = (Opc0 == ISD::ZERO_EXTEND) ? ISD::ABDU : ISD::ABDS;
12152
12153 // fold abs(sext(x) - sext(y)) -> zext(abds(x, y))
12154 // fold abs(zext(x) - zext(y)) -> zext(abdu(x, y))
12155 EVT MaxVT = VT0.bitsGT(VT1) ? VT0 : VT1;
12156 if ((VT0 == MaxVT || Op0->hasOneUse()) &&
12157 (VT1 == MaxVT || Op1->hasOneUse()) &&
12158 (!LegalTypes || hasOperation(ABDOpcode, MaxVT))) {
12159 SDValue ABD = DAG.getNode(ABDOpcode, DL, MaxVT,
12160 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op0),
12161 DAG.getNode(ISD::TRUNCATE, DL, MaxVT, Op1));
12162 ABD = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ABD);
12163 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12164 }
12165
12166 // fold abs(sext(x) - sext(y)) -> abds(sext(x), sext(y))
12167 // fold abs(zext(x) - zext(y)) -> abdu(zext(x), zext(y))
12168 if (!LegalOperations || hasOperation(ABDOpcode, VT)) {
12169 SDValue ABD = DAG.getNode(ABDOpcode, DL, VT, Op0, Op1);
12170 return DAG.getZExtOrTrunc(ABD, DL, SrcVT);
12171 }
12172
12173 return SDValue();
12174}
12175
12176SDValue DAGCombiner::visitABS(SDNode *N) {
12177 SDValue N0 = N->getOperand(0);
12178 EVT VT = N->getValueType(0);
12179 SDLoc DL(N);
12180
12181 // fold (abs c1) -> c2
12182 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ABS, DL, VT, {N0}))
12183 return C;
12184 // fold (abs (abs x)) -> (abs x)
12185 // fold (abs (abs_min_poison x)) -> (abs_min_poison x)
12186 if (ISD::isAbsOpcode(N0.getOpcode()))
12187 return N0;
12188 // fold (abs x) -> x iff not-negative
12189 if (DAG.SignBitIsZero(N0))
12190 return N0;
12191
12192 if (SDValue ABD = foldABSToABD(N, DL))
12193 return ABD;
12194
12195 // fold (abs (sign_extend_inreg x)) -> (zero_extend (abs (truncate x)))
12196 // iff zero_extend/truncate are free.
12197 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12198 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12199 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12200 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12201 hasOperation(ISD::ABS, ExtVT)) {
12202 return DAG.getNode(
12203 ISD::ZERO_EXTEND, DL, VT,
12204 DAG.getNode(ISD::ABS, DL, ExtVT,
12205 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12206 }
12207 }
12208
12209 return SDValue();
12210}
12211
12212SDValue DAGCombiner::visitABS_MIN_POISON(SDNode *N) {
12213 SDValue N0 = N->getOperand(0);
12214 EVT VT = N->getValueType(0);
12215 SDLoc DL(N);
12216
12217 // fold (abs_min_poison c1) -> c2 (or poison if c1 == INT_MIN)
12219 return C;
12220 // fold (abs_min_poison (abs_min_poison x)) -> (abs_min_poison x)
12221 // fold (abs_min_poison (abs x)) -> (abs x)
12222 // fold (abs_min_poison (freeze (abs x))) -> (freeze (abs x))
12223 // fold (abs_min_poison (freeze (abs_min_poison x))) ->
12224 // (freeze (abs_min_poison x))
12225 //
12226 // Freeze case is valid because: for x != INT_MIN both sides equal abs(x);
12227 // for x == INT_MIN both forms produce a non-deterministic but well-defined
12228 // value since freeze already consumed the poison.
12229 if (ISD::isAbsOpcode(peekThroughFreeze(N0).getOpcode()))
12230 return N0;
12231 // fold (abs_min_poison x) -> x iff not-negative
12232 if (DAG.SignBitIsZero(N0))
12233 return N0;
12234
12235 if (SDValue ABD = foldABSToABD(N, DL))
12236 return ABD;
12237
12238 // fold (abs_min_poison (sign_extend_inreg x)) ->
12239 // (zero_extend (abs (truncate x)))
12240 // iff zero_extend/truncate are free. The sign_extend_inreg keeps the value
12241 // in the narrow type's range, so the wide abs_min_poison is never actually
12242 // poison.
12243 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
12244 EVT ExtVT = cast<VTSDNode>(N0.getOperand(1))->getVT();
12245 if (TLI.isTruncateFree(VT, ExtVT) && TLI.isZExtFree(ExtVT, VT) &&
12246 TLI.isTypeDesirableForOp(ISD::ABS, ExtVT) &&
12247 hasOperation(ISD::ABS, ExtVT)) {
12248 return DAG.getNode(
12249 ISD::ZERO_EXTEND, DL, VT,
12250 DAG.getNode(ISD::ABS, DL, ExtVT,
12251 DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N0.getOperand(0))));
12252 }
12253 }
12254
12255 return SDValue();
12256}
12257
12258SDValue DAGCombiner::visitCLMUL(SDNode *N) {
12259 unsigned Opcode = N->getOpcode();
12260 SDValue N0 = N->getOperand(0);
12261 SDValue N1 = N->getOperand(1);
12262 EVT VT = N->getValueType(0);
12263 SDLoc DL(N);
12264
12265 // fold (clmul c1, c2)
12266 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
12267 return C;
12268
12269 // canonicalize constant to RHS
12272 return DAG.getNode(Opcode, DL, VT, N1, N0);
12273
12274 // fold (clmul x, 0) -> 0
12276 return DAG.getConstant(0, DL, VT);
12277
12278 // fold (clmul x, c_pow2) -> (shl x, log2(c_pow2))
12279 // This also handles (clmul x, 1) -> x since (shl x, 0) simplifies to x.
12280 if (Opcode == ISD::CLMUL) {
12281 if (ConstantSDNode *C = isConstOrConstSplat(N1)) {
12282 APInt CV = C->getAPIntValue().trunc(VT.getScalarSizeInBits());
12283 if (CV.isPowerOf2() &&
12284 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)))
12285 return DAG.getNode(ISD::SHL, DL, VT, N0,
12286 DAG.getShiftAmountConstant(CV.logBase2(), VT, DL));
12287 }
12288 }
12289
12290 return SDValue();
12291}
12292
12293SDValue DAGCombiner::visitPEXT(SDNode *N) {
12294 EVT VT = N->getValueType(0);
12295 SDValue N0 = N->getOperand(0);
12296 SDValue N1 = N->getOperand(1);
12297 SDLoc DL(N);
12298
12299 // pext(x, 0) -> 0
12300 if (isNullOrNullSplat(N1))
12301 return DAG.getConstant(0, DL, VT);
12302 // pext(x, -1) -> x (all bits selected, packed into low positions = x)
12304 return N0;
12305 // fold pext(c1, c2) -> c3
12306 if (SDValue C = DAG.FoldConstantArithmetic(ISD::PEXT, DL, VT, {N0, N1}))
12307 return C;
12308 return SDValue();
12309}
12310
12311SDValue DAGCombiner::visitPDEP(SDNode *N) {
12312 EVT VT = N->getValueType(0);
12313 SDValue N0 = N->getOperand(0);
12314 SDValue N1 = N->getOperand(1);
12315 SDLoc DL(N);
12316
12317 // pdep(x, 0) -> 0
12318 if (isNullOrNullSplat(N1))
12319 return DAG.getConstant(0, DL, VT);
12320
12321 // pdep(x, -1) -> x (all positions selected, bits deposited at identity)
12323 return N0;
12324
12325 // fold pdep(c1, c2) -> c3
12326 if (SDValue C = DAG.FoldConstantArithmetic(ISD::PDEP, DL, VT, {N0, N1}))
12327 return C;
12328
12330 return SDValue(N, 0);
12331
12332 return SDValue();
12333}
12334
12335SDValue DAGCombiner::visitBSWAP(SDNode *N) {
12336 SDValue N0 = N->getOperand(0);
12337 EVT VT = N->getValueType(0);
12338 SDLoc DL(N);
12339
12340 // fold (bswap c1) -> c2
12341 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BSWAP, DL, VT, {N0}))
12342 return C;
12343 // fold (bswap (bswap x)) -> x
12344 if (N0.getOpcode() == ISD::BSWAP)
12345 return N0.getOperand(0);
12346
12347 // Canonicalize bswap(bitreverse(x)) -> bitreverse(bswap(x)). If bitreverse
12348 // isn't supported, it will be expanded to bswap followed by a manual reversal
12349 // of bits in each byte. By placing bswaps before bitreverse, we can remove
12350 // the two bswaps if the bitreverse gets expanded.
12351 if (N0.getOpcode() == ISD::BITREVERSE && N0.hasOneUse()) {
12352 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12353 return DAG.getNode(ISD::BITREVERSE, DL, VT, BSwap);
12354 }
12355
12356 unsigned BW = VT.getScalarSizeInBits();
12357 // fold (bswap shl(x,c)) -> (zext(bswap(trunc(shl(x,sub(c,bw/2))))))
12358 // iff x >= bw/2 (i.e. lower half is known zero)
12359 if (BW >= 32 && N0.getOpcode() == ISD::SHL && N0.hasOneUse()) {
12360 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12361 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), BW / 2);
12362 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12363 ShAmt->getZExtValue() >= (BW / 2) && (ShAmt->getZExtValue() % 8) == 0 &&
12364 TLI.isTypeLegal(HalfVT) && TLI.isTruncateFree(VT, HalfVT) &&
12365 (!LegalOperations || hasOperation(ISD::BSWAP, HalfVT))) {
12366 SDValue Res = N0.getOperand(0);
12367 if (uint64_t NewShAmt = (ShAmt->getZExtValue() - (BW / 2)))
12368 Res = DAG.getNode(ISD::SHL, DL, VT, Res,
12369 DAG.getShiftAmountConstant(NewShAmt, VT, DL));
12370 Res = DAG.getZExtOrTrunc(Res, DL, HalfVT);
12371 Res = DAG.getNode(ISD::BSWAP, DL, HalfVT, Res);
12372 return DAG.getZExtOrTrunc(Res, DL, VT);
12373 }
12374 }
12375
12376 // Try to canonicalize bswap-of-logical-shift-by-8-bit-multiple as
12377 // inverse-shift-of-bswap:
12378 // bswap (X u<< C) --> (bswap X) u>> C
12379 // bswap (X u>> C) --> (bswap X) u<< C
12380 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
12381 N0.hasOneUse()) {
12382 auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12383 if (ShAmt && ShAmt->getAPIntValue().ult(BW) &&
12384 ShAmt->getZExtValue() % 8 == 0) {
12385 SDValue NewSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
12386 unsigned InverseShift = N0.getOpcode() == ISD::SHL ? ISD::SRL : ISD::SHL;
12387 return DAG.getNode(InverseShift, DL, VT, NewSwap, N0.getOperand(1));
12388 }
12389 }
12390
12391 if (SDValue V = foldBitOrderCrossLogicOp(N, DAG))
12392 return V;
12393
12394 // Folds that depend on computeKnownBits of the operand.
12395 KnownBits Known = DAG.computeKnownBits(N0);
12396 // bswap(0) = 0. Catch cases that computeKnownBits can prove are zero but
12397 // that structural combines haven't simplified to a constant yet
12398 // (e.g. and of disjoint byte masks).
12399 if (Known.isZero())
12400 return DAG.getConstant(0, DL, VT);
12401 // If only one byte of the operand may be nonzero, bswap becomes a shift
12402 // to the mirror byte.
12403 unsigned TZ = alignDown(Known.countMinTrailingZeros(), 8);
12404 unsigned LZ = alignDown(Known.countMinLeadingZeros(), 8);
12405 if (BW - (LZ + TZ) == 8) {
12406 unsigned Opc = LZ > TZ ? ISD::SHL : ISD::SRL;
12407 // Skip if the target would re-expand the produced shift post-legalize.
12408 // Targets that custom-lower byte-multiple shifts via bswap (e.g. MSP430
12409 // for shl i16) would loop with this combine.
12410 if (!LegalOperations || hasOperation(Opc, VT)) {
12411 unsigned Amt = AbsoluteDifference(LZ, TZ);
12412 SDNodeFlags Flags =
12414 return DAG.getNode(Opc, DL, VT, N0,
12415 DAG.getShiftAmountConstant(Amt, VT, DL), Flags);
12416 }
12417 }
12418
12419 return SDValue();
12420}
12421
12422SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
12423 SDValue N0 = N->getOperand(0);
12424 EVT VT = N->getValueType(0);
12425 SDLoc DL(N);
12426
12427 // fold (bitreverse c1) -> c2
12428 if (SDValue C = DAG.FoldConstantArithmetic(ISD::BITREVERSE, DL, VT, {N0}))
12429 return C;
12430
12431 // fold (bitreverse (bitreverse x)) -> x
12432 if (N0.getOpcode() == ISD::BITREVERSE)
12433 return N0.getOperand(0);
12434
12435 SDValue X, Y;
12436
12437 // fold (bitreverse (lshr (bitreverse x), y)) -> (shl x, y)
12438 if ((!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
12440 return DAG.getNode(ISD::SHL, DL, VT, X, Y);
12441
12442 // fold (bitreverse (shl (bitreverse x), y)) -> (lshr x, y)
12443 if ((!LegalOperations || TLI.isOperationLegal(ISD::SRL, VT)) &&
12445 return DAG.getNode(ISD::SRL, DL, VT, X, Y);
12446
12447 // fold bitreverse(clmul(bitreverse(x), bitreverse(y))) -> clmulr(x, y)
12448 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::CLMULR, VT)) &&
12450 return DAG.getNode(ISD::CLMULR, DL, VT, X, Y);
12451
12452 return SDValue();
12453}
12454
12455// Fold (ctlz (xor x, (sra x, bitwidth-1))) -> (add (ctls x), 1).
12456// Fold (ctlz (or (shl (xor x, (sra x, bitwidth-1)), 1), 1) -> (ctls x)
12457SDValue DAGCombiner::foldCTLZToCTLS(SDValue Src, const SDLoc &DL) {
12458 EVT VT = Src.getValueType();
12459
12460 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
12461 if ((LK.first != TargetLoweringBase::TypeLegal &&
12463 !TLI.isOperationLegalOrCustom(ISD::CTLS, LK.second))
12464 return SDValue();
12465
12466 unsigned BitWidth = VT.getScalarSizeInBits();
12467
12468 bool NeedAdd = true;
12469
12470 SDValue X;
12471 if (sd_match(Src,
12473 NeedAdd = false;
12474 Src = X;
12475 }
12476
12477 if (!sd_match(Src,
12480 m_SpecificInt(BitWidth - 1)))))))
12481 return SDValue();
12482
12483 SDValue Res = DAG.getNode(ISD::CTLS, DL, VT, X);
12484 if (!NeedAdd)
12485 return Res;
12486
12487 return DAG.getNode(ISD::ADD, DL, VT, Res, DAG.getConstant(1, DL, VT));
12488}
12489
12490SDValue DAGCombiner::visitCTLZ(SDNode *N) {
12491 SDValue N0 = N->getOperand(0);
12492 EVT VT = N->getValueType(0);
12493 SDLoc DL(N);
12494
12495 // fold (ctlz c1) -> c2
12496 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTLZ, DL, VT, {N0}))
12497 return C;
12498
12499 // If the value is known never to be zero, switch to the poison version.
12500 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_POISON, VT))
12501 if (DAG.isKnownNeverZero(N0))
12502 return DAG.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, N0);
12503
12504 if (SDValue V = foldCTLZToCTLS(N0, DL))
12505 return V;
12506
12507 return SDValue();
12508}
12509
12510SDValue DAGCombiner::visitCTLZ_ZERO_POISON(SDNode *N) {
12511 SDValue N0 = N->getOperand(0);
12512 EVT VT = N->getValueType(0);
12513 SDLoc DL(N);
12514
12515 // fold (ctlz_zero_poison c1) -> c2
12516 if (SDValue C =
12518 return C;
12519
12520 if (SDValue V = foldCTLZToCTLS(N0, DL))
12521 return V;
12522
12523 return SDValue();
12524}
12525
12526SDValue DAGCombiner::visitCTTZ(SDNode *N) {
12527 SDValue N0 = N->getOperand(0);
12528 EVT VT = N->getValueType(0);
12529 SDLoc DL(N);
12530
12531 // fold (cttz c1) -> c2
12532 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTTZ, DL, VT, {N0}))
12533 return C;
12534
12535 // If the value is known never to be zero, switch to the poison version.
12536 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_POISON, VT))
12537 if (DAG.isKnownNeverZero(N0))
12538 return DAG.getNode(ISD::CTTZ_ZERO_POISON, DL, VT, N0);
12539
12540 return SDValue();
12541}
12542
12543SDValue DAGCombiner::visitCTTZ_ZERO_POISON(SDNode *N) {
12544 SDValue N0 = N->getOperand(0);
12545 EVT VT = N->getValueType(0);
12546 SDLoc DL(N);
12547
12548 // fold (cttz_zero_poison c1) -> c2
12549 if (SDValue C =
12551 return C;
12552 return SDValue();
12553}
12554
12555SDValue DAGCombiner::visitCTPOP(SDNode *N) {
12556 SDValue N0 = N->getOperand(0);
12557 EVT VT = N->getValueType(0);
12558 unsigned NumBits = VT.getScalarSizeInBits();
12559 SDLoc DL(N);
12560
12561 // fold (ctpop c1) -> c2
12562 if (SDValue C = DAG.FoldConstantArithmetic(ISD::CTPOP, DL, VT, {N0}))
12563 return C;
12564
12565 // If the source is being shifted, but doesn't affect any active bits,
12566 // then we can call CTPOP on the shift source directly.
12567 if (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SHL) {
12568 if (ConstantSDNode *AmtC = isConstOrConstSplat(N0.getOperand(1))) {
12569 const APInt &Amt = AmtC->getAPIntValue();
12570 if (Amt.ult(NumBits)) {
12571 KnownBits KnownSrc = DAG.computeKnownBits(N0.getOperand(0));
12572 if ((N0.getOpcode() == ISD::SRL &&
12573 Amt.ule(KnownSrc.countMinTrailingZeros())) ||
12574 (N0.getOpcode() == ISD::SHL &&
12575 Amt.ule(KnownSrc.countMinLeadingZeros()))) {
12576 return DAG.getNode(ISD::CTPOP, DL, VT, N0.getOperand(0));
12577 }
12578 }
12579 }
12580 }
12581
12582 // If the upper bits are known to be zero, then see if its profitable to
12583 // only count the lower bits.
12584 if (VT.isScalarInteger() && NumBits > 8 && (NumBits & 1) == 0) {
12585 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), NumBits / 2);
12586 if (hasOperation(ISD::CTPOP, HalfVT) &&
12587 TLI.isTypeDesirableForOp(ISD::CTPOP, HalfVT) &&
12588 TLI.isTruncateFree(N0, HalfVT) && TLI.isZExtFree(HalfVT, VT)) {
12589 APInt UpperBits = APInt::getHighBitsSet(NumBits, NumBits / 2);
12590 if (DAG.MaskedValueIsZero(N0, UpperBits)) {
12591 SDValue PopCnt = DAG.getNode(ISD::CTPOP, DL, HalfVT,
12592 DAG.getZExtOrTrunc(N0, DL, HalfVT));
12593 return DAG.getZExtOrTrunc(PopCnt, DL, VT);
12594 }
12595 }
12596 }
12597
12598 return SDValue();
12599}
12600
12602 SDValue RHS, const SDNodeFlags Flags,
12603 const TargetLowering &TLI) {
12604 EVT VT = LHS.getValueType();
12605 if (!VT.isFloatingPoint())
12606 return false;
12607
12608 return Flags.hasNoSignedZeros() &&
12610 (Flags.hasNoNaNs() ||
12611 (DAG.isKnownNeverNaN(RHS) && DAG.isKnownNeverNaN(LHS)));
12612}
12613
12615 SDValue RHS, SDValue True, SDValue False,
12616 ISD::CondCode CC,
12617 const TargetLowering &TLI,
12618 SelectionDAG &DAG) {
12619 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12620 switch (CC) {
12621 case ISD::SETOLT:
12622 case ISD::SETOLE:
12623 case ISD::SETLT:
12624 case ISD::SETLE:
12625 case ISD::SETULT:
12626 case ISD::SETULE: {
12627 // Since it's known never nan to get here already, either fminnum or
12628 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
12629 // expanded in terms of it.
12630 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
12631 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12632 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
12633
12634 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
12635 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12636 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
12637 return SDValue();
12638 }
12639 case ISD::SETOGT:
12640 case ISD::SETOGE:
12641 case ISD::SETGT:
12642 case ISD::SETGE:
12643 case ISD::SETUGT:
12644 case ISD::SETUGE: {
12645 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
12646 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
12647 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
12648
12649 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
12650 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
12651 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
12652 return SDValue();
12653 }
12654 default:
12655 return SDValue();
12656 }
12657}
12658
12659// Convert (sr[al] (add n[su]w x, y)) -> (avgfloor[su] x, y)
12660SDValue DAGCombiner::foldShiftToAvg(SDNode *N, const SDLoc &DL) {
12661 const unsigned Opcode = N->getOpcode();
12662 if (Opcode != ISD::SRA && Opcode != ISD::SRL)
12663 return SDValue();
12664
12665 EVT VT = N->getValueType(0);
12666 bool IsUnsigned = Opcode == ISD::SRL;
12667
12668 // Captured values.
12669 SDValue A, B;
12670
12671 // Match floor average as it is common to both floor/ceil avgs, ensure the add
12672 // doesn't wrap.
12673 SDNodeFlags Flags =
12675 if (sd_match(N, m_BinOp(Opcode,
12676 m_c_BinOp(ISD::ADD, m_Value(A), m_Value(B), Flags),
12677 m_One()))) {
12678 // Decide whether signed or unsigned.
12679 unsigned FloorISD = IsUnsigned ? ISD::AVGFLOORU : ISD::AVGFLOORS;
12680 if (hasOperation(FloorISD, VT))
12681 return DAG.getNode(FloorISD, DL, VT, {A, B});
12682 }
12683
12684 return SDValue();
12685}
12686
12687SDValue DAGCombiner::foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT) {
12688 unsigned Opc = N->getOpcode();
12689 SDValue X, Y, Z;
12690 if (sd_match(
12692 return DAG.getNode(Opc, DL, VT, X,
12693 DAG.getNOT(DL, DAG.getNode(ISD::SUB, DL, VT, Y, Z), VT));
12694
12696 m_Value(Z)))))
12697 return DAG.getNode(Opc, DL, VT, X,
12698 DAG.getNOT(DL, DAG.getNode(ISD::ADD, DL, VT, Y, Z), VT));
12699
12700 return SDValue();
12701}
12702
12703/// Generate Min/Max node
12704SDValue DAGCombiner::combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
12705 SDValue RHS, SDValue True,
12706 SDValue False, ISD::CondCode CC) {
12707 if ((LHS == True && RHS == False) || (LHS == False && RHS == True))
12708 return combineMinNumMaxNumImpl(DL, VT, LHS, RHS, True, False, CC, TLI, DAG);
12709
12710 // If we can't directly match this, try to see if we can pull an fneg out of
12711 // the select.
12713 True, DAG, LegalOperations, ForCodeSize);
12714 if (!NegTrue)
12715 return SDValue();
12716
12717 HandleSDNode NegTrueHandle(NegTrue);
12718
12719 // Try to unfold an fneg from the select if we are comparing the negated
12720 // constant.
12721 //
12722 // select (setcc x, K) (fneg x), -K -> fneg(minnum(x, K))
12723 //
12724 // TODO: Handle fabs
12725 if (LHS == NegTrue) {
12726 // If we can't directly match this, try to see if we can pull an fneg out of
12727 // the select.
12729 RHS, DAG, LegalOperations, ForCodeSize);
12730 if (NegRHS) {
12731 HandleSDNode NegRHSHandle(NegRHS);
12732 if (NegRHS == False) {
12733 SDValue Combined = combineMinNumMaxNumImpl(DL, VT, LHS, RHS, NegTrue,
12734 False, CC, TLI, DAG);
12735 if (Combined)
12736 return DAG.getNode(ISD::FNEG, DL, VT, Combined);
12737 }
12738 }
12739 }
12740
12741 return SDValue();
12742}
12743
12744/// If a (v)select has a condition value that is a sign-bit test, try to smear
12745/// the condition operand sign-bit across the value width and use it as a mask.
12747 SelectionDAG &DAG) {
12748 SDValue Cond = N->getOperand(0);
12749 SDValue C1 = N->getOperand(1);
12750 SDValue C2 = N->getOperand(2);
12752 return SDValue();
12753
12754 EVT VT = N->getValueType(0);
12755 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
12756 VT != Cond.getOperand(0).getValueType())
12757 return SDValue();
12758
12759 // The inverted-condition + commuted-select variants of these patterns are
12760 // canonicalized to these forms in IR.
12761 SDValue X = Cond.getOperand(0);
12762 SDValue CondC = Cond.getOperand(1);
12763 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12764 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
12766 // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
12767 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12768 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12769 return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
12770 }
12771 if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
12772 // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
12773 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
12774 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
12775 return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
12776 }
12777 return SDValue();
12778}
12779
12781 const TargetLowering &TLI) {
12782 if (!TLI.convertSelectOfConstantsToMath(VT))
12783 return false;
12784
12785 if (Cond.getOpcode() != ISD::SETCC || !Cond->hasOneUse())
12786 return true;
12788 return true;
12789
12790 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12791 if (CC == ISD::SETLT && isNullOrNullSplat(Cond.getOperand(1)))
12792 return true;
12793 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond.getOperand(1)))
12794 return true;
12795
12796 return false;
12797}
12798
12799SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
12800 SDValue Cond = N->getOperand(0);
12801 SDValue N1 = N->getOperand(1);
12802 SDValue N2 = N->getOperand(2);
12803 EVT VT = N->getValueType(0);
12804 EVT CondVT = Cond.getValueType();
12805 SDLoc DL(N);
12806
12807 if (!VT.isInteger())
12808 return SDValue();
12809
12810 auto *C1 = dyn_cast<ConstantSDNode>(N1);
12811 auto *C2 = dyn_cast<ConstantSDNode>(N2);
12812 if (!C1 || !C2)
12813 return SDValue();
12814
12815 if (CondVT != MVT::i1 || LegalOperations) {
12816 // We can't do this reliably if integer based booleans have different contents
12817 // to floating point based booleans. This is because we can't tell whether we
12818 // have an integer-based boolean or a floating-point-based boolean unless we
12819 // can find the SETCC that produced it and inspect its operands. This is
12820 // fairly easy if C is the SETCC node, but it can potentially be
12821 // undiscoverable (or not reasonably discoverable). For example, it could be
12822 // in another basic block or it could require searching a complicated
12823 // expression.
12824 if (CondVT.isInteger() &&
12825 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
12827 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
12829 // fold (select Cond, 0, 1) -> (xor Cond, 1)
12830 if (C1->isZero() && C2->isOne()) {
12831 SDValue NotCond = DAG.getNode(ISD::XOR, DL, CondVT, Cond,
12832 DAG.getConstant(1, DL, CondVT));
12833 if (VT.bitsEq(CondVT))
12834 return NotCond;
12835 return DAG.getZExtOrTrunc(NotCond, DL, VT);
12836 }
12837
12838 // fold (select Cond, 1, 0) -> Cond
12839 if (C1->isOne() && C2->isZero() && CondVT == VT)
12840 return Cond;
12841 }
12842
12843 return SDValue();
12844 }
12845
12846 // Only do this before legalization to avoid conflicting with target-specific
12847 // transforms in the other direction (create a select from a zext/sext). There
12848 // is also a target-independent combine here in DAGCombiner in the other
12849 // direction for (select Cond, -1, 0) when the condition is not i1.
12850 assert(CondVT == MVT::i1 && !LegalOperations);
12851
12852 // select Cond, 1, 0 --> zext (Cond)
12853 if (C1->isOne() && C2->isZero())
12854 return DAG.getZExtOrTrunc(Cond, DL, VT);
12855
12856 // select Cond, -1, 0 --> sext (Cond)
12857 if (C1->isAllOnes() && C2->isZero())
12858 return DAG.getSExtOrTrunc(Cond, DL, VT);
12859
12860 // select Cond, 0, 1 --> zext (!Cond)
12861 if (C1->isZero() && C2->isOne()) {
12862 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12863 NotCond = DAG.getZExtOrTrunc(NotCond, DL, VT);
12864 return NotCond;
12865 }
12866
12867 // select Cond, 0, -1 --> sext (!Cond)
12868 if (C1->isZero() && C2->isAllOnes()) {
12869 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12870 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
12871 return NotCond;
12872 }
12873
12874 // Use a target hook because some targets may prefer to transform in the
12875 // other direction.
12877 return SDValue();
12878
12879 // For any constants that differ by 1, we can transform the select into
12880 // an extend and add.
12881 const APInt &C1Val = C1->getAPIntValue();
12882 const APInt &C2Val = C2->getAPIntValue();
12883
12884 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
12885 if (C1Val - 1 == C2Val) {
12886 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
12887 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
12888 }
12889
12890 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
12891 if (C1Val + 1 == C2Val) {
12892 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
12893 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
12894 }
12895
12896 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
12897 if (C1Val.isPowerOf2() && C2Val.isZero()) {
12898 Cond = DAG.getZExtOrTrunc(Cond, DL, VT);
12899 SDValue ShAmtC =
12900 DAG.getShiftAmountConstant(C1Val.exactLogBase2(), VT, DL);
12901 return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
12902 }
12903
12904 // select Cond, -1, C --> or (sext Cond), C
12905 if (C1->isAllOnes()) {
12906 Cond = DAG.getSExtOrTrunc(Cond, DL, VT);
12907 return DAG.getNode(ISD::OR, DL, VT, Cond, N2);
12908 }
12909
12910 // select Cond, C, -1 --> or (sext (not Cond)), C
12911 if (C2->isAllOnes()) {
12912 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
12913 NotCond = DAG.getSExtOrTrunc(NotCond, DL, VT);
12914 return DAG.getNode(ISD::OR, DL, VT, NotCond, N1);
12915 }
12916
12918 return V;
12919
12920 return SDValue();
12921}
12922
12923template <class MatchContextClass>
12925 SelectionDAG &DAG) {
12926 assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT ||
12927 N->getOpcode() == ISD::VP_SELECT) &&
12928 "Expected a (v)(vp.)select");
12929 SDValue Cond = N->getOperand(0);
12930 SDValue T = N->getOperand(1), F = N->getOperand(2);
12931 EVT VT = N->getValueType(0);
12932 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12933 MatchContextClass matcher(DAG, TLI, N);
12934
12935 if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1)
12936 return SDValue();
12937
12938 // select Cond, Cond, F --> or Cond, freeze(F)
12939 // select Cond, 1, F --> or Cond, freeze(F)
12940 if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true))
12941 return matcher.getNode(ISD::OR, DL, VT, Cond, DAG.getFreeze(F));
12942
12943 // select Cond, T, Cond --> and Cond, freeze(T)
12944 // select Cond, T, 0 --> and Cond, freeze(T)
12945 if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true))
12946 return matcher.getNode(ISD::AND, DL, VT, Cond, DAG.getFreeze(T));
12947
12948 // select Cond, T, 1 --> or (not Cond), freeze(T)
12949 if (isOneOrOneSplat(F, /* AllowUndefs */ true)) {
12950 SDValue NotCond =
12951 matcher.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
12952 return matcher.getNode(ISD::OR, DL, VT, NotCond, DAG.getFreeze(T));
12953 }
12954
12955 // select Cond, 0, F --> and (not Cond), freeze(F)
12956 if (isNullOrNullSplat(T, /* AllowUndefs */ true)) {
12957 SDValue NotCond =
12958 matcher.getNode(ISD::XOR, DL, VT, Cond, DAG.getAllOnesConstant(DL, VT));
12959 return matcher.getNode(ISD::AND, DL, VT, NotCond, DAG.getFreeze(F));
12960 }
12961
12962 return SDValue();
12963}
12964
12966 SDValue N0 = N->getOperand(0);
12967 SDValue N1 = N->getOperand(1);
12968 SDValue N2 = N->getOperand(2);
12969 EVT VT = N->getValueType(0);
12970 unsigned EltSizeInBits = VT.getScalarSizeInBits();
12971
12972 SDValue Cond0, Cond1;
12973 ISD::CondCode CC;
12974 if (!sd_match(N0, m_OneUse(m_SetCC(m_Value(Cond0), m_Value(Cond1),
12975 m_CondCode(CC)))) ||
12976 VT != Cond0.getValueType())
12977 return SDValue();
12978
12979 // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the
12980 // compare is inverted from that pattern ("Cond0 s> -1").
12981 if (CC == ISD::SETLT && isNullOrNullSplat(Cond1))
12982 ; // This is the pattern we are looking for.
12983 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1))
12984 std::swap(N1, N2);
12985 else
12986 return SDValue();
12987
12988 // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & freeze(N1)
12989 if (isNullOrNullSplat(N2)) {
12990 SDLoc DL(N);
12991 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
12992 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
12993 return DAG.getNode(ISD::AND, DL, VT, Sra, DAG.getFreeze(N1));
12994 }
12995
12996 // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | freeze(N2)
12997 if (isAllOnesOrAllOnesSplat(N1)) {
12998 SDLoc DL(N);
12999 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
13000 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
13001 return DAG.getNode(ISD::OR, DL, VT, Sra, DAG.getFreeze(N2));
13002 }
13003
13004 // If we have to invert the sign bit mask, only do that transform if the
13005 // target has a bitwise 'and not' instruction (the invert is free).
13006 // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & freeze(N2)
13007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13008 if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) {
13009 SDLoc DL(N);
13010 SDValue ShiftAmt = DAG.getShiftAmountConstant(EltSizeInBits - 1, VT, DL);
13011 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
13012 SDValue Not = DAG.getNOT(DL, Sra, VT);
13013 return DAG.getNode(ISD::AND, DL, VT, Not, DAG.getFreeze(N2));
13014 }
13015
13016 // TODO: There's another pattern in this family, but it may require
13017 // implementing hasOrNot() to check for profitability:
13018 // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | freeze(N2)
13019
13020 return SDValue();
13021}
13022
13023// Match SELECTs with absolute difference patterns.
13024// (select (setcc a, b, set?gt), (sub a, b), (sub b, a)) --> (abd? a, b)
13025// (select (setcc a, b, set?ge), (sub a, b), (sub b, a)) --> (abd? a, b)
13026// (select (setcc a, b, set?lt), (sub b, a), (sub a, b)) --> (abd? a, b)
13027// (select (setcc a, b, set?le), (sub b, a), (sub a, b)) --> (abd? a, b)
13028SDValue DAGCombiner::foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
13029 SDValue False, ISD::CondCode CC,
13030 const SDLoc &DL) {
13031 bool IsSigned = isSignedIntSetCC(CC);
13032 unsigned ABDOpc = IsSigned ? ISD::ABDS : ISD::ABDU;
13033 EVT VT = LHS.getValueType();
13034
13035 if (LegalOperations && !hasOperation(ABDOpc, VT))
13036 return SDValue();
13037
13038 // (setcc 0, b set???) --> (setcc b, 0, set???)
13039 if (isZeroOrZeroSplat(LHS)) {
13040 std::swap(LHS, RHS);
13042 }
13043
13044 // (setcc (add nsw A, Const), 0, sets??) --> (setcc A, -Const, sets??)
13045 SDValue A, B;
13046 if (ISD::isSignedIntSetCC(CC) && LHS->getFlags().hasNoSignedWrap() &&
13049 RHS = DAG.getNegative(B, LHS, B.getValueType());
13050 LHS = A;
13051 }
13052
13053 bool IsTypeLegalOrPromote =
13054 TLI.isTypeLegal(VT) || TLI.getTypeAction(*DAG.getContext(), VT) ==
13056
13057 switch (CC) {
13058 case ISD::SETGT:
13059 case ISD::SETGE:
13060 case ISD::SETUGT:
13061 case ISD::SETUGE:
13066 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
13071 IsTypeLegalOrPromote)
13072 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
13073 break;
13074 case ISD::SETLT:
13075 case ISD::SETLE:
13076 case ISD::SETULT:
13077 case ISD::SETULE:
13082 return DAG.getNode(ABDOpc, DL, VT, LHS, RHS);
13087 IsTypeLegalOrPromote)
13088 return DAG.getNegative(DAG.getNode(ABDOpc, DL, VT, LHS, RHS), DL, VT);
13089 break;
13090 default:
13091 break;
13092 }
13093
13094 return SDValue();
13095}
13096
13097// ([v]select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
13098// ([v]select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
13099SDValue DAGCombiner::foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
13100 SDValue False, ISD::CondCode CC,
13101 const SDLoc &DL) {
13102 APInt C;
13103 EVT VT = True.getValueType();
13104 if (sd_match(RHS, m_ConstInt(C)) && hasUMin(VT)) {
13105 if (CC == ISD::SETUGT && LHS == False &&
13106 sd_match(True, m_Add(m_Specific(False), m_SpecificInt(~C)))) {
13107 SDValue AddC = DAG.getConstant(~C, DL, VT);
13108 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, False, AddC);
13109 return DAG.getNode(ISD::UMIN, DL, VT, Add, False);
13110 }
13111 if (CC == ISD::SETULT && LHS == True &&
13112 sd_match(False, m_Add(m_Specific(True), m_SpecificInt(-C)))) {
13113 SDValue AddC = DAG.getConstant(-C, DL, VT);
13114 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, True, AddC);
13115 return DAG.getNode(ISD::UMIN, DL, VT, True, Add);
13116 }
13117 }
13118 return SDValue();
13119}
13120
13121// Combine x olt y ? x : y to pseudo_fmin and x ogt y ? x : y to pseudo_fmax.
13122// Op0/Op1 are the setcc operands, LHS/RHS are the select operands, Flags are
13123// from the select.
13124// The return value is the opcode and its operands.
13125static std::tuple<unsigned, SDValue, SDValue> combineSelectCCToPseudoMinMax(
13126 SelectionDAG &DAG, const SDLoc &DL, ISD::CondCode CC, SDValue Op0,
13127 SDValue Op1, SDValue LHS, SDValue RHS, SDNodeFlags Flags, bool IsStrict) {
13128 std::tuple<unsigned, SDValue, SDValue> Invalid(0, {}, {});
13129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13130 EVT VT = LHS.getValueType();
13131 if (!VT.isFloatingPoint())
13132 return Invalid;
13133
13134 // Check for x CC y ? x : y.
13135 if (!DAG.isEqualTo(LHS, Op0) || !DAG.isEqualTo(RHS, Op1)) {
13136 if (!DAG.isEqualTo(LHS, Op1) || !DAG.isEqualTo(RHS, Op0))
13137 return Invalid;
13138
13139 // Convert x CC y ? y : x to x inv(CC) y ? x : y.
13140 CC = ISD::getSetCCInverse(CC, VT);
13141 std::swap(LHS, RHS);
13142 }
13143
13144 // Convert x CC y ? x : y to y swap(inv(CC)) x ? y : x
13145 // to convert an unordered into an ordered comparison.
13146 if (ISD::getUnorderedFlavor(CC) == 1) {
13148 std::swap(LHS, RHS);
13149 }
13150
13151 unsigned Opcode = 0;
13152 switch (CC) {
13153 default:
13154 break;
13155 case ISD::SETOLE:
13156 // Converting this to a min would handle comparisons between positive
13157 // and negative zero incorrectly.
13158 if (!Flags.hasNoSignedZeros() && !DAG.isKnownNeverLogicalZero(LHS) &&
13160 break;
13161 Opcode = ISD::PSEUDO_FMIN;
13162 break;
13163 case ISD::SETLE:
13164 // Convert setle to setlt via inv+swap.
13165 std::swap(LHS, RHS);
13166 [[fallthrough]];
13167 case ISD::SETOLT:
13168 case ISD::SETLT:
13169 Opcode = ISD::PSEUDO_FMIN;
13170 break;
13171
13172 case ISD::SETOGE:
13173 // Converting this to a max would handle comparisons between positive
13174 // and negative zero incorrectly.
13175 if (!Flags.hasNoSignedZeros() && !DAG.isKnownNeverLogicalZero(LHS) &&
13177 break;
13178 Opcode = ISD::PSEUDO_FMAX;
13179 break;
13180 case ISD::SETGE:
13181 // Convert setge to setgt via inv+swap.
13182 std::swap(LHS, RHS);
13183 [[fallthrough]];
13184 case ISD::SETOGT:
13185 case ISD::SETGT:
13186 Opcode = ISD::PSEUDO_FMAX;
13187 break;
13188 }
13189
13190 if (!Opcode)
13191 return Invalid;
13192
13193 if (IsStrict)
13194 Opcode = Opcode == ISD::PSEUDO_FMIN ? ISD::STRICT_PSEUDO_FMIN
13196 if (!TLI.isOperationLegalOrCustom(Opcode, VT))
13197 return Invalid;
13198
13199 return {Opcode, LHS, RHS};
13200}
13201
13203 SDLoc DL(N);
13204 SDValue Cond = N->getOperand(0);
13205 SDValue LHS = N->getOperand(1);
13206 SDValue RHS = N->getOperand(2);
13207 EVT VT = LHS.getValueType();
13208 if ((Cond.getOpcode() != ISD::SETCC &&
13209 Cond.getOpcode() != ISD::STRICT_FSETCCS))
13210 return SDValue();
13211
13212 bool IsStrict = Cond->isStrictFPOpcode();
13213 ISD::CondCode CC =
13214 cast<CondCodeSDNode>(Cond.getOperand(IsStrict ? 3 : 2))->get();
13215 SDValue Op0 = Cond.getOperand(IsStrict ? 1 : 0);
13216 SDValue Op1 = Cond.getOperand(IsStrict ? 2 : 1);
13217 auto [Opcode, NewLHS, NewRHS] = combineSelectCCToPseudoMinMax(
13218 DAG, DL, CC, Op0, Op1, LHS, RHS, N->getFlags(), IsStrict);
13219 if (!Opcode)
13220 return SDValue();
13221
13222 // Propagate fast-math-flags.
13223 SelectionDAG::FlagInserter FlagsInserter(DAG, N->getFlags());
13224 if (IsStrict) {
13225 SDValue Ret = DAG.getNode(Opcode, DL, {VT, MVT::Other},
13226 {Cond.getOperand(0), NewLHS, NewRHS});
13227 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Ret.getValue(1));
13228 return Ret;
13229 }
13230 return DAG.getNode(Opcode, DL, VT, NewLHS, NewRHS);
13231}
13232
13233SDValue DAGCombiner::visitSELECT(SDNode *N) {
13234 SDValue N0 = N->getOperand(0);
13235 SDValue N1 = N->getOperand(1);
13236 SDValue N2 = N->getOperand(2);
13237 EVT VT = N->getValueType(0);
13238 EVT VT0 = N0.getValueType();
13239 SDLoc DL(N);
13240 SDNodeFlags Flags = N->getFlags();
13241
13242 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
13243 return V;
13244
13246 return V;
13247
13248 // select (not Cond), N1, N2 -> select Cond, N2, N1
13249 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
13250 return DAG.getSelect(DL, VT, F, N2, N1, Flags);
13251
13252 if (SDValue V = foldSelectOfConstants(N))
13253 return V;
13254
13255 // If we can fold this based on the true/false value, do so.
13256 if (SimplifySelectOps(N, N1, N2))
13257 return SDValue(N, 0); // Don't revisit N.
13258
13259 if (VT0 == MVT::i1) {
13260 // The code in this block deals with the following 2 equivalences:
13261 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
13262 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
13263 // The target can specify its preferred form with the
13264 // shouldNormalizeToSelectSequence() callback. However we always transform
13265 // to the right anyway if we find the inner select exists in the DAG anyway
13266 // and we always transform to the left side if we know that we can further
13267 // optimize the combination of the conditions.
13268 bool normalizeToSequence =
13269 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT, VT0);
13270 // select (and Cond0, Cond1), X, Y
13271 // -> select Cond0, (select Cond1, X, Y), Y
13272 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
13273 SDValue Cond0 = N0->getOperand(0);
13274 SDValue Cond1 = N0->getOperand(1);
13275 SDValue InnerSelect =
13276 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
13277 if (normalizeToSequence || !InnerSelect.use_empty())
13278 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
13279 InnerSelect, N2, Flags);
13280 // Cleanup on failure.
13281 if (InnerSelect.use_empty())
13282 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13283 }
13284 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
13285 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
13286 SDValue Cond0 = N0->getOperand(0);
13287 SDValue Cond1 = N0->getOperand(1);
13288 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
13289 Cond1, N1, N2, Flags);
13290 if (normalizeToSequence || !InnerSelect.use_empty())
13291 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
13292 InnerSelect, Flags);
13293 // Cleanup on failure.
13294 if (InnerSelect.use_empty())
13295 recursivelyDeleteUnusedNodes(InnerSelect.getNode());
13296 }
13297
13298 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
13299 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
13300 SDValue N1_0 = N1->getOperand(0);
13301 SDValue N1_1 = N1->getOperand(1);
13302 SDValue N1_2 = N1->getOperand(2);
13303 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
13304 // Create the actual and node if we can generate good code for it.
13305 if (!normalizeToSequence) {
13306 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
13307 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
13308 N2, Flags);
13309 }
13310 // Otherwise see if we can optimize the "and" to a better pattern.
13311 if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
13312 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
13313 N2, Flags);
13314 }
13315 }
13316 }
13317 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
13318 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
13319 SDValue N2_0 = N2->getOperand(0);
13320 SDValue N2_1 = N2->getOperand(1);
13321 SDValue N2_2 = N2->getOperand(2);
13322 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
13323 // Create the actual or node if we can generate good code for it.
13324 if (!normalizeToSequence) {
13325 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
13326 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
13327 N2_2, Flags);
13328 }
13329 // Otherwise see if we can optimize to a better pattern.
13330 if (SDValue Combined = visitORLike(N0, N2_0, DL))
13331 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
13332 N2_2, Flags);
13333 }
13334 }
13335
13336 // select usubo(x, y).overflow, (sub y, x), (usubo x, y) -> abdu(x, y)
13337 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13338 N2.getNode() == N0.getNode() && N2.getResNo() == 0 &&
13339 N1.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13340 N2.getOperand(1) == N1.getOperand(0) &&
13341 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13342 return DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1));
13343
13344 // select usubo(x, y).overflow, (usubo x, y), (sub y, x) -> neg (abdu x, y)
13345 if (N0.getOpcode() == ISD::USUBO && N0.getResNo() == 1 &&
13346 N1.getNode() == N0.getNode() && N1.getResNo() == 0 &&
13347 N2.getOpcode() == ISD::SUB && N2.getOperand(0) == N1.getOperand(1) &&
13348 N2.getOperand(1) == N1.getOperand(0) &&
13349 (!LegalOperations || TLI.isOperationLegal(ISD::ABDU, VT)))
13350 return DAG.getNegative(
13351 DAG.getNode(ISD::ABDU, DL, VT, N0.getOperand(0), N0.getOperand(1)),
13352 DL, VT);
13353 }
13354
13355 // Fold selects based on a setcc into other things, such as min/max/abs.
13356 if (N0.getOpcode() == ISD::SETCC) {
13357 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
13359
13360 // select (fcmp lt x, y), x, y -> fminnum x, y
13361 // select (fcmp gt x, y), x, y -> fmaxnum x, y
13362 //
13363 // This is OK if we don't care what happens if either operand is a NaN.
13364 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, Flags, TLI))
13365 if (SDValue FMinMax =
13366 combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, CC))
13367 return FMinMax;
13368
13369 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
13370 // This is conservatively limited to pre-legal-operations to give targets
13371 // a chance to reverse the transform if they want to do that. Also, it is
13372 // unlikely that the pattern would be formed late, so it's probably not
13373 // worth going through the other checks.
13374 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
13375 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
13376 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
13377 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
13378 auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
13379 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
13380 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
13381 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
13382 //
13383 // The IR equivalent of this transform would have this form:
13384 // %a = add %x, C
13385 // %c = icmp ugt %x, ~C
13386 // %r = select %c, -1, %a
13387 // =>
13388 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
13389 // %u0 = extractvalue %u, 0
13390 // %u1 = extractvalue %u, 1
13391 // %r = select %u1, -1, %u0
13392 SDVTList VTs = DAG.getVTList(VT, VT0);
13393 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
13394 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
13395 }
13396 }
13397
13398 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
13399 (!LegalOperations &&
13401 // Any flags available in a select/setcc fold will be on the setcc as they
13402 // migrated from fcmp
13403 return DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, N2,
13404 N0.getOperand(2), N0->getFlags());
13405 }
13406
13407 if (SDValue ABD = foldSelectToABD(Cond0, Cond1, N1, N2, CC, DL))
13408 return ABD;
13409
13410 if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
13411 return NewSel;
13412
13413 // (select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
13414 // (select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
13415 if (SDValue UMin = foldSelectToUMin(Cond0, Cond1, N1, N2, CC, DL))
13416 return UMin;
13417 }
13418
13419 if (!VT.isVector())
13420 if (SDValue BinOp = foldSelectOfBinops(N))
13421 return BinOp;
13422
13423 if (SDValue R = combineSelectAsExtAnd(N0, N1, N2, DL, DAG))
13424 return R;
13425
13427 return R;
13428
13429 return SDValue();
13430}
13431
13432// This function assumes all the vselect's arguments are CONCAT_VECTOR
13433// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
13435 SDLoc DL(N);
13436 SDValue Cond = N->getOperand(0);
13437 SDValue LHS = N->getOperand(1);
13438 SDValue RHS = N->getOperand(2);
13439 EVT VT = N->getValueType(0);
13440 int NumElems = VT.getVectorNumElements();
13441 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
13442 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
13443 Cond.getOpcode() == ISD::BUILD_VECTOR);
13444
13445 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
13446 // binary ones here.
13447 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
13448 return SDValue();
13449
13450 // We're sure we have an even number of elements due to the
13451 // concat_vectors we have as arguments to vselect.
13452 // Skip BV elements until we find one that's not an UNDEF
13453 // After we find an UNDEF element, keep looping until we get to half the
13454 // length of the BV and see if all the non-undef nodes are the same.
13455 ConstantSDNode *BottomHalf = nullptr;
13456 for (int i = 0; i < NumElems / 2; ++i) {
13457 if (Cond->getOperand(i)->isUndef())
13458 continue;
13459
13460 if (BottomHalf == nullptr)
13461 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13462 else if (Cond->getOperand(i).getNode() != BottomHalf)
13463 return SDValue();
13464 }
13465
13466 // Do the same for the second half of the BuildVector
13467 ConstantSDNode *TopHalf = nullptr;
13468 for (int i = NumElems / 2; i < NumElems; ++i) {
13469 if (Cond->getOperand(i)->isUndef())
13470 continue;
13471
13472 if (TopHalf == nullptr)
13473 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
13474 else if (Cond->getOperand(i).getNode() != TopHalf)
13475 return SDValue();
13476 }
13477
13478 assert(TopHalf && BottomHalf &&
13479 "One half of the selector was all UNDEFs and the other was all the "
13480 "same value. This should have been addressed before this function.");
13481 return DAG.getNode(
13483 BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0),
13484 TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1));
13485}
13486
13487bool refineUniformBase(SDValue &BasePtr, SDValue &Index, bool IndexIsScaled,
13488 SelectionDAG &DAG, const SDLoc &DL) {
13489
13490 // Only perform the transformation when existing operands can be reused.
13491 if (IndexIsScaled)
13492 return false;
13493
13494 if (!isNullConstant(BasePtr) && !Index.hasOneUse())
13495 return false;
13496
13497 EVT VT = BasePtr.getValueType();
13498
13499 if (SDValue SplatVal = DAG.getSplatValue(Index);
13500 SplatVal && !isNullConstant(SplatVal) &&
13501 SplatVal.getValueType() == VT) {
13502 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13503 Index = DAG.getSplat(Index.getValueType(), DL, DAG.getConstant(0, DL, VT));
13504 return true;
13505 }
13506
13507 if (Index.getOpcode() != ISD::ADD)
13508 return false;
13509
13510 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(0));
13511 SplatVal && SplatVal.getValueType() == VT) {
13512 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13513 Index = Index.getOperand(1);
13514 return true;
13515 }
13516 if (SDValue SplatVal = DAG.getSplatValue(Index.getOperand(1));
13517 SplatVal && SplatVal.getValueType() == VT) {
13518 BasePtr = DAG.getNode(ISD::ADD, DL, VT, BasePtr, SplatVal);
13519 Index = Index.getOperand(0);
13520 return true;
13521 }
13522 return false;
13523}
13524
13525// Fold sext/zext of index into index type.
13526bool refineIndexType(SDValue &Index, ISD::MemIndexType &IndexType, EVT DataVT,
13527 SelectionDAG &DAG) {
13528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13529
13530 // It's always safe to look through zero extends.
13531 if (Index.getOpcode() == ISD::ZERO_EXTEND) {
13532 if (TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13533 IndexType = ISD::UNSIGNED_SCALED;
13534 Index = Index.getOperand(0);
13535 return true;
13536 }
13537 if (ISD::isIndexTypeSigned(IndexType)) {
13538 IndexType = ISD::UNSIGNED_SCALED;
13539 return true;
13540 }
13541 }
13542
13543 // It's only safe to look through sign extends when Index is signed.
13544 if (Index.getOpcode() == ISD::SIGN_EXTEND &&
13545 ISD::isIndexTypeSigned(IndexType) &&
13546 TLI.shouldRemoveExtendFromGSIndex(Index, DataVT)) {
13547 Index = Index.getOperand(0);
13548 return true;
13549 }
13550
13551 return false;
13552}
13553
13554SDValue DAGCombiner::visitVPSCATTER(SDNode *N) {
13555 VPScatterSDNode *MSC = cast<VPScatterSDNode>(N);
13556 SDValue Mask = MSC->getMask();
13557 SDValue Chain = MSC->getChain();
13558 SDValue Index = MSC->getIndex();
13559 SDValue Scale = MSC->getScale();
13560 SDValue StoreVal = MSC->getValue();
13561 SDValue BasePtr = MSC->getBasePtr();
13562 SDValue VL = MSC->getVectorLength();
13563 ISD::MemIndexType IndexType = MSC->getIndexType();
13564 SDLoc DL(N);
13565
13566 // Zap scatters with a zero mask.
13568 return Chain;
13569
13570 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13571 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13572 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13573 DL, Ops, MSC->getMemOperand(), IndexType);
13574 }
13575
13576 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13577 SDValue Ops[] = {Chain, StoreVal, BasePtr, Index, Scale, Mask, VL};
13578 return DAG.getScatterVP(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13579 DL, Ops, MSC->getMemOperand(), IndexType);
13580 }
13581
13582 return SDValue();
13583}
13584
13585SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
13586 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
13587 SDValue Mask = MSC->getMask();
13588 SDValue Chain = MSC->getChain();
13589 SDValue Index = MSC->getIndex();
13590 SDValue Scale = MSC->getScale();
13591 SDValue StoreVal = MSC->getValue();
13592 SDValue BasePtr = MSC->getBasePtr();
13593 ISD::MemIndexType IndexType = MSC->getIndexType();
13594 SDLoc DL(N);
13595
13596 // Zap scatters with a zero mask.
13598 return Chain;
13599
13600 if (refineUniformBase(BasePtr, Index, MSC->isIndexScaled(), DAG, DL)) {
13601 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13602 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13603 DL, Ops, MSC->getMemOperand(), IndexType,
13604 MSC->isTruncatingStore());
13605 }
13606
13607 if (refineIndexType(Index, IndexType, StoreVal.getValueType(), DAG)) {
13608 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
13609 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), MSC->getMemoryVT(),
13610 DL, Ops, MSC->getMemOperand(), IndexType,
13611 MSC->isTruncatingStore());
13612 }
13613
13614 return SDValue();
13615}
13616
13617SDValue DAGCombiner::visitMSTORE(SDNode *N) {
13618 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
13619 SDValue Mask = MST->getMask();
13620 SDValue Chain = MST->getChain();
13621 SDValue Value = MST->getValue();
13622 SDValue Ptr = MST->getBasePtr();
13623
13624 // Zap masked stores with a zero mask.
13626 return Chain;
13627
13628 // Remove a masked store if base pointers and masks are equal.
13629 if (MaskedStoreSDNode *MST1 = dyn_cast<MaskedStoreSDNode>(Chain)) {
13630 if (MST->isUnindexed() && MST->isSimple() && MST1->isUnindexed() &&
13631 MST1->isSimple() && MST1->getBasePtr() == Ptr &&
13632 !MST->getBasePtr().isUndef() &&
13633 ((Mask == MST1->getMask() && MST->getMemoryVT().getStoreSize() ==
13634 MST1->getMemoryVT().getStoreSize()) ||
13636 TypeSize::isKnownLE(MST1->getMemoryVT().getStoreSize(),
13637 MST->getMemoryVT().getStoreSize())) {
13638 CombineTo(MST1, MST1->getChain());
13639 if (N->getOpcode() != ISD::DELETED_NODE)
13640 AddToWorklist(N);
13641 return SDValue(N, 0);
13642 }
13643 }
13644
13645 // If this is a masked load with an all ones mask, we can use a unmasked load.
13646 // FIXME: Can we do this for indexed, compressing, or truncating stores?
13647 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MST->isUnindexed() &&
13648 !MST->isCompressingStore() && !MST->isTruncatingStore())
13649 return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(),
13650 MST->getBasePtr(), MST->getPointerInfo(),
13651 MST->getBaseAlign(), MST->getMemOperand()->getFlags(),
13652 MST->getAAInfo());
13653
13654 // Try transforming N to an indexed store.
13655 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13656 return SDValue(N, 0);
13657
13658 if (MST->isTruncatingStore() && MST->isUnindexed() &&
13659 Value.getValueType().isInteger() &&
13661 !cast<ConstantSDNode>(Value)->isOpaque())) {
13662 APInt TruncDemandedBits =
13663 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13665
13666 // See if we can simplify the operation with
13667 // SimplifyDemandedBits, which only works if the value has a single use.
13668 if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
13669 // Re-visit the store if anything changed and the store hasn't been merged
13670 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13671 // node back to the worklist if necessary, but we also need to re-visit
13672 // the Store node itself.
13673 if (N->getOpcode() != ISD::DELETED_NODE)
13674 AddToWorklist(N);
13675 return SDValue(N, 0);
13676 }
13677 }
13678
13679 // If this is a TRUNC followed by a masked store, fold this into a masked
13680 // truncating store. We can do this even if this is already a masked
13681 // truncstore.
13682 // TODO: Try combine to masked compress store if possiable.
13683 if ((Value.getOpcode() == ISD::TRUNCATE) && Value->hasOneUse() &&
13684 MST->isUnindexed() && !MST->isCompressingStore() &&
13685 TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
13686 MST->getMemoryVT(), MST->getAlign(),
13687 MST->getAddressSpace(), LegalOperations)) {
13688 auto Mask = TLI.promoteTargetBoolean(DAG, MST->getMask(),
13689 Value.getOperand(0).getValueType());
13690 return DAG.getMaskedStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13691 MST->getOffset(), Mask, MST->getMemoryVT(),
13692 MST->getMemOperand(), MST->getAddressingMode(),
13693 /*IsTruncating=*/true);
13694 }
13695
13696 return SDValue();
13697}
13698
13699SDValue DAGCombiner::visitVP_STRIDED_STORE(SDNode *N) {
13700 auto *SST = cast<VPStridedStoreSDNode>(N);
13701 EVT EltVT = SST->getValue().getValueType().getVectorElementType();
13702 // Combine strided stores with unit-stride to a regular VP store.
13703 if (auto *CStride = dyn_cast<ConstantSDNode>(SST->getStride());
13704 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
13705 return DAG.getStoreVP(SST->getChain(), SDLoc(N), SST->getValue(),
13706 SST->getBasePtr(), SST->getOffset(), SST->getMask(),
13707 SST->getVectorLength(), SST->getMemoryVT(),
13708 SST->getMemOperand(), SST->getAddressingMode(),
13709 SST->isTruncatingStore(), SST->isCompressingStore());
13710 }
13711 return SDValue();
13712}
13713
13714SDValue DAGCombiner::visitVECTOR_COMPRESS(SDNode *N) {
13715 SDLoc DL(N);
13716 SDValue Vec = N->getOperand(0);
13717 SDValue Mask = N->getOperand(1);
13718 SDValue Passthru = N->getOperand(2);
13719 EVT VecVT = Vec.getValueType();
13720
13721 bool HasPassthru = !Passthru.isUndef();
13722
13723 APInt SplatVal;
13724 if (ISD::isConstantSplatVector(Mask.getNode(), SplatVal))
13725 return TLI.isConstTrueVal(Mask) ? Vec : Passthru;
13726
13727 if (Vec.isUndef() || Mask.isUndef())
13728 return Passthru;
13729
13730 // No need for potentially expensive compress if the mask is constant.
13733 EVT ScalarVT = VecVT.getVectorElementType();
13734 unsigned NumSelected = 0;
13735 unsigned NumElmts = VecVT.getVectorNumElements();
13736 for (unsigned I = 0; I < NumElmts; ++I) {
13737 SDValue MaskI = Mask.getOperand(I);
13738 // We treat undef mask entries as "false".
13739 if (MaskI.isUndef())
13740 continue;
13741
13742 if (TLI.isConstTrueVal(MaskI)) {
13743 SDValue VecI = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Vec,
13744 DAG.getVectorIdxConstant(I, DL));
13745 Ops.push_back(VecI);
13746 NumSelected++;
13747 }
13748 }
13749 for (unsigned Rest = NumSelected; Rest < NumElmts; ++Rest) {
13750 SDValue Val =
13751 HasPassthru
13752 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Passthru,
13753 DAG.getVectorIdxConstant(Rest, DL))
13754 : DAG.getUNDEF(ScalarVT);
13755 Ops.push_back(Val);
13756 }
13757 return DAG.getBuildVector(VecVT, DL, Ops);
13758 }
13759
13760 return SDValue();
13761}
13762
13763SDValue DAGCombiner::visitVPGATHER(SDNode *N) {
13764 VPGatherSDNode *MGT = cast<VPGatherSDNode>(N);
13765 SDValue Mask = MGT->getMask();
13766 SDValue Chain = MGT->getChain();
13767 SDValue Index = MGT->getIndex();
13768 SDValue Scale = MGT->getScale();
13769 SDValue BasePtr = MGT->getBasePtr();
13770 SDValue VL = MGT->getVectorLength();
13771 ISD::MemIndexType IndexType = MGT->getIndexType();
13772 SDLoc DL(N);
13773
13774 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
13775 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
13776 return DAG.getGatherVP(
13777 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13778 Ops, MGT->getMemOperand(), IndexType);
13779 }
13780
13781 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
13782 SDValue Ops[] = {Chain, BasePtr, Index, Scale, Mask, VL};
13783 return DAG.getGatherVP(
13784 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13785 Ops, MGT->getMemOperand(), IndexType);
13786 }
13787
13788 return SDValue();
13789}
13790
13791SDValue DAGCombiner::visitMGATHER(SDNode *N) {
13792 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
13793 SDValue Mask = MGT->getMask();
13794 SDValue Chain = MGT->getChain();
13795 SDValue Index = MGT->getIndex();
13796 SDValue Scale = MGT->getScale();
13797 SDValue PassThru = MGT->getPassThru();
13798 SDValue BasePtr = MGT->getBasePtr();
13799 ISD::MemIndexType IndexType = MGT->getIndexType();
13800 SDLoc DL(N);
13801
13802 // Zap gathers with a zero mask.
13804 return CombineTo(N, PassThru, MGT->getChain());
13805
13806 if (refineUniformBase(BasePtr, Index, MGT->isIndexScaled(), DAG, DL)) {
13807 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
13808 return DAG.getMaskedGather(
13809 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13810 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
13811 }
13812
13813 if (refineIndexType(Index, IndexType, N->getValueType(0), DAG)) {
13814 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
13815 return DAG.getMaskedGather(
13816 DAG.getVTList(N->getValueType(0), MVT::Other), MGT->getMemoryVT(), DL,
13817 Ops, MGT->getMemOperand(), IndexType, MGT->getExtensionType());
13818 }
13819
13820 return SDValue();
13821}
13822
13823SDValue DAGCombiner::visitMLOAD(SDNode *N) {
13824 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
13825 SDValue Mask = MLD->getMask();
13826
13827 // Zap masked loads with a zero mask.
13829 return CombineTo(N, MLD->getPassThru(), MLD->getChain());
13830
13831 // If this is a masked load with an all ones mask, we can use a unmasked load.
13832 // FIXME: Can we do this for indexed, expanding, or extending loads?
13833 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MLD->isUnindexed() &&
13834 !MLD->isExpandingLoad() && MLD->getExtensionType() == ISD::NON_EXTLOAD) {
13835 SDValue NewLd = DAG.getLoad(
13836 N->getValueType(0), SDLoc(N), MLD->getChain(), MLD->getBasePtr(),
13837 MLD->getPointerInfo(), MLD->getBaseAlign(),
13838 MLD->getMemOperand()->getFlags(), MLD->getAAInfo(), MLD->getRanges());
13839 return CombineTo(N, NewLd, NewLd.getValue(1));
13840 }
13841
13842 // Try transforming N to an indexed load.
13843 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13844 return SDValue(N, 0);
13845
13846 return SDValue();
13847}
13848
13849SDValue DAGCombiner::visitMHISTOGRAM(SDNode *N) {
13850 MaskedHistogramSDNode *HG = cast<MaskedHistogramSDNode>(N);
13851 SDValue Chain = HG->getChain();
13852 SDValue Inc = HG->getInc();
13853 SDValue Mask = HG->getMask();
13854 SDValue BasePtr = HG->getBasePtr();
13855 SDValue Index = HG->getIndex();
13856 SDLoc DL(HG);
13857
13858 EVT MemVT = HG->getMemoryVT();
13859 EVT DataVT = Index.getValueType();
13860 MachineMemOperand *MMO = HG->getMemOperand();
13861 ISD::MemIndexType IndexType = HG->getIndexType();
13862
13864 return Chain;
13865
13866 if (refineUniformBase(BasePtr, Index, HG->isIndexScaled(), DAG, DL) ||
13867 refineIndexType(Index, IndexType, DataVT, DAG)) {
13868 SDValue Ops[] = {Chain, Inc, Mask, BasePtr, Index,
13869 HG->getScale(), HG->getIntID()};
13870 return DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), MemVT, DL, Ops,
13871 MMO, IndexType);
13872 }
13873
13874 return SDValue();
13875}
13876
13877SDValue DAGCombiner::visitPARTIAL_REDUCE_MLA(SDNode *N) {
13878 if (SDValue Res = foldPartialReduceMLAMulOp(N))
13879 return Res;
13880 if (SDValue Res = foldPartialReduceAdd(N))
13881 return Res;
13882 return SDValue();
13883}
13884
13885// partial_reduce_*mla(acc, mul(*ext(a), *ext(b)), splat(1))
13886// -> partial_reduce_*mla(acc, a, b)
13887//
13888// partial_reduce_*mla(acc, mul(*ext(x), splat(C)), splat(1))
13889// -> partial_reduce_*mla(acc, x, splat(C))
13890//
13891// partial_reduce_*mla(acc, sel(p, mul(*ext(a), *ext(b)), splat(0)), splat(1))
13892// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), b)
13893//
13894// partial_reduce_*mla(acc, sel(p, mul(*ext(a), splat(C)), splat(0)), splat(1))
13895// -> partial_reduce_*mla(acc, sel(p, a, splat(0)), splat(C))
13896//
13897// `sel` could either be VSELECT or VP_MERGE.
13898SDValue DAGCombiner::foldPartialReduceMLAMulOp(SDNode *N) {
13899 SDLoc DL(N);
13900 auto *Context = DAG.getContext();
13901 SDValue Tmp;
13902 SDValue Acc = N->getOperand(0);
13903 SDValue Op1 = N->getOperand(1);
13904 SDValue OrigOp1 = Op1;
13905 SDValue Op2 = N->getOperand(2);
13906 unsigned Opc = Op1->getOpcode();
13907
13908 // Handle predication by moving the VSELECT / VP_MERGE into the operand of the
13909 // MUL.
13910 SDValue Pred;
13911 if ((Opc == ISD::VSELECT || Opc == ISD::VP_MERGE) &&
13912 (isZeroOrZeroSplat(Op1->getOperand(2)) ||
13913 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
13914 Pred = Op1->getOperand(0);
13915 Op1 = Op1->getOperand(1);
13916 Opc = Op1->getOpcode();
13917 }
13918
13919 // Handle negation (sub-reduction).
13920 bool IsMLS = false;
13921 if (sd_match(Op1, m_Neg(m_Value(Tmp)))) {
13922 Op1 = Tmp;
13923 Opc = Op1->getOpcode();
13924 IsMLS = true;
13925 }
13926
13927 if (Opc != ISD::MUL && Opc != ISD::FMUL && Opc != ISD::SHL)
13928 return SDValue();
13929
13930 SDValue LHS = Op1->getOperand(0);
13931 SDValue RHS = Op1->getOperand(1);
13932
13933 // After instcombine, negation for FP operations is on the RHS, so implement:
13934 // fmul(fpext(a), fneg(fpext(b)))
13935 //-> fmul(fpext(a), fpext(fneg(b)))
13936 if (sd_match(RHS, m_FNeg(m_Value(Tmp)))) {
13937 RHS = Tmp;
13938 IsMLS = true;
13939 }
13940
13941 // Try to treat (shl %a, %c) as (mul %a, (1 << %c)) for constant %c.
13942 if (Opc == ISD::SHL) {
13943 APInt C;
13944 if (!ISD::isConstantSplatVector(RHS.getNode(), C))
13945 return SDValue();
13946
13947 RHS =
13948 DAG.getSplatVector(RHS.getValueType(), DL,
13949 DAG.getConstant(APInt(C.getBitWidth(), 1).shl(C), DL,
13950 RHS.getValueType().getScalarType()));
13951 Opc = ISD::MUL;
13952 }
13953
13954 if (!(Opc == ISD::MUL && llvm::isOneOrOneSplat(Op2)) &&
13956 return SDValue();
13957
13958 auto IsIntOrFPExtOpcode = [](unsigned int Opcode) {
13959 return (ISD::isExtOpcode(Opcode) || Opcode == ISD::FP_EXTEND);
13960 };
13961
13962 unsigned LHSOpcode = LHS->getOpcode();
13963 if (!IsIntOrFPExtOpcode(LHSOpcode))
13964 return SDValue();
13965
13966 SDValue LHSExtOp = LHS->getOperand(0);
13967 EVT LHSExtOpVT = LHSExtOp.getValueType();
13968
13969 // When Pred is non-zero, set Op = select(Pred, Op, splat(0)) and freeze
13970 // OtherOp to keep the same semantics when moving the selects into the MUL
13971 // operands.
13972 auto ApplyPredicate = [&](SDValue &Op, SDValue &OtherOp) {
13973 if (Pred) {
13974 EVT OpVT = Op.getValueType();
13975 SDValue Zero = OpVT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, OpVT)
13976 : DAG.getConstant(0, DL, OpVT);
13977 if (OrigOp1.getOpcode() == ISD::VP_MERGE)
13978 Op = DAG.getNode(ISD::VP_MERGE, DL, OpVT, Pred, Op, Zero,
13979 OrigOp1.getOperand(3));
13980 else
13981 Op = DAG.getSelect(DL, OpVT, Pred, Op, Zero);
13982 OtherOp = DAG.getFreeze(OtherOp);
13983 }
13984 };
13985
13986 // Generate an MLA or MLS.
13987 auto GetMLA = [&](unsigned Opc, SDValue Acc, SDValue LHS,
13988 SDValue RHS) -> SDValue {
13989 EVT AccVT = Acc.getValueType();
13990 return IsMLS ? DAG.getPartialReduceMLS(Opc, DL, Acc, LHS, RHS)
13991 : DAG.getNode(Opc, DL, AccVT, Acc, LHS, RHS);
13992 };
13993
13994 // partial_reduce_*mla(acc, mul(ext(x), splat(C)), splat(1))
13995 // -> partial_reduce_*mla(acc, x, C)
13996 APInt C;
13997 if (ISD::isConstantSplatVector(RHS.getNode(), C)) {
13998 // TODO: Make use of partial_reduce_sumla here
13999 APInt CTrunc = C.trunc(LHSExtOpVT.getScalarSizeInBits());
14000 unsigned LHSBits = LHS.getValueType().getScalarSizeInBits();
14001 if ((LHSOpcode != ISD::ZERO_EXTEND || CTrunc.zext(LHSBits) != C) &&
14002 (LHSOpcode != ISD::SIGN_EXTEND || CTrunc.sext(LHSBits) != C))
14003 return SDValue();
14004
14005 unsigned NewOpcode = LHSOpcode == ISD::SIGN_EXTEND
14008
14009 // Only perform these combines if the target supports folding
14010 // the extends into the operation.
14012 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14013 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
14014 return SDValue();
14015
14016 SDValue C = DAG.getConstant(CTrunc, DL, LHSExtOpVT);
14017 ApplyPredicate(C, LHSExtOp);
14018 return GetMLA(NewOpcode, Acc, LHSExtOp, C);
14019 }
14020
14021 unsigned RHSOpcode = RHS->getOpcode();
14022 if (!IsIntOrFPExtOpcode(RHSOpcode))
14023 return SDValue();
14024
14025 SDValue RHSExtOp = RHS->getOperand(0);
14026 if (LHSExtOpVT != RHSExtOp.getValueType())
14027 return SDValue();
14028
14029 unsigned NewOpc;
14030 if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::SIGN_EXTEND)
14031 NewOpc = ISD::PARTIAL_REDUCE_SMLA;
14032 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
14033 NewOpc = ISD::PARTIAL_REDUCE_UMLA;
14034 else if (LHSOpcode == ISD::SIGN_EXTEND && RHSOpcode == ISD::ZERO_EXTEND)
14036 else if (LHSOpcode == ISD::ZERO_EXTEND && RHSOpcode == ISD::SIGN_EXTEND) {
14038 std::swap(LHSExtOp, RHSExtOp);
14039 } else if (LHSOpcode == ISD::FP_EXTEND && RHSOpcode == ISD::FP_EXTEND) {
14040 NewOpc = ISD::PARTIAL_REDUCE_FMLA;
14041 } else
14042 return SDValue();
14043 // For a 2-stage extend the signedness of both of the extends must match
14044 // If the mul has the same type, there is no outer extend, and thus we
14045 // can simply use the inner extends to pick the result node.
14046 // TODO: extend to handle nonneg zext as sext
14047 EVT AccElemVT = Acc.getValueType().getVectorElementType();
14048 if (Op1.getValueType().getVectorElementType() != AccElemVT &&
14049 NewOpc != N->getOpcode())
14050 return SDValue();
14051
14052 // Only perform these combines if the target supports folding
14053 // the extends into the operation.
14055 NewOpc, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14056 TLI.getTypeToTransformTo(*Context, LHSExtOpVT)))
14057 return SDValue();
14058
14059 ApplyPredicate(RHSExtOp, LHSExtOp);
14060 return GetMLA(NewOpc, Acc, LHSExtOp, RHSExtOp);
14061}
14062
14063// partial.reduce.*mla(acc, *ext(op), splat(1))
14064// -> partial.reduce.*mla(acc, op, splat(trunc(1)))
14065// partial.reduce.sumla(acc, sext(op), splat(1))
14066// -> partial.reduce.smla(acc, op, splat(trunc(1)))
14067//
14068// partial.reduce.*mla(acc, sel(p, *ext(op), splat(0)), splat(1))
14069// -> partial.reduce.*mla(acc, sel(p, op, splat(0)), splat(trunc(1)))
14070SDValue DAGCombiner::foldPartialReduceAdd(SDNode *N) {
14071 SDLoc DL(N);
14072 SDValue Tmp;
14073 SDValue Acc = N->getOperand(0);
14074 SDValue Op1 = N->getOperand(1);
14075 SDValue Op2 = N->getOperand(2);
14076
14078 return SDValue();
14079
14080 SDValue Pred;
14081 unsigned Op1Opcode = Op1.getOpcode();
14082 if (Op1Opcode == ISD::VSELECT && (isZeroOrZeroSplat(Op1->getOperand(2)) ||
14083 isZeroOrZeroSplatFP(Op1->getOperand(2)))) {
14084 Pred = Op1->getOperand(0);
14085 Op1 = Op1->getOperand(1);
14086 Op1Opcode = Op1->getOpcode();
14087 }
14088
14089 // Handle negation (sub-reduction).
14090 bool IsMLS = false;
14091 if (sd_match(Op1, m_AnyOf(m_Neg(m_Value(Tmp)), m_FNeg(m_Value(Tmp))))) {
14092 Op1 = Tmp;
14093 Op1Opcode = Op1.getOpcode();
14094 IsMLS = true;
14095 }
14096
14097 if (!ISD::isExtOpcode(Op1Opcode) && Op1Opcode != ISD::FP_EXTEND)
14098 return SDValue();
14099
14100 bool Op1IsSigned =
14101 Op1Opcode == ISD::SIGN_EXTEND || Op1Opcode == ISD::FP_EXTEND;
14102 bool NodeIsSigned = N->getOpcode() != ISD::PARTIAL_REDUCE_UMLA;
14103 EVT AccElemVT = Acc.getValueType().getVectorElementType();
14104 if (Op1IsSigned != NodeIsSigned &&
14105 Op1.getValueType().getVectorElementType() != AccElemVT)
14106 return SDValue();
14107
14108 unsigned NewOpcode = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14110 : Op1IsSigned ? ISD::PARTIAL_REDUCE_SMLA
14112
14113 SDValue UnextOp1 = Op1.getOperand(0);
14114 EVT UnextOp1VT = UnextOp1.getValueType();
14115 auto *Context = DAG.getContext();
14117 NewOpcode, TLI.getTypeToTransformTo(*Context, N->getValueType(0)),
14118 TLI.getTypeToTransformTo(*Context, UnextOp1VT)))
14119 return SDValue();
14120
14121 SDValue Constant = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14122 ? DAG.getConstantFP(1, DL, UnextOp1VT)
14123 : DAG.getConstant(1, DL, UnextOp1VT);
14124
14125 if (Pred) {
14126 SDValue Zero = N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA
14127 ? DAG.getConstantFP(0, DL, UnextOp1VT)
14128 : DAG.getConstant(0, DL, UnextOp1VT);
14129 Constant = DAG.getSelect(DL, UnextOp1VT, Pred, Constant, Zero);
14130 }
14131 EVT AccVT = Acc.getValueType();
14132 return IsMLS ? DAG.getPartialReduceMLS(NewOpcode, DL, Acc, UnextOp1, Constant)
14133 : DAG.getNode(NewOpcode, DL, AccVT, Acc, UnextOp1, Constant);
14134}
14135
14136SDValue DAGCombiner::visitVP_STRIDED_LOAD(SDNode *N) {
14137 auto *SLD = cast<VPStridedLoadSDNode>(N);
14138 EVT EltVT = SLD->getValueType(0).getVectorElementType();
14139 // Combine strided loads with unit-stride to a regular VP load.
14140 if (auto *CStride = dyn_cast<ConstantSDNode>(SLD->getStride());
14141 CStride && CStride->getZExtValue() == EltVT.getStoreSize()) {
14142 SDValue NewLd = DAG.getLoadVP(
14143 SLD->getAddressingMode(), SLD->getExtensionType(), SLD->getValueType(0),
14144 SDLoc(N), SLD->getChain(), SLD->getBasePtr(), SLD->getOffset(),
14145 SLD->getMask(), SLD->getVectorLength(), SLD->getMemoryVT(),
14146 SLD->getMemOperand(), SLD->isExpandingLoad());
14147 return CombineTo(N, NewLd, NewLd.getValue(1));
14148 }
14149 return SDValue();
14150}
14151
14152/// A vector select of 2 constant vectors can be simplified to math/logic to
14153/// avoid a variable select instruction and possibly avoid constant loads.
14154SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
14155 SDValue Cond = N->getOperand(0);
14156 SDValue N1 = N->getOperand(1);
14157 SDValue N2 = N->getOperand(2);
14158 EVT VT = N->getValueType(0);
14159 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
14163 return SDValue();
14164
14165 // Check if we can use the condition value to increment/decrement a single
14166 // constant value. This simplifies a select to an add and removes a constant
14167 // load/materialization from the general case.
14168 bool AllAddOne = true;
14169 bool AllSubOne = true;
14170 unsigned Elts = VT.getVectorNumElements();
14171 for (unsigned i = 0; i != Elts; ++i) {
14172 SDValue N1Elt = N1.getOperand(i);
14173 SDValue N2Elt = N2.getOperand(i);
14174 if (N1Elt.isUndef())
14175 continue;
14176 // N2 should not contain undef values since it will be reused in the fold.
14177 if (N2Elt.isUndef() || N1Elt.getValueType() != N2Elt.getValueType()) {
14178 AllAddOne = false;
14179 AllSubOne = false;
14180 break;
14181 }
14182
14183 const APInt &C1 = N1Elt->getAsAPIntVal();
14184 const APInt &C2 = N2Elt->getAsAPIntVal();
14185 if (C1 != C2 + 1)
14186 AllAddOne = false;
14187 if (C1 != C2 - 1)
14188 AllSubOne = false;
14189 }
14190
14191 // Further simplifications for the extra-special cases where the constants are
14192 // all 0 or all -1 should be implemented as folds of these patterns.
14193 SDLoc DL(N);
14194 if (AllAddOne || AllSubOne) {
14195 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
14196 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
14197 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14198 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
14199 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
14200 }
14201
14202 // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
14203 APInt Pow2C;
14204 if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
14205 isNullOrNullSplat(N2)) {
14206 SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
14207 SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
14208 return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
14209 }
14210
14212 return V;
14213
14214 // The general case for select-of-constants:
14215 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
14216 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
14217 // leave that to a machine-specific pass.
14218 return SDValue();
14219}
14220
14221SDValue DAGCombiner::visitVP_SELECT(SDNode *N) {
14222 SDValue N0 = N->getOperand(0);
14223 SDValue N1 = N->getOperand(1);
14224 SDValue N2 = N->getOperand(2);
14225 SDLoc DL(N);
14226
14227 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
14228 return V;
14229
14231 return V;
14232
14233 return SDValue();
14234}
14235
14237 SDValue FVal,
14238 const TargetLowering &TLI,
14239 SelectionDAG &DAG,
14240 const SDLoc &DL) {
14241 EVT VT = TVal.getValueType();
14242 if (!TLI.isTypeLegal(VT))
14243 return SDValue();
14244
14245 EVT CondVT = Cond.getValueType();
14246 assert(CondVT.isVector() && "Vector select expects a vector selector!");
14247
14248 bool IsTAllZero = ISD::isConstantSplatVectorAllZeros(TVal.getNode());
14249 bool IsTAllOne = ISD::isConstantSplatVectorAllOnes(TVal.getNode());
14250 bool IsFAllZero = ISD::isConstantSplatVectorAllZeros(FVal.getNode());
14251 bool IsFAllOne = ISD::isConstantSplatVectorAllOnes(FVal.getNode());
14252
14253 // no vselect(cond, 0/-1, X) or vselect(cond, X, 0/-1), return
14254 if (!IsTAllZero && !IsTAllOne && !IsFAllZero && !IsFAllOne)
14255 return SDValue();
14256
14257 // select Cond, 0, 0 → 0
14258 if (IsTAllZero && IsFAllZero) {
14259 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, DL, VT)
14260 : DAG.getConstant(0, DL, VT);
14261 }
14262
14263 // check select(setgt lhs, -1), 1, -1 --> or (sra lhs, bitwidth - 1), 1
14264 APInt TValAPInt;
14265 if (Cond.getOpcode() == ISD::SETCC &&
14266 Cond.getOperand(2) == DAG.getCondCode(ISD::SETGT) &&
14267 Cond.getOperand(0).getValueType() == VT && VT.isSimple() &&
14268 ISD::isConstantSplatVector(TVal.getNode(), TValAPInt) &&
14269 TValAPInt.isOne() &&
14270 ISD::isConstantSplatVectorAllOnes(Cond.getOperand(1).getNode()) &&
14273 SDValue LHS = Cond.getOperand(0);
14274 SDValue ShiftC =
14276 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, ShiftC);
14277 return DAG.getNode(ISD::OR, DL, VT, Shift, TVal);
14278 }
14279
14280 // To use the condition operand as a bitwise mask, it must have elements that
14281 // are the same size as the select elements. i.e, the condition operand must
14282 // have already been promoted from the IR select condition type <N x i1>.
14283 // Don't check if the types themselves are equal because that excludes
14284 // vector floating-point selects.
14285 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
14286 return SDValue();
14287
14288 // Cond value must be 'sign splat' to be converted to a logical op.
14289 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
14290 return SDValue();
14291
14292 // Try inverting Cond and swapping T/F if it gives all-ones/all-zeros form
14293 if (!IsTAllOne && !IsFAllZero && Cond.hasOneUse() &&
14294 Cond.getOpcode() == ISD::SETCC &&
14295 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
14296 CondVT) {
14297 if (IsTAllZero || IsFAllOne) {
14298 SDValue CC = Cond.getOperand(2);
14300 cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
14301 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
14302 InverseCC);
14303 std::swap(TVal, FVal);
14304 std::swap(IsTAllOne, IsFAllOne);
14305 std::swap(IsTAllZero, IsFAllZero);
14306 }
14307 }
14308
14310 "Select condition no longer all-sign bits");
14311
14312 // select Cond, -1, 0 → bitcast Cond
14313 if (IsTAllOne && IsFAllZero)
14314 return DAG.getBitcast(VT, Cond);
14315
14316 // select Cond, -1, x → or Cond, x
14317 if (IsTAllOne) {
14318 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14319 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, X);
14320 return DAG.getBitcast(VT, Or);
14321 }
14322
14323 // select Cond, x, 0 → and Cond, x
14324 if (IsFAllZero) {
14325 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(TVal));
14326 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, X);
14327 return DAG.getBitcast(VT, And);
14328 }
14329
14330 // select Cond, 0, x -> and not(Cond), x
14331 if (IsTAllZero &&
14333 SDValue X = DAG.getBitcast(CondVT, DAG.getFreeze(FVal));
14334 SDValue And =
14335 DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT), X);
14336 return DAG.getBitcast(VT, And);
14337 }
14338
14339 return SDValue();
14340}
14341
14342SDValue DAGCombiner::visitVSELECT(SDNode *N) {
14343 SDValue N0 = N->getOperand(0);
14344 SDValue N1 = N->getOperand(1);
14345 SDValue N2 = N->getOperand(2);
14346 EVT VT = N->getValueType(0);
14347 SDLoc DL(N);
14348
14349 if (SDValue V = DAG.simplifySelect(N0, N1, N2))
14350 return V;
14351
14353 return V;
14354
14355 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
14356 if (!TLI.isTargetCanonicalSelect(N))
14357 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
14358 return DAG.getSelect(DL, VT, F, N2, N1, N->getFlags());
14359
14360 // select (sext m), (add X, C), X --> (add X, (and C, (sext m))))
14361 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N2 && N1->hasOneUse() &&
14364 TLI.getBooleanContents(N0.getValueType()) ==
14366 return DAG.getNode(
14367 ISD::ADD, DL, N1.getValueType(), N2,
14368 DAG.getNode(ISD::AND, DL, N0.getValueType(), N1.getOperand(1), N0));
14369 }
14370
14371 // Canonicalize integer abs.
14372 // vselect (setg[te] X, 0), X, -X ->
14373 // vselect (setgt X, -1), X, -X ->
14374 // vselect (setl[te] X, 0), -X, X ->
14375 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14376 if (N0.getOpcode() == ISD::SETCC) {
14377 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
14379 bool isAbs = false;
14380 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
14381
14382 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14383 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
14384 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
14386 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
14387 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
14389
14390 if (isAbs) {
14392 return DAG.getNode(ISD::ABS, DL, VT, LHS);
14393
14394 SDValue Shift = DAG.getNode(
14395 ISD::SRA, DL, VT, LHS,
14396 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, DL));
14397 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
14398 AddToWorklist(Shift.getNode());
14399 AddToWorklist(Add.getNode());
14400 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
14401 }
14402
14403 // vselect x, y (fcmp lt x, y) -> fminnum x, y
14404 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
14405 //
14406 // This is OK if we don't care about what happens if either operand is a
14407 // NaN.
14408 //
14409 if (N0.hasOneUse() &&
14410 isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, N->getFlags(), TLI)) {
14411 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC))
14412 return FMinMax;
14413 }
14414
14415 if (SDValue S = PerformMinMaxFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14416 return S;
14417 if (SDValue S = PerformUMinFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
14418 return S;
14419
14420 // If this select has a condition (setcc) with narrower operands than the
14421 // select, try to widen the compare to match the select width.
14422 // TODO: This should be extended to handle any constant.
14423 // TODO: This could be extended to handle non-loading patterns, but that
14424 // requires thorough testing to avoid regressions.
14425 if (isNullOrNullSplat(RHS)) {
14426 EVT NarrowVT = LHS.getValueType();
14428 EVT SetCCVT = getSetCCResultType(LHS.getValueType());
14429 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
14430 unsigned WideWidth = WideVT.getScalarSizeInBits();
14431 bool IsSigned = isSignedIntSetCC(CC);
14432 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14433 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && SetCCWidth != 1 &&
14434 SetCCWidth < WideWidth &&
14435 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
14436 LoadSDNode *Ld = cast<LoadSDNode>(LHS);
14437
14438 if (TLI.isLoadLegalOrCustom(WideVT, NarrowVT, Ld->getAlign(),
14439 Ld->getAddressSpace(), LoadExtOpcode,
14440 false)) {
14441 // Both compare operands can be widened for free. The LHS can use an
14442 // extended load, and the RHS is a constant:
14443 // vselect (ext (setcc load(X), C)), N1, N2 -->
14444 // vselect (setcc extload(X), C'), N1, N2
14445 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14446 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
14447 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
14448 EVT WideSetCCVT = getSetCCResultType(WideVT);
14449 SDValue WideSetCC =
14450 DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
14451 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
14452 }
14453 }
14454 }
14455
14456 if (SDValue ABD = foldSelectToABD(LHS, RHS, N1, N2, CC, DL))
14457 return ABD;
14458
14459 // Match VSELECTs into add with unsigned saturation.
14460 if (hasOperation(ISD::UADDSAT, VT)) {
14461 // Check if one of the arms of the VSELECT is vector with all bits set.
14462 // If it's on the left side invert the predicate to simplify logic below.
14463 SDValue Other;
14464 ISD::CondCode SatCC = CC;
14466 Other = N2;
14467 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14468 } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) {
14469 Other = N1;
14470 }
14471
14472 if (Other && Other.getOpcode() == ISD::ADD) {
14473 SDValue CondLHS = LHS, CondRHS = RHS;
14474 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14475
14476 // Canonicalize condition operands.
14477 if (SatCC == ISD::SETUGE) {
14478 std::swap(CondLHS, CondRHS);
14479 SatCC = ISD::SETULE;
14480 }
14481
14482 // We can test against either of the addition operands.
14483 // x <= x+y ? x+y : ~0 --> uaddsat x, y
14484 // x+y >= x ? x+y : ~0 --> uaddsat x, y
14485 if (SatCC == ISD::SETULE && Other == CondRHS &&
14486 (OpLHS == CondLHS || OpRHS == CondLHS))
14487 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14488
14489 if (OpRHS.getOpcode() == CondRHS.getOpcode() &&
14490 (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14491 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) &&
14492 CondLHS == OpLHS) {
14493 // If the RHS is a constant we have to reverse the const
14494 // canonicalization.
14495 // x >= ~C ? x+C : ~0 --> uaddsat x, C
14496 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14497 return Cond->getAPIntValue() == ~Op->getAPIntValue();
14498 };
14499 if (SatCC == ISD::SETULE &&
14500 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
14501 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
14502 }
14503 }
14504 }
14505
14506 // Match VSELECTs into sub with unsigned saturation.
14507 if (hasOperation(ISD::USUBSAT, VT)) {
14508 // Check if one of the arms of the VSELECT is a zero vector. If it's on
14509 // the left side invert the predicate to simplify logic below.
14510 SDValue Other;
14511 ISD::CondCode SatCC = CC;
14513 Other = N2;
14514 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
14516 Other = N1;
14517 }
14518
14519 // zext(x) >= y ? trunc(zext(x) - y) : 0
14520 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14521 // zext(x) > y ? trunc(zext(x) - y) : 0
14522 // --> usubsat(trunc(zext(x)),trunc(umin(y,SatLimit)))
14523 if (Other && Other.getOpcode() == ISD::TRUNCATE &&
14524 Other.getOperand(0).getOpcode() == ISD::SUB &&
14525 (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT)) {
14526 SDValue OpLHS = Other.getOperand(0).getOperand(0);
14527 SDValue OpRHS = Other.getOperand(0).getOperand(1);
14528 if (LHS == OpLHS && RHS == OpRHS && LHS.getOpcode() == ISD::ZERO_EXTEND)
14529 if (SDValue R = getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS,
14530 DAG, DL))
14531 return R;
14532 }
14533
14534 if (Other && Other.getNumOperands() == 2) {
14535 SDValue CondRHS = RHS;
14536 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
14537
14538 if (OpLHS == LHS) {
14539 // Look for a general sub with unsigned saturation first.
14540 // x >= y ? x-y : 0 --> usubsat x, y
14541 // x > y ? x-y : 0 --> usubsat x, y
14542 if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) &&
14543 Other.getOpcode() == ISD::SUB && OpRHS == CondRHS)
14544 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14545
14546 if (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
14547 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14548 if (CondRHS.getOpcode() == ISD::BUILD_VECTOR ||
14549 CondRHS.getOpcode() == ISD::SPLAT_VECTOR) {
14550 // If the RHS is a constant we have to reverse the const
14551 // canonicalization.
14552 // x > C-1 ? x+-C : 0 --> usubsat x, C
14553 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
14554 return (!Op && !Cond) ||
14555 (Op && Cond &&
14556 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
14557 };
14558 if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD &&
14559 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
14560 /*AllowUndefs*/ true)) {
14561 OpRHS = DAG.getNegative(OpRHS, DL, VT);
14562 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14563 }
14564
14565 // Another special case: If C was a sign bit, the sub has been
14566 // canonicalized into a xor.
14567 // FIXME: Would it be better to use computeKnownBits to
14568 // determine whether it's safe to decanonicalize the xor?
14569 // x s< 0 ? x^C : 0 --> usubsat x, C
14570 APInt SplatValue;
14571 if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
14572 ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) &&
14574 SplatValue.isSignMask()) {
14575 // Note that we have to rebuild the RHS constant here to
14576 // ensure we don't rely on particular values of undef lanes.
14577 OpRHS = DAG.getConstant(SplatValue, DL, VT);
14578 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
14579 }
14580 }
14581 }
14582 }
14583 }
14584 }
14585
14586 // (vselect (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
14587 // (vselect (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
14588 if (SDValue UMin = foldSelectToUMin(LHS, RHS, N1, N2, CC, DL))
14589 return UMin;
14590 }
14591
14592 if (SimplifySelectOps(N, N1, N2))
14593 return SDValue(N, 0); // Don't revisit N.
14594
14595 // Fold (vselect all_ones, N1, N2) -> N1
14597 return N1;
14598 // Fold (vselect all_zeros, N1, N2) -> N2
14600 return N2;
14601
14602 // The ConvertSelectToConcatVector function is assuming both the above
14603 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
14604 // and addressed.
14605 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14608 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
14609 return CV;
14610 }
14611
14612 if (SDValue V = foldVSelectOfConstants(N))
14613 return V;
14614
14615 if (hasOperation(ISD::SRA, VT))
14617 return V;
14618
14620 return SDValue(N, 0);
14621
14622 if (SDValue V = combineVSelectWithAllOnesOrZeros(N0, N1, N2, TLI, DAG, DL))
14623 return V;
14624
14626 return R;
14627
14628 return SDValue();
14629}
14630
14631SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
14632 SDValue N0 = N->getOperand(0);
14633 SDValue N1 = N->getOperand(1);
14634 SDValue N2 = N->getOperand(2);
14635 SDValue N3 = N->getOperand(3);
14636 SDValue N4 = N->getOperand(4);
14637 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
14638 SDLoc DL(N);
14639
14640 // fold select_cc lhs, rhs, x, x, cc -> x
14641 if (N2 == N3)
14642 return N2;
14643
14644 // select_cc bool, 0, x, y, seteq -> select bool, y, x
14645 if (CC == ISD::SETEQ && !LegalTypes && N0.getValueType() == MVT::i1 &&
14646 isNullConstant(N1))
14647 return DAG.getSelect(DL, N2.getValueType(), N0, N3, N2);
14648
14649 // Determine if the condition we're dealing with is constant
14650 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
14651 CC, DL, false)) {
14652 AddToWorklist(SCC.getNode());
14653
14654 // cond always true -> true val
14655 // cond always false -> false val
14656 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode()))
14657 return SCCC->isZero() ? N3 : N2;
14658
14659 // When the condition is UNDEF, just return the first operand. This is
14660 // coherent the DAG creation, no setcc node is created in this case
14661 if (SCC->isUndef())
14662 return N2;
14663
14664 // Fold to a simpler select_cc
14665 if (SCC.getOpcode() == ISD::SETCC) {
14666 return DAG.getNode(ISD::SELECT_CC, DL, N2.getValueType(),
14667 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
14668 SCC.getOperand(2), SCC->getFlags());
14669 }
14670 }
14671
14672 // If we can fold this based on the true/false value, do so.
14673 if (SimplifySelectOps(N, N2, N3))
14674 return SDValue(N, 0); // Don't revisit N.
14675
14676 auto [Opcode, NewLHS, NewRHS] = combineSelectCCToPseudoMinMax(
14677 DAG, DL, CC, N0, N1, N2, N3, N->getFlags(), /*IsStrict=*/false);
14678 if (Opcode)
14679 return DAG.getNode(Opcode, DL, N->getValueType(0), NewLHS, NewRHS,
14680 N->getFlags());
14681
14682 // fold select_cc into other things, such as min/max/abs
14683 return SimplifySelectCC(DL, N0, N1, N2, N3, CC);
14684}
14685
14686SDValue DAGCombiner::visitSETCC(SDNode *N) {
14687 // setcc is very commonly used as an argument to brcond or cond_loop. This
14688 // pattern also lend itself to numerous combines and, as a result, it is
14689 // desired we keep the argument to a brcond as a setcc as much as possible.
14690 bool PreferSetCC =
14691 N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::BRCOND ||
14692 N->user_begin()->getOpcode() == ISD::COND_LOOP);
14693
14694 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
14695 EVT VT = N->getValueType(0);
14696 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
14697 SDLoc DL(N);
14698
14699 if (SDValue Combined = SimplifySetCC(VT, N0, N1, Cond, DL, !PreferSetCC)) {
14700 // If we prefer to have a setcc, and we don't, we'll try our best to
14701 // recreate one using rebuildSetCC.
14702 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
14703 SDValue NewSetCC = rebuildSetCC(Combined);
14704
14705 // We don't have anything interesting to combine to.
14706 if (NewSetCC.getNode() == N)
14707 return SDValue();
14708
14709 if (NewSetCC)
14710 return NewSetCC;
14711 }
14712 return Combined;
14713 }
14714
14715 // Optimize
14716 // 1) (icmp eq/ne (and X, C0), (shift X, C1))
14717 // or
14718 // 2) (icmp eq/ne X, (rotate X, C1))
14719 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
14720 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
14721 // Then:
14722 // If C1 is a power of 2, then the rotate and shift+and versions are
14723 // equivilent, so we can interchange them depending on target preference.
14724 // Otherwise, if we have the shift+and version we can interchange srl/shl
14725 // which inturn affects the constant C0. We can use this to get better
14726 // constants again determined by target preference.
14727 if (Cond == ISD::SETNE || Cond == ISD::SETEQ) {
14728 auto IsAndWithShift = [](SDValue A, SDValue B) {
14729 return A.getOpcode() == ISD::AND &&
14730 (B.getOpcode() == ISD::SRL || B.getOpcode() == ISD::SHL) &&
14731 A.getOperand(0) == B.getOperand(0);
14732 };
14733 auto IsRotateWithOp = [](SDValue A, SDValue B) {
14734 return (B.getOpcode() == ISD::ROTL || B.getOpcode() == ISD::ROTR) &&
14735 B.getOperand(0) == A;
14736 };
14737 SDValue AndOrOp = SDValue(), ShiftOrRotate = SDValue();
14738 bool IsRotate = false;
14739
14740 // Find either shift+and or rotate pattern.
14741 if (IsAndWithShift(N0, N1)) {
14742 AndOrOp = N0;
14743 ShiftOrRotate = N1;
14744 } else if (IsAndWithShift(N1, N0)) {
14745 AndOrOp = N1;
14746 ShiftOrRotate = N0;
14747 } else if (IsRotateWithOp(N0, N1)) {
14748 IsRotate = true;
14749 AndOrOp = N0;
14750 ShiftOrRotate = N1;
14751 } else if (IsRotateWithOp(N1, N0)) {
14752 IsRotate = true;
14753 AndOrOp = N1;
14754 ShiftOrRotate = N0;
14755 }
14756
14757 if (AndOrOp && ShiftOrRotate && ShiftOrRotate.hasOneUse() &&
14758 (IsRotate || AndOrOp.hasOneUse())) {
14759 EVT OpVT = N0.getValueType();
14760 // Get constant shift/rotate amount and possibly mask (if its shift+and
14761 // variant).
14762 auto GetAPIntValue = [](SDValue Op) -> std::optional<APInt> {
14763 ConstantSDNode *CNode = isConstOrConstSplat(Op, /*AllowUndefs*/ false,
14764 /*AllowTrunc*/ false);
14765 if (CNode == nullptr)
14766 return std::nullopt;
14767 return CNode->getAPIntValue();
14768 };
14769 std::optional<APInt> AndCMask =
14770 IsRotate ? std::nullopt : GetAPIntValue(AndOrOp.getOperand(1));
14771 std::optional<APInt> ShiftCAmt =
14772 GetAPIntValue(ShiftOrRotate.getOperand(1));
14773 unsigned NumBits = OpVT.getScalarSizeInBits();
14774
14775 // We found constants.
14776 if (ShiftCAmt && (IsRotate || AndCMask) && ShiftCAmt->ult(NumBits)) {
14777 unsigned ShiftOpc = ShiftOrRotate.getOpcode();
14778 // Check that the constants meet the constraints.
14779 bool CanTransform = IsRotate;
14780 if (!CanTransform) {
14781 // Check that mask and shift compliment eachother
14782 CanTransform = *ShiftCAmt == (~*AndCMask).popcount();
14783 // Check that we are comparing all bits
14784 CanTransform &= (*ShiftCAmt + AndCMask->popcount()) == NumBits;
14785 // Check that the and mask is correct for the shift
14786 CanTransform &=
14787 ShiftOpc == ISD::SHL ? (~*AndCMask).isMask() : AndCMask->isMask();
14788 }
14789
14790 // See if target prefers another shift/rotate opcode.
14791 unsigned NewShiftOpc = TLI.preferedOpcodeForCmpEqPiecesOfOperand(
14792 OpVT, ShiftOpc, ShiftCAmt->isPowerOf2(), *ShiftCAmt, AndCMask);
14793 // Transform is valid and we have a new preference.
14794 if (CanTransform && NewShiftOpc != ShiftOpc) {
14795 SDValue NewShiftOrRotate =
14796 DAG.getNode(NewShiftOpc, DL, OpVT, ShiftOrRotate.getOperand(0),
14797 ShiftOrRotate.getOperand(1));
14798 SDValue NewAndOrOp = SDValue();
14799
14800 if (NewShiftOpc == ISD::SHL || NewShiftOpc == ISD::SRL) {
14801 APInt NewMask =
14802 NewShiftOpc == ISD::SHL
14803 ? APInt::getHighBitsSet(NumBits,
14804 NumBits - ShiftCAmt->getZExtValue())
14805 : APInt::getLowBitsSet(NumBits,
14806 NumBits - ShiftCAmt->getZExtValue());
14807 NewAndOrOp =
14808 DAG.getNode(ISD::AND, DL, OpVT, ShiftOrRotate.getOperand(0),
14809 DAG.getConstant(NewMask, DL, OpVT));
14810 } else {
14811 NewAndOrOp = ShiftOrRotate.getOperand(0);
14812 }
14813
14814 return DAG.getSetCC(DL, VT, NewAndOrOp, NewShiftOrRotate, Cond);
14815 }
14816 }
14817 }
14818 }
14819 return SDValue();
14820}
14821
14822SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
14823 SDValue LHS = N->getOperand(0);
14824 SDValue RHS = N->getOperand(1);
14825 SDValue Carry = N->getOperand(2);
14826 SDValue Cond = N->getOperand(3);
14827
14828 // If Carry is false, fold to a regular SETCC.
14829 if (isNullConstant(Carry))
14830 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
14831
14832 return SDValue();
14833}
14834
14835/// Check if N satisfies:
14836/// N is used once.
14837/// N is a Load.
14838/// The load is compatible with ExtOpcode. It means
14839/// If load has explicit zero/sign extension, ExpOpcode must have the same
14840/// extension.
14841/// Otherwise returns true.
14842static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) {
14843 if (!N.hasOneUse())
14844 return false;
14845
14846 if (!isa<LoadSDNode>(N))
14847 return false;
14848
14849 LoadSDNode *Load = cast<LoadSDNode>(N);
14850 ISD::LoadExtType LoadExt = Load->getExtensionType();
14851 if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD)
14852 return true;
14853
14854 // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same
14855 // extension.
14856 if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) ||
14857 (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND))
14858 return false;
14859
14860 return true;
14861}
14862
14863/// Fold
14864/// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y)
14865/// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y)
14866/// (aext (select c, load x, load y)) -> (select c, extload x, extload y)
14867/// This function is called by the DAGCombiner when visiting sext/zext/aext
14868/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
14870 SelectionDAG &DAG, const SDLoc &DL,
14871 CombineLevel Level) {
14872 unsigned Opcode = N->getOpcode();
14873 SDValue N0 = N->getOperand(0);
14874 EVT VT = N->getValueType(0);
14875 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
14876 Opcode == ISD::ANY_EXTEND) &&
14877 "Expected EXTEND dag node in input!");
14878
14879 SDValue Cond, Op1, Op2;
14881 m_Value(Op2)))))
14882 return SDValue();
14883
14884 if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode))
14885 return SDValue();
14886
14887 auto ExtLoadOpcode = ISD::EXTLOAD;
14888 if (Opcode == ISD::SIGN_EXTEND)
14889 ExtLoadOpcode = ISD::SEXTLOAD;
14890 else if (Opcode == ISD::ZERO_EXTEND)
14891 ExtLoadOpcode = ISD::ZEXTLOAD;
14892
14893 // Illegal VSELECT may ISel fail if happen after legalization (DAG
14894 // Combine2), so we should conservatively check the OperationAction.
14895 LoadSDNode *Load1 = cast<LoadSDNode>(Op1);
14896 LoadSDNode *Load2 = cast<LoadSDNode>(Op2);
14897 if (!TLI.isLoadLegal(VT, Load1->getMemoryVT(), Load1->getAlign(),
14898 Load1->getAddressSpace(), ExtLoadOpcode, false) ||
14899 !TLI.isLoadLegal(VT, Load2->getMemoryVT(), Load2->getAlign(),
14900 Load2->getAddressSpace(), ExtLoadOpcode, false) ||
14901 (N0->getOpcode() == ISD::VSELECT && Level >= AfterLegalizeTypes &&
14903 return SDValue();
14904
14905 SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1);
14906 SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2);
14907 return DAG.getSelect(DL, VT, Cond, Ext1, Ext2);
14908}
14909
14910/// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
14911/// a build_vector of constants.
14912/// This function is called by the DAGCombiner when visiting sext/zext/aext
14913/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
14914/// Vector extends are not folded if operations are legal; this is to
14915/// avoid introducing illegal build_vector dag nodes.
14917 const TargetLowering &TLI,
14918 SelectionDAG &DAG, bool LegalTypes) {
14919 unsigned Opcode = N->getOpcode();
14920 SDValue N0 = N->getOperand(0);
14921 EVT VT = N->getValueType(0);
14922
14923 assert((ISD::isExtOpcode(Opcode) || ISD::isExtVecInRegOpcode(Opcode)) &&
14924 "Expected EXTEND dag node in input!");
14925
14926 // fold (sext c1) -> c1
14927 // fold (zext c1) -> c1
14928 // fold (aext c1) -> c1
14929 if (isa<ConstantSDNode>(N0))
14930 return DAG.getNode(Opcode, DL, VT, N0);
14931
14932 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
14933 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
14934 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
14935 if (N0->getOpcode() == ISD::SELECT) {
14936 SDValue Op1 = N0->getOperand(1);
14937 SDValue Op2 = N0->getOperand(2);
14938 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
14939 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
14940 // For any_extend, choose sign extension of the constants to allow a
14941 // possible further transform to sign_extend_inreg.i.e.
14942 //
14943 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
14944 // t2: i64 = any_extend t1
14945 // -->
14946 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
14947 // -->
14948 // t4: i64 = sign_extend_inreg t3
14949 unsigned FoldOpc = Opcode;
14950 if (FoldOpc == ISD::ANY_EXTEND)
14951 FoldOpc = ISD::SIGN_EXTEND;
14952 return DAG.getSelect(DL, VT, N0->getOperand(0),
14953 DAG.getNode(FoldOpc, DL, VT, Op1),
14954 DAG.getNode(FoldOpc, DL, VT, Op2));
14955 }
14956 }
14957
14958 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
14959 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
14960 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
14961 EVT SVT = VT.getScalarType();
14962 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
14964 return SDValue();
14965
14966 // We can fold this node into a build_vector.
14967 unsigned VTBits = SVT.getSizeInBits();
14968 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
14970 unsigned NumElts = VT.getVectorNumElements();
14971
14972 for (unsigned i = 0; i != NumElts; ++i) {
14973 SDValue Op = N0.getOperand(i);
14974 if (Op.isUndef()) {
14975 if (Opcode == ISD::ANY_EXTEND || Opcode == ISD::ANY_EXTEND_VECTOR_INREG)
14976 Elts.push_back(DAG.getUNDEF(SVT));
14977 else
14978 Elts.push_back(DAG.getConstant(0, DL, SVT));
14979 continue;
14980 }
14981
14982 SDLoc DL(Op);
14983 // Get the constant value and if needed trunc it to the size of the type.
14984 // Nodes like build_vector might have constants wider than the scalar type.
14985 APInt C = Op->getAsAPIntVal().zextOrTrunc(EVTBits);
14986 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
14987 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
14988 else
14989 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
14990 }
14991
14992 return DAG.getBuildVector(VT, DL, Elts);
14993}
14994
14995// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
14996// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
14997// transformation. Returns true if extension are possible and the above
14998// mentioned transformation is profitable.
15000 unsigned ExtOpc,
15001 SmallVectorImpl<SDNode *> &ExtendNodes,
15002 const TargetLowering &TLI) {
15003 bool HasCopyToRegUses = false;
15004 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
15005 for (SDUse &Use : N0->uses()) {
15006 SDNode *User = Use.getUser();
15007 if (User == N)
15008 continue;
15009 if (Use.getResNo() != N0.getResNo())
15010 continue;
15011 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
15012 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
15014 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
15015 // Sign bits will be lost after a zext.
15016 return false;
15017 bool Add = false;
15018 for (unsigned i = 0; i != 2; ++i) {
15019 SDValue UseOp = User->getOperand(i);
15020 if (UseOp == N0)
15021 continue;
15022 if (!isa<ConstantSDNode>(UseOp))
15023 return false;
15024 Add = true;
15025 }
15026 if (Add)
15027 ExtendNodes.push_back(User);
15028 continue;
15029 }
15030 // If truncates aren't free and there are users we can't
15031 // extend, it isn't worthwhile.
15032 if (!isTruncFree)
15033 return false;
15034 // Remember if this value is live-out.
15035 if (User->getOpcode() == ISD::CopyToReg)
15036 HasCopyToRegUses = true;
15037 }
15038
15039 if (HasCopyToRegUses) {
15040 bool BothLiveOut = false;
15041 for (SDUse &Use : N->uses()) {
15042 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
15043 BothLiveOut = true;
15044 break;
15045 }
15046 }
15047 if (BothLiveOut)
15048 // Both unextended and extended values are live out. There had better be
15049 // a good reason for the transformation.
15050 return !ExtendNodes.empty();
15051 }
15052 return true;
15053}
15054
15055void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
15056 SDValue OrigLoad, SDValue ExtLoad,
15057 ISD::NodeType ExtType) {
15058 // Extend SetCC uses if necessary.
15059 SDLoc DL(ExtLoad);
15060 for (SDNode *SetCC : SetCCs) {
15062
15063 for (unsigned j = 0; j != 2; ++j) {
15064 SDValue SOp = SetCC->getOperand(j);
15065 if (SOp == OrigLoad)
15066 Ops.push_back(ExtLoad);
15067 else
15068 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
15069 }
15070
15071 Ops.push_back(SetCC->getOperand(2));
15072 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
15073 }
15074}
15075
15076// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
15077SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
15078 SDValue N0 = N->getOperand(0);
15079 EVT DstVT = N->getValueType(0);
15080 EVT SrcVT = N0.getValueType();
15081
15082 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
15083 N->getOpcode() == ISD::ZERO_EXTEND) &&
15084 "Unexpected node type (not an extend)!");
15085
15086 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
15087 // For example, on a target with legal v4i32, but illegal v8i32, turn:
15088 // (v8i32 (sext (v8i16 (load x))))
15089 // into:
15090 // (v8i32 (concat_vectors (v4i32 (sextload x)),
15091 // (v4i32 (sextload (x + 16)))))
15092 // Where uses of the original load, i.e.:
15093 // (v8i16 (load x))
15094 // are replaced with:
15095 // (v8i16 (truncate
15096 // (v8i32 (concat_vectors (v4i32 (sextload x)),
15097 // (v4i32 (sextload (x + 16)))))))
15098 //
15099 // This combine is only applicable to illegal, but splittable, vectors.
15100 // All legal types, and illegal non-vector types, are handled elsewhere.
15101 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
15102 //
15103 if (N0->getOpcode() != ISD::LOAD)
15104 return SDValue();
15105
15106 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15107
15108 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
15109 !N0.hasOneUse() || !LN0->isSimple() ||
15110 !DstVT.isVector() || !DstVT.isPow2VectorType() ||
15112 return SDValue();
15113
15115 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
15116 return SDValue();
15117
15118 ISD::LoadExtType ExtType =
15119 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15120
15121 // Try to split the vector types to get down to legal types.
15122 EVT SplitSrcVT = SrcVT;
15123 EVT SplitDstVT = DstVT;
15124 while (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
15125 LN0->getAddressSpace(), ExtType, false) &&
15126 SplitSrcVT.getVectorNumElements() > 1) {
15127 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
15128 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
15129 }
15130
15131 if (!TLI.isLoadLegalOrCustom(SplitDstVT, SplitSrcVT, LN0->getAlign(),
15132 LN0->getAddressSpace(), ExtType, false))
15133 return SDValue();
15134
15135 assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
15136
15137 SDLoc DL(N);
15138 const unsigned NumSplits =
15139 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
15140 const unsigned Stride = SplitSrcVT.getStoreSize();
15143
15144 SDValue BasePtr = LN0->getBasePtr();
15145 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
15146 const unsigned Offset = Idx * Stride;
15147
15149 DAG.getExtLoad(ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(),
15150 BasePtr, LN0->getPointerInfo().getWithOffset(Offset),
15151 SplitSrcVT, LN0->getBaseAlign(),
15152 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
15153
15154 BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::getFixed(Stride), DL);
15155
15156 Loads.push_back(SplitLoad.getValue(0));
15157 Chains.push_back(SplitLoad.getValue(1));
15158 }
15159
15160 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15161 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
15162
15163 // Simplify TF.
15164 AddToWorklist(NewChain.getNode());
15165
15166 CombineTo(N, NewValue);
15167
15168 // Replace uses of the original load (before extension)
15169 // with a truncate of the concatenated sextloaded vectors.
15170 SDValue Trunc =
15171 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
15172 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
15173 CombineTo(N0.getNode(), Trunc, NewChain);
15174 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15175}
15176
15177// fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
15178// (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
15179SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
15180 assert(N->getOpcode() == ISD::ZERO_EXTEND);
15181 EVT VT = N->getValueType(0);
15182 EVT OrigVT = N->getOperand(0).getValueType();
15183 if (TLI.isZExtFree(OrigVT, VT))
15184 return SDValue();
15185
15186 // and/or/xor
15187 SDValue N0 = N->getOperand(0);
15188 if (!ISD::isBitwiseLogicOp(N0.getOpcode()) ||
15189 N0.getOperand(1).getOpcode() != ISD::Constant ||
15190 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
15191 return SDValue();
15192
15193 // shl/shr
15194 SDValue N1 = N0->getOperand(0);
15195 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
15196 N1.getOperand(1).getOpcode() != ISD::Constant ||
15197 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
15198 return SDValue();
15199
15200 // load
15201 if (!isa<LoadSDNode>(N1.getOperand(0)))
15202 return SDValue();
15203 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
15204 EVT MemVT = Load->getMemoryVT();
15205 if (!TLI.isLoadLegal(VT, MemVT, Load->getAlign(), Load->getAddressSpace(),
15206 ISD::ZEXTLOAD, false) ||
15207 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
15208 return SDValue();
15209
15210
15211 // If the shift op is SHL, the logic op must be AND, otherwise the result
15212 // will be wrong.
15213 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
15214 return SDValue();
15215
15216 if (!N0.hasOneUse() || !N1.hasOneUse())
15217 return SDValue();
15218
15220 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
15221 ISD::ZERO_EXTEND, SetCCs, TLI))
15222 return SDValue();
15223
15224 // Actually do the transformation.
15225 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
15226 Load->getChain(), Load->getBasePtr(),
15227 Load->getMemoryVT(), Load->getMemOperand());
15228
15229 SDLoc DL1(N1);
15230 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
15231 N1.getOperand(1));
15232
15233 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
15234 SDLoc DL0(N0);
15235 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
15236 DAG.getConstant(Mask, DL0, VT));
15237
15238 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
15239 CombineTo(N, And);
15240 if (SDValue(Load, 0).hasOneUse()) {
15241 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15242 } else {
15243 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
15244 Load->getValueType(0), ExtLoad);
15245 CombineTo(Load, Trunc, ExtLoad.getValue(1));
15246 }
15247
15248 // N0 is dead at this point.
15249 recursivelyDeleteUnusedNodes(N0.getNode());
15250
15251 return SDValue(N,0); // Return N so it doesn't get rechecked!
15252}
15253
15254/// If we're narrowing or widening the result of a vector select and the final
15255/// size is the same size as a setcc (compare) feeding the select, then try to
15256/// apply the cast operation to the select's operands because matching vector
15257/// sizes for a select condition and other operands should be more efficient.
15258SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
15259 unsigned CastOpcode = Cast->getOpcode();
15260 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
15261 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
15262 CastOpcode == ISD::FP_ROUND) &&
15263 "Unexpected opcode for vector select narrowing/widening");
15264
15265 // We only do this transform before legal ops because the pattern may be
15266 // obfuscated by target-specific operations after legalization. Do not create
15267 // an illegal select op, however, because that may be difficult to lower.
15268 EVT VT = Cast->getValueType(0);
15269 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
15270 return SDValue();
15271
15272 SDValue VSel = Cast->getOperand(0);
15273 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
15274 VSel.getOperand(0).getOpcode() != ISD::SETCC)
15275 return SDValue();
15276
15277 // Does the setcc have the same vector size as the casted select?
15278 SDValue SetCC = VSel.getOperand(0);
15279 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
15280 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
15281 return SDValue();
15282
15283 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
15284 SDValue A = VSel.getOperand(1);
15285 SDValue B = VSel.getOperand(2);
15286 SDValue CastA, CastB;
15287 SDLoc DL(Cast);
15288 if (CastOpcode == ISD::FP_ROUND) {
15289 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
15290 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
15291 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
15292 } else {
15293 CastA = DAG.getNode(CastOpcode, DL, VT, A);
15294 CastB = DAG.getNode(CastOpcode, DL, VT, B);
15295 }
15296 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
15297}
15298
15299// fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15300// fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15302 const TargetLowering &TLI, EVT VT,
15303 bool LegalOperations, SDNode *N,
15304 SDValue N0, ISD::LoadExtType ExtLoadType) {
15305 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15306 auto *OldExtLoad = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15307 if (!OldExtLoad)
15308 return SDValue();
15309
15310 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD)
15311 ? ISD::isSEXTLoad(OldExtLoad)
15312 : ISD::isZEXTLoad(OldExtLoad);
15313 if ((!isAExtLoad && !ISD::isEXTLoad(OldExtLoad)) ||
15314 !ISD::isUNINDEXEDLoad(OldExtLoad) || !OldExtLoad->hasNUsesOfValue(1, 0))
15315 return SDValue();
15316
15317 EVT MemVT = OldExtLoad->getMemoryVT();
15318 if ((LegalOperations || !OldExtLoad->isSimple() || VT.isVector()) &&
15319 !TLI.isLoadLegal(VT, MemVT, OldExtLoad->getAlign(),
15320 OldExtLoad->getAddressSpace(), ExtLoadType, false))
15321 return SDValue();
15322
15323 SDLoc DL(OldExtLoad);
15324 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, DL, VT, OldExtLoad->getChain(),
15325 OldExtLoad->getBasePtr(), MemVT,
15326 OldExtLoad->getMemOperand());
15327 SDValue Res = ExtLoad;
15328 if (Frozen) {
15329 Res = DAG.getFreeze(ExtLoad);
15330 Res = DAG.getNode(
15331 ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext : ISD::AssertZext, DL,
15332 Res.getValueType(), Res,
15333 DAG.getValueType(OldExtLoad->getValueType(0).getScalarType()));
15334 }
15335 Combiner.CombineTo(N, Res);
15336 DAG.ReplaceAllUsesOfValueWith(SDValue(OldExtLoad, 1), ExtLoad.getValue(1));
15337 if (N0->use_empty())
15338 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15339 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15340}
15341
15342// fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
15343// Only generate vector extloads when 1) they're legal, and 2) they are
15344// deemed desirable by the target. NonNegZExt can be set to true if a zero
15345// extend has the nonneg flag to allow use of sextload if profitable.
15347 const TargetLowering &TLI, EVT VT,
15348 bool LegalOperations, SDNode *N, SDValue N0,
15349 ISD::LoadExtType ExtLoadType,
15350 ISD::NodeType ExtOpc,
15351 bool NonNegZExt = false) {
15352
15353 bool Frozen = N0.getOpcode() == ISD::FREEZE;
15354 SDValue Freeze = Frozen ? N0 : SDValue();
15355 auto *Load = dyn_cast<LoadSDNode>(Frozen ? N0.getOperand(0) : N0);
15356 // TODO: Support multiple uses of the load when frozen.
15357 if (!Load || !ISD::isNON_EXTLoad(Load) || !ISD::isUNINDEXEDLoad(Load) ||
15358 (Frozen && !Load->hasNUsesOfValue(1, 0)))
15359 return {};
15360
15361 // If this is zext nneg, see if it would make sense to treat it as a sext.
15362 if (NonNegZExt) {
15363 assert(ExtLoadType == ISD::ZEXTLOAD && ExtOpc == ISD::ZERO_EXTEND &&
15364 "Unexpected load type or opcode");
15365 for (SDNode *User : Load->users()) {
15366 if (User->getOpcode() == ISD::SETCC) {
15368 if (ISD::isSignedIntSetCC(CC)) {
15369 ExtLoadType = ISD::SEXTLOAD;
15370 ExtOpc = ISD::SIGN_EXTEND;
15371 break;
15372 }
15373 }
15374 }
15375 }
15376
15377 // TODO: isFixedLengthVector() should be removed and any negative effects on
15378 // code generation being the result of that target's implementation of
15379 // isVectorLoadExtDesirable().
15380 if ((LegalOperations || VT.isFixedLengthVector() || !Load->isSimple()) &&
15381 !TLI.isLoadLegal(VT, Load->getValueType(0), Load->getAlign(),
15382 Load->getAddressSpace(), ExtLoadType, false))
15383 return {};
15384
15385 bool DoXform = true;
15387 if (!N0->hasOneUse())
15388 DoXform = ExtendUsesToFormExtLoad(VT, N, Frozen ? Freeze : SDValue(Load, 0),
15389 ExtOpc, SetCCs, TLI);
15390 if (VT.isVector())
15391 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
15392 if (!DoXform)
15393 return {};
15394
15395 SDLoc DL(Load);
15396
15397 auto SalvageDbgValue = [&](SDDbgValue *Dbg, SDValue Old, SDValue New,
15398 unsigned OldBits, unsigned NewBits,
15399 bool IsSigned) {
15400 SmallVector<SDDbgOperand> Locs = Dbg->copyLocationOps();
15401 bool Changed = false;
15402
15403 bool IsVariadic = Dbg->isVariadic();
15404 SmallVector<unsigned, 2> AffectedArgs;
15405
15406 for (unsigned I = 0, E = Locs.size(); I != E; ++I) {
15407 SDDbgOperand &Op = Locs[I];
15408 if (Op.getKind() != SDDbgOperand::SDNODE)
15409 continue;
15410
15411 if (Op.getSDNode() == Old.getNode() && Op.getResNo() == Old.getResNo()) {
15412 Op = SDDbgOperand::fromNode(New.getNode(), New.getResNo());
15413 Changed = true;
15414
15415 if (IsVariadic)
15416 AffectedArgs.push_back(I);
15417 }
15418 }
15419
15420 if (!Changed)
15421 return;
15422
15423 const DIExpression *OldExpr = Dbg->getExpression();
15424 const DIExpression *NewExpr = nullptr;
15425
15426 if (!IsVariadic) {
15427 // Do not introduce DW_OP_LLVM_arg into ordinary single-location
15428 // DBG_VALUEs.
15429 NewExpr = DIExpression::appendExt(OldExpr, NewBits, OldBits, IsSigned);
15430 } else {
15431 auto ExtOps = DIExpression::getExtOps(NewBits, OldBits, IsSigned);
15432
15434
15435 for (unsigned ArgNo : AffectedArgs)
15437 /*StackValue=*/false);
15438 }
15439
15440 SDDbgValue *NewDV = DAG.getDbgValueList(
15441 Dbg->getVariable(), const_cast<DIExpression *>(NewExpr), Locs,
15442 Dbg->getAdditionalDependencies(), Dbg->isIndirect(), Dbg->getDebugLoc(),
15443 Dbg->getOrder(), Dbg->isVariadic());
15444
15445 Dbg->setIsInvalidated();
15446 Dbg->setIsEmitted();
15447 DAG.AddDbgValue(NewDV, /*isParameter=*/false);
15448 };
15449
15450 // Because we are replacing a load and a s|z ext with a load-s|z ext
15451 // instruction, the dbg_value attached to the load will be of a smaller bit
15452 // width, and we have to add a DW_OP_LLVM_convert expression to get the
15453 // correct size.
15454 auto SalvageToOldLoadSize = [&](SDValue Old, SDValue New, bool IsSigned) {
15456 DAG.GetDbgValues(Old.getNode()).begin(),
15457 DAG.GetDbgValues(Old.getNode()).end());
15458
15459 unsigned VarBitsOld = Old.getValueSizeInBits();
15460 unsigned VarBitsNew = New.getValueSizeInBits();
15461
15462 for (SDDbgValue *Dbg : DbgVals) {
15463 if (Dbg->isInvalidated())
15464 continue;
15465
15466 SalvageDbgValue(Dbg, Old, New, VarBitsOld, VarBitsNew, IsSigned);
15467 }
15468 };
15469
15470 SDValue ExtLoad =
15471 DAG.getExtLoad(ExtLoadType, DL, VT, Load->getChain(), Load->getBasePtr(),
15472 Load->getValueType(0), Load->getMemOperand());
15473 SDValue Res = ExtLoad;
15474 if (Frozen) {
15475 Res = DAG.getFreeze(ExtLoad);
15476 Res = DAG.getNode(ExtLoadType == ISD::SEXTLOAD ? ISD::AssertSext
15478 DL, Res.getValueType(), Res,
15479 DAG.getValueType(Load->getValueType(0).getScalarType()));
15480 }
15481 Combiner.ExtendSetCCUses(SetCCs, N0, Res, ExtOpc);
15482 // If the load value is used only by N, replace it via CombineTo N.
15483 bool NoReplaceTrunc = N0.hasOneUse();
15484 if (N->getHasDebugValue()) {
15485 SDValue OldExtValue(N, 0);
15486 DAG.transferDbgValues(OldExtValue, ExtLoad);
15487 }
15488 if (NoReplaceTrunc) {
15489 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
15490 if (Load->getHasDebugValue()) {
15491 SDValue OldLoadVal(Load, 0);
15492 SalvageToOldLoadSize(OldLoadVal, ExtLoad, IsSigned);
15493 }
15494 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15495 Combiner.CombineTo(N, Res);
15496 Combiner.recursivelyDeleteUnusedNodes(N0.getNode());
15497 } else {
15498 Combiner.CombineTo(N, Res);
15499 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Load->getValueType(0), Res);
15500 if (Frozen) {
15501 Combiner.CombineTo(Freeze.getNode(), Trunc);
15502 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
15503 } else {
15504 Combiner.CombineTo(Load, Trunc, ExtLoad.getValue(1));
15505 }
15506 }
15507 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15508}
15509
15510static SDValue
15512 bool LegalOperations, SDNode *N, SDValue N0,
15513 ISD::LoadExtType ExtLoadType, ISD::NodeType ExtOpc) {
15514 if (!N0.hasOneUse())
15515 return SDValue();
15516
15518 if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
15519 return SDValue();
15520
15521 if ((LegalOperations || !cast<MaskedLoadSDNode>(N0)->isSimple()) &&
15522 !TLI.isLoadLegalOrCustom(VT, Ld->getValueType(0), Ld->getAlign(),
15523 Ld->getAddressSpace(), ExtLoadType, false))
15524 return SDValue();
15525
15526 if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
15527 return SDValue();
15528
15529 SDLoc dl(Ld);
15530 SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
15531 SDValue NewLoad = DAG.getMaskedLoad(
15532 VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
15533 PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
15534 ExtLoadType, Ld->isExpandingLoad());
15535 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
15536 return NewLoad;
15537}
15538
15539// fold ([s|z]ext (atomic_load)) -> ([s|z]ext (truncate ([s|z]ext atomic_load)))
15541 const TargetLowering &TLI, EVT VT,
15542 SDValue N0,
15543 ISD::LoadExtType ExtLoadType) {
15544 auto *ALoad = dyn_cast<AtomicSDNode>(N0);
15545 if (!ALoad || ALoad->getOpcode() != ISD::ATOMIC_LOAD)
15546 return {};
15547 EVT MemoryVT = ALoad->getMemoryVT();
15548 if (!TLI.isLoadLegal(VT, MemoryVT, ALoad->getAlign(),
15549 ALoad->getAddressSpace(), ExtLoadType, true))
15550 return {};
15551 // Can't fold into ALoad if it is already extending differently.
15552 ISD::LoadExtType ALoadExtTy = ALoad->getExtensionType();
15553 if ((ALoadExtTy == ISD::ZEXTLOAD && ExtLoadType == ISD::SEXTLOAD) ||
15554 (ALoadExtTy == ISD::SEXTLOAD && ExtLoadType == ISD::ZEXTLOAD))
15555 return {};
15556
15557 EVT OrigVT = ALoad->getValueType(0);
15558 assert(OrigVT.getSizeInBits() < VT.getSizeInBits() && "VT should be wider.");
15559 auto *NewALoad = cast<AtomicSDNode>(DAG.getAtomicLoad(
15560 ExtLoadType, SDLoc(ALoad), MemoryVT, VT, ALoad->getChain(),
15561 ALoad->getBasePtr(), ALoad->getMemOperand()));
15563 SDValue(ALoad, 0),
15564 DAG.getNode(ISD::TRUNCATE, SDLoc(ALoad), OrigVT, SDValue(NewALoad, 0)));
15565 // Update the chain uses.
15566 DAG.ReplaceAllUsesOfValueWith(SDValue(ALoad, 1), SDValue(NewALoad, 1));
15567 return SDValue(NewALoad, 0);
15568}
15569
15571 bool LegalOperations) {
15572 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
15573 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
15574
15575 SDValue SetCC = N->getOperand(0);
15576 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
15577 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
15578 return SDValue();
15579
15580 SDValue X = SetCC.getOperand(0);
15581 SDValue Ones = SetCC.getOperand(1);
15582 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
15583 EVT VT = N->getValueType(0);
15584 EVT XVT = X.getValueType();
15585 // setge X, C is canonicalized to setgt, so we do not need to match that
15586 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
15587 // not require the 'not' op.
15588 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
15589 // Invert and smear/shift the sign bit:
15590 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
15591 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
15592 SDLoc DL(N);
15593 unsigned ShCt = VT.getSizeInBits() - 1;
15594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15595 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
15596 SDValue NotX = DAG.getNOT(DL, X, VT);
15597 SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
15598 auto ShiftOpcode =
15599 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
15600 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
15601 }
15602 }
15603 return SDValue();
15604}
15605
15606SDValue DAGCombiner::foldSextSetcc(SDNode *N) {
15607 SDValue N0 = N->getOperand(0);
15608 if (N0.getOpcode() != ISD::SETCC)
15609 return SDValue();
15610
15611 SDValue N00 = N0.getOperand(0);
15612 SDValue N01 = N0.getOperand(1);
15614 EVT VT = N->getValueType(0);
15615 EVT N00VT = N00.getValueType();
15616 SDLoc DL(N);
15617
15618 // Propagate fast-math-flags.
15619 SDNodeFlags Flags = N0->getFlags();
15620
15621 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
15622 // the same size as the compared operands. Try to optimize sext(setcc())
15623 // if this is the case.
15624 if (VT.isVector() && !LegalOperations &&
15625 TLI.getBooleanContents(N00VT) ==
15627 EVT SVT = getSetCCResultType(N00VT);
15628
15629 // If we already have the desired type, don't change it.
15630 if (SVT != N0.getValueType()) {
15631 // We know that the # elements of the results is the same as the
15632 // # elements of the compare (and the # elements of the compare result
15633 // for that matter). Check to see that they are the same size. If so,
15634 // we know that the element size of the sext'd result matches the
15635 // element size of the compare operands.
15636 if (VT.getSizeInBits() == SVT.getSizeInBits())
15637 return DAG.getSetCC(DL, VT, N00, N01, CC, /*Chain=*/{},
15638 /*Signaling=*/false, Flags);
15639
15640 // If the desired elements are smaller or larger than the source
15641 // elements, we can use a matching integer vector type and then
15642 // truncate/sign extend.
15643 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
15644 if (SVT == MatchingVecType) {
15645 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC,
15646 /*Chain=*/{}, /*Signaling=*/false, Flags);
15647 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
15648 }
15649 }
15650
15651 // Try to eliminate the sext of a setcc by zexting the compare operands.
15652 if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) &&
15654 bool IsSignedCmp = ISD::isSignedIntSetCC(CC);
15655 unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15656 unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15657
15658 // We have an unsupported narrow vector compare op that would be legal
15659 // if extended to the destination type. See if the compare operands
15660 // can be freely extended to the destination type.
15661 auto IsFreeToExtend = [&](SDValue V) {
15662 if (isConstantOrConstantVector(V, /*NoOpaques*/ true))
15663 return true;
15664 // Match a simple, non-extended load that can be converted to a
15665 // legal {z/s}ext-load.
15666 // TODO: Allow widening of an existing {z/s}ext-load?
15667 if (!(ISD::isNON_EXTLoad(V.getNode()) &&
15668 ISD::isUNINDEXEDLoad(V.getNode())))
15669 return false;
15670
15671 LoadSDNode *Ld = cast<LoadSDNode>(V.getNode());
15672
15673 if (!Ld->isSimple() ||
15674 !TLI.isLoadLegal(VT, V.getValueType(), Ld->getAlign(),
15675 Ld->getAddressSpace(), LoadOpcode, false))
15676 return false;
15677
15678 // Non-chain users of this value must either be the setcc in this
15679 // sequence or extends that can be folded into the new {z/s}ext-load.
15680 for (SDUse &Use : V->uses()) {
15681 // Skip uses of the chain and the setcc.
15682 SDNode *User = Use.getUser();
15683 if (Use.getResNo() != 0 || User == N0.getNode())
15684 continue;
15685 // Extra users must have exactly the same cast we are about to create.
15686 // TODO: This restriction could be eased if ExtendUsesToFormExtLoad()
15687 // is enhanced similarly.
15688 if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT)
15689 return false;
15690 }
15691 return true;
15692 };
15693
15694 if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) {
15695 SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00);
15696 SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01);
15697 return DAG.getSetCC(DL, VT, Ext0, Ext1, CC, /*Chain=*/{},
15698 /*Signaling=*/false, Flags);
15699 }
15700 }
15701 }
15702
15703 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
15704 // Here, T can be 1 or -1, depending on the type of the setcc and
15705 // getBooleanContents().
15706 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
15707
15708 // To determine the "true" side of the select, we need to know the high bit
15709 // of the value returned by the setcc if it evaluates to true.
15710 // If the type of the setcc is i1, then the true case of the select is just
15711 // sext(i1 1), that is, -1.
15712 // If the type of the setcc is larger (say, i8) then the value of the high
15713 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
15714 // of the appropriate width.
15715 SDValue ExtTrueVal = (SetCCWidth == 1)
15716 ? DAG.getAllOnesConstant(DL, VT)
15717 : DAG.getBoolConstant(true, DL, VT, N00VT);
15718 SDValue Zero = DAG.getConstant(0, DL, VT);
15719 if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
15720 return SCC;
15721
15722 if (!VT.isVector() && !shouldConvertSelectOfConstantsToMath(N0, VT, TLI)) {
15723 EVT SetCCVT = getSetCCResultType(N00VT);
15724 // Don't do this transform for i1 because there's a select transform
15725 // that would reverse it.
15726 // TODO: We should not do this transform at all without a target hook
15727 // because a sext is likely cheaper than a select?
15728 if (SetCCVT.getScalarSizeInBits() != 1 &&
15729 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
15730 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC, /*Chain=*/{},
15731 /*Signaling=*/false, Flags);
15732 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero, Flags);
15733 }
15734 }
15735
15736 return SDValue();
15737}
15738
15739SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
15740 SDValue N0 = N->getOperand(0);
15741 EVT VT = N->getValueType(0);
15742 SDLoc DL(N);
15743
15744 if (VT.isVector())
15745 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
15746 return FoldedVOp;
15747
15748 // sext(undef) = 0 because the top bit will all be the same.
15749 if (N0.isUndef())
15750 return DAG.getConstant(0, DL, VT);
15751
15752 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
15753 return Res;
15754
15755 // fold (sext (sext x)) -> (sext x)
15756 // fold (sext (aext x)) -> (sext x)
15757 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
15758 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
15759
15760 // fold (sext (aext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
15761 // fold (sext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
15764 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT,
15765 N0.getOperand(0));
15766
15767 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
15768 SDValue N00 = N0.getOperand(0);
15769 EVT ExtVT = cast<VTSDNode>(N0->getOperand(1))->getVT();
15770 if (N00.getOpcode() == ISD::TRUNCATE || TLI.isTruncateFree(N00, ExtVT)) {
15771 // fold (sext (sext_inreg x)) -> (sext (trunc x))
15772 if ((!LegalTypes || TLI.isTypeLegal(ExtVT))) {
15773 SDValue T = DAG.getNode(ISD::TRUNCATE, DL, ExtVT, N00);
15774 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, T);
15775 }
15776
15777 // If the trunc wasn't legal, try to fold to (sext_inreg (anyext x))
15778 if (!LegalTypes || TLI.isTypeLegal(VT)) {
15779 SDValue ExtSrc = DAG.getAnyExtOrTrunc(N00, DL, VT);
15780 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, ExtSrc,
15781 N0->getOperand(1));
15782 }
15783 }
15784 }
15785
15786 if (N0.getOpcode() == ISD::TRUNCATE) {
15787 // fold (sext (truncate (load x))) -> (sext (smaller load x))
15788 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
15789 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
15790 SDNode *oye = N0.getOperand(0).getNode();
15791 if (NarrowLoad.getNode() != N0.getNode()) {
15792 CombineTo(N0.getNode(), NarrowLoad);
15793 // CombineTo deleted the truncate, if needed, but not what's under it.
15794 AddToWorklist(oye);
15795 }
15796 return SDValue(N, 0); // Return N so it doesn't get rechecked!
15797 }
15798
15799 // See if the value being truncated is already sign extended. If so, just
15800 // eliminate the trunc/sext pair.
15801 SDValue Op = N0.getOperand(0);
15802 unsigned OpBits = Op.getScalarValueSizeInBits();
15803 unsigned MidBits = N0.getScalarValueSizeInBits();
15804 unsigned DestBits = VT.getScalarSizeInBits();
15805
15806 if (N0->getFlags().hasNoSignedWrap() ||
15807 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
15808 if (OpBits == DestBits) {
15809 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
15810 // bits, it is already ready.
15811 return Op;
15812 }
15813
15814 if (OpBits < DestBits) {
15815 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
15816 // bits, just sext from i32.
15817 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
15818 }
15819
15820 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
15821 // bits, just truncate to i32.
15822 SDNodeFlags Flags;
15823 Flags.setNoSignedWrap(true);
15824 Flags.setNoUnsignedWrap(N0->getFlags().hasNoUnsignedWrap());
15825 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
15826 }
15827
15828 // fold (sext (truncate x)) -> (sextinreg x).
15829 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
15830 N0.getValueType())) {
15831 if (OpBits < DestBits)
15832 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
15833 else if (OpBits > DestBits)
15834 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
15835 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
15836 DAG.getValueType(N0.getValueType()));
15837 }
15838 }
15839
15840 // Try to simplify (sext (load x)).
15841 if (SDValue foldedExt =
15842 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
15844 return foldedExt;
15845
15846 if (SDValue foldedExt =
15847 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
15849 return foldedExt;
15850
15851 // fold (sext (load x)) to multiple smaller sextloads.
15852 // Only on illegal but splittable vectors.
15853 if (SDValue ExtLoad = CombineExtLoad(N))
15854 return ExtLoad;
15855
15856 // Try to simplify (sext (sextload x)).
15857 if (SDValue foldedExt = tryToFoldExtOfExtload(
15858 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
15859 return foldedExt;
15860
15861 // Try to simplify (sext (atomic_load x)).
15862 if (SDValue foldedExt =
15863 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::SEXTLOAD))
15864 return foldedExt;
15865
15866 // fold (sext (and/or/xor (load x), cst)) ->
15867 // (and/or/xor (sextload x), (sext cst))
15868 if (ISD::isBitwiseLogicOp(N0.getOpcode()) &&
15869 isa<LoadSDNode>(N0.getOperand(0)) &&
15870 N0.getOperand(1).getOpcode() == ISD::Constant &&
15871 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
15872 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
15873 EVT MemVT = LN00->getMemoryVT();
15874 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
15875 ISD::SEXTLOAD, false) &&
15876 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
15878 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
15879 ISD::SIGN_EXTEND, SetCCs, TLI);
15880 if (DoXform) {
15881 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
15882 LN00->getChain(), LN00->getBasePtr(),
15883 LN00->getMemoryVT(),
15884 LN00->getMemOperand());
15885 APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
15886 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
15887 ExtLoad, DAG.getConstant(Mask, DL, VT));
15888 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
15889 bool NoReplaceTruncAnd = !N0.hasOneUse();
15890 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
15891 CombineTo(N, And);
15892 // If N0 has multiple uses, change other uses as well.
15893 if (NoReplaceTruncAnd) {
15894 SDValue TruncAnd =
15896 CombineTo(N0.getNode(), TruncAnd);
15897 }
15898 if (NoReplaceTrunc) {
15899 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
15900 } else {
15901 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
15902 LN00->getValueType(0), ExtLoad);
15903 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
15904 }
15905 return SDValue(N,0); // Return N so it doesn't get rechecked!
15906 }
15907 }
15908 }
15909
15910 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
15911 return V;
15912
15913 if (SDValue V = foldSextSetcc(N))
15914 return V;
15915
15916 // fold (sext x) -> (zext x) if the sign bit is known zero.
15917 if (!TLI.isSExtCheaperThanZExt(N0.getValueType(), VT) &&
15918 (!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
15919 DAG.SignBitIsZero(N0))
15920 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0, SDNodeFlags::NonNeg);
15921
15922 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
15923 return NewVSel;
15924
15925 // Eliminate this sign extend by doing a negation in the destination type:
15926 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
15927 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
15931 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
15932 return DAG.getNegative(Zext, DL, VT);
15933 }
15934 // Eliminate this sign extend by doing a decrement in the destination type:
15935 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
15936 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
15940 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
15941 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
15942 }
15943
15944 // fold sext (not i1 X) -> add (zext i1 X), -1
15945 // TODO: This could be extended to handle bool vectors.
15946 if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() &&
15947 (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) &&
15948 TLI.isOperationLegal(ISD::ADD, VT)))) {
15949 // If we can eliminate the 'not', the sext form should be better
15950 if (SDValue NewXor = visitXOR(N0.getNode())) {
15951 // Returning N0 is a form of in-visit replacement that may have
15952 // invalidated N0.
15953 if (NewXor.getNode() == N0.getNode()) {
15954 // Return SDValue here as the xor should have already been replaced in
15955 // this sext.
15956 return SDValue();
15957 }
15958
15959 // Return a new sext with the new xor.
15960 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor);
15961 }
15962
15963 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
15964 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
15965 }
15966
15967 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
15968 return Res;
15969
15970 return SDValue();
15971}
15972
15973/// Given an extending node with a pop-count operand, if the target does not
15974/// support a pop-count in the narrow source type but does support it in the
15975/// destination type, widen the pop-count to the destination type.
15976static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG, const SDLoc &DL) {
15977 assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
15978 Extend->getOpcode() == ISD::ANY_EXTEND) &&
15979 "Expected extend op");
15980
15981 SDValue CtPop = Extend->getOperand(0);
15982 if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
15983 return SDValue();
15984
15985 EVT VT = Extend->getValueType(0);
15986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15989 return SDValue();
15990
15991 // zext (ctpop X) --> ctpop (zext X)
15992 SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
15993 return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
15994}
15995
15996// If we have (zext (abs X)) where X is a type that will be promoted by type
15997// legalization, convert to (abs_min_poison (sext X)). But do not extend
15998// past a legal type.
15999static SDValue widenAbs(SDNode *Extend, SelectionDAG &DAG) {
16000 assert(Extend->getOpcode() == ISD::ZERO_EXTEND && "Expected zero extend.");
16001
16002 EVT VT = Extend->getValueType(0);
16003 if (VT.isVector())
16004 return SDValue();
16005
16006 SDValue Abs = Extend->getOperand(0);
16007 if (!ISD::isAbsOpcode(Abs.getOpcode()) || !Abs.hasOneUse())
16008 return SDValue();
16009
16010 EVT AbsVT = Abs.getValueType();
16011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16012 if (TLI.getTypeAction(*DAG.getContext(), AbsVT) !=
16014 return SDValue();
16015
16016 EVT LegalVT = TLI.getTypeToTransformTo(*DAG.getContext(), AbsVT);
16017
16018 SDValue SExt =
16019 DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Abs), LegalVT, Abs.getOperand(0));
16020 SDValue NewAbs = DAG.getNode(ISD::ABS_MIN_POISON, SDLoc(Abs), LegalVT, SExt);
16021 return DAG.getZExtOrTrunc(NewAbs, SDLoc(Extend), VT);
16022}
16023
16024SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
16025 SDValue N0 = N->getOperand(0);
16026 EVT VT = N->getValueType(0);
16027 SDLoc DL(N);
16028
16029 if (VT.isVector())
16030 if (SDValue FoldedVOp = SimplifyVCastOp(N, DL))
16031 return FoldedVOp;
16032
16033 // zext(undef) = 0
16034 if (N0.isUndef())
16035 return DAG.getConstant(0, DL, VT);
16036
16037 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16038 return Res;
16039
16040 // fold (zext (zext x)) -> (zext x)
16041 // fold (zext (aext x)) -> (zext x)
16042 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
16043 SDNodeFlags Flags;
16044 if (N0.getOpcode() == ISD::ZERO_EXTEND)
16045 Flags.setNonNeg(N0->getFlags().hasNonNeg());
16046 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0), Flags);
16047 }
16048
16049 // fold (zext (aext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16050 // fold (zext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16053 return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, N0.getOperand(0));
16054
16055 // fold (zext (truncate x)) -> (zext x) or
16056 // (zext (truncate x)) -> (truncate x)
16057 // This is valid when the truncated bits of x are already zero.
16058 SDValue Op;
16059 KnownBits Known;
16060 if (isTruncateOf(DAG, N0, Op, Known)) {
16061 APInt TruncatedBits =
16062 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
16063 APInt(Op.getScalarValueSizeInBits(), 0) :
16064 APInt::getBitsSet(Op.getScalarValueSizeInBits(),
16065 N0.getScalarValueSizeInBits(),
16066 std::min(Op.getScalarValueSizeInBits(),
16067 VT.getScalarSizeInBits()));
16068 if (TruncatedBits.isSubsetOf(Known.Zero)) {
16069 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
16070 DAG.salvageDebugInfo(*N0.getNode());
16071
16072 return ZExtOrTrunc;
16073 }
16074 }
16075
16076 // fold (zext (truncate x)) -> (and x, mask)
16077 if (N0.getOpcode() == ISD::TRUNCATE) {
16078 // fold (zext (truncate (load x))) -> (zext (smaller load x))
16079 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
16080 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16081 SDNode *oye = N0.getOperand(0).getNode();
16082 if (NarrowLoad.getNode() != N0.getNode()) {
16083 CombineTo(N0.getNode(), NarrowLoad);
16084 // CombineTo deleted the truncate, if needed, but not what's under it.
16085 AddToWorklist(oye);
16086 }
16087 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16088 }
16089
16090 EVT SrcVT = N0.getOperand(0).getValueType();
16091 EVT MinVT = N0.getValueType();
16092
16093 if (N->getFlags().hasNonNeg()) {
16094 SDValue Op = N0.getOperand(0);
16095 unsigned OpBits = SrcVT.getScalarSizeInBits();
16096 unsigned MidBits = MinVT.getScalarSizeInBits();
16097 unsigned DestBits = VT.getScalarSizeInBits();
16098
16099 if (N0->getFlags().hasNoSignedWrap() ||
16100 DAG.ComputeNumSignBits(Op) > OpBits - MidBits) {
16101 if (OpBits == DestBits) {
16102 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
16103 // bits, it is already ready.
16104 return Op;
16105 }
16106
16107 if (OpBits < DestBits) {
16108 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
16109 // bits, just sext from i32.
16110 // FIXME: This can probably be ZERO_EXTEND nneg?
16111 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
16112 }
16113
16114 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
16115 // bits, just truncate to i32.
16116 SDNodeFlags Flags;
16117 Flags.setNoSignedWrap(true);
16118 Flags.setNoUnsignedWrap(true);
16119 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op, Flags);
16120 }
16121 }
16122
16123 // Try to mask before the extension to avoid having to generate a larger mask,
16124 // possibly over several sub-vectors.
16125 if (SrcVT.bitsLT(VT) && VT.isVector()) {
16126 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
16128 SDValue Op = N0.getOperand(0);
16129 Op = DAG.getZeroExtendInReg(Op, DL, MinVT);
16130 AddToWorklist(Op.getNode());
16131 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, DL, VT);
16132 // Transfer the debug info; the new node is equivalent to N0.
16133 DAG.transferDbgValues(N0, ZExtOrTrunc);
16134 return ZExtOrTrunc;
16135 }
16136 }
16137
16138 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
16139 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
16140 AddToWorklist(Op.getNode());
16141 SDValue And = DAG.getZeroExtendInReg(Op, DL, MinVT);
16142 // We may safely transfer the debug info describing the truncate node over
16143 // to the equivalent and operation.
16144 DAG.transferDbgValues(N0, And);
16145 return And;
16146 }
16147 }
16148
16149 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
16150 // if either of the casts is not free.
16151 // Also handles (zext (and (bitcast (extract_subvector vNi1, 0)) cst))
16152 // by treating the bitcast+extract as equivalent to a truncate of the
16153 // wider bitcast, e.g. on AVX512DQ where v8i1 extract replaces truncate.
16154 if (N0.getOpcode() == ISD::AND &&
16155 N0.getOperand(1).getOpcode() == ISD::Constant) {
16156 SDValue AndSrc = N0.getOperand(0);
16157 SDValue X;
16158 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
16159 X = AndSrc.getOperand(0);
16160 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
16162 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
16163 // (bitcast (extract_subvector vNi1, 0) -> iK) is equivalent to
16164 // (truncate (bitcast vNi1 -> iN) -> iK); use the wider vNi1 as X.
16165 SDValue Src = AndSrc.getOperand(0).getOperand(0);
16166 EVT SrcVT = Src.getValueType();
16167 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
16168 EVT WideIntVT =
16170 if (TLI.isTypeLegal(WideIntVT))
16171 X = DAG.getBitcast(WideIntVT, Src);
16172 }
16173 }
16174 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
16175 !TLI.isZExtFree(N0.getValueType(), VT))) {
16176 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
16177 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16178 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
16179 }
16180 }
16181
16182 // Try to simplify (zext (load x)).
16183 if (SDValue foldedExt = tryToFoldExtOfLoad(
16184 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD,
16185 ISD::ZERO_EXTEND, N->getFlags().hasNonNeg()))
16186 return foldedExt;
16187
16188 if (SDValue foldedExt =
16189 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, LegalOperations, N, N0,
16191 return foldedExt;
16192
16193 // fold (zext (load x)) to multiple smaller zextloads.
16194 // Only on illegal but splittable vectors.
16195 if (SDValue ExtLoad = CombineExtLoad(N))
16196 return ExtLoad;
16197
16198 // Try to simplify (zext (atomic_load x)).
16199 if (SDValue foldedExt =
16200 tryToFoldExtOfAtomicLoad(DAG, TLI, VT, N0, ISD::ZEXTLOAD))
16201 return foldedExt;
16202
16203 // fold (zext (and/or/xor (load x), cst)) ->
16204 // (and/or/xor (zextload x), (zext cst))
16205 // Unless (and (load x) cst) will match as a zextload already and has
16206 // additional users, or the zext is already free.
16207 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && !TLI.isZExtFree(N0, VT) &&
16208 isa<LoadSDNode>(N0.getOperand(0)) &&
16209 N0.getOperand(1).getOpcode() == ISD::Constant &&
16210 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
16211 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
16212 EVT MemVT = LN00->getMemoryVT();
16213 if (TLI.isLoadLegal(VT, MemVT, LN00->getAlign(), LN00->getAddressSpace(),
16214 ISD::ZEXTLOAD, false) &&
16215 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
16216 bool DoXform = true;
16218 if (!N0.hasOneUse()) {
16219 if (N0.getOpcode() == ISD::AND) {
16220 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
16221 EVT LoadResultTy = AndC->getValueType(0);
16222 EVT ExtVT;
16223 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
16224 DoXform = false;
16225 }
16226 }
16227 if (DoXform)
16228 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
16229 ISD::ZERO_EXTEND, SetCCs, TLI);
16230 if (DoXform) {
16231 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
16232 LN00->getChain(), LN00->getBasePtr(),
16233 LN00->getMemoryVT(),
16234 LN00->getMemOperand());
16235 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16236 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
16237 ExtLoad, DAG.getConstant(Mask, DL, VT));
16238 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
16239 bool NoReplaceTruncAnd = !N0.hasOneUse();
16240 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
16241 CombineTo(N, And);
16242 // If N0 has multiple uses, change other uses as well.
16243 if (NoReplaceTruncAnd) {
16244 SDValue TruncAnd =
16246 CombineTo(N0.getNode(), TruncAnd);
16247 }
16248 if (NoReplaceTrunc) {
16249 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
16250 } else {
16251 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
16252 LN00->getValueType(0), ExtLoad);
16253 CombineTo(LN00, Trunc, ExtLoad.getValue(1));
16254 }
16255 return SDValue(N,0); // Return N so it doesn't get rechecked!
16256 }
16257 }
16258 }
16259
16260 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
16261 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
16262 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
16263 return ZExtLoad;
16264
16265 // Try to simplify (zext (zextload x)).
16266 if (SDValue foldedExt = tryToFoldExtOfExtload(
16267 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
16268 return foldedExt;
16269
16270 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
16271 return V;
16272
16273 if (N0.getOpcode() == ISD::SETCC) {
16274 // Propagate fast-math-flags.
16275 SelectionDAG::FlagInserter FlagsInserter(DAG, N0->getFlags());
16276
16277 // Only do this before legalize for now.
16278 if (!LegalOperations && VT.isVector() &&
16279 N0.getValueType().getVectorElementType() == MVT::i1) {
16280 EVT N00VT = N0.getOperand(0).getValueType();
16281 if (getSetCCResultType(N00VT) == N0.getValueType())
16282 return SDValue();
16283
16284 // We know that the # elements of the results is the same as the #
16285 // elements of the compare (and the # elements of the compare result for
16286 // that matter). Check to see that they are the same size. If so, we know
16287 // that the element size of the sext'd result matches the element size of
16288 // the compare operands.
16289 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
16290 // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
16291 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
16292 N0.getOperand(1), N0.getOperand(2));
16293 return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
16294 }
16295
16296 // If the desired elements are smaller or larger than the source
16297 // elements we can use a matching integer vector type and then
16298 // truncate/any extend followed by zext_in_reg.
16299 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16300 SDValue VsetCC =
16301 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
16302 N0.getOperand(1), N0.getOperand(2));
16303 return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
16304 N0.getValueType());
16305 }
16306
16307 // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc)
16308 EVT N0VT = N0.getValueType();
16309 EVT N00VT = N0.getOperand(0).getValueType();
16310 if (SDValue SCC = SimplifySelectCC(
16311 DL, N0.getOperand(0), N0.getOperand(1),
16312 DAG.getBoolConstant(true, DL, N0VT, N00VT),
16313 DAG.getBoolConstant(false, DL, N0VT, N00VT),
16314 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16315 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC);
16316 }
16317
16318 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
16319 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
16320 !TLI.isZExtFree(N0, VT)) {
16321 SDValue ShVal = N0.getOperand(0);
16322 SDValue ShAmt = N0.getOperand(1);
16323 if (auto *ShAmtC = dyn_cast<ConstantSDNode>(ShAmt)) {
16324 if (ShVal.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse()) {
16325 if (N0.getOpcode() == ISD::SHL) {
16326 // If the original shl may be shifting out bits, do not perform this
16327 // transformation.
16328 unsigned KnownZeroBits = ShVal.getValueSizeInBits() -
16329 ShVal.getOperand(0).getValueSizeInBits();
16330 if (ShAmtC->getAPIntValue().ugt(KnownZeroBits)) {
16331 // If the shift is too large, then see if we can deduce that the
16332 // shift is safe anyway.
16333
16334 // Check if the bits being shifted out are known to be zero.
16335 KnownBits KnownShVal = DAG.computeKnownBits(ShVal);
16336 if (ShAmtC->getAPIntValue().ugt(KnownShVal.countMinLeadingZeros()))
16337 return SDValue();
16338 }
16339 }
16340
16341 // Ensure that the shift amount is wide enough for the shifted value.
16342 if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
16343 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
16344
16345 return DAG.getNode(N0.getOpcode(), DL, VT,
16346 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, ShVal), ShAmt);
16347 }
16348 }
16349 }
16350
16351 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
16352 return NewVSel;
16353
16354 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16355 return NewCtPop;
16356
16357 if (SDValue V = widenAbs(N, DAG))
16358 return V;
16359
16360 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16361 return Res;
16362
16363 // CSE zext nneg with sext if the zext is not free.
16364 if (N->getFlags().hasNonNeg() && !TLI.isZExtFree(N0.getValueType(), VT)) {
16365 SDNode *CSENode = DAG.getNodeIfExists(ISD::SIGN_EXTEND, N->getVTList(), N0);
16366 if (CSENode)
16367 return SDValue(CSENode, 0);
16368 }
16369
16370 return SDValue();
16371}
16372
16373SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
16374 SDValue N0 = N->getOperand(0);
16375 EVT VT = N->getValueType(0);
16376 SDLoc DL(N);
16377
16378 // aext(undef) = undef
16379 if (N0.isUndef())
16380 return DAG.getUNDEF(VT);
16381
16382 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
16383 return Res;
16384
16385 // fold (aext (aext x)) -> (aext x)
16386 // fold (aext (zext x)) -> (zext x)
16387 // fold (aext (sext x)) -> (sext x)
16388 if (N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::ZERO_EXTEND ||
16389 N0.getOpcode() == ISD::SIGN_EXTEND) {
16390 SDNodeFlags Flags;
16391 if (N0.getOpcode() == ISD::ZERO_EXTEND)
16392 Flags.setNonNeg(N0->getFlags().hasNonNeg());
16393 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
16394 }
16395
16396 // fold (aext (aext_extend_vector_inreg x)) -> (aext_extend_vector_inreg x)
16397 // fold (aext (zext_extend_vector_inreg x)) -> (zext_extend_vector_inreg x)
16398 // fold (aext (sext_extend_vector_inreg x)) -> (sext_extend_vector_inreg x)
16402 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
16403
16404 // fold (aext (truncate (load x))) -> (aext (smaller load x))
16405 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
16406 if (N0.getOpcode() == ISD::TRUNCATE) {
16407 if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
16408 SDNode *oye = N0.getOperand(0).getNode();
16409 if (NarrowLoad.getNode() != N0.getNode()) {
16410 CombineTo(N0.getNode(), NarrowLoad);
16411 // CombineTo deleted the truncate, if needed, but not what's under it.
16412 AddToWorklist(oye);
16413 }
16414 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16415 }
16416 }
16417
16418 // fold (aext (truncate x))
16419 if (N0.getOpcode() == ISD::TRUNCATE)
16420 return DAG.getAnyExtOrTrunc(N0.getOperand(0), DL, VT);
16421
16422 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
16423 // if either of the casts is not free, and sign-extending the narrow type is
16424 // not cheaper than zero-extending it (which would indicate the target prefers
16425 // to keep operations at the narrower width).
16426 // Also handles (aext (and (bitcast (extract_subvector vNi1, 0)) cst))
16427 // which arises on AVX512DQ where v8i1 extract replaces truncate.
16428 if (N0.getOpcode() == ISD::AND &&
16429 N0.getOperand(1).getOpcode() == ISD::Constant) {
16430 SDValue AndSrc = N0.getOperand(0);
16431 SDValue X;
16432 if (AndSrc.getOpcode() == ISD::TRUNCATE) {
16433 X = AndSrc.getOperand(0);
16434 } else if (AndSrc.getOpcode() == ISD::BITCAST &&
16436 AndSrc.getOperand(0).getConstantOperandVal(1) == 0) {
16437 SDValue Src = AndSrc.getOperand(0).getOperand(0);
16438 EVT SrcVT = Src.getValueType();
16439 if (SrcVT.isFixedLengthVectorOf(MVT::i1)) {
16440 EVT WideIntVT =
16442 if (TLI.isTypeLegal(WideIntVT))
16443 X = DAG.getBitcast(WideIntVT, Src);
16444 }
16445 }
16446 if (X && (!TLI.isTruncateFree(X, N0.getValueType()) ||
16447 (!TLI.isZExtFree(N0.getValueType(), VT) &&
16448 !TLI.isSExtCheaperThanZExt(N0.getValueType(), VT)))) {
16449 X = DAG.getAnyExtOrTrunc(X, DL, VT);
16450 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
16451 return DAG.getNode(ISD::AND, DL, VT, X, DAG.getConstant(Mask, DL, VT));
16452 }
16453 }
16454
16455 // fold (aext (load x)) -> (aext (truncate (extload x)))
16456 // None of the supported targets knows how to perform load and any_ext
16457 // on vectors in one instruction, so attempt to fold to zext instead.
16458 if (VT.isVector()) {
16459 // Try to simplify (zext (load x)).
16460 if (SDValue foldedExt =
16461 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
16463 return foldedExt;
16464 } else if (ISD::isNON_EXTLoad(N0.getNode()) &&
16466 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16467 if (TLI.isLoadLegalOrCustom(VT, N0.getValueType(), LN0->getAlign(),
16468 LN0->getAddressSpace(), ISD::EXTLOAD, false)) {
16469 bool DoXform = true;
16471 if (!N0.hasOneUse())
16472 DoXform =
16473 ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
16474 if (DoXform) {
16475 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, DL, VT, LN0->getChain(),
16476 LN0->getBasePtr(), N0.getValueType(),
16477 LN0->getMemOperand());
16478 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
16479 // If the load value is used only by N, replace it via CombineTo N.
16480 bool NoReplaceTrunc = N0.hasOneUse();
16481 CombineTo(N, ExtLoad);
16482 if (NoReplaceTrunc) {
16483 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16484 recursivelyDeleteUnusedNodes(LN0);
16485 } else {
16486 SDValue Trunc =
16487 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
16488 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
16489 }
16490 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16491 }
16492 }
16493 }
16494
16495 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
16496 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
16497 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
16498 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
16499 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
16500 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16501 ISD::LoadExtType ExtType = LN0->getExtensionType();
16502 EVT MemVT = LN0->getMemoryVT();
16503 if (!LegalOperations ||
16504 TLI.isLoadLegal(VT, MemVT, LN0->getAlign(), LN0->getAddressSpace(),
16505 ExtType, false)) {
16506 SDValue ExtLoad =
16507 DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), LN0->getBasePtr(),
16508 MemVT, LN0->getMemOperand());
16509 CombineTo(N, ExtLoad);
16510 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
16511 recursivelyDeleteUnusedNodes(LN0);
16512 return SDValue(N, 0); // Return N so it doesn't get rechecked!
16513 }
16514 }
16515
16516 if (N0.getOpcode() == ISD::SETCC) {
16517 // Propagate fast-math-flags.
16518 SDNodeFlags Flags = N0->getFlags();
16519 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
16520
16521 // For vectors:
16522 // aext(setcc) -> vsetcc
16523 // aext(setcc) -> truncate(vsetcc)
16524 // aext(setcc) -> aext(vsetcc)
16525 // Only do this before legalize for now.
16526 if (VT.isVector() && !LegalOperations) {
16527 EVT N00VT = N0.getOperand(0).getValueType();
16528 if (getSetCCResultType(N00VT) == N0.getValueType())
16529 return SDValue();
16530
16531 // We know that the # elements of the results is the same as the
16532 // # elements of the compare (and the # elements of the compare result
16533 // for that matter). Check to see that they are the same size. If so,
16534 // we know that the element size of the sext'd result matches the
16535 // element size of the compare operands.
16536 if (VT.getSizeInBits() == N00VT.getSizeInBits())
16537 return DAG.getSetCC(DL, VT, N0.getOperand(0), N0.getOperand(1),
16538 cast<CondCodeSDNode>(N0.getOperand(2))->get(),
16539 /*Chain=*/{}, /*Signaling=*/false, Flags);
16540
16541 // If the desired elements are smaller or larger than the source
16542 // elements we can use a matching integer vector type and then
16543 // truncate/any extend
16544 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
16545 SDValue VsetCC = DAG.getSetCC(
16546 DL, MatchingVectorType, N0.getOperand(0), N0.getOperand(1),
16547 cast<CondCodeSDNode>(N0.getOperand(2))->get(), /*Chain=*/{},
16548 /*Signaling=*/false, Flags);
16549 return DAG.getAnyExtOrTrunc(VsetCC, DL, VT);
16550 }
16551
16552 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
16553 if (SDValue SCC = SimplifySelectCC(
16554 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
16555 DAG.getConstant(0, DL, VT),
16556 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
16557 return SCC;
16558 }
16559
16560 if (SDValue NewCtPop = widenCtPop(N, DAG, DL))
16561 return NewCtPop;
16562
16563 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG, DL, Level))
16564 return Res;
16565
16566 return SDValue();
16567}
16568
16569SDValue DAGCombiner::visitAssertExt(SDNode *N) {
16570 unsigned Opcode = N->getOpcode();
16571 SDValue N0 = N->getOperand(0);
16572 SDValue N1 = N->getOperand(1);
16573 EVT AssertVT = cast<VTSDNode>(N1)->getVT();
16574
16575 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
16576 if (N0.getOpcode() == Opcode &&
16577 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
16578 return N0;
16579
16580 // fold (assert?ext c, vt) -> c
16581 if (isa<ConstantSDNode>(N0))
16582 return N0;
16583
16584 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16585 N0.getOperand(0).getOpcode() == Opcode) {
16586 // We have an assert, truncate, assert sandwich. Make one stronger assert
16587 // by asserting on the smallest asserted type to the larger source type.
16588 // This eliminates the later assert:
16589 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
16590 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
16591 SDLoc DL(N);
16592 SDValue BigA = N0.getOperand(0);
16593 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16594 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
16595 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
16596 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16597 BigA.getOperand(0), MinAssertVTVal);
16598 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16599 }
16600
16601 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
16602 // than X. Just move the AssertZext in front of the truncate and drop the
16603 // AssertSExt.
16604 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
16606 Opcode == ISD::AssertZext) {
16607 SDValue BigA = N0.getOperand(0);
16608 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16609 if (AssertVT.bitsLT(BigA_AssertVT)) {
16610 SDLoc DL(N);
16611 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
16612 BigA.getOperand(0), N1);
16613 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
16614 }
16615 }
16616
16617 if (Opcode == ISD::AssertZext && N0.getOpcode() == ISD::AND &&
16619 const APInt &Mask = N0.getConstantOperandAPInt(1);
16620
16621 // If we have (AssertZext (and (AssertSext X, iX), M), iY) and Y is smaller
16622 // than X, and the And doesn't change the lower iX bits, we can move the
16623 // AssertZext in front of the And and drop the AssertSext.
16624 if (N0.getOperand(0).getOpcode() == ISD::AssertSext && N0.hasOneUse()) {
16625 SDValue BigA = N0.getOperand(0);
16626 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
16627 if (AssertVT.bitsLT(BigA_AssertVT) &&
16628 Mask.countr_one() >= BigA_AssertVT.getScalarSizeInBits()) {
16629 SDLoc DL(N);
16630 SDValue NewAssert =
16631 DAG.getNode(Opcode, DL, N->getValueType(0), BigA.getOperand(0), N1);
16632 return DAG.getNode(ISD::AND, DL, N->getValueType(0), NewAssert,
16633 N0.getOperand(1));
16634 }
16635 }
16636
16637 // Remove AssertZext entirely if the mask guarantees the assertion cannot
16638 // fail.
16639 // TODO: Use KB countMinLeadingZeros to handle non-constant masks?
16640 if (Mask.isIntN(AssertVT.getScalarSizeInBits()))
16641 return N0;
16642 }
16643
16644 return SDValue();
16645}
16646
16647SDValue DAGCombiner::visitAssertAlign(SDNode *N) {
16648 SDLoc DL(N);
16649
16650 Align AL = cast<AssertAlignSDNode>(N)->getAlign();
16651 SDValue N0 = N->getOperand(0);
16652
16653 // Fold (assertalign (assertalign x, AL0), AL1) ->
16654 // (assertalign x, max(AL0, AL1))
16655 if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0))
16656 return DAG.getAssertAlign(DL, N0.getOperand(0),
16657 std::max(AL, AAN->getAlign()));
16658
16659 // In rare cases, there are trivial arithmetic ops in source operands. Sink
16660 // this assert down to source operands so that those arithmetic ops could be
16661 // exposed to the DAG combining.
16662 switch (N0.getOpcode()) {
16663 default:
16664 break;
16665 case ISD::ADD:
16666 case ISD::PTRADD:
16667 case ISD::SUB: {
16668 unsigned AlignShift = Log2(AL);
16669 SDValue LHS = N0.getOperand(0);
16670 SDValue RHS = N0.getOperand(1);
16671 unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros();
16672 unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros();
16673 if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) {
16674 if (LHSAlignShift < AlignShift)
16675 LHS = DAG.getAssertAlign(DL, LHS, AL);
16676 if (RHSAlignShift < AlignShift)
16677 RHS = DAG.getAssertAlign(DL, RHS, AL);
16678 return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS);
16679 }
16680 break;
16681 }
16682 }
16683
16684 return SDValue();
16685}
16686
16687SDValue DAGCombiner::visitIS_FPCLASS(SDNode *N) {
16688 SDValue Src = N->getOperand(0);
16689 FPClassTest Mask = static_cast<FPClassTest>(N->getConstantOperandVal(1));
16690 EVT VT = N->getValueType(0);
16691 SDLoc DL(N);
16692
16693 // is.fpclass(poison, mask) -> poison
16694 if (Src.getOpcode() == ISD::POISON)
16695 return DAG.getPOISON(VT);
16696
16697 KnownFPClass Known = DAG.computeKnownFPClass(Src, Mask);
16698
16699 // All possible classes are within the mask: result is always true.
16700 if ((~Mask & Known.KnownFPClasses) == fcNone)
16701 return DAG.getBoolConstant(true, DL, VT, Src.getValueType());
16702
16703 // Clear test bits we know must be false from the source value.
16704 // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
16705 // fp_class (ninf x), ninf|pinf|other -> fp_class (ninf x), other
16706 if ((Mask & Known.KnownFPClasses) != Mask) {
16707 return DAG.getNode(
16708 ISD::IS_FPCLASS, DL, VT, Src,
16709 DAG.getTargetConstant(Mask & Known.KnownFPClasses, DL, MVT::i32),
16710 N->getFlags());
16711 }
16712
16713 return SDValue();
16714}
16715
16716/// If the result of a load is shifted/masked/truncated to an effectively
16717/// narrower type, try to transform the load to a narrower type and/or
16718/// use an extending load.
16719SDValue DAGCombiner::reduceLoadWidth(SDNode *N) {
16720 unsigned Opc = N->getOpcode();
16721
16723 SDValue N0 = N->getOperand(0);
16724 EVT VT = N->getValueType(0);
16725 EVT ExtVT = VT;
16726
16727 // This transformation isn't valid for vector loads.
16728 if (VT.isVector())
16729 return SDValue();
16730
16731 // The ShAmt variable is used to indicate that we've consumed a right
16732 // shift. I.e. we want to narrow the width of the load by skipping to load the
16733 // ShAmt least significant bits.
16734 unsigned ShAmt = 0;
16735 // A special case is when the least significant bits from the load are masked
16736 // away, but using an AND rather than a right shift. HasShiftedOffset is used
16737 // to indicate that the narrowed load should be left-shifted ShAmt bits to get
16738 // the result.
16739 unsigned ShiftedOffset = 0;
16740 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
16741 // extended to VT.
16742 if (Opc == ISD::SIGN_EXTEND_INREG) {
16743 ExtType = ISD::SEXTLOAD;
16744 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
16745 } else if (Opc == ISD::SRL || Opc == ISD::SRA) {
16746 // Another special-case: SRL/SRA is basically zero/sign-extending a narrower
16747 // value, or it may be shifting a higher subword, half or byte into the
16748 // lowest bits.
16749
16750 // Only handle shift with constant shift amount, and the shiftee must be a
16751 // load.
16752 auto *LN = dyn_cast<LoadSDNode>(N0);
16753 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16754 if (!N1C || !LN)
16755 return SDValue();
16756 // If the shift amount is larger than the memory type then we're not
16757 // accessing any of the loaded bytes.
16758 ShAmt = N1C->getZExtValue();
16759 uint64_t MemoryWidth = LN->getMemoryVT().getScalarSizeInBits();
16760 if (MemoryWidth <= ShAmt)
16761 return SDValue();
16762 // Attempt to fold away the SRL by using ZEXTLOAD and SRA by using SEXTLOAD.
16763 ExtType = Opc == ISD::SRL ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
16764 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
16765 // If original load is a SEXTLOAD then we can't simply replace it by a
16766 // ZEXTLOAD (we could potentially replace it by a more narrow SEXTLOAD
16767 // followed by a ZEXT, but that is not handled at the moment). Similarly if
16768 // the original load is a ZEXTLOAD and we want to use a SEXTLOAD.
16769 if ((LN->getExtensionType() == ISD::SEXTLOAD ||
16770 LN->getExtensionType() == ISD::ZEXTLOAD) &&
16771 LN->getExtensionType() != ExtType)
16772 return SDValue();
16773 } else if (Opc == ISD::AND) {
16774 // An AND with a constant mask is the same as a truncate + zero-extend.
16775 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
16776 if (!AndC)
16777 return SDValue();
16778
16779 const APInt &Mask = AndC->getAPIntValue();
16780 unsigned ActiveBits = 0;
16781 if (Mask.isMask()) {
16782 ActiveBits = Mask.countr_one();
16783 } else if (Mask.isShiftedMask(ShAmt, ActiveBits)) {
16784 ShiftedOffset = ShAmt;
16785 } else {
16786 return SDValue();
16787 }
16788
16789 ExtType = ISD::ZEXTLOAD;
16790 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
16791 }
16792
16793 // In case Opc==SRL we've already prepared ExtVT/ExtType/ShAmt based on doing
16794 // a right shift. Here we redo some of those checks, to possibly adjust the
16795 // ExtVT even further based on "a masking AND". We could also end up here for
16796 // other reasons (e.g. based on Opc==TRUNCATE) and that is why some checks
16797 // need to be done here as well.
16798 if (Opc == ISD::SRL || N0.getOpcode() == ISD::SRL) {
16799 SDValue SRL = Opc == ISD::SRL ? SDValue(N, 0) : N0;
16800 // Bail out when the SRL has more than one use. This is done for historical
16801 // (undocumented) reasons. Maybe intent was to guard the AND-masking below
16802 // check below? And maybe it could be non-profitable to do the transform in
16803 // case the SRL has multiple uses and we get here with Opc!=ISD::SRL?
16804 // FIXME: Can't we just skip this check for the Opc==ISD::SRL case.
16805 if (!SRL.hasOneUse())
16806 return SDValue();
16807
16808 // Only handle shift with constant shift amount, and the shiftee must be a
16809 // load.
16810 auto *LN = dyn_cast<LoadSDNode>(SRL.getOperand(0));
16811 auto *SRL1C = dyn_cast<ConstantSDNode>(SRL.getOperand(1));
16812 if (!SRL1C || !LN)
16813 return SDValue();
16814
16815 // If the shift amount is larger than the input type then we're not
16816 // accessing any of the loaded bytes. If the load was a zextload/extload
16817 // then the result of the shift+trunc is zero/undef (handled elsewhere).
16818 ShAmt = SRL1C->getZExtValue();
16819 uint64_t MemoryWidth = LN->getMemoryVT().getSizeInBits();
16820 if (ShAmt >= MemoryWidth)
16821 return SDValue();
16822
16823 // Because a SRL must be assumed to *need* to zero-extend the high bits
16824 // (as opposed to anyext the high bits), we can't combine the zextload
16825 // lowering of SRL and an sextload.
16826 if (LN->getExtensionType() == ISD::SEXTLOAD)
16827 return SDValue();
16828
16829 // Avoid reading outside the memory accessed by the original load (could
16830 // happened if we only adjust the load base pointer by ShAmt). Instead we
16831 // try to narrow the load even further. The typical scenario here is:
16832 // (i64 (truncate (i96 (srl (load x), 64)))) ->
16833 // (i64 (truncate (i96 (zextload (load i32 + offset) from i32))))
16834 if (ExtVT.getScalarSizeInBits() > MemoryWidth - ShAmt) {
16835 // Don't replace sextload by zextload.
16836 if (ExtType == ISD::SEXTLOAD)
16837 return SDValue();
16838 // Narrow the load.
16839 ExtType = ISD::ZEXTLOAD;
16840 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
16841 }
16842
16843 // If the SRL is only used by a masking AND, we may be able to adjust
16844 // the ExtVT to make the AND redundant.
16845 SDNode *Mask = *(SRL->user_begin());
16846 if (SRL.hasOneUse() && Mask->getOpcode() == ISD::AND &&
16847 isa<ConstantSDNode>(Mask->getOperand(1))) {
16848 unsigned Offset, ActiveBits;
16849 const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
16850 if (ShiftMask.isMask()) {
16851 EVT MaskedVT =
16852 EVT::getIntegerVT(*DAG.getContext(), ShiftMask.countr_one());
16853 // If the mask is smaller, recompute the type.
16854 if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) &&
16855 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
16856 LN->getAddressSpace(), ExtType, false))
16857 ExtVT = MaskedVT;
16858 } else if (ExtType == ISD::ZEXTLOAD &&
16859 ShiftMask.isShiftedMask(Offset, ActiveBits) &&
16860 (Offset + ShAmt) < VT.getScalarSizeInBits()) {
16861 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
16862 // If the mask is shifted we can use a narrower load and a shl to insert
16863 // the trailing zeros.
16864 if (((Offset + ActiveBits) <= ExtVT.getScalarSizeInBits()) &&
16865 TLI.isLoadLegal(SRL.getValueType(), MaskedVT, LN->getAlign(),
16866 LN->getAddressSpace(), ExtType, false)) {
16867 ExtVT = MaskedVT;
16868 ShAmt = Offset + ShAmt;
16869 ShiftedOffset = Offset;
16870 }
16871 }
16872 }
16873
16874 N0 = SRL.getOperand(0);
16875 }
16876
16877 // If the load is shifted left (and the result isn't shifted back right), we
16878 // can fold a truncate through the shift. The typical scenario is that N
16879 // points at a TRUNCATE here so the attempted fold is:
16880 // (truncate (shl (load x), c))) -> (shl (narrow load x), c)
16881 // ShLeftAmt will indicate how much a narrowed load should be shifted left.
16882 unsigned ShLeftAmt = 0;
16883 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
16884 ExtVT == VT && TLI.isNarrowingProfitable(N, N0.getValueType(), VT)) {
16885 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
16886 ShLeftAmt = N01->getZExtValue();
16887 N0 = N0.getOperand(0);
16888 }
16889 }
16890
16891 // Look through a freeze if present between the operation and the load.
16892 // The freeze will be preserved on the narrowed result.
16893 SDValue FreezeNode;
16894 if (N0.getOpcode() == ISD::FREEZE) {
16895 FreezeNode = N0;
16896 N0 = N0.getOperand(0);
16897 }
16898
16899 // If we haven't found a load, we can't narrow it.
16900 if (!isa<LoadSDNode>(N0))
16901 return SDValue();
16902
16903 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
16904 // Reducing the width of a volatile load is illegal. For atomics, we may be
16905 // able to reduce the width provided we never widen again. (see D66309)
16906 if (!LN0->isSimple() ||
16907 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
16908 return SDValue();
16909
16910 // Bail early when looking through a multi-use freeze, since other users of
16911 // the freeze can depend on the full load value. But its still safe to change
16912 // the extension type from anyext to zext.
16913 if (FreezeNode && !FreezeNode.hasOneUse() &&
16914 (LN0->getMemoryVT().bitsGT(ExtVT) || ExtType != ISD::ZEXTLOAD ||
16915 (LN0->getExtensionType() != ISD::EXTLOAD &&
16916 LN0->getExtensionType() != ISD::ZEXTLOAD)))
16917 return SDValue();
16918
16919 auto AdjustBigEndianShift = [&](unsigned ShAmt) {
16920 unsigned LVTStoreBits =
16922 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedValue();
16923 return LVTStoreBits - EVTStoreBits - ShAmt;
16924 };
16925
16926 // We need to adjust the pointer to the load by ShAmt bits in order to load
16927 // the correct bytes.
16928 unsigned PtrAdjustmentInBits =
16929 DAG.getDataLayout().isBigEndian() ? AdjustBigEndianShift(ShAmt) : ShAmt;
16930
16931 uint64_t PtrOff = PtrAdjustmentInBits / 8;
16932 SDLoc DL(LN0);
16933 // The original load itself didn't wrap, so an offset within it doesn't.
16934 SDValue NewPtr =
16937 AddToWorklist(NewPtr.getNode());
16938
16939 SDValue Load;
16940 if (ExtType == ISD::NON_EXTLOAD) {
16941 const MDNode *OldRanges = LN0->getRanges();
16942 const MDNode *NewRanges = nullptr;
16943 // If LSBs are loaded and the truncated ConstantRange for the OldRanges
16944 // metadata is not the full-set for the new width then create a NewRanges
16945 // metadata for the truncated load
16946 if (ShAmt == 0 && OldRanges) {
16947 ConstantRange CR = getConstantRangeFromMetadata(*OldRanges);
16948 unsigned BitSize = VT.getScalarSizeInBits();
16949
16950 // It is possible for an 8-bit extending load with 8-bit range
16951 // metadata to be narrowed to an 8-bit load. This guard is necessary to
16952 // ensure that truncation is strictly smaller.
16953 if (CR.getBitWidth() > BitSize) {
16954 ConstantRange TruncatedCR = CR.truncate(BitSize);
16955 if (!TruncatedCR.isFullSet()) {
16956 Metadata *Bounds[2] = {
16958 ConstantInt::get(*DAG.getContext(), TruncatedCR.getLower())),
16960 ConstantInt::get(*DAG.getContext(), TruncatedCR.getUpper()))};
16961 NewRanges = MDNode::get(*DAG.getContext(), Bounds);
16962 }
16963 } else if (CR.getBitWidth() == BitSize)
16964 NewRanges = OldRanges;
16965 }
16966 Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
16967 LN0->getPointerInfo().getWithOffset(PtrOff),
16968 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
16969 LN0->getAAInfo(), NewRanges);
16970 } else
16971 Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
16972 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
16973 LN0->getBaseAlign(), LN0->getMemOperand()->getFlags(),
16974 LN0->getAAInfo());
16975
16976 // Replace the old load's chain with the new load's chain.
16977 WorklistRemover DeadNodes(*this);
16978 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
16979
16980 // Replace old load value for multi-use freeze so all users benefit.
16981 if (FreezeNode && !FreezeNode.hasOneUse())
16982 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), Load.getValue(0));
16983
16984 // If we looked through a freeze, rewrap the narrowed result and add an
16985 // Assert node so downstream analyses can see the range.
16987 if (FreezeNode) {
16988 Result = DAG.getNode(ISD::FREEZE, DL, VT, Result);
16989 if (ExtType == ISD::ZEXTLOAD)
16990 Result =
16991 DAG.getNode(ISD::AssertZext, DL, VT, Result, DAG.getValueType(ExtVT));
16992 else if (ExtType == ISD::SEXTLOAD)
16993 Result =
16994 DAG.getNode(ISD::AssertSext, DL, VT, Result, DAG.getValueType(ExtVT));
16995 }
16996
16997 // Shift the result left, if we've swallowed a left shift.
16998 if (ShLeftAmt != 0) {
16999 // If the shift amount is as large as the result size (but, presumably,
17000 // no larger than the source) then the useful bits of the result are
17001 // zero; we can't simply return the shortened shift, because the result
17002 // of that operation is undefined.
17003 if (ShLeftAmt >= VT.getScalarSizeInBits())
17004 Result = DAG.getConstant(0, DL, VT);
17005 else
17006 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
17007 DAG.getShiftAmountConstant(ShLeftAmt, VT, DL));
17008 }
17009
17010 if (ShiftedOffset != 0) {
17011 // We're using a shifted mask, so the load now has an offset. This means
17012 // that data has been loaded into the lower bytes than it would have been
17013 // before, so we need to shl the loaded data into the correct position in the
17014 // register.
17015 SDValue ShiftC = DAG.getConstant(ShiftedOffset, DL, VT);
17016 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
17017 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
17018 }
17019
17020 // Return the new loaded value.
17021 return Result;
17022}
17023
17024SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
17025 SDValue N0 = N->getOperand(0);
17026 SDValue N1 = N->getOperand(1);
17027 EVT VT = N->getValueType(0);
17028 EVT ExtVT = cast<VTSDNode>(N1)->getVT();
17029 unsigned VTBits = VT.getScalarSizeInBits();
17030 unsigned ExtVTBits = ExtVT.getScalarSizeInBits();
17031 SDLoc DL(N);
17032
17033 // sext_vector_inreg(undef) = 0 because the top bit will all be the same.
17034 if (N0.isUndef())
17035 return DAG.getConstant(0, DL, VT);
17036
17037 // fold (sext_in_reg c1) -> c1
17038 if (SDValue C =
17040 return C;
17041
17042 // If the input is already sign extended, just drop the extension.
17043 if (ExtVTBits >= DAG.ComputeMaxSignificantBits(N0))
17044 return N0;
17045
17046 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
17047 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
17048 ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
17049 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N0.getOperand(0), N1);
17050
17051 // fold (sext_in_reg (sext x)) -> (sext x)
17052 // fold (sext_in_reg (aext x)) -> (sext x)
17053 // if x is small enough or if we know that x has more than 1 sign bit and the
17054 // sign_extend_inreg is extending from one of them.
17055 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
17056 SDValue N00 = N0.getOperand(0);
17057 unsigned N00Bits = N00.getScalarValueSizeInBits();
17058 if ((N00Bits <= ExtVTBits ||
17059 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits) &&
17060 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
17061 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
17062 }
17063
17064 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
17065 // if x is small enough or if we know that x has more than 1 sign bit and the
17066 // sign_extend_inreg is extending from one of them.
17068 SDValue N00 = N0.getOperand(0);
17069 unsigned N00Bits = N00.getScalarValueSizeInBits();
17070 bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
17071 if ((N00Bits == ExtVTBits ||
17072 (!IsZext && (N00Bits < ExtVTBits ||
17073 DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits))) &&
17074 (!LegalOperations ||
17076 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, N00);
17077 }
17078
17079 // fold (sext_in_reg (zext x)) -> (sext x)
17080 // iff we are extending the source sign bit.
17081 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
17082 SDValue N00 = N0.getOperand(0);
17083 if (N00.getScalarValueSizeInBits() == ExtVTBits &&
17084 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
17085 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N00);
17086 }
17087
17088 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
17089 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1)))
17090 return DAG.getZeroExtendInReg(N0, DL, ExtVT);
17091
17092 // fold operands of sext_in_reg based on knowledge that the top bits are not
17093 // demanded.
17095 return SDValue(N, 0);
17096
17097 // fold (sext_in_reg (load x)) -> (smaller sextload x)
17098 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
17099 if (SDValue NarrowLoad = reduceLoadWidth(N))
17100 return NarrowLoad;
17101
17102 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
17103 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
17104 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
17105 if (N0.getOpcode() == ISD::SRL) {
17106 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
17107 if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) {
17108 // We can turn this into an SRA iff the input to the SRL is already sign
17109 // extended enough.
17110 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
17111 if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits)
17112 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
17113 N0.getOperand(1));
17114 }
17115 }
17116
17117 // fold (sext_inreg (extload x)) -> (sextload x)
17118 // If sextload is not supported by target, we can only do the combine when
17119 // load has one use. Doing otherwise can block folding the extload with other
17120 // extends that the target does support.
17122 auto *LN0 = cast<LoadSDNode>(N0);
17123 if (ExtVT == LN0->getMemoryVT() &&
17124 ((!LegalOperations && LN0->isSimple() && N0.hasOneUse()) ||
17125 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
17126 ISD::SEXTLOAD, false))) {
17127 SDValue ExtLoad =
17128 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
17129 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
17130 CombineTo(N, ExtLoad);
17131 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17132 AddToWorklist(ExtLoad.getNode());
17133 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17134 }
17135 }
17136
17137 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
17139 auto *LN0 = cast<LoadSDNode>(N0);
17140
17141 if (N0.hasOneUse() && ExtVT == LN0->getMemoryVT() &&
17142 ((!LegalOperations && LN0->isSimple()) &&
17143 TLI.isLoadLegal(VT, ExtVT, LN0->getAlign(), LN0->getAddressSpace(),
17144 ISD::SEXTLOAD, false))) {
17145 SDValue ExtLoad =
17146 DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
17147 LN0->getBasePtr(), ExtVT, LN0->getMemOperand());
17148 CombineTo(N, ExtLoad);
17149 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17151 }
17152 }
17153
17154 // fold (sext_inreg (masked_load x)) -> (sext_masked_load x)
17155 // ignore it if the masked load is already sign extended
17156 bool Frozen = N0.getOpcode() == ISD::FREEZE && N0.hasOneUse();
17157 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(Frozen ? N0.getOperand(0) : N0)) {
17158 if (ExtVT == Ld->getMemoryVT() && Ld->hasNUsesOfValue(1, 0) &&
17160 TLI.isLoadLegal(VT, ExtVT, Ld->getAlign(), Ld->getAddressSpace(),
17161 ISD::SEXTLOAD, false)) {
17162 SDValue ExtMaskedLoad = DAG.getMaskedLoad(
17163 VT, DL, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(),
17164 Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(),
17165 Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad());
17166 CombineTo(N, Frozen ? N0 : ExtMaskedLoad);
17167 CombineTo(Ld, ExtMaskedLoad, ExtMaskedLoad.getValue(1));
17168 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17169 }
17170 }
17171
17172 // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x)
17173 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
17174 if (SDValue(GN0, 0).hasOneUse() && ExtVT == GN0->getMemoryVT() &&
17176 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
17177 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
17178
17179 SDValue ExtLoad = DAG.getMaskedGather(
17180 DAG.getVTList(VT, MVT::Other), ExtVT, DL, Ops, GN0->getMemOperand(),
17181 GN0->getIndexType(), ISD::SEXTLOAD);
17182
17183 CombineTo(N, ExtLoad);
17184 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
17185 AddToWorklist(ExtLoad.getNode());
17186 return SDValue(N, 0); // Return N so it doesn't get rechecked!
17187 }
17188 }
17189
17190 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
17191 if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) {
17192 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
17193 N0.getOperand(1), false))
17194 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, BSwap, N1);
17195 }
17196
17197 // Fold (iM_signext_inreg
17198 // (extract_subvector (zext|anyext|sext iN_v to _) _)
17199 // from iN)
17200 // -> (extract_subvector (signext iN_v to iM))
17201 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR && N0.hasOneUse() &&
17203 SDValue InnerExt = N0.getOperand(0);
17204 EVT InnerExtVT = InnerExt->getValueType(0);
17205 SDValue Extendee = InnerExt->getOperand(0);
17206
17207 if (ExtVTBits == Extendee.getValueType().getScalarSizeInBits() &&
17208 (!LegalOperations ||
17209 TLI.isOperationLegal(ISD::SIGN_EXTEND, InnerExtVT))) {
17210 SDValue SignExtExtendee =
17211 DAG.getNode(ISD::SIGN_EXTEND, DL, InnerExtVT, Extendee);
17212 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SignExtExtendee,
17213 N0.getOperand(1));
17214 }
17215 }
17216
17217 return SDValue();
17218}
17219
17221 SDNode *N, const SDLoc &DL, const TargetLowering &TLI, SelectionDAG &DAG,
17222 bool LegalOperations) {
17223 unsigned InregOpcode = N->getOpcode();
17224 unsigned Opcode = DAG.getOpcode_EXTEND(InregOpcode);
17225
17226 SDValue Src = N->getOperand(0);
17227 EVT VT = N->getValueType(0);
17228 EVT SrcVT = VT.changeVectorElementType(
17229 *DAG.getContext(), Src.getValueType().getVectorElementType());
17230
17231 assert(ISD::isExtVecInRegOpcode(InregOpcode) &&
17232 "Expected EXTEND_VECTOR_INREG dag node in input!");
17233
17234 // Profitability check: our operand must be an one-use CONCAT_VECTORS.
17235 // FIXME: one-use check may be overly restrictive
17236 if (!Src.hasOneUse() || Src.getOpcode() != ISD::CONCAT_VECTORS)
17237 return SDValue();
17238
17239 // Profitability check: we must be extending exactly one of it's operands.
17240 // FIXME: this is probably overly restrictive.
17241 Src = Src.getOperand(0);
17242 if (Src.getValueType() != SrcVT)
17243 return SDValue();
17244
17245 if (LegalOperations && !TLI.isOperationLegal(Opcode, VT))
17246 return SDValue();
17247
17248 return DAG.getNode(Opcode, DL, VT, Src);
17249}
17250
17251SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) {
17252 SDValue N0 = N->getOperand(0);
17253 EVT VT = N->getValueType(0);
17254 SDLoc DL(N);
17255
17256 if (N0.isUndef()) {
17257 // aext_vector_inreg(undef) = undef because the top bits are undefined.
17258 // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same.
17259 return N->getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
17260 ? DAG.getUNDEF(VT)
17261 : DAG.getConstant(0, DL, VT);
17262 }
17263
17264 if (SDValue Res = tryToFoldExtendOfConstant(N, DL, TLI, DAG, LegalTypes))
17265 return Res;
17266
17268 return SDValue(N, 0);
17269
17271 LegalOperations))
17272 return R;
17273
17274 return SDValue();
17275}
17276
17277SDValue DAGCombiner::visitTRUNCATE_USAT_U(SDNode *N) {
17278 EVT VT = N->getValueType(0);
17279 SDValue N0 = N->getOperand(0);
17280
17281 SDValue FPVal;
17282 if (sd_match(N0, m_FPToUI(m_Value(FPVal))) &&
17284 ISD::FP_TO_UINT_SAT, FPVal.getValueType(), VT))
17285 return DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), VT, FPVal,
17286 DAG.getValueType(VT.getScalarType()));
17287
17288 return SDValue();
17289}
17290
17291/// Detect patterns of truncation with unsigned saturation:
17292///
17293/// (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
17294/// Return the source value x to be truncated or SDValue() if the pattern was
17295/// not matched.
17296///
17298 unsigned NumDstBits = VT.getScalarSizeInBits();
17299 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17300 // Saturation with truncation. We truncate from InVT to VT.
17301 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17302
17303 SDValue Min;
17304 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17305 if (sd_match(In, m_UMin(m_Value(Min), m_SpecificInt(UnsignedMax))))
17306 return Min;
17307
17308 return SDValue();
17309}
17310
17311/// Detect patterns of truncation with signed saturation:
17312/// (truncate (smin (smax (x, signed_min_of_dest_type),
17313/// signed_max_of_dest_type)) to dest_type)
17314/// or:
17315/// (truncate (smax (smin (x, signed_max_of_dest_type),
17316/// signed_min_of_dest_type)) to dest_type).
17317///
17318/// Return the source value to be truncated or SDValue() if the pattern was not
17319/// matched.
17321 unsigned NumDstBits = VT.getScalarSizeInBits();
17322 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17323 // Saturation with truncation. We truncate from InVT to VT.
17324 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17325
17326 SDValue Val;
17327 APInt SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
17328 APInt SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
17329
17330 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_SpecificInt(SignedMin)),
17331 m_SpecificInt(SignedMax))))
17332 return Val;
17333
17334 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(SignedMax)),
17335 m_SpecificInt(SignedMin))))
17336 return Val;
17337
17338 return SDValue();
17339}
17340
17341/// Detect patterns of truncation with unsigned saturation:
17343 const SDLoc &DL) {
17344 unsigned NumDstBits = VT.getScalarSizeInBits();
17345 unsigned NumSrcBits = In.getScalarValueSizeInBits();
17346 // Saturation with truncation. We truncate from InVT to VT.
17347 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
17348
17349 SDValue Val;
17350 APInt UnsignedMax = APInt::getMaxValue(NumDstBits).zext(NumSrcBits);
17351 // Min == 0, Max is unsigned max of destination type.
17352 if (sd_match(In, m_SMax(m_SMin(m_Value(Val), m_SpecificInt(UnsignedMax)),
17353 m_Zero())))
17354 return Val;
17355
17356 if (sd_match(In, m_SMin(m_SMax(m_Value(Val), m_Zero()),
17357 m_SpecificInt(UnsignedMax))))
17358 return Val;
17359
17360 if (sd_match(In, m_UMin(m_SMax(m_Value(Val), m_Zero()),
17361 m_SpecificInt(UnsignedMax))))
17362 return Val;
17363
17364 return SDValue();
17365}
17366
17367static SDValue foldToSaturated(SDNode *N, EVT &VT, SDValue &Src, EVT &SrcVT,
17368 SDLoc &DL, const TargetLowering &TLI,
17369 SelectionDAG &DAG) {
17370 auto AllowedTruncateSat = [&](unsigned Opc, EVT SrcVT, EVT VT) -> bool {
17371 return (TLI.isOperationLegalOrCustom(Opc, SrcVT) &&
17372 TLI.isTypeDesirableForOp(Opc, VT));
17373 };
17374
17375 if (Src.getOpcode() == ISD::SMIN || Src.getOpcode() == ISD::SMAX) {
17376 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_S, SrcVT, VT))
17377 if (SDValue SSatVal = detectSSatSPattern(Src, VT))
17378 return DAG.getNode(ISD::TRUNCATE_SSAT_S, DL, VT, SSatVal);
17379 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17380 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17381 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17382 } else if (Src.getOpcode() == ISD::UMIN) {
17383 if (AllowedTruncateSat(ISD::TRUNCATE_SSAT_U, SrcVT, VT))
17384 if (SDValue SSatVal = detectSSatUPattern(Src, VT, DAG, DL))
17385 return DAG.getNode(ISD::TRUNCATE_SSAT_U, DL, VT, SSatVal);
17386 if (AllowedTruncateSat(ISD::TRUNCATE_USAT_U, SrcVT, VT))
17387 if (SDValue USatVal = detectUSatUPattern(Src, VT))
17388 return DAG.getNode(ISD::TRUNCATE_USAT_U, DL, VT, USatVal);
17389 }
17390
17391 return SDValue();
17392}
17393
17394SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
17395 SDValue N0 = N->getOperand(0);
17396 EVT VT = N->getValueType(0);
17397 EVT SrcVT = N0.getValueType();
17398 bool isLE = DAG.getDataLayout().isLittleEndian();
17399 SDLoc DL(N);
17400
17401 // trunc(undef) = undef
17402 if (N0.isUndef())
17403 return DAG.getUNDEF(VT);
17404
17405 // fold (truncate (truncate x)) -> (truncate x)
17406 if (N0.getOpcode() == ISD::TRUNCATE)
17407 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17408
17409 // fold saturated truncate
17410 if (SDValue SaturatedTR = foldToSaturated(N, VT, N0, SrcVT, DL, TLI, DAG))
17411 return SaturatedTR;
17412
17413 // fold (truncate c1) -> c1
17414 if (SDValue C = DAG.FoldConstantArithmetic(ISD::TRUNCATE, DL, VT, {N0}))
17415 return C;
17416
17417 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
17418 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
17419 N0.getOpcode() == ISD::SIGN_EXTEND ||
17420 N0.getOpcode() == ISD::ANY_EXTEND) {
17421 // if the source is smaller than the dest, we still need an extend.
17422 if (N0.getOperand(0).getValueType().bitsLT(VT)) {
17423 SDNodeFlags Flags;
17424 if (N0.getOpcode() == ISD::ZERO_EXTEND)
17425 Flags.setNonNeg(N0->getFlags().hasNonNeg());
17426 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), Flags);
17427 }
17428 // if the source is larger than the dest, than we just need the truncate.
17429 if (N0.getOperand(0).getValueType().bitsGT(VT))
17430 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17431 // if the source and dest are the same type, we can drop both the extend
17432 // and the truncate.
17433 return N0.getOperand(0);
17434 }
17435
17436 // Try to narrow a truncate-of-sext_in_reg to the destination type:
17437 // trunc (sign_ext_inreg X, iM) to iN --> sign_ext_inreg (trunc X to iN), iM
17438 if (!LegalTypes && N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
17439 N0.hasOneUse()) {
17440 SDValue X = N0.getOperand(0);
17441 SDValue ExtVal = N0.getOperand(1);
17442 EVT ExtVT = cast<VTSDNode>(ExtVal)->getVT();
17443 if (ExtVT.bitsLT(VT) && TLI.preferSextInRegOfTruncate(VT, SrcVT, ExtVT)) {
17444 SDValue TrX = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
17445 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, TrX, ExtVal);
17446 }
17447 }
17448
17449 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
17450 if (N->hasOneUse() && (N->user_begin()->getOpcode() == ISD::ANY_EXTEND))
17451 return SDValue();
17452
17453 // Fold extract-and-trunc into a narrow extract. For example:
17454 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
17455 // i32 y = TRUNCATE(i64 x)
17456 // -- becomes --
17457 // v16i8 b = BITCAST (v2i64 val)
17458 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
17459 //
17460 // Note: We only run this optimization after type legalization (which often
17461 // creates this pattern) and before operation legalization after which
17462 // we need to be more careful about the vector instructions that we generate.
17463 if (LegalTypes && !LegalOperations && VT.isScalarInteger() && VT != MVT::i1 &&
17464 N0->hasOneUse()) {
17465 EVT TrTy = N->getValueType(0);
17466 SDValue Src = N0;
17467
17468 // Check for cases where we shift down an upper element before truncation.
17469 int EltOffset = 0;
17470 if (Src.getOpcode() == ISD::SRL && Src.getOperand(0)->hasOneUse()) {
17471 if (auto ShAmt = DAG.getValidShiftAmount(Src)) {
17472 if ((*ShAmt % TrTy.getSizeInBits()) == 0) {
17473 Src = Src.getOperand(0);
17474 EltOffset = *ShAmt / TrTy.getSizeInBits();
17475 }
17476 }
17477 }
17478
17479 if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17480 EVT VecTy = Src.getOperand(0).getValueType();
17481 EVT ExTy = Src.getValueType();
17482
17483 auto EltCnt = VecTy.getVectorElementCount();
17484 unsigned SizeRatio = ExTy.getSizeInBits() / TrTy.getSizeInBits();
17485 auto NewEltCnt = EltCnt * SizeRatio;
17486
17487 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt);
17488 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
17489
17490 SDValue EltNo = Src->getOperand(1);
17491 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
17492 int Elt = EltNo->getAsZExtVal();
17493 int Index = isLE ? (Elt * SizeRatio + EltOffset)
17494 : (Elt * SizeRatio + (SizeRatio - 1) - EltOffset);
17495 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
17496 DAG.getBitcast(NVT, Src.getOperand(0)),
17497 DAG.getVectorIdxConstant(Index, DL));
17498 }
17499 }
17500 }
17501
17502 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
17503 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse() &&
17504 TLI.isTruncateFree(SrcVT, VT)) {
17505 if (!LegalOperations ||
17506 (TLI.isOperationLegal(ISD::SELECT, SrcVT) &&
17507 TLI.isNarrowingProfitable(N0.getNode(), SrcVT, VT))) {
17508 SDLoc SL(N0);
17509 SDValue Cond = N0.getOperand(0);
17510 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
17511 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
17512 return DAG.getNode(ISD::SELECT, DL, VT, Cond, TruncOp0, TruncOp1);
17513 }
17514 }
17515
17516 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
17517 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
17518 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
17519 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
17520 SDValue Amt = N0.getOperand(1);
17521 KnownBits Known = DAG.computeKnownBits(Amt);
17522 unsigned Size = VT.getScalarSizeInBits();
17523 if (Known.countMaxActiveBits() <= Log2_32(Size)) {
17524 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
17525 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17526 if (AmtVT != Amt.getValueType()) {
17527 Amt = DAG.getZExtOrTrunc(Amt, DL, AmtVT);
17528 AddToWorklist(Amt.getNode());
17529 }
17530 return DAG.getNode(ISD::SHL, DL, VT, Trunc, Amt);
17531 }
17532 }
17533
17534 if (SDValue V = foldSubToUSubSat(VT, N0.getNode(), DL))
17535 return V;
17536
17537 if (SDValue ABD = foldABSToABD(N, DL))
17538 return ABD;
17539
17540 // Attempt to pre-truncate BUILD_VECTOR sources.
17541 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
17542 N0.hasOneUse() &&
17543 // Avoid creating illegal types if running after type legalizer.
17544 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
17545 if (TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()))
17546 return DAG.UnrollVectorOp(N);
17547
17548 // trunc(build_vector(ext(x), ext(x)) -> build_vector(x,x)
17549 if (SDValue SplatVal = DAG.getSplatValue(N0)) {
17550 if (ISD::isExtOpcode(SplatVal.getOpcode()) &&
17551 SrcVT.getScalarType() == SplatVal.getValueType())
17552 return DAG.UnrollVectorOp(N);
17553 }
17554 }
17555
17556 // trunc (splat_vector x) -> splat_vector (trunc x)
17557 if (N0.getOpcode() == ISD::SPLAT_VECTOR &&
17558 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType())) &&
17559 (!LegalOperations || TLI.isOperationLegal(ISD::SPLAT_VECTOR, VT))) {
17560 EVT SVT = VT.getScalarType();
17561 return DAG.getSplatVector(
17562 VT, DL, DAG.getNode(ISD::TRUNCATE, DL, SVT, N0->getOperand(0)));
17563 }
17564
17565 // Fold a series of buildvector, bitcast, and truncate if possible.
17566 // For example fold
17567 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
17568 // (2xi32 (buildvector x, y)).
17569 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
17570 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
17572 N0.getOperand(0).hasOneUse()) {
17573 SDValue BuildVect = N0.getOperand(0);
17574 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
17575 EVT TruncVecEltTy = VT.getVectorElementType();
17576
17577 // Check that the element types match.
17578 if (BuildVectEltTy == TruncVecEltTy) {
17579 // Now we only need to compute the offset of the truncated elements.
17580 unsigned BuildVecNumElts = BuildVect.getNumOperands();
17581 unsigned TruncVecNumElts = VT.getVectorNumElements();
17582 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
17583 unsigned FirstElt = isLE ? 0 : (TruncEltOffset - 1);
17584
17585 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
17586 "Invalid number of elements");
17587
17589 for (unsigned i = FirstElt, e = BuildVecNumElts; i < e;
17590 i += TruncEltOffset)
17591 Opnds.push_back(BuildVect.getOperand(i));
17592
17593 return DAG.getBuildVector(VT, DL, Opnds);
17594 }
17595 }
17596
17597 // fold (truncate (load x)) -> (smaller load x)
17598 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
17599 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
17600 if (SDValue Reduced = reduceLoadWidth(N))
17601 return Reduced;
17602
17603 // Handle the case where the truncated result is at least as wide as the
17604 // loaded type.
17605 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
17606 auto *LN0 = cast<LoadSDNode>(N0);
17607 if (LN0->isSimple() && LN0->getMemoryVT().bitsLE(VT)) {
17608 SDValue NewLoad = DAG.getExtLoad(
17609 LN0->getExtensionType(), SDLoc(LN0), VT, LN0->getChain(),
17610 LN0->getBasePtr(), LN0->getMemoryVT(), LN0->getMemOperand());
17611 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
17612 return NewLoad;
17613 }
17614 }
17615 }
17616
17617 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
17618 // where ... are all 'undef'.
17619 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
17621 SDValue V;
17622 unsigned Idx = 0;
17623 unsigned NumDefs = 0;
17624
17625 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
17626 SDValue X = N0.getOperand(i);
17627 if (!X.isUndef()) {
17628 V = X;
17629 Idx = i;
17630 NumDefs++;
17631 }
17632 // Stop if more than one members are non-undef.
17633 if (NumDefs > 1)
17634 break;
17635
17638 X.getValueType().getVectorElementCount()));
17639 }
17640
17641 if (NumDefs == 0)
17642 return DAG.getUNDEF(VT);
17643
17644 if (NumDefs == 1) {
17645 assert(V.getNode() && "The single defined operand is empty!");
17647 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
17648 if (i != Idx) {
17649 Opnds.push_back(DAG.getUNDEF(VTs[i]));
17650 continue;
17651 }
17652 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
17653 AddToWorklist(NV.getNode());
17654 Opnds.push_back(NV);
17655 }
17656 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
17657 }
17658 }
17659
17660 // Fold truncate of a bitcast of a vector to an extract of the low vector
17661 // element.
17662 //
17663 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
17664 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
17665 SDValue VecSrc = N0.getOperand(0);
17666 EVT VecSrcVT = VecSrc.getValueType();
17667 if (VecSrcVT.isVectorOf(VT) &&
17668 (!LegalOperations ||
17669 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
17670 unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
17671 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VecSrc,
17672 DAG.getVectorIdxConstant(Idx, DL));
17673 }
17674 }
17675
17676 // Simplify the operands using demanded-bits information.
17678 return SDValue(N, 0);
17679
17680 // fold (truncate (extract_subvector(ext x))) ->
17681 // (extract_subvector x)
17682 // TODO: This can be generalized to cover cases where the truncate and extract
17683 // do not fully cancel each other out.
17684 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
17685 SDValue N00 = N0.getOperand(0);
17686 if (N00.getOpcode() == ISD::SIGN_EXTEND ||
17687 N00.getOpcode() == ISD::ZERO_EXTEND ||
17688 N00.getOpcode() == ISD::ANY_EXTEND) {
17689 if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
17691 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
17692 N00.getOperand(0), N0.getOperand(1));
17693 }
17694 }
17695
17696 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
17697 return NewVSel;
17698
17699 // Narrow a suitable binary operation with a non-opaque constant operand by
17700 // moving it ahead of the truncate. This is limited to pre-legalization
17701 // because targets may prefer a wider type during later combines and invert
17702 // this transform.
17703 switch (N0.getOpcode()) {
17704 case ISD::ADD:
17705 case ISD::SUB:
17706 case ISD::MUL:
17707 case ISD::AND:
17708 case ISD::OR:
17709 case ISD::XOR:
17710 if (!LegalOperations && N0.hasOneUse() &&
17711 (N0.getOperand(0) == N0.getOperand(1) ||
17713 isConstantOrConstantVector(N0.getOperand(1), true))) {
17714 // TODO: We already restricted this to pre-legalization, but for vectors
17715 // we are extra cautious to not create an unsupported operation.
17716 // Target-specific changes are likely needed to avoid regressions here.
17717 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
17718 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17719 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
17720 SDNodeFlags Flags;
17721 // Propagate nuw for sub.
17722 if (N0->getOpcode() == ISD::SUB && N0->getFlags().hasNoUnsignedWrap() &&
17724 N0->getOperand(0),
17726 VT.getScalarSizeInBits())))
17727 Flags.setNoUnsignedWrap(true);
17728 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR, Flags);
17729 }
17730 }
17731 break;
17732 case ISD::ADDE:
17733 case ISD::UADDO_CARRY:
17734 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
17735 // (trunc uaddo_carry(X, Y, Carry)) ->
17736 // (uaddo_carry trunc(X), trunc(Y), Carry)
17737 // When the adde's carry is not used.
17738 // We only do for uaddo_carry before legalize operation
17739 if (((!LegalOperations && N0.getOpcode() == ISD::UADDO_CARRY) ||
17740 TLI.isOperationLegal(N0.getOpcode(), VT)) &&
17741 N0.hasOneUse() && !N0->hasAnyUseOfValue(1)) {
17742 SDValue X = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
17743 SDValue Y = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
17744 SDVTList VTs = DAG.getVTList(VT, N0->getValueType(1));
17745 return DAG.getNode(N0.getOpcode(), DL, VTs, X, Y, N0.getOperand(2));
17746 }
17747 break;
17748 case ISD::USUBSAT:
17749 // Truncate the USUBSAT only if LHS is a known zero-extension, its not
17750 // enough to know that the upper bits are zero we must ensure that we don't
17751 // introduce an extra truncate.
17752 if (!LegalOperations && N0.hasOneUse() &&
17755 VT.getScalarSizeInBits() &&
17756 hasOperation(N0.getOpcode(), VT)) {
17757 return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1),
17758 DAG, DL);
17759 }
17760 break;
17761 case ISD::AVGCEILS:
17762 case ISD::AVGCEILU:
17763 // trunc (avgceilu (sext (x), sext (y))) -> avgceils(x, y)
17764 // trunc (avgceils (zext (x), zext (y))) -> avgceilu(x, y)
17765 if (N0.hasOneUse()) {
17766 SDValue Op0 = N0.getOperand(0);
17767 SDValue Op1 = N0.getOperand(1);
17768 if (N0.getOpcode() == ISD::AVGCEILU) {
17770 Op0.getOpcode() == ISD::SIGN_EXTEND &&
17771 Op1.getOpcode() == ISD::SIGN_EXTEND &&
17772 Op0.getOperand(0).getValueType() == VT &&
17773 Op1.getOperand(0).getValueType() == VT)
17774 return DAG.getNode(ISD::AVGCEILS, DL, VT, Op0.getOperand(0),
17775 Op1.getOperand(0));
17776 } else {
17778 Op0.getOpcode() == ISD::ZERO_EXTEND &&
17779 Op1.getOpcode() == ISD::ZERO_EXTEND &&
17780 Op0.getOperand(0).getValueType() == VT &&
17781 Op1.getOperand(0).getValueType() == VT)
17782 return DAG.getNode(ISD::AVGCEILU, DL, VT, Op0.getOperand(0),
17783 Op1.getOperand(0));
17784 }
17785 }
17786 [[fallthrough]];
17787 case ISD::AVGFLOORS:
17788 case ISD::AVGFLOORU:
17789 case ISD::ABDS:
17790 case ISD::ABDU:
17791 // (trunc (avg a, b)) -> (avg (trunc a), (trunc b))
17792 // (trunc (abdu/abds a, b)) -> (abdu/abds (trunc a), (trunc b))
17793 if (!LegalOperations && N0.hasOneUse() &&
17794 TLI.isOperationLegal(N0.getOpcode(), VT)) {
17795 EVT TruncVT = VT;
17796 unsigned SrcBits = SrcVT.getScalarSizeInBits();
17797 unsigned TruncBits = TruncVT.getScalarSizeInBits();
17798
17799 SDValue A = N0.getOperand(0);
17800 SDValue B = N0.getOperand(1);
17801 bool CanFold = false;
17802
17803 if (N0.getOpcode() == ISD::AVGFLOORU || N0.getOpcode() == ISD::AVGCEILU ||
17804 N0.getOpcode() == ISD::ABDU) {
17805 APInt UpperBits = APInt::getBitsSetFrom(SrcBits, TruncBits);
17806 CanFold = DAG.MaskedValueIsZero(B, UpperBits) &&
17807 DAG.MaskedValueIsZero(A, UpperBits);
17808 } else {
17809 unsigned NeededBits = SrcBits - TruncBits;
17810 CanFold = DAG.ComputeNumSignBits(B) > NeededBits &&
17811 DAG.ComputeNumSignBits(A) > NeededBits;
17812 }
17813
17814 if (CanFold) {
17815 SDValue NewA = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, A);
17816 SDValue NewB = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, B);
17817 return DAG.getNode(N0.getOpcode(), DL, TruncVT, NewA, NewB);
17818 }
17819 }
17820 break;
17821 }
17822
17823 return SDValue();
17824}
17825
17826static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
17827 SDValue Elt = N->getOperand(i);
17828 if (Elt.getOpcode() != ISD::MERGE_VALUES)
17829 return Elt.getNode();
17830 return Elt.getOperand(Elt.getResNo()).getNode();
17831}
17832
17833/// build_pair (load, load) -> load
17834/// if load locations are consecutive.
17835SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
17836 assert(N->getOpcode() == ISD::BUILD_PAIR);
17837
17838 auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
17839 auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
17840
17841 // A BUILD_PAIR is always having the least significant part in elt 0 and the
17842 // most significant part in elt 1. So when combining into one large load, we
17843 // need to consider the endianness.
17844 if (DAG.getDataLayout().isBigEndian())
17845 std::swap(LD1, LD2);
17846
17847 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) ||
17848 !LD1->hasOneUse() || !LD2->hasOneUse() ||
17849 LD1->getAddressSpace() != LD2->getAddressSpace())
17850 return SDValue();
17851
17852 unsigned LD1Fast = 0;
17853 EVT LD1VT = LD1->getValueType(0);
17854 unsigned LD1Bytes = LD1VT.getStoreSize();
17855 if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
17856 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) &&
17857 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
17858 *LD1->getMemOperand(), &LD1Fast) && LD1Fast)
17859 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
17860 LD1->getPointerInfo(), LD1->getAlign());
17861
17862 return SDValue();
17863}
17864
17865static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
17866 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
17867 // and Lo parts; on big-endian machines it doesn't.
17868 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
17869}
17870
17871SDValue DAGCombiner::foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
17872 const TargetLowering &TLI) {
17873 // If this is not a bitcast to an FP type or if the target doesn't have
17874 // IEEE754-compliant FP logic, we're done.
17875 EVT VT = N->getValueType(0);
17876 SDValue N0 = N->getOperand(0);
17877 EVT SourceVT = N0.getValueType();
17878
17879 if (!VT.isFloatingPoint())
17880 return SDValue();
17881
17882 // TODO: Handle cases where the integer constant is a different scalar
17883 // bitwidth to the FP.
17884 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
17885 return SDValue();
17886
17887 unsigned FPOpcode;
17888 APInt SignMask;
17889 switch (N0.getOpcode()) {
17890 case ISD::AND:
17891 FPOpcode = ISD::FABS;
17892 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
17893 break;
17894 case ISD::XOR:
17895 FPOpcode = ISD::FNEG;
17896 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
17897 break;
17898 case ISD::OR:
17899 FPOpcode = ISD::FABS;
17900 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
17901 break;
17902 default:
17903 return SDValue();
17904 }
17905
17906 if (LegalOperations && !TLI.isOperationLegal(FPOpcode, VT))
17907 return SDValue();
17908
17909 // This needs to be the inverse of logic in foldSignChangeInBitcast.
17910 // FIXME: I don't think looking for bitcast intrinsically makes sense, but
17911 // removing this would require more changes.
17912 auto IsBitCastOrFree = [&TLI, FPOpcode](SDValue Op, EVT VT) {
17913 if (sd_match(Op, m_BitCast(m_SpecificVT(VT))))
17914 return true;
17915
17916 return FPOpcode == ISD::FABS ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT);
17917 };
17918
17919 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
17920 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
17921 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
17922 // fneg (fabs X)
17923 SDValue LogicOp0 = N0.getOperand(0);
17924 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
17925 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
17926 IsBitCastOrFree(LogicOp0, VT)) {
17927 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, LogicOp0);
17928 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, CastOp0);
17929 NumFPLogicOpsConv++;
17930 if (N0.getOpcode() == ISD::OR)
17931 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
17932 return FPOp;
17933 }
17934
17935 return SDValue();
17936}
17937
17938SDValue DAGCombiner::visitBITCAST(SDNode *N) {
17939 SDValue N0 = N->getOperand(0);
17940 EVT VT = N->getValueType(0);
17941
17942 if (N0.isUndef())
17943 return DAG.getUNDEF(VT);
17944
17945 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
17946 // Only do this before legalize types, unless both types are integer and the
17947 // scalar type is legal. Only do this before legalize ops, since the target
17948 // maybe depending on the bitcast.
17949 // First check to see if this is all constant.
17950 // TODO: Support FP bitcasts after legalize types.
17951 if (VT.isVector() &&
17952 (!LegalTypes ||
17953 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
17954 TLI.isTypeLegal(VT.getVectorElementType()))) &&
17955 N0.getOpcode() == ISD::BUILD_VECTOR && N0->hasOneUse() &&
17956 cast<BuildVectorSDNode>(N0)->isConstant())
17957 return DAG.FoldConstantBuildVector(cast<BuildVectorSDNode>(N0), SDLoc(N),
17959
17960 // If the input is a constant, let getNode fold it.
17961 if (isIntOrFPConstant(N0)) {
17962 // If we can't allow illegal operations, we need to check that this is just
17963 // a fp -> int or int -> conversion and that the resulting operation will
17964 // be legal.
17965 if (!LegalOperations ||
17966 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
17968 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
17969 TLI.isOperationLegal(ISD::Constant, VT))) {
17970 SDValue C = DAG.getBitcast(VT, N0);
17971 if (C.getNode() != N)
17972 return C;
17973 }
17974 }
17975
17976 // (conv (conv x, t1), t2) -> (conv x, t2)
17977 if (N0.getOpcode() == ISD::BITCAST)
17978 return DAG.getBitcast(VT, N0.getOperand(0));
17979
17980 // fold (conv (logicop (conv x), (c))) -> (logicop x, (conv c))
17981 // iff the current bitwise logicop type isn't legal
17982 if (ISD::isBitwiseLogicOp(N0.getOpcode()) && VT.isInteger() &&
17983 !TLI.isTypeLegal(N0.getOperand(0).getValueType())) {
17984 auto IsFreeBitcast = [VT](SDValue V) {
17985 return (V.getOpcode() == ISD::BITCAST &&
17986 V.getOperand(0).getValueType() == VT) ||
17988 V->hasOneUse());
17989 };
17990 if (IsFreeBitcast(N0.getOperand(0)) && IsFreeBitcast(N0.getOperand(1)))
17991 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
17992 DAG.getBitcast(VT, N0.getOperand(0)),
17993 DAG.getBitcast(VT, N0.getOperand(1)));
17994 }
17995
17996 // fold (conv (load x)) -> (load (conv*)x)
17997 // fold (conv (freeze (load x))) -> (freeze (load (conv*)x))
17998 // If the resultant load doesn't need a higher alignment than the original!
17999 auto CastLoad = [this, &VT](SDValue N0, const SDLoc &DL) {
18000 // Peek through scalar_to_vector if the scalar is same size as VT - often a
18001 // leftover from legalization.
18002 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && N0.hasOneUse() &&
18004 N0 = N0.getOperand(0);
18005 if (N0.getOpcode() == ISD::AssertNoFPClass)
18006 N0 = N0.getOperand(0);
18007 if (!ISD::isNormalLoad(N0.getNode()) || !N0.hasOneUse())
18008 return SDValue();
18009
18010 // Do not remove the cast if the types differ in endian layout.
18013 return SDValue();
18014
18015 // If the load is volatile, we only want to change the load type if the
18016 // resulting load is legal. Otherwise we might increase the number of
18017 // memory accesses. We don't care if the original type was legal or not
18018 // as we assume software couldn't rely on the number of accesses of an
18019 // illegal type.
18020 auto *LN0 = cast<LoadSDNode>(N0);
18021 if ((LegalOperations || !LN0->isSimple()) &&
18022 !TLI.isOperationLegal(ISD::LOAD, VT))
18023 return SDValue();
18024
18025 if (!TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
18026 *LN0->getMemOperand()))
18027 return SDValue();
18028
18029 // If the range metadata type does not match the new memory
18030 // operation type, remove the range metadata.
18031 if (const MDNode *MD = LN0->getRanges()) {
18032 ConstantInt *Lower = mdconst::extract<ConstantInt>(MD->getOperand(0));
18033 if (Lower->getBitWidth() != VT.getScalarSizeInBits() || !VT.isInteger()) {
18034 LN0->getMemOperand()->clearRanges();
18035 }
18036 }
18037 SDValue Load = DAG.getLoad(VT, DL, LN0->getChain(), LN0->getBasePtr(),
18038 LN0->getMemOperand());
18039 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
18040 return Load;
18041 };
18042
18043 if (SDValue NewLd = CastLoad(N0, SDLoc(N)))
18044 return NewLd;
18045
18046 if (N0.getOpcode() == ISD::FREEZE && N0.hasOneUse())
18047 if (SDValue NewLd = CastLoad(N0.getOperand(0), SDLoc(N)))
18048 return DAG.getFreeze(NewLd);
18049
18050 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
18051 return V;
18052
18053 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
18054 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
18055 //
18056 // For ppc_fp128:
18057 // fold (bitcast (fneg x)) ->
18058 // flipbit = signbit
18059 // (xor (bitcast x) (build_pair flipbit, flipbit))
18060 //
18061 // fold (bitcast (fabs x)) ->
18062 // flipbit = (and (extract_element (bitcast x), 0), signbit)
18063 // (xor (bitcast x) (build_pair flipbit, flipbit))
18064 // This often reduces constant pool loads.
18065 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
18066 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
18067 N0->hasOneUse() && VT.isInteger() && !VT.isVector() &&
18068 !N0.getValueType().isVector()) {
18069 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
18070 AddToWorklist(NewConv.getNode());
18071
18072 SDLoc DL(N);
18073 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
18074 assert(VT.getSizeInBits() == 128);
18075 SDValue SignBit = DAG.getConstant(
18076 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
18077 SDValue FlipBit;
18078 if (N0.getOpcode() == ISD::FNEG) {
18079 FlipBit = SignBit;
18080 AddToWorklist(FlipBit.getNode());
18081 } else {
18082 assert(N0.getOpcode() == ISD::FABS);
18083 SDValue Hi =
18084 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
18086 SDLoc(NewConv)));
18087 AddToWorklist(Hi.getNode());
18088 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
18089 AddToWorklist(FlipBit.getNode());
18090 }
18091 SDValue FlipBits =
18092 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
18093 AddToWorklist(FlipBits.getNode());
18094 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
18095 }
18096 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
18097 if (N0.getOpcode() == ISD::FNEG)
18098 return DAG.getNode(ISD::XOR, DL, VT,
18099 NewConv, DAG.getConstant(SignBit, DL, VT));
18100 assert(N0.getOpcode() == ISD::FABS);
18101 return DAG.getNode(ISD::AND, DL, VT,
18102 NewConv, DAG.getConstant(~SignBit, DL, VT));
18103 }
18104
18105 // fold (bitconvert (fcopysign cst, x)) ->
18106 // (or (and (bitconvert x), sign), (and cst, (not sign)))
18107 // Note that we don't handle (copysign x, cst) because this can always be
18108 // folded to an fneg or fabs.
18109 //
18110 // For ppc_fp128:
18111 // fold (bitcast (fcopysign cst, x)) ->
18112 // flipbit = (and (extract_element
18113 // (xor (bitcast cst), (bitcast x)), 0),
18114 // signbit)
18115 // (xor (bitcast cst) (build_pair flipbit, flipbit))
18116 if (N0.getOpcode() == ISD::FCOPYSIGN && N0->hasOneUse() &&
18118 !VT.isVector()) {
18119 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
18120 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
18121 if (isTypeLegal(IntXVT)) {
18122 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
18123 AddToWorklist(X.getNode());
18124
18125 // If X has a different width than the result/lhs, sext it or truncate it.
18126 unsigned VTWidth = VT.getSizeInBits();
18127 if (OrigXWidth < VTWidth) {
18128 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
18129 AddToWorklist(X.getNode());
18130 } else if (OrigXWidth > VTWidth) {
18131 // To get the sign bit in the right place, we have to shift it right
18132 // before truncating.
18133 SDLoc DL(X);
18134 X = DAG.getNode(ISD::SRL, DL,
18135 X.getValueType(), X,
18136 DAG.getConstant(OrigXWidth-VTWidth, DL,
18137 X.getValueType()));
18138 AddToWorklist(X.getNode());
18139 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
18140 AddToWorklist(X.getNode());
18141 }
18142
18143 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
18144 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
18145 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
18146 AddToWorklist(Cst.getNode());
18147 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
18148 AddToWorklist(X.getNode());
18149 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
18150 AddToWorklist(XorResult.getNode());
18151 SDValue XorResult64 = DAG.getNode(
18152 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
18154 SDLoc(XorResult)));
18155 AddToWorklist(XorResult64.getNode());
18156 SDValue FlipBit =
18157 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
18158 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
18159 AddToWorklist(FlipBit.getNode());
18160 SDValue FlipBits =
18161 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
18162 AddToWorklist(FlipBits.getNode());
18163 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
18164 }
18165 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
18166 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
18167 X, DAG.getConstant(SignBit, SDLoc(X), VT));
18168 AddToWorklist(X.getNode());
18169
18170 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
18171 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
18172 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
18173 AddToWorklist(Cst.getNode());
18174
18175 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
18176 }
18177 }
18178
18179 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
18180 if (N0.getOpcode() == ISD::BUILD_PAIR)
18181 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
18182 return CombineLD;
18183
18184 // int_vt (bitcast (vec_vt (scalar_to_vector elt_vt:x)))
18185 // => int_vt (any_extend elt_vt:x)
18186 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isScalarInteger()) {
18187 SDValue SrcScalar = N0.getOperand(0);
18188 if (SrcScalar.getValueType().isScalarInteger())
18189 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SrcScalar);
18190 }
18191
18192 // Remove double bitcasts from shuffles - this is often a legacy of
18193 // XformToShuffleWithZero being used to combine bitmaskings (of
18194 // float vectors bitcast to integer vectors) into shuffles.
18195 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
18196 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
18197 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
18200 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
18201
18202 // If operands are a bitcast, peek through if it casts the original VT.
18203 // If operands are a constant, just bitcast back to original VT.
18204 auto PeekThroughBitcast = [&](SDValue Op) {
18205 if (Op.getOpcode() == ISD::BITCAST &&
18206 Op.getOperand(0).getValueType() == VT)
18207 return SDValue(Op.getOperand(0));
18208 if (Op.isUndef() || isAnyConstantBuildVector(Op))
18209 return DAG.getBitcast(VT, Op);
18210 return SDValue();
18211 };
18212
18213 // FIXME: If either input vector is bitcast, try to convert the shuffle to
18214 // the result type of this bitcast. This would eliminate at least one
18215 // bitcast. See the transform in InstCombine.
18216 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
18217 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
18218 if (!(SV0 && SV1))
18219 return SDValue();
18220
18221 int MaskScale =
18223 SmallVector<int, 8> NewMask;
18224 for (int M : SVN->getMask())
18225 for (int i = 0; i != MaskScale; ++i)
18226 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
18227
18228 SDValue LegalShuffle =
18229 TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
18230 if (LegalShuffle)
18231 return LegalShuffle;
18232 }
18233
18234 return SDValue();
18235}
18236
18237SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
18238 EVT VT = N->getValueType(0);
18239 return CombineConsecutiveLoads(N, VT);
18240}
18241
18242SDValue DAGCombiner::visitFREEZE(SDNode *N) {
18243 SDValue N0 = N->getOperand(0);
18244
18246 return N0;
18247
18248 // If we have frozen and unfrozen users of N0, update so everything uses N.
18249 if (!N0.isUndef() && !N0.hasOneUse()) {
18250 SDValue FrozenN0(N, 0);
18251 // Unfreeze all (possibly nested) uses of N to avoid double deleting N from
18252 // the CSE map.
18253 while (!N->use_empty())
18254 DAG.ReplaceAllUsesOfValueWith(FrozenN0, N0);
18255 DAG.ReplaceAllUsesOfValueWith(N0, FrozenN0);
18256 // ReplaceAllUsesOfValueWith will have also updated the use in N, thus
18257 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18258 assert(N->getOperand(0) == FrozenN0 && "Expected cycle in DAG");
18259 DAG.UpdateNodeOperands(N, N0);
18260 // Revisit the node.
18261 AddToWorklist(N);
18262 return FrozenN0;
18263 }
18264
18265 // We currently avoid folding freeze over SRA/SRL, due to the problems seen
18266 // with (freeze (assert ext)) blocking simplifications of SRA/SRL. See for
18267 // example https://reviews.llvm.org/D136529#4120959.
18268 if (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)
18269 return SDValue();
18270
18271 // Fold freeze(op(x, ...)) -> op(freeze(x), ...).
18272 // Try to push freeze through instructions that propagate but don't produce
18273 // poison as far as possible. If an operand of freeze follows three
18274 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
18275 // guaranteed-non-poison operands (or is a BUILD_VECTOR or similar) then push
18276 // the freeze through to the operands that are not guaranteed non-poison.
18277 // NOTE: we will strip poison-generating flags, so ignore them here.
18279 /*ConsiderFlags*/ false) ||
18280 N0->getNumValues() != 1 || !N0->hasOneUse())
18281 return SDValue();
18282
18283 // TOOD: we should always allow multiple operands, however this increases the
18284 // likelihood of infinite loops due to the ReplaceAllUsesOfValueWith call
18285 // below causing later nodes that share frozen operands to fold again and no
18286 // longer being able to confirm other operands are not poison due to recursion
18287 // depth limits on isGuaranteedNotToBeUndefOrPoison.
18288 bool AllowMultipleMaybePoisonOperands =
18289 N0.getOpcode() == ISD::SELECT_CC || N0.getOpcode() == ISD::SETCC ||
18290 N0.getOpcode() == ISD::BUILD_VECTOR ||
18292 N0.getOpcode() == ISD::BUILD_PAIR ||
18295
18296 // Avoid turning a BUILD_VECTOR that can be recognized as "all zeros", "all
18297 // ones" or "constant" into something that depends on FrozenUndef. We can
18298 // instead pick undef values to keep those properties, while at the same time
18299 // folding away the freeze.
18300 // If we implement a more general solution for folding away freeze(undef) in
18301 // the future, then this special handling can be removed.
18302 if (N0.getOpcode() == ISD::BUILD_VECTOR) {
18303 SDLoc DL(N0);
18304 EVT VT = N0.getValueType();
18306 return DAG.getAllOnesConstant(DL, VT);
18309 for (const SDValue &Op : N0->op_values())
18310 NewVecC.push_back(
18311 Op.isUndef() ? DAG.getConstant(0, DL, Op.getValueType()) : Op);
18312 return DAG.getBuildVector(VT, DL, NewVecC);
18313 }
18314 }
18315
18316 SmallSet<SDValue, 8> MaybePoisonOperands;
18317 SmallVector<unsigned, 8> MaybePoisonOperandNumbers;
18318 for (auto [OpNo, Op] : enumerate(N0->ops())) {
18321 continue;
18322 bool HadMaybePoisonOperands = !MaybePoisonOperands.empty();
18323 bool IsNewMaybePoisonOperand = MaybePoisonOperands.insert(Op).second;
18324 if (IsNewMaybePoisonOperand)
18325 MaybePoisonOperandNumbers.push_back(OpNo);
18326 if (!HadMaybePoisonOperands)
18327 continue;
18328 if (IsNewMaybePoisonOperand && !AllowMultipleMaybePoisonOperands) {
18329 // Multiple maybe-poison ops when not allowed - bail out.
18330 return SDValue();
18331 }
18332 }
18333 // NOTE: the whole op may be not guaranteed to not be undef or poison because
18334 // it could create undef or poison due to it's poison-generating flags.
18335 // So not finding any maybe-poison operands is fine.
18336
18337 for (unsigned OpNo : MaybePoisonOperandNumbers) {
18338 // N0 can mutate during iteration, so make sure to refetch the maybe poison
18339 // operands via the operand numbers. The typical scenario is that we have
18340 // something like this
18341 // t262: i32 = freeze t181
18342 // t150: i32 = ctlz_zero_poison t262
18343 // t184: i32 = ctlz_zero_poison t181
18344 // t268: i32 = select_cc t181, Constant:i32<0>, t184, t186, setne:ch
18345 // When freezing the t181 operand we get t262 back, and then the
18346 // ReplaceAllUsesOfValueWith call will not only replace t181 by t262, but
18347 // also recursively replace t184 by t150.
18348 SDValue MaybePoisonOperand = N->getOperand(0).getOperand(OpNo);
18349 // Don't replace every single UNDEF everywhere with frozen UNDEF, though.
18350 if (MaybePoisonOperand.isUndef())
18351 continue;
18352 // First, freeze each offending operand.
18353 SDValue FrozenMaybePoisonOperand = DAG.getFreeze(MaybePoisonOperand);
18354 // Then, change all other uses of unfrozen operand to use frozen operand.
18355 DAG.ReplaceAllUsesOfValueWith(MaybePoisonOperand, FrozenMaybePoisonOperand);
18356 if (FrozenMaybePoisonOperand.getOpcode() == ISD::FREEZE &&
18357 FrozenMaybePoisonOperand.getOperand(0) == FrozenMaybePoisonOperand) {
18358 // But, that also updated the use in the freeze we just created, thus
18359 // creating a cycle in a DAG. Let's undo that by mutating the freeze.
18360 DAG.UpdateNodeOperands(FrozenMaybePoisonOperand.getNode(),
18361 MaybePoisonOperand);
18362 }
18363
18364 // This node has been merged with another.
18365 if (N->getOpcode() == ISD::DELETED_NODE)
18366 return SDValue(N, 0);
18367 }
18368
18369 assert(N->getOpcode() != ISD::DELETED_NODE && "Node was deleted!");
18370
18371 // The whole node may have been updated, so the value we were holding
18372 // may no longer be valid. Re-fetch the operand we're `freeze`ing.
18373 N0 = N->getOperand(0);
18374
18375 // Finally, recreate the node, it's operands were updated to use
18376 // frozen operands, so we just need to use it's "original" operands.
18378 // TODO: ISD::UNDEF and ISD::POISON should get separate handling, but best
18379 // leave for a future patch.
18380 for (SDValue &Op : Ops) {
18381 if (Op.isUndef())
18382 Op = DAG.getFreeze(Op);
18383 }
18384
18385 SDLoc DL(N0);
18386
18387 // Special case handling for ShuffleVectorSDNode nodes.
18388 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N0))
18389 return DAG.getVectorShuffle(N0.getValueType(), DL, Ops[0], Ops[1],
18390 SVN->getMask());
18391
18392 // NOTE: this strips poison generating flags.
18393 // Folding freeze(op(x, ...)) -> op(freeze(x), ...) does not require nnan,
18394 // ninf, nsz, or fast.
18395 // However, contract, reassoc, afn, and arcp should be preserved,
18396 // as these fast-math flags do not introduce poison values.
18397 SDNodeFlags SrcFlags = N0->getFlags();
18398 SDNodeFlags SafeFlags;
18399 SafeFlags.setAllowContract(SrcFlags.hasAllowContract());
18400 SafeFlags.setAllowReassociation(SrcFlags.hasAllowReassociation());
18401 SafeFlags.setApproximateFuncs(SrcFlags.hasApproximateFuncs());
18402 SafeFlags.setAllowReciprocal(SrcFlags.hasAllowReciprocal());
18403 return DAG.getNode(N0.getOpcode(), DL, N0->getVTList(), Ops, SafeFlags);
18404}
18405
18406// Returns true if floating point contraction is allowed on the FMUL-SDValue
18407// `N`
18409 assert(N.getOpcode() == ISD::FMUL);
18410
18411 return Options.AllowFPOpFusion == FPOpFusion::Fast ||
18412 N->getFlags().hasAllowContract();
18413}
18414
18415/// Try to perform FMA combining on a given FADD node.
18416SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
18417 SDValue N0 = N->getOperand(0);
18418 SDValue N1 = N->getOperand(1);
18419 EVT VT = N->getValueType(0);
18420 SDLoc SL(N);
18421 const TargetOptions &Options = DAG.getTarget().Options;
18422
18423 // Floating-point multiply-add with intermediate rounding.
18424 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18425
18426 // Floating-point multiply-add without intermediate rounding.
18427 bool HasFMA =
18428 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18430
18431 // No valid opcode, do not combine.
18432 if (!HasFMAD && !HasFMA)
18433 return SDValue();
18434
18435 bool AllowFusionGlobally =
18436 Options.AllowFPOpFusion == FPOpFusion::Fast || HasFMAD;
18437 // If the addition is not contractable, do not combine.
18438 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18439 return SDValue();
18440
18441 // Folding fadd (fmul x, y), (fmul x, y) -> fma x, y, (fmul x, y) is never
18442 // beneficial. It does not reduce latency. It increases register pressure. It
18443 // replaces an fadd with an fma which is a more complex instruction, so is
18444 // likely to have a larger encoding, use more functional units, etc.
18445 if (N0 == N1)
18446 return SDValue();
18447
18448 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18449 return SDValue();
18450
18451 // Always prefer FMAD to FMA for precision.
18452 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18454
18455 auto isFusedOp = [&](SDValue N) {
18456 unsigned Opcode = N.getOpcode();
18457 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
18458 };
18459
18460 // Is the node an FMUL and contractable either due to global flags or
18461 // SDNodeFlags.
18462 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18463 if (N.getOpcode() != ISD::FMUL)
18464 return false;
18465 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18466 };
18467 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
18468 // prefer to fold the multiply with fewer uses.
18470 if (N0->use_size() > N1->use_size())
18471 std::swap(N0, N1);
18472 }
18473
18474 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
18475 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
18476 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
18477 N0.getOperand(1), N1);
18478 }
18479
18480 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
18481 // Note: Commutes FADD operands.
18482 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
18483 return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0),
18484 N1.getOperand(1), N0);
18485 }
18486
18487 // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E)
18488 // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E)
18489 // This also works with nested fma instructions:
18490 // fadd (fma A, B, (fma (C, D, (fmul (E, F))))), G -->
18491 // fma A, B, (fma C, D, fma (E, F, G))
18492 // fadd (G, (fma A, B, (fma (C, D, (fmul (E, F)))))) -->
18493 // fma A, B, (fma C, D, fma (E, F, G)).
18494 // This requires reassociation because it changes the order of operations.
18495 bool CanReassociate = N->getFlags().hasAllowReassociation();
18496 if (CanReassociate) {
18497 SDValue FMA, E;
18498 if (isFusedOp(N0) && N0.hasOneUse()) {
18499 FMA = N0;
18500 E = N1;
18501 } else if (isFusedOp(N1) && N1.hasOneUse()) {
18502 FMA = N1;
18503 E = N0;
18504 }
18505
18506 SDValue TmpFMA = FMA;
18507 while (E && isFusedOp(TmpFMA) && TmpFMA.hasOneUse()) {
18508 SDValue FMul = TmpFMA->getOperand(2);
18509 if (FMul.getOpcode() == ISD::FMUL && FMul.hasOneUse()) {
18510 SDValue C = FMul.getOperand(0);
18511 SDValue D = FMul.getOperand(1);
18512 SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E);
18514 // Replacing the inner FMul could cause the outer FMA to be simplified
18515 // away.
18516 return FMA.getOpcode() == ISD::DELETED_NODE ? SDValue(N, 0) : FMA;
18517 }
18518
18519 TmpFMA = TmpFMA->getOperand(2);
18520 }
18521 }
18522
18523 // Look through FP_EXTEND nodes to do more combining.
18524
18525 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
18526 if (N0.getOpcode() == ISD::FP_EXTEND) {
18527 SDValue N00 = N0.getOperand(0);
18528 if (isContractableFMUL(N00) &&
18529 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18530 N00.getValueType())) {
18531 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18532 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18533 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18534 N1);
18535 }
18536 }
18537
18538 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
18539 // Note: Commutes FADD operands.
18540 if (N1.getOpcode() == ISD::FP_EXTEND) {
18541 SDValue N10 = N1.getOperand(0);
18542 if (isContractableFMUL(N10) &&
18543 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18544 N10.getValueType())) {
18545 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18546 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)),
18547 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)),
18548 N0);
18549 }
18550 }
18551
18552 // More folding opportunities when target permits.
18553 if (Aggressive) {
18554 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
18555 // -> (fma x, y, (fma (fpext u), (fpext v), z))
18556 auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18557 SDValue Z) {
18558 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
18559 DAG.getNode(PreferredFusedOpcode, SL, VT,
18560 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18561 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
18562 Z));
18563 };
18564 if (isFusedOp(N0)) {
18565 SDValue N02 = N0.getOperand(2);
18566 if (N02.getOpcode() == ISD::FP_EXTEND) {
18567 SDValue N020 = N02.getOperand(0);
18568 if (isContractableFMUL(N020) &&
18569 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18570 N020.getValueType())) {
18571 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
18572 N020.getOperand(0), N020.getOperand(1),
18573 N1);
18574 }
18575 }
18576 }
18577
18578 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
18579 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
18580 // FIXME: This turns two single-precision and one double-precision
18581 // operation into two double-precision operations, which might not be
18582 // interesting for all targets, especially GPUs.
18583 auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
18584 SDValue Z) {
18585 return DAG.getNode(
18586 PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
18587 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
18588 DAG.getNode(PreferredFusedOpcode, SL, VT,
18589 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
18590 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z));
18591 };
18592 if (N0.getOpcode() == ISD::FP_EXTEND) {
18593 SDValue N00 = N0.getOperand(0);
18594 if (isFusedOp(N00)) {
18595 SDValue N002 = N00.getOperand(2);
18596 if (isContractableFMUL(N002) &&
18597 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18598 N00.getValueType())) {
18599 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
18600 N002.getOperand(0), N002.getOperand(1),
18601 N1);
18602 }
18603 }
18604 }
18605
18606 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
18607 // -> (fma y, z, (fma (fpext u), (fpext v), x))
18608 if (isFusedOp(N1)) {
18609 SDValue N12 = N1.getOperand(2);
18610 if (N12.getOpcode() == ISD::FP_EXTEND) {
18611 SDValue N120 = N12.getOperand(0);
18612 if (isContractableFMUL(N120) &&
18613 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18614 N120.getValueType())) {
18615 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
18616 N120.getOperand(0), N120.getOperand(1),
18617 N0);
18618 }
18619 }
18620 }
18621
18622 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
18623 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
18624 // FIXME: This turns two single-precision and one double-precision
18625 // operation into two double-precision operations, which might not be
18626 // interesting for all targets, especially GPUs.
18627 if (N1.getOpcode() == ISD::FP_EXTEND) {
18628 SDValue N10 = N1.getOperand(0);
18629 if (isFusedOp(N10)) {
18630 SDValue N102 = N10.getOperand(2);
18631 if (isContractableFMUL(N102) &&
18632 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18633 N10.getValueType())) {
18634 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
18635 N102.getOperand(0), N102.getOperand(1),
18636 N0);
18637 }
18638 }
18639 }
18640 }
18641
18642 return SDValue();
18643}
18644
18645/// Try to perform FMA combining on a given FSUB node.
18646SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
18647 SDValue N0 = N->getOperand(0);
18648 SDValue N1 = N->getOperand(1);
18649 EVT VT = N->getValueType(0);
18650 SDLoc SL(N);
18651
18652 const TargetOptions &Options = DAG.getTarget().Options;
18653 // Floating-point multiply-add with intermediate rounding.
18654 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
18655
18656 // Floating-point multiply-add without intermediate rounding.
18657 bool HasFMA =
18658 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18660
18661 // No valid opcode, do not combine.
18662 if (!HasFMAD && !HasFMA)
18663 return SDValue();
18664
18665 const SDNodeFlags Flags = N->getFlags();
18666 bool AllowFusionGlobally =
18667 (Options.AllowFPOpFusion == FPOpFusion::Fast || HasFMAD);
18668
18669 // If the subtraction is not contractable, do not combine.
18670 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
18671 return SDValue();
18672
18673 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
18674 return SDValue();
18675
18676 // Always prefer FMAD to FMA for precision.
18677 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18679 bool NoSignedZero = Flags.hasNoSignedZeros();
18680
18681 // Is the node an FMUL and contractable either due to global flags or
18682 // SDNodeFlags.
18683 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
18684 if (N.getOpcode() != ISD::FMUL)
18685 return false;
18686 return AllowFusionGlobally || N->getFlags().hasAllowContract();
18687 };
18688
18689 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18690 auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
18691 if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
18692 return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
18693 XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z));
18694 }
18695 return SDValue();
18696 };
18697
18698 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18699 // Note: Commutes FSUB operands.
18700 auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
18701 if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
18702 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18703 DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
18704 YZ.getOperand(1), X);
18705 }
18706 return SDValue();
18707 };
18708
18709 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
18710 // prefer to fold the multiply with fewer uses.
18711 if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
18712 (N0->use_size() > N1->use_size())) {
18713 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
18714 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18715 return V;
18716 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
18717 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18718 return V;
18719 } else {
18720 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
18721 if (SDValue V = tryToFoldXYSubZ(N0, N1))
18722 return V;
18723 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
18724 if (SDValue V = tryToFoldXSubYZ(N0, N1))
18725 return V;
18726 }
18727
18728 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
18729 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
18730 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
18731 SDValue N00 = N0.getOperand(0).getOperand(0);
18732 SDValue N01 = N0.getOperand(0).getOperand(1);
18733 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18734 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
18735 DAG.getNode(ISD::FNEG, SL, VT, N1));
18736 }
18737
18738 // Look through FP_EXTEND nodes to do more combining.
18739
18740 // fold (fsub (fpext (fmul x, y)), z)
18741 // -> (fma (fpext x), (fpext y), (fneg z))
18742 if (N0.getOpcode() == ISD::FP_EXTEND) {
18743 SDValue N00 = N0.getOperand(0);
18744 if (isContractableFMUL(N00) &&
18745 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18746 N00.getValueType())) {
18747 return DAG.getNode(PreferredFusedOpcode, SL, VT,
18748 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18749 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18750 DAG.getNode(ISD::FNEG, SL, VT, N1));
18751 }
18752 }
18753
18754 // fold (fsub x, (fpext (fmul y, z)))
18755 // -> (fma (fneg (fpext y)), (fpext z), x)
18756 // Note: Commutes FSUB operands.
18757 if (N1.getOpcode() == ISD::FP_EXTEND) {
18758 SDValue N10 = N1.getOperand(0);
18759 if (isContractableFMUL(N10) &&
18760 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18761 N10.getValueType())) {
18762 return DAG.getNode(
18763 PreferredFusedOpcode, SL, VT,
18764 DAG.getNode(ISD::FNEG, SL, VT,
18765 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))),
18766 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0);
18767 }
18768 }
18769
18770 // fold (fsub (fpext (fneg (fmul, x, y))), z)
18771 // -> (fneg (fma (fpext x), (fpext y), z))
18772 // Note: This could be removed with appropriate canonicalization of the
18773 // input expression into (fneg (fadd (fpext (fmul, x, y)), z)). However, the
18774 // command line flag -fp-contract=fast and fast-math flag contract prevent
18775 // from implementing the canonicalization in visitFSUB.
18776 if (N0.getOpcode() == ISD::FP_EXTEND) {
18777 SDValue N00 = N0.getOperand(0);
18778 if (N00.getOpcode() == ISD::FNEG) {
18779 SDValue N000 = N00.getOperand(0);
18780 if (isContractableFMUL(N000) &&
18781 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18782 N00.getValueType())) {
18783 return DAG.getNode(
18784 ISD::FNEG, SL, VT,
18785 DAG.getNode(PreferredFusedOpcode, SL, VT,
18786 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
18787 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
18788 N1));
18789 }
18790 }
18791 }
18792
18793 // fold (fsub (fneg (fpext (fmul, x, y))), z)
18794 // -> (fneg (fma (fpext x)), (fpext y), z)
18795 // Note: This could be removed with appropriate canonicalization of the
18796 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
18797 // command line flag -fp-contract=fast and fast-math flag contract prevent
18798 // from implementing the canonicalization in visitFSUB.
18799 if (N0.getOpcode() == ISD::FNEG) {
18800 SDValue N00 = N0.getOperand(0);
18801 if (N00.getOpcode() == ISD::FP_EXTEND) {
18802 SDValue N000 = N00.getOperand(0);
18803 if (isContractableFMUL(N000) &&
18804 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18805 N000.getValueType())) {
18806 return DAG.getNode(
18807 ISD::FNEG, SL, VT,
18808 DAG.getNode(PreferredFusedOpcode, SL, VT,
18809 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
18810 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
18811 N1));
18812 }
18813 }
18814 }
18815
18816 auto isContractableAndReassociableFMUL = [&isContractableFMUL](SDValue N) {
18817 return isContractableFMUL(N) && N->getFlags().hasAllowReassociation();
18818 };
18819
18820 auto isFusedOp = [&](SDValue N) {
18821 unsigned Opcode = N.getOpcode();
18822 return Opcode == ISD::FMA || Opcode == ISD::FMAD;
18823 };
18824
18825 // More folding opportunities when target permits.
18826 if (Aggressive && N->getFlags().hasAllowReassociation()) {
18827 bool CanFuse = N->getFlags().hasAllowContract();
18828 // fold (fsub (fma x, y, (fmul u, v)), z)
18829 // -> (fma x, y (fma u, v, (fneg z)))
18830 if (CanFuse && isFusedOp(N0) &&
18831 isContractableAndReassociableFMUL(N0.getOperand(2)) &&
18832 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
18833 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
18834 N0.getOperand(1),
18835 DAG.getNode(PreferredFusedOpcode, SL, VT,
18836 N0.getOperand(2).getOperand(0),
18837 N0.getOperand(2).getOperand(1),
18838 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18839 }
18840
18841 // fold (fsub x, (fma y, z, (fmul u, v)))
18842 // -> (fma (fneg y), z, (fma (fneg u), v, x))
18843 if (CanFuse && isFusedOp(N1) &&
18844 isContractableAndReassociableFMUL(N1.getOperand(2)) &&
18845 N1->hasOneUse() && NoSignedZero) {
18846 SDValue N20 = N1.getOperand(2).getOperand(0);
18847 SDValue N21 = N1.getOperand(2).getOperand(1);
18848 return DAG.getNode(
18849 PreferredFusedOpcode, SL, VT,
18850 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
18851 DAG.getNode(PreferredFusedOpcode, SL, VT,
18852 DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0));
18853 }
18854
18855 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
18856 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
18857 if (isFusedOp(N0) && N0->hasOneUse()) {
18858 SDValue N02 = N0.getOperand(2);
18859 if (N02.getOpcode() == ISD::FP_EXTEND) {
18860 SDValue N020 = N02.getOperand(0);
18861 if (isContractableAndReassociableFMUL(N020) &&
18862 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18863 N020.getValueType())) {
18864 return DAG.getNode(
18865 PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1),
18866 DAG.getNode(
18867 PreferredFusedOpcode, SL, VT,
18868 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)),
18869 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)),
18870 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18871 }
18872 }
18873 }
18874
18875 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
18876 // -> (fma (fpext x), (fpext y),
18877 // (fma (fpext u), (fpext v), (fneg z)))
18878 // FIXME: This turns two single-precision and one double-precision
18879 // operation into two double-precision operations, which might not be
18880 // interesting for all targets, especially GPUs.
18881 if (N0.getOpcode() == ISD::FP_EXTEND) {
18882 SDValue N00 = N0.getOperand(0);
18883 if (isFusedOp(N00)) {
18884 SDValue N002 = N00.getOperand(2);
18885 if (isContractableAndReassociableFMUL(N002) &&
18886 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18887 N00.getValueType())) {
18888 return DAG.getNode(
18889 PreferredFusedOpcode, SL, VT,
18890 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
18891 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
18892 DAG.getNode(
18893 PreferredFusedOpcode, SL, VT,
18894 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)),
18895 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)),
18896 DAG.getNode(ISD::FNEG, SL, VT, N1)));
18897 }
18898 }
18899 }
18900
18901 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
18902 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
18903 if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
18904 N1->hasOneUse()) {
18905 SDValue N120 = N1.getOperand(2).getOperand(0);
18906 if (isContractableAndReassociableFMUL(N120) &&
18907 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18908 N120.getValueType())) {
18909 SDValue N1200 = N120.getOperand(0);
18910 SDValue N1201 = N120.getOperand(1);
18911 return DAG.getNode(
18912 PreferredFusedOpcode, SL, VT,
18913 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
18914 DAG.getNode(PreferredFusedOpcode, SL, VT,
18915 DAG.getNode(ISD::FNEG, SL, VT,
18916 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)),
18917 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0));
18918 }
18919 }
18920
18921 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
18922 // -> (fma (fneg (fpext y)), (fpext z),
18923 // (fma (fneg (fpext u)), (fpext v), x))
18924 // FIXME: This turns two single-precision and one double-precision
18925 // operation into two double-precision operations, which might not be
18926 // interesting for all targets, especially GPUs.
18927 if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) {
18928 SDValue CvtSrc = N1.getOperand(0);
18929 SDValue N100 = CvtSrc.getOperand(0);
18930 SDValue N101 = CvtSrc.getOperand(1);
18931 SDValue N102 = CvtSrc.getOperand(2);
18932 if (isContractableAndReassociableFMUL(N102) &&
18933 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
18934 CvtSrc.getValueType())) {
18935 SDValue N1020 = N102.getOperand(0);
18936 SDValue N1021 = N102.getOperand(1);
18937 return DAG.getNode(
18938 PreferredFusedOpcode, SL, VT,
18939 DAG.getNode(ISD::FNEG, SL, VT,
18940 DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)),
18941 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
18942 DAG.getNode(PreferredFusedOpcode, SL, VT,
18943 DAG.getNode(ISD::FNEG, SL, VT,
18944 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)),
18945 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0));
18946 }
18947 }
18948 }
18949
18950 return SDValue();
18951}
18952
18953/// Try to perform FMA combining on a given FMUL node based on the distributive
18954/// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
18955/// subtraction instead of addition).
18956SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
18957 SDValue N0 = N->getOperand(0);
18958 SDValue N1 = N->getOperand(1);
18959 EVT VT = N->getValueType(0);
18960 SDLoc SL(N);
18961
18962 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
18963
18964 const TargetOptions &Options = DAG.getTarget().Options;
18965
18966 // The transforms below are incorrect when x == 0 and y == inf, because the
18967 // intermediate multiplication produces a nan.
18968 SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1;
18969 if (!FAdd->getFlags().hasNoInfs())
18970 return SDValue();
18971
18972 // Floating-point multiply-add without intermediate rounding.
18973 bool HasFMA =
18975 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
18977
18978 // Floating-point multiply-add with intermediate rounding. This can result
18979 // in a less precise result due to the changed rounding order.
18980 bool HasFMAD = LegalOperations && TLI.isFMADLegal(DAG, N);
18981
18982 // No valid opcode, do not combine.
18983 if (!HasFMAD && !HasFMA)
18984 return SDValue();
18985
18986 // Always prefer FMAD to FMA for precision.
18987 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
18989
18990 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
18991 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
18992 auto FuseFADD = [&](SDValue X, SDValue Y) {
18993 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
18994 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
18995 if (C->isOne())
18996 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
18997 Y);
18998 if (C->isMinusOne())
18999 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19000 DAG.getNode(ISD::FNEG, SL, VT, Y));
19001 }
19002 }
19003 return SDValue();
19004 };
19005
19006 if (SDValue FMA = FuseFADD(N0, N1))
19007 return FMA;
19008 if (SDValue FMA = FuseFADD(N1, N0))
19009 return FMA;
19010
19011 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
19012 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
19013 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
19014 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
19015 auto FuseFSUB = [&](SDValue X, SDValue Y) {
19016 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
19017 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
19018 if (C0->isOne())
19019 return DAG.getNode(PreferredFusedOpcode, SL, VT,
19020 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
19021 Y);
19022 if (C0->isMinusOne())
19023 return DAG.getNode(PreferredFusedOpcode, SL, VT,
19024 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
19025 DAG.getNode(ISD::FNEG, SL, VT, Y));
19026 }
19027 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
19028 if (C1->isOne())
19029 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19030 DAG.getNode(ISD::FNEG, SL, VT, Y));
19031 if (C1->isMinusOne())
19032 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
19033 Y);
19034 }
19035 }
19036 return SDValue();
19037 };
19038
19039 if (SDValue FMA = FuseFSUB(N0, N1))
19040 return FMA;
19041 if (SDValue FMA = FuseFSUB(N1, N0))
19042 return FMA;
19043
19044 return SDValue();
19045}
19046
19047SDValue DAGCombiner::visitFADD(SDNode *N) {
19048 SDValue N0 = N->getOperand(0);
19049 SDValue N1 = N->getOperand(1);
19050 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0);
19051 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1);
19052 EVT VT = N->getValueType(0);
19053 SDLoc DL(N);
19054 SDNodeFlags Flags = N->getFlags();
19055 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19056
19057 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19058 return R;
19059
19060 // fold (fadd c1, c2) -> c1 + c2
19061 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FADD, DL, VT, {N0, N1}))
19062 return C;
19063
19064 // canonicalize constant to RHS
19065 if (N0CFP && !N1CFP)
19066 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
19067
19068 // fold vector ops
19069 if (VT.isVector())
19070 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19071 return FoldedVOp;
19072
19073 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
19074 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
19075 if (N1C && N1C->isZero())
19076 if (N1C->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0)))
19077 return N0;
19078
19079 if (SDValue NewSel = foldBinOpIntoSelect(N))
19080 return NewSel;
19081
19082 // fold (fadd A, (fneg B)) -> (fsub A, B)
19083 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
19084 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
19085 N1, DAG, LegalOperations, ForCodeSize))
19086 return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1);
19087
19088 // fold (fadd (fneg A), B) -> (fsub B, A)
19089 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
19090 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
19091 N0, DAG, LegalOperations, ForCodeSize))
19092 return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0);
19093
19094 auto isFMulNegTwo = [](SDValue FMul) {
19095 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
19096 return false;
19097 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
19098 return C && C->isExactlyValue(-2.0);
19099 };
19100
19101 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
19102 if (isFMulNegTwo(N0)) {
19103 SDValue B = N0.getOperand(0);
19104 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
19105 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add);
19106 }
19107 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
19108 if (isFMulNegTwo(N1)) {
19109 SDValue B = N1.getOperand(0);
19110 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
19111 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add);
19112 }
19113
19114 // No FP constant should be created after legalization as Instruction
19115 // Selection pass has a hard time dealing with FP constants.
19116 bool AllowNewConst = (Level < AfterLegalizeDAG);
19117
19118 // If nnan is enabled, fold lots of things.
19119 if (Flags.hasNoNaNs() && AllowNewConst) {
19120 // If allowed, fold (fadd (fneg x), x) -> 0.0
19121 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
19122 return DAG.getConstantFP(0.0, DL, VT);
19123
19124 // If allowed, fold (fadd x, (fneg x)) -> 0.0
19125 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
19126 return DAG.getConstantFP(0.0, DL, VT);
19127 }
19128
19129 // If reassoc and nsz, fold lots of things.
19130 // TODO: break out portions of the transformations below for which Unsafe is
19131 // considered and which do not require both nsz and reassoc
19132 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
19133 AllowNewConst) {
19134 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
19135 if (N1CFP && N0.getOpcode() == ISD::FADD &&
19137 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1);
19138 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC);
19139 }
19140
19141 // We can fold chains of FADD's of the same value into multiplications.
19142 // This transform is not safe in general because we are reducing the number
19143 // of rounding steps.
19144 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
19145 if (N0.getOpcode() == ISD::FMUL) {
19146 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
19147 bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
19148
19149 // (fadd (fmul x, c), x) -> (fmul x, c+1)
19150 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
19151 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
19152 DAG.getConstantFP(1.0, DL, VT));
19153 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
19154 }
19155
19156 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
19157 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
19158 N1.getOperand(0) == N1.getOperand(1) &&
19159 N0.getOperand(0) == N1.getOperand(0)) {
19160 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
19161 DAG.getConstantFP(2.0, DL, VT));
19162 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
19163 }
19164 }
19165
19166 if (N1.getOpcode() == ISD::FMUL) {
19167 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
19168 bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
19169
19170 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
19171 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
19172 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
19173 DAG.getConstantFP(1.0, DL, VT));
19174 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
19175 }
19176
19177 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
19178 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
19179 N0.getOperand(0) == N0.getOperand(1) &&
19180 N1.getOperand(0) == N0.getOperand(0)) {
19181 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
19182 DAG.getConstantFP(2.0, DL, VT));
19183 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
19184 }
19185 }
19186
19187 if (N0.getOpcode() == ISD::FADD) {
19188 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
19189 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
19190 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
19191 (N0.getOperand(0) == N1)) {
19192 return DAG.getNode(ISD::FMUL, DL, VT, N1,
19193 DAG.getConstantFP(3.0, DL, VT));
19194 }
19195 }
19196
19197 if (N1.getOpcode() == ISD::FADD) {
19198 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
19199 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
19200 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
19201 N1.getOperand(0) == N0) {
19202 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19203 DAG.getConstantFP(3.0, DL, VT));
19204 }
19205 }
19206
19207 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
19208 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
19209 N0.getOperand(0) == N0.getOperand(1) &&
19210 N1.getOperand(0) == N1.getOperand(1) &&
19211 N0.getOperand(0) == N1.getOperand(0)) {
19212 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
19213 DAG.getConstantFP(4.0, DL, VT));
19214 }
19215 }
19216 } // reassoc && nsz && AllowNewConst
19217
19218 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros()) {
19219 // Fold fadd(vecreduce(x), vecreduce(y)) -> vecreduce(fadd(x, y))
19220 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FADD, ISD::FADD, DL,
19221 VT, N0, N1, Flags))
19222 return SD;
19223 }
19224
19225 // FADD -> FMA combines:
19226 if (SDValue Fused = visitFADDForFMACombine(N)) {
19227 if (Fused.getOpcode() != ISD::DELETED_NODE)
19228 AddToWorklist(Fused.getNode());
19229 return Fused;
19230 }
19231 return SDValue();
19232}
19233
19234SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) {
19235 SDValue Chain = N->getOperand(0);
19236 SDValue N0 = N->getOperand(1);
19237 SDValue N1 = N->getOperand(2);
19238 EVT VT = N->getValueType(0);
19239 EVT ChainVT = N->getValueType(1);
19240 SDLoc DL(N);
19241 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19242
19243 // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B)
19244 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
19245 if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
19246 N1, DAG, LegalOperations, ForCodeSize)) {
19247 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
19248 {Chain, N0, NegN1});
19249 }
19250
19251 // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A)
19252 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
19253 if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
19254 N0, DAG, LegalOperations, ForCodeSize)) {
19255 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
19256 {Chain, N1, NegN0});
19257 }
19258 return SDValue();
19259}
19260
19261SDValue DAGCombiner::visitFSUB(SDNode *N) {
19262 SDValue N0 = N->getOperand(0);
19263 SDValue N1 = N->getOperand(1);
19264 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
19265 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19266 EVT VT = N->getValueType(0);
19267 SDLoc DL(N);
19268 const SDNodeFlags Flags = N->getFlags();
19269 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19270
19271 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19272 return R;
19273
19274 // fold (fsub c1, c2) -> c1-c2
19275 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FSUB, DL, VT, {N0, N1}))
19276 return C;
19277
19278 // fold vector ops
19279 if (VT.isVector())
19280 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19281 return FoldedVOp;
19282
19283 if (SDValue NewSel = foldBinOpIntoSelect(N))
19284 return NewSel;
19285
19286 // (fsub A, 0) -> A
19287 if (N1CFP && N1CFP->isZero()) {
19288 if (!N1CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19289 return N0;
19290 }
19291 }
19292
19293 if (N0 == N1) {
19294 // (fsub x, x) -> 0.0
19295 if (Flags.hasNoNaNs())
19296 return DAG.getConstantFP(0.0f, DL, VT);
19297 }
19298
19299 // (fsub -0.0, N1) -> -N1
19300 if (N0CFP && N0CFP->isZero()) {
19301 if (N0CFP->isNegative() || DAG.canIgnoreSignBitOfZero(SDValue(N, 0))) {
19302 // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are
19303 // flushed to zero, unless all users treat denorms as zero (DAZ).
19304 // FIXME: This transform will change the sign of a NaN and the behavior
19305 // of a signaling NaN. It is only valid when a NoNaN flag is present.
19306 DenormalMode DenormMode = DAG.getDenormalMode(VT);
19307 if (DenormMode == DenormalMode::getIEEE()) {
19308 if (SDValue NegN1 =
19309 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19310 return NegN1;
19311 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
19312 return DAG.getNode(ISD::FNEG, DL, VT, N1);
19313 }
19314 }
19315 }
19316
19317 if (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros() &&
19318 N1.getOpcode() == ISD::FADD) {
19319 // X - (X + Y) -> -Y
19320 if (N0 == N1->getOperand(0))
19321 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1));
19322 // X - (Y + X) -> -Y
19323 if (N0 == N1->getOperand(1))
19324 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0));
19325 }
19326
19327 // fold (fsub A, (fneg B)) -> (fadd A, B)
19328 if (SDValue NegN1 =
19329 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
19330 return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1);
19331
19332 // FSUB -> FMA combines:
19333 if (SDValue Fused = visitFSUBForFMACombine(N)) {
19334 AddToWorklist(Fused.getNode());
19335 return Fused;
19336 }
19337
19338 return SDValue();
19339}
19340
19341// Transform IEEE Floats:
19342// (fmul C, (uitofp Pow2))
19343// -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
19344// (fdiv C, (uitofp Pow2))
19345// -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
19346//
19347// The rationale is fmul/fdiv by a power of 2 is just change the exponent, so
19348// there is no need for more than an add/sub.
19349//
19350// This is valid under the following circumstances:
19351// 1) We are dealing with IEEE floats
19352// 2) C is normal
19353// 3) The fmul/fdiv add/sub will not go outside of min/max exponent bounds.
19354// TODO: Much of this could also be used for generating `ldexp` on targets the
19355// prefer it.
19356SDValue DAGCombiner::combineFMulOrFDivWithIntPow2(SDNode *N) {
19357 EVT VT = N->getValueType(0);
19359 return SDValue();
19360
19361 SDValue ConstOp, Pow2Op;
19362
19363 std::optional<int> Mantissa;
19364 auto GetConstAndPow2Ops = [&](unsigned ConstOpIdx) {
19365 if (ConstOpIdx == 1 && N->getOpcode() == ISD::FDIV)
19366 return false;
19367
19368 ConstOp = peekThroughBitcasts(N->getOperand(ConstOpIdx));
19369 Pow2Op = N->getOperand(1 - ConstOpIdx);
19370 unsigned Pow2Opc = Pow2Op.getOpcode();
19371 if (Pow2Opc != ISD::UINT_TO_FP && Pow2Opc != ISD::SINT_TO_FP)
19372 return false;
19373
19374 Pow2Op = Pow2Op.getOperand(0);
19375
19376 KnownBits Pow2OpKnownBits = DAG.computeKnownBits(Pow2Op);
19377 if (Pow2Opc == ISD::SINT_TO_FP && !Pow2OpKnownBits.isNonNegative())
19378 return false;
19379
19380 int MaxExpChange = Pow2OpKnownBits.countMaxActiveBits();
19381
19382 auto IsFPConstValid = [N, MaxExpChange, &Mantissa](ConstantFPSDNode *CFP) {
19383 if (CFP == nullptr)
19384 return false;
19385
19386 const APFloat &APF = CFP->getValueAPF();
19387
19388 // Make sure we have normal constant.
19389 if (!APF.isNormal())
19390 return false;
19391
19392 // Make sure the floats exponent is within the bounds that this transform
19393 // produces bitwise equals value.
19394 int CurExp = ilogb(APF);
19395 // FMul by pow2 will only increase exponent.
19396 int MinExp =
19397 N->getOpcode() == ISD::FMUL ? CurExp : (CurExp - MaxExpChange);
19398 // FDiv by pow2 will only decrease exponent.
19399 int MaxExp =
19400 N->getOpcode() == ISD::FDIV ? CurExp : (CurExp + MaxExpChange);
19401 if (MinExp <= APFloat::semanticsMinExponent(APF.getSemantics()) ||
19403 return false;
19404
19405 // Finally make sure we actually know the mantissa for the float type.
19406 int ThisMantissa = APFloat::semanticsPrecision(APF.getSemantics()) - 1;
19407 if (!Mantissa)
19408 Mantissa = ThisMantissa;
19409
19410 return *Mantissa == ThisMantissa && ThisMantissa > 0;
19411 };
19412
19413 // TODO: We may be able to include undefs.
19414 return ISD::matchUnaryFpPredicate(ConstOp, IsFPConstValid);
19415 };
19416
19417 if (!GetConstAndPow2Ops(0) && !GetConstAndPow2Ops(1))
19418 return SDValue();
19419
19420 if (!TLI.optimizeFMulOrFDivAsShiftAddBitcast(N, ConstOp, Pow2Op))
19421 return SDValue();
19422
19423 // Get log2 after all other checks have taken place. This is because
19424 // BuildLogBase2 may create a new node.
19425 SDLoc DL(N);
19426 // Get Log2 type with same bitwidth as the float type (VT).
19427 EVT NewIntVT = VT.changeElementType(
19428 *DAG.getContext(),
19430
19431 SDValue Log2 = BuildLogBase2(Pow2Op, DL, DAG.isKnownNeverZero(Pow2Op),
19432 /*InexpensiveOnly*/ true, NewIntVT);
19433 if (!Log2)
19434 return SDValue();
19435
19436 // Perform actual transform.
19437 SDValue MantissaShiftCnt =
19438 DAG.getShiftAmountConstant(*Mantissa, NewIntVT, DL);
19439 // TODO: Sometimes Log2 is of form `(X + C)`. `(X + C) << C1` should fold to
19440 // `(X << C1) + (C << C1)`, but that isn't always the case because of the
19441 // cast. We could implement that by handle here to handle the casts.
19442 SDValue Shift = DAG.getNode(ISD::SHL, DL, NewIntVT, Log2, MantissaShiftCnt);
19443 SDValue ResAsInt =
19444 DAG.getNode(N->getOpcode() == ISD::FMUL ? ISD::ADD : ISD::SUB, DL,
19445 NewIntVT, DAG.getBitcast(NewIntVT, ConstOp), Shift);
19446 SDValue ResAsFP = DAG.getBitcast(VT, ResAsInt);
19447 return ResAsFP;
19448}
19449
19450SDValue DAGCombiner::visitFMUL(SDNode *N) {
19451 SDValue N0 = N->getOperand(0);
19452 SDValue N1 = N->getOperand(1);
19453 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
19454 EVT VT = N->getValueType(0);
19455 SDLoc DL(N);
19456 const SDNodeFlags Flags = N->getFlags();
19457 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19458
19459 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19460 return R;
19461
19462 // fold (fmul c1, c2) -> c1*c2
19463 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMUL, DL, VT, {N0, N1}))
19464 return C;
19465
19466 // canonicalize constant to RHS
19469 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
19470
19471 // fold vector ops
19472 if (VT.isVector())
19473 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19474 return FoldedVOp;
19475
19476 if (SDValue NewSel = foldBinOpIntoSelect(N))
19477 return NewSel;
19478
19479 if (Flags.hasAllowReassociation()) {
19480 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
19482 N0.getOpcode() == ISD::FMUL) {
19483 SDValue N00 = N0.getOperand(0);
19484 SDValue N01 = N0.getOperand(1);
19485 // Avoid an infinite loop by making sure that N00 is not a constant
19486 // (the inner multiply has not been constant folded yet).
19489 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
19490 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
19491 }
19492 }
19493
19494 // Match a special-case: we convert X * 2.0 into fadd.
19495 // fmul (fadd X, X), C -> fmul X, 2.0 * C
19496 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
19497 N0.getOperand(0) == N0.getOperand(1)) {
19498 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
19499 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
19500 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
19501 }
19502
19503 // Fold fmul(vecreduce(x), vecreduce(y)) -> vecreduce(fmul(x, y))
19504 if (SDValue SD = reassociateReduction(ISD::VECREDUCE_FMUL, ISD::FMUL, DL,
19505 VT, N0, N1, Flags))
19506 return SD;
19507 }
19508
19509 // fold (fmul X, 2.0) -> (fadd X, X)
19510 if (N1CFP && N1CFP->isExactlyValue(+2.0))
19511 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
19512
19513 // fold (fmul X, -1.0) -> (fsub -0.0, X)
19514 if (N1CFP && N1CFP->isMinusOne()) {
19515 if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) {
19516 return DAG.getNode(ISD::FSUB, DL, VT,
19517 DAG.getConstantFP(-0.0, DL, VT), N0, Flags);
19518 }
19519 }
19520
19521 // -N0 * -N1 --> N0 * N1
19526 SDValue NegN0 =
19527 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19528 if (NegN0) {
19529 HandleSDNode NegN0Handle(NegN0);
19530 SDValue NegN1 =
19531 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19532 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19534 return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1);
19535 }
19536
19537 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
19538 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
19539 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
19540 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
19541 TLI.isOperationLegal(ISD::FABS, VT)) {
19542 SDValue Select = N0, X = N1;
19543 if (Select.getOpcode() != ISD::SELECT)
19544 std::swap(Select, X);
19545
19546 SDValue Cond = Select.getOperand(0);
19547 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
19548 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
19549
19550 if (TrueOpnd && FalseOpnd && Cond.getOpcode() == ISD::SETCC &&
19551 Cond.getOperand(0) == X && isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
19552 cast<ConstantFPSDNode>(Cond.getOperand(1))->isPosZero()) {
19553 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19554 switch (CC) {
19555 default: break;
19556 case ISD::SETOLT:
19557 case ISD::SETULT:
19558 case ISD::SETOLE:
19559 case ISD::SETULE:
19560 case ISD::SETLT:
19561 case ISD::SETLE:
19562 std::swap(TrueOpnd, FalseOpnd);
19563 [[fallthrough]];
19564 case ISD::SETOGT:
19565 case ISD::SETUGT:
19566 case ISD::SETOGE:
19567 case ISD::SETUGE:
19568 case ISD::SETGT:
19569 case ISD::SETGE:
19570 if (TrueOpnd->isMinusOne() && FalseOpnd->isOne() &&
19571 TLI.isOperationLegal(ISD::FNEG, VT))
19572 return DAG.getNode(ISD::FNEG, DL, VT,
19573 DAG.getNode(ISD::FABS, DL, VT, X));
19574 if (TrueOpnd->isOne() && FalseOpnd->isMinusOne())
19575 return DAG.getNode(ISD::FABS, DL, VT, X);
19576
19577 break;
19578 }
19579 }
19580 }
19581
19582 // FMUL -> FMA combines:
19583 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
19584 AddToWorklist(Fused.getNode());
19585 return Fused;
19586 }
19587
19588 // Don't do `combineFMulOrFDivWithIntPow2` until after FMUL -> FMA has been
19589 // able to run.
19590 if (SDValue R = combineFMulOrFDivWithIntPow2(N))
19591 return R;
19592
19593 return SDValue();
19594}
19595
19596SDValue DAGCombiner::visitFMA(SDNode *N) {
19597 SDValue N0 = N->getOperand(0);
19598 SDValue N1 = N->getOperand(1);
19599 SDValue N2 = N->getOperand(2);
19600 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
19601 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
19602 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
19603 EVT VT = N->getValueType(0);
19604 SDLoc DL(N);
19605 // FMA nodes have flags that propagate to the created nodes.
19606 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19607
19608 // Constant fold FMA.
19609 if (SDValue C =
19610 DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1, N2}))
19611 return C;
19612
19613 // (-N0 * -N1) + N2 --> (N0 * N1) + N2
19618 SDValue NegN0 =
19619 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
19620 if (NegN0) {
19621 HandleSDNode NegN0Handle(NegN0);
19622 SDValue NegN1 =
19623 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
19624 if (NegN1 && (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
19626 return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2);
19627 }
19628
19629 if (N->getFlags().hasNoNaNs() && N->getFlags().hasNoInfs()) {
19630 if (N->getFlags().hasNoSignedZeros() || (N2CFP && !N2CFP->isNegZero())) {
19631 if (N0CFP && N0CFP->isZero())
19632 return N2;
19633 if (N1CFP && N1CFP->isZero())
19634 return N2;
19635 }
19636 }
19637
19638 if (N0CFP && N0CFP->isOne())
19639 return DAG.getNode(ISD::FADD, DL, VT, N1, N2);
19640 if (N1CFP && N1CFP->isOne())
19641 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19642
19643 // Canonicalize (fma c, x, y) -> (fma x, c, y)
19646 return DAG.getNode(ISD::FMA, DL, VT, N1, N0, N2);
19647
19648 bool CanReassociate = N->getFlags().hasAllowReassociation();
19649 if (CanReassociate) {
19650 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
19651 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
19654 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19655 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1)));
19656 }
19657
19658 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
19659 if (N0.getOpcode() == ISD::FMUL &&
19662 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19663 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)),
19664 N2);
19665 }
19666 }
19667
19668 // (fma x, -1, y) -> (fadd (fneg x), y)
19669 if (N1CFP) {
19670 if (N1CFP->isOne())
19671 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
19672
19673 if (N1CFP->isMinusOne() &&
19674 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
19675 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
19676 AddToWorklist(RHSNeg.getNode());
19677 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
19678 }
19679
19680 // fma (fneg x), K, y -> fma x -K, y
19681 if (N0.getOpcode() == ISD::FNEG &&
19683 (N1.hasOneUse() &&
19684 !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, ForCodeSize)))) {
19685 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
19686 DAG.getNode(ISD::FNEG, DL, VT, N1), N2);
19687 }
19688 }
19689
19690 if (CanReassociate) {
19691 // (fma x, c, x) -> (fmul x, (c+1))
19692 if (N1CFP && N0 == N2) {
19693 return DAG.getNode(
19694 ISD::FMUL, DL, VT, N0,
19695 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT)));
19696 }
19697
19698 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
19699 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
19700 return DAG.getNode(
19701 ISD::FMUL, DL, VT, N0,
19702 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT)));
19703 }
19704 }
19705
19706 // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z))
19707 // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z))
19708 if (!TLI.isFNegFree(VT))
19710 SDValue(N, 0), DAG, LegalOperations, ForCodeSize))
19711 return DAG.getNode(ISD::FNEG, DL, VT, Neg);
19712 return SDValue();
19713}
19714
19715SDValue DAGCombiner::visitFMAD(SDNode *N) {
19716 SDValue N0 = N->getOperand(0);
19717 SDValue N1 = N->getOperand(1);
19718 SDValue N2 = N->getOperand(2);
19719 EVT VT = N->getValueType(0);
19720 SDLoc DL(N);
19721
19722 // Constant fold FMAD.
19723 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMAD, DL, VT, {N0, N1, N2}))
19724 return C;
19725
19726 return SDValue();
19727}
19728
19729SDValue DAGCombiner::visitFMULADD(SDNode *N) {
19730 SDValue N0 = N->getOperand(0);
19731 SDValue N1 = N->getOperand(1);
19732 SDValue N2 = N->getOperand(2);
19733 EVT VT = N->getValueType(0);
19734 SDLoc DL(N);
19735
19736 // Constant fold FMULADD.
19737 if (SDValue C =
19738 DAG.FoldConstantArithmetic(ISD::FMULADD, DL, VT, {N0, N1, N2}))
19739 return C;
19740
19741 return SDValue();
19742}
19743
19744// Combine multiple FDIVs with the same divisor into multiple FMULs by the
19745// reciprocal.
19746// E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
19747// Notice that this is not always beneficial. One reason is different targets
19748// may have different costs for FDIV and FMUL, so sometimes the cost of two
19749// FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
19750// is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
19751SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
19752 // TODO: Limit this transform based on optsize/minsize - it always creates at
19753 // least 1 extra instruction. But the perf win may be substantial enough
19754 // that only minsize should restrict this.
19755 const SDNodeFlags Flags = N->getFlags();
19756 if (LegalDAG || !Flags.hasAllowReciprocal())
19757 return SDValue();
19758
19759 // Skip if current node is a reciprocal/fneg-reciprocal.
19760 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
19761 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
19762 if (N0CFP && (N0CFP->isOne() || N0CFP->isMinusOne()))
19763 return SDValue();
19764
19765 // Exit early if the target does not want this transform or if there can't
19766 // possibly be enough uses of the divisor to make the transform worthwhile.
19767 unsigned MinUses = TLI.combineRepeatedFPDivisors();
19768
19769 // For splat vectors, scale the number of uses by the splat factor. If we can
19770 // convert the division into a scalar op, that will likely be much faster.
19771 unsigned NumElts = 1;
19772 EVT VT = N->getValueType(0);
19773 if (VT.isVector() && DAG.isSplatValue(N1))
19774 NumElts = VT.getVectorMinNumElements();
19775
19776 if (!MinUses || (N1->use_size() * NumElts) < MinUses)
19777 return SDValue();
19778
19779 // Find all FDIV users of the same divisor.
19780 // Use a set because duplicates may be present in the user list.
19781 SetVector<SDNode *> Users;
19782 for (auto *U : N1->users()) {
19783 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
19784 // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet.
19785 if (U->getOperand(1).getOpcode() == ISD::FSQRT &&
19786 U->getOperand(0) == U->getOperand(1).getOperand(0) &&
19787 U->getFlags().hasAllowReassociation() &&
19788 U->getFlags().hasNoSignedZeros())
19789 continue;
19790
19791 // This division is eligible for optimization only if global unsafe math
19792 // is enabled or if this division allows reciprocal formation.
19793 if (U->getFlags().hasAllowReciprocal())
19794 Users.insert(U);
19795 }
19796 }
19797
19798 // Now that we have the actual number of divisor uses, make sure it meets
19799 // the minimum threshold specified by the target.
19800 if ((Users.size() * NumElts) < MinUses)
19801 return SDValue();
19802
19803 SDLoc DL(N);
19804 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
19805 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
19806
19807 // Dividend / Divisor -> Dividend * Reciprocal
19808 for (auto *U : Users) {
19809 SDValue Dividend = U->getOperand(0);
19810 if (Dividend != FPOne) {
19811 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
19812 Reciprocal, Flags);
19813 CombineTo(U, NewNode);
19814 } else if (U != Reciprocal.getNode()) {
19815 // In the absence of fast-math-flags, this user node is always the
19816 // same node as Reciprocal, but with FMF they may be different nodes.
19817 CombineTo(U, Reciprocal);
19818 }
19819 }
19820 return SDValue(N, 0); // N was replaced.
19821}
19822
19823SDValue DAGCombiner::visitFDIV(SDNode *N) {
19824 SDValue N0 = N->getOperand(0);
19825 SDValue N1 = N->getOperand(1);
19826 EVT VT = N->getValueType(0);
19827 SDLoc DL(N);
19828 SDNodeFlags Flags = N->getFlags();
19829 SelectionDAG::FlagInserter FlagsInserter(DAG, N);
19830
19831 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
19832 return R;
19833
19834 // fold (fdiv c1, c2) -> c1/c2
19835 if (SDValue C = DAG.FoldConstantArithmetic(ISD::FDIV, DL, VT, {N0, N1}))
19836 return C;
19837
19838 // fold vector ops
19839 if (VT.isVector())
19840 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
19841 return FoldedVOp;
19842
19843 if (SDValue NewSel = foldBinOpIntoSelect(N))
19844 return NewSel;
19845
19847 return V;
19848
19849 // fold (fdiv X, c2) -> (fmul X, 1/c2) if there is no loss in precision, or
19850 // the loss is acceptable with AllowReciprocal.
19851 if (auto *N1CFP = isConstOrConstSplatFP(N1, true)) {
19852 // Compute the reciprocal 1.0 / c2.
19853 const APFloat &N1APF = N1CFP->getValueAPF();
19854 APFloat Recip = APFloat::getOne(N1APF.getSemantics());
19856 // Only do the transform if the reciprocal is a legal fp immediate that
19857 // isn't too nasty (eg NaN, denormal, ...).
19858 if (((st == APFloat::opOK && !Recip.isDenormal()) ||
19859 (st == APFloat::opInexact && Flags.hasAllowReciprocal())) &&
19860 (!LegalOperations ||
19861 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
19862 // backend)... we should handle this gracefully after Legalize.
19863 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
19865 TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
19866 return DAG.getNode(ISD::FMUL, DL, VT, N0,
19867 DAG.getConstantFP(Recip, DL, VT));
19868 }
19869
19870 if (Flags.hasAllowReciprocal()) {
19871 // If this FDIV is part of a reciprocal square root, it may be folded
19872 // into a target-specific square root estimate instruction.
19873 bool N1AllowReciprocal = N1->getFlags().hasAllowReciprocal();
19874 if (N1.getOpcode() == ISD::FSQRT) {
19875 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), N1->getFlags()))
19876 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19877 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
19878 N1.getOperand(0).getOpcode() == ISD::FSQRT &&
19879 N1AllowReciprocal) {
19880 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
19881 N1.getOperand(0)->getFlags())) {
19882 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
19883 AddToWorklist(RV.getNode());
19884 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19885 }
19886 } else if (N1.getOpcode() == ISD::FP_ROUND &&
19887 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
19888 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
19889 N1.getOperand(0)->getFlags())) {
19890 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
19891 AddToWorklist(RV.getNode());
19892 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
19893 }
19894 } else if (N1.getOpcode() == ISD::FMUL) {
19895 // Look through an FMUL. Even though this won't remove the FDIV directly,
19896 // it's still worthwhile to get rid of the FSQRT if possible.
19897 SDValue Sqrt, Y;
19898 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
19899 Sqrt = N1.getOperand(0);
19900 Y = N1.getOperand(1);
19901 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
19902 Sqrt = N1.getOperand(1);
19903 Y = N1.getOperand(0);
19904 }
19905 if (Sqrt.getNode()) {
19906 // If the other multiply operand is known positive, pull it into the
19907 // sqrt. That will eliminate the division if we convert to an estimate.
19908 if (Flags.hasAllowReassociation() && N1.hasOneUse() &&
19909 N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) {
19910 SDValue A;
19911 if (Y.getOpcode() == ISD::FABS && Y.hasOneUse())
19912 A = Y.getOperand(0);
19913 else if (Y == Sqrt.getOperand(0))
19914 A = Y;
19915 if (A) {
19916 // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z)
19917 // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A)
19918 SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A);
19919 SDValue AAZ =
19920 DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0));
19921 if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Sqrt->getFlags()))
19922 return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt);
19923
19924 // Estimate creation failed. Clean up speculatively created nodes.
19925 recursivelyDeleteUnusedNodes(AAZ.getNode()