LLVM 24.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 "SDNodeDbgValue.h"
83
84using namespace llvm;
85using namespace llvm::SDPatternMatch;
86
87#define DEBUG_TYPE "dagcombine"
88
89STATISTIC(NodesCombined , "Number of dag nodes combined");
90STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
91STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
92STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
93STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
94STATISTIC(SlicedLoads, "Number of load sliced");
95STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
96
97DEBUG_COUNTER(DAGCombineCounter, "dagcombine",
98 "Controls whether a DAG combine is performed for a node");
99
100static cl::opt<bool>
101CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
102 cl::desc("Enable DAG combiner's use of IR alias analysis"));
103
104static cl::opt<bool>
105UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
106 cl::desc("Enable DAG combiner's use of TBAA"));
107
108#ifndef NDEBUG
110CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
111 cl::desc("Only use DAG-combiner alias analysis in this"
112 " function"));
113#endif
114
115/// Hidden option to stress test load slicing, i.e., when this option
116/// is enabled, load slicing bypasses most of its profitability guards.
117static cl::opt<bool>
118StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
119 cl::desc("Bypass the profitability model of load slicing"),
120 cl::init(false));
121
122static cl::opt<bool>
123 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
124 cl::desc("DAG combiner may split indexing from loads"));
125
126static cl::opt<bool>
127 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
128 cl::desc("DAG combiner enable merging multiple stores "
129 "into a wider store"));
130
132 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
133 cl::desc("Limit the number of operands to inline for Token Factors"));
134
136 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
137 cl::desc("Limit the number of times for the same StoreNode and RootNode "
138 "to bail out in store merging dependence check"));
139
141 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
142 cl::desc("DAG combiner enable reducing the width of load/op/store "
143 "sequence"));
145 "combiner-reduce-load-op-store-width-force-narrowing-profitable",
146 cl::Hidden, cl::init(false),
147 cl::desc("DAG combiner force override the narrowing profitable check when "
148 "reducing the width of load/op/store sequences"));
149
151 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
152 cl::desc("DAG combiner enable load/<replace bytes>/store with "
153 "a narrower store"));
154
156 "combiner-topological-sorting", cl::Hidden, cl::init(false),
157 cl::desc("DAG combiner nodes consistently processed in topological order"));
158
159static cl::opt<bool> DisableCombines("combiner-disabled", cl::Hidden,
160 cl::init(false),
161 cl::desc("Disable the DAG combiner"));
162
163namespace {
164
165 class DAGCombiner {
166 SelectionDAG &DAG;
167 const TargetLowering &TLI;
168 const SelectionDAGTargetInfo *STI;
170 CodeGenOptLevel OptLevel;
171 bool LegalDAG = false;
172 bool LegalOperations = false;
173 bool LegalTypes = false;
174 bool ForCodeSize;
175 bool DisableGenericCombines;
176
177 /// Worklist of all of the nodes that need to be simplified.
178 ///
179 /// This must behave as a stack -- new nodes to process are pushed onto the
180 /// back and when processing we pop off of the back.
181 ///
182 /// The worklist will not contain duplicates but may contain null entries
183 /// due to nodes being deleted from the underlying DAG. For fast lookup and
184 /// deduplication, the index of the node in this vector is stored in the
185 /// node in SDNode::CombinerWorklistIndex.
187
188 /// This records all nodes attempted to be added to the worklist since we
189 /// considered a new worklist entry. As we keep do not add duplicate nodes
190 /// in the worklist, this is different from the tail of the worklist.
192
193 /// Map from candidate StoreNode to the pair of RootNode and count.
194 /// The count is used to track how many times we have seen the StoreNode
195 /// with the same RootNode bail out in dependence check. If we have seen
196 /// the bail out for the same pair many times over a limit, we won't
197 /// consider the StoreNode with the same RootNode as store merging
198 /// candidate again.
200
201 // BatchAA - Used for DAG load/store alias analysis.
202 BatchAAResults *BatchAA;
203
204 /// This caches all chains that have already been processed in
205 /// DAGCombiner::getStoreMergeCandidates() and found to have no mergeable
206 /// stores candidates.
207 SmallPtrSet<SDNode *, 4> ChainsWithoutMergeableStores;
208
209 /// When an instruction is simplified, add all users of the instruction to
210 /// the work lists because they might get more simplified now.
211 void AddUsersToWorklist(SDNode *N) {
212 for (SDNode *Node : N->users())
213 AddToWorklist(Node);
214 }
215
216 /// Convenient shorthand to add a node and all of its user to the worklist.
217 void AddToWorklistWithUsers(SDNode *N) {
218 AddUsersToWorklist(N);
219 AddToWorklist(N);
220 }
221
222 // Prune potentially dangling nodes. This is called after
223 // any visit to a node, but should also be called during a visit after any
224 // failed combine which may have created a DAG node.
225 void clearAddedDanglingWorklistEntries() {
226 // Check any nodes added to the worklist to see if they are prunable.
227 while (!PruningList.empty()) {
228 auto *N = PruningList.pop_back_val();
229 if (N->use_empty())
230 recursivelyDeleteUnusedNodes(N);
231 }
232 }
233
234 SDNode *getNextWorklistEntry() {
235 // Before we do any work, remove nodes that are not in use.
236 clearAddedDanglingWorklistEntries();
237 SDNode *N = nullptr;
238 // The Worklist holds the SDNodes in order, but it may contain null
239 // entries.
240 while (!N && !Worklist.empty()) {
241 N = Worklist.pop_back_val();
242 }
243
244 if (N) {
245 assert(N->getCombinerWorklistIndex() >= 0 &&
246 "Found a worklist entry without a corresponding map entry!");
247 // Set to -2 to indicate that we combined the node.
248 N->setCombinerWorklistIndex(-2);
249 }
250 return N;
251 }
252
253 /// Call the node-specific routine that folds each particular type of node.
254 SDValue visit(SDNode *N);
255
256 public:
257 DAGCombiner(SelectionDAG &D, BatchAAResults *BatchAA, CodeGenOptLevel OL)
258 : DAG(D), TLI(D.getTargetLoweringInfo()),
259 STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL),
260 BatchAA(BatchAA) {
261 ForCodeSize = DAG.shouldOptForSize();
262 DisableGenericCombines =
263 DisableCombines || (STI && STI->disableGenericCombines(OptLevel));
264 }
265
266 void ConsiderForPruning(SDNode *N) {
267 // Mark this for potential pruning.
268 PruningList.insert(N);
269 }
270
271 /// Add to the worklist making sure its instance is at the back (next to be
272 /// processed.)
273 void AddToWorklist(SDNode *N, bool IsCandidateForPruning = true,
274 bool SkipIfCombinedBefore = false) {
275 assert(N->getOpcode() != ISD::DELETED_NODE &&
276 "Deleted Node added to Worklist");
277
278 // Skip handle nodes as they can't usefully be combined and confuse the
279 // zero-use deletion strategy.
280 if (N->getOpcode() == ISD::HANDLENODE)
281 return;
282
283 if (SkipIfCombinedBefore && N->getCombinerWorklistIndex() == -2)
284 return;
285
286 if (IsCandidateForPruning)
287 ConsiderForPruning(N);
288
289 if (N->getCombinerWorklistIndex() < 0) {
290 N->setCombinerWorklistIndex(Worklist.size());
291 Worklist.push_back(N);
292 }
293 }
294
295 /// Remove all instances of N from the worklist.
296 void removeFromWorklist(SDNode *N) {
297 PruningList.remove(N);
298 StoreRootCountMap.erase(N);
299
300 int WorklistIndex = N->getCombinerWorklistIndex();
301 // If not in the worklist, the index might be -1 or -2 (was combined
302 // before). As the node gets deleted anyway, there's no need to update
303 // the index.
304 if (WorklistIndex < 0)
305 return; // Not in the worklist.
306
307 // Null out the entry rather than erasing it to avoid a linear operation.
308 Worklist[WorklistIndex] = nullptr;
309 N->setCombinerWorklistIndex(-1);
310 }
311
312 void deleteAndRecombine(SDNode *N);
313 bool recursivelyDeleteUnusedNodes(SDNode *N);
314
315 /// Replaces all uses of the results of one DAG node with new values.
316 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
317 bool AddTo = true);
318
319 /// Replaces all uses of the results of one DAG node with new values.
320 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
321 return CombineTo(N, &Res, 1, AddTo);
322 }
323
324 /// Replaces all uses of the results of one DAG node with new values.
325 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
326 bool AddTo = true) {
327 SDValue To[] = { Res0, Res1 };
328 return CombineTo(N, To, 2, AddTo);
329 }
330
331 SDValue CombineTo(SDNode *N, SmallVectorImpl<SDValue> *To,
332 bool AddTo = true) {
333 return CombineTo(N, To->data(), To->size(), AddTo);
334 }
335
336 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
337
338 private:
339 /// Check the specified integer node value to see if it can be simplified or
340 /// if things it uses can be simplified by bit propagation.
341 /// If so, return true.
342 bool SimplifyDemandedBits(SDValue Op) {
343 unsigned BitWidth = Op.getScalarValueSizeInBits();
344 APInt DemandedBits = APInt::getAllOnes(BitWidth);
345 return SimplifyDemandedBits(Op, DemandedBits);
346 }
347
348 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
349 EVT VT = Op.getValueType();
350 APInt DemandedElts = VT.isFixedLengthVector()
352 : APInt(1, 1);
353 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, false);
354 }
355
356 /// Check the specified vector node value to see if it can be simplified or
357 /// if things it uses can be simplified as it only uses some of the
358 /// elements. If so, return true.
359 bool SimplifyDemandedVectorElts(SDValue Op) {
360 // TODO: For now just pretend it cannot be simplified.
361 if (Op.getValueType().isScalableVector())
362 return false;
363
364 unsigned NumElts = Op.getValueType().getVectorNumElements();
365 APInt DemandedElts = APInt::getAllOnes(NumElts);
366 return SimplifyDemandedVectorElts(Op, DemandedElts);
367 }
368
369 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
370 const APInt &DemandedElts,
371 bool AssumeSingleUse = false);
372 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
373 bool AssumeSingleUse = false);
374
375 bool CombineToPreIndexedLoadStore(SDNode *N);
376 bool CombineToPostIndexedLoadStore(SDNode *N);
377 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
378 bool SliceUpLoad(SDNode *N);
379
380 // Looks up the chain to find a unique (unaliased) store feeding the passed
381 // load. If no such store is found, returns a nullptr.
382 // Note: This will look past a CALLSEQ_START if the load is chained to it so
383 // so that it can find stack stores for byval params.
384 StoreSDNode *getUniqueStoreFeeding(LoadSDNode *LD, int64_t &Offset);
385 // Scalars have size 0 to distinguish from singleton vectors.
386 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
387 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
388 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
389
390 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
391 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
392 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
393 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
394 SDValue PromoteIntBinOp(SDValue Op);
395 SDValue PromoteIntShiftOp(SDValue Op);
396 SDValue PromoteExtend(SDValue Op);
397 bool PromoteLoad(SDValue Op);
398
399 SDValue foldShiftToAvg(SDNode *N, const SDLoc &DL);
400 // Fold `a bitwiseop (~b +/- c)` -> `a bitwiseop ~(b -/+ c)`
401 SDValue foldBitwiseOpWithNeg(SDNode *N, const SDLoc &DL, EVT VT);
402
403 SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
404 SDValue RHS, SDValue True, SDValue False,
405 ISD::CondCode CC);
406
407 /// Call the node-specific routine that knows how to fold each
408 /// particular type of node. If that doesn't do anything, try the
409 /// target-specific DAG combines.
410 SDValue combine(SDNode *N);
411
412 // Visitation implementation - Implement dag node combining for different
413 // node types. The semantics are as follows:
414 // Return Value:
415 // SDValue.getNode() == 0 - No change was made
416 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
417 // otherwise - N should be replaced by the returned Operand.
418 //
419 SDValue visitTokenFactor(SDNode *N);
420 SDValue visitMERGE_VALUES(SDNode *N);
421 SDValue visitADD(SDNode *N);
422 SDValue visitADDLike(SDNode *N);
423 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, const SDLoc &DL);
424 SDValue visitPTRADD(SDNode *N);
425 SDValue visitSUB(SDNode *N);
426 SDValue visitADDSAT(SDNode *N);
427 SDValue visitSUBSAT(SDNode *N);
428 SDValue visitADDC(SDNode *N);
429 SDValue visitADDO(SDNode *N);
430 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
431 SDValue visitSUBC(SDNode *N);
432 SDValue visitSUBO(SDNode *N);
433 SDValue visitADDE(SDNode *N);
434 SDValue visitUADDO_CARRY(SDNode *N);
435 SDValue visitSADDO_CARRY(SDNode *N);
436 SDValue visitUADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
437 SDNode *N);
438 SDValue visitSADDO_CARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
439 SDNode *N);
440 SDValue visitSUBE(SDNode *N);
441 SDValue visitUSUBO_CARRY(SDNode *N);
442 SDValue visitSSUBO_CARRY(SDNode *N);
443 SDValue visitMUL(SDNode *N);
444 SDValue visitMULFIX(SDNode *N);
445 SDValue useDivRem(SDNode *N);
446 SDValue visitSDIV(SDNode *N);
447 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
448 SDValue visitUDIV(SDNode *N);
449 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
450 SDValue visitREM(SDNode *N);
451 SDValue visitMULHU(SDNode *N);
452 SDValue visitMULHS(SDNode *N);
453 SDValue visitAVG(SDNode *N);
454 SDValue visitABD(SDNode *N);
455 SDValue visitSMUL_LOHI(SDNode *N);
456 SDValue visitUMUL_LOHI(SDNode *N);
457 SDValue visitMULO(SDNode *N);
458 SDValue visitIMINMAX(SDNode *N);
459 SDValue visitAND(SDNode *N);
460 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
461 SDValue visitOR(SDNode *N);
462 SDValue visitORLike(SDValue N0, SDValue N1, const SDLoc &DL);
463 SDValue visitXOR(SDNode *N);
464 SDValue SimplifyVCastOp(SDNode *N, const SDLoc &DL);
465 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
466 SDValue visitSHL(SDNode *N);
467 SDValue visitSRA(SDNode *N);
468 SDValue visitSRL(SDNode *N);
469 SDValue visitFunnelShift(SDNode *N);
470 SDValue visitSHLSAT(SDNode *N);
471 SDValue visitRotate(SDNode *N);
472 SDValue visitABS(SDNode *N);
473 SDValue visitABS_MIN_POISON(SDNode *N);
474 SDValue visitCLMUL(SDNode *N);
475 SDValue visitPEXT(SDNode *N);
476 SDValue visitPDEP(SDNode *N);
477 SDValue visitBSWAP(SDNode *N);
478 SDValue visitBITREVERSE(SDNode *N);
479 SDValue visitCTLZ(SDNode *N);
480 SDValue visitCTLZ_ZERO_POISON(SDNode *N);
481 SDValue visitCTTZ(SDNode *N);
482 SDValue visitCTTZ_ZERO_POISON(SDNode *N);
483 SDValue visitCTPOP(SDNode *N);
484 SDValue visitSELECT(SDNode *N);
485 SDValue visitVSELECT(SDNode *N);
486 SDValue visitSELECT_CC(SDNode *N);
487 SDValue visitSETCC(SDNode *N);
488 SDValue visitSETCCCARRY(SDNode *N);
489 SDValue visitSIGN_EXTEND(SDNode *N);
490 SDValue visitZERO_EXTEND(SDNode *N);
491 SDValue visitANY_EXTEND(SDNode *N);
492 SDValue visitAssertExt(SDNode *N);
493 SDValue visitAssertAlign(SDNode *N);
494 SDValue visitIS_FPCLASS(SDNode *N);
495 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
496 SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
497 SDValue visitTRUNCATE(SDNode *N);
498 SDValue visitTRUNCATE_USAT_U(SDNode *N);
499 SDValue visitBITCAST(SDNode *N);
500 SDValue visitFREEZE(SDNode *N);
501 SDValue visitBUILD_PAIR(SDNode *N);
502 SDValue visitFADD(SDNode *N);
503 SDValue visitSTRICT_FADD(SDNode *N);
504 SDValue visitFSUB(SDNode *N);
505 SDValue visitFMUL(SDNode *N);
506 SDValue visitFMA(SDNode *N);
507 SDValue visitFMAD(SDNode *N);
508 SDValue visitFMULADD(SDNode *N);
509 SDValue visitFDIV(SDNode *N);
510 SDValue visitFREM(SDNode *N);
511 SDValue visitFSQRT(SDNode *N);
512 SDValue visitFCOPYSIGN(SDNode *N);
513 SDValue visitFPOW(SDNode *N);
514 SDValue visitFCANONICALIZE(SDNode *N);
515 SDValue visitSINT_TO_FP(SDNode *N);
516 SDValue visitUINT_TO_FP(SDNode *N);
517 SDValue visitFP_TO_SINT(SDNode *N);
518 SDValue visitFP_TO_UINT(SDNode *N);
519 SDValue visitXROUND(SDNode *N);
520 SDValue visitFP_ROUND(SDNode *N);
521 SDValue visitFP_EXTEND(SDNode *N);
522 SDValue visitFNEG(SDNode *N);
523 SDValue visitFABS(SDNode *N);
524 SDValue visitFCEIL(SDNode *N);
525 SDValue visitFTRUNC(SDNode *N);
526 SDValue visitFFREXP(SDNode *N);
527 SDValue visitFFLOOR(SDNode *N);
528 SDValue visitFMinMax(SDNode *N);
529 SDValue visitBRCOND(SDNode *N);
530 SDValue visitBR_CC(SDNode *N);
531 SDValue visitLOAD(SDNode *N);
532
533 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
534 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
535 SDValue replaceStoreOfInsertLoad(StoreSDNode *ST);
536
537 bool refineExtractVectorEltIntoMultipleNarrowExtractVectorElts(SDNode *N);
538 SDValue combineStoreConcatTruncVector(StoreSDNode *N);
539 SDValue visitSTORE(SDNode *N);
540 SDValue visitATOMIC_STORE(SDNode *N);
541 SDValue visitLIFETIME_END(SDNode *N);
542 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
543 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
544 SDValue visitBUILD_VECTOR(SDNode *N);
545 SDValue visitCONCAT_VECTORS(SDNode *N);
546 SDValue visitVECTOR_INTERLEAVE(SDNode *N);
547 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
548 SDValue visitVECTOR_SHUFFLE(SDNode *N);
549 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
550 SDValue visitINSERT_SUBVECTOR(SDNode *N);
551 SDValue visitVECTOR_COMPRESS(SDNode *N);
552 SDValue visitMLOAD(SDNode *N);
553 SDValue visitMSTORE(SDNode *N);
554 SDValue visitMGATHER(SDNode *N);
555 SDValue visitMSCATTER(SDNode *N);
556 SDValue visitMHISTOGRAM(SDNode *N);
557 SDValue visitPARTIAL_REDUCE_MLA(SDNode *N);
558 SDValue visitLOOP_DEPENDENCE_MASK(SDNode *N);
559 SDValue visitVPGATHER(SDNode *N);
560 SDValue visitVPSCATTER(SDNode *N);
561 SDValue visitVP_STRIDED_LOAD(SDNode *N);
562 SDValue visitVP_STRIDED_STORE(SDNode *N);
563 SDValue visitFP_TO_FP16(SDNode *N);
564 SDValue visitFP16_TO_FP(SDNode *N);
565 SDValue visitFP_TO_BF16(SDNode *N);
566 SDValue visitBF16_TO_FP(SDNode *N);
567 SDValue visitVECREDUCE(SDNode *N);
568 SDValue visitVPOp(SDNode *N);
569 SDValue visitGET_FPENV_MEM(SDNode *N);
570 SDValue visitSET_FPENV_MEM(SDNode *N);
571
572 SDValue visitFADDForFMACombine(SDNode *N);
573 SDValue visitFSUBForFMACombine(SDNode *N);
574 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
575
576 SDValue XformToShuffleWithZero(SDNode *N);
577 bool reassociationCanBreakAddressingModePattern(unsigned Opc,
578 const SDLoc &DL,
579 SDNode *N,
580 SDValue N0,
581 SDValue N1);
582 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
583 SDValue N1, SDNodeFlags Flags);
584 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
585 SDValue N1, SDNodeFlags Flags);
586 SDValue reassociateReduction(unsigned RedOpc, unsigned Opc, const SDLoc &DL,
587 EVT VT, SDValue N0, SDValue N1,
588 SDNodeFlags Flags = SDNodeFlags());
589
590 SDValue visitShiftByConstant(SDNode *N);
591
592 SDValue foldSelectOfConstants(SDNode *N);
593 SDValue foldVSelectOfConstants(SDNode *N);
594 SDValue foldBinOpIntoSelect(SDNode *BO);
595 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
596 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
597 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
598 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
599 SDValue N2, SDValue N3, ISD::CondCode CC,
600 bool NotExtCompare = false);
601 SDValue convertSelectOfFPConstantsToLoadOffset(
602 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
603 ISD::CondCode CC);
604 SDValue foldSignChangeInBitcast(SDNode *N);
605 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
606 SDValue N2, SDValue N3, ISD::CondCode CC);
607 SDValue foldSelectOfBinops(SDNode *N);
608 SDValue foldSextSetcc(SDNode *N);
609 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
610 const SDLoc &DL);
611 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL);
612 SDValue foldABSToABD(SDNode *N, const SDLoc &DL);
613 SDValue foldSelectToABD(SDValue LHS, SDValue RHS, SDValue True,
614 SDValue False, ISD::CondCode CC, const SDLoc &DL);
615 SDValue foldSelectToUMin(SDValue LHS, SDValue RHS, SDValue True,
616 SDValue False, ISD::CondCode CC, const SDLoc &DL);
617 SDValue unfoldMaskedMerge(SDNode *N);
618 SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
619 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
620 const SDLoc &DL, bool foldBooleans);
621 SDValue rebuildSetCC(SDValue N);
622
623 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
624 SDValue &CC, bool MatchStrict = false) const;
625 bool isOneUseSetCC(SDValue N) const;
626
627 SDValue foldAddToAvg(SDNode *N, const SDLoc &DL);
628 SDValue foldSubToAvg(SDNode *N, const SDLoc &DL);
629
630 SDValue foldCTLZToCTLS(SDValue Src, const SDLoc &DL);
631
632 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
633 unsigned HiOp);
634 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
635 SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
636 const TargetLowering &TLI);
637 SDValue foldPartialReduceMLAMulOp(SDNode *N);
638 SDValue foldPartialReduceAdd(SDNode *N);
639
640 SDValue CombineExtLoad(SDNode *N);
641 SDValue CombineZExtLogicopShiftLoad(SDNode *N);
642 SDValue combineRepeatedFPDivisors(SDNode *N);
643 SDValue combineFMulOrFDivWithIntPow2(SDNode *N);
644 SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf);
645 SDValue mergeInsertEltWithShuffle(SDNode *N, unsigned InsIndex);
646 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
647 SDValue combineInsertEltToLoad(SDNode *N, unsigned InsIndex);
648 SDValue foldExtractSubvectorFromConcatVectors(EVT VT, SDValue V,
649 uint64_t ExtIdx,
650 const SDLoc &DL);
651 SDValue BuildSDIV(SDNode *N);
652 SDValue BuildSDIVPow2(SDNode *N);
653 SDValue BuildUDIV(SDNode *N);
654 SDValue BuildSREMPow2(SDNode *N);
655 SDValue buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N);
656 SDValue BuildLogBase2(SDValue V, const SDLoc &DL,
657 bool KnownNeverZero = false,
658 bool InexpensiveOnly = false,
659 std::optional<EVT> OutVT = std::nullopt);
660 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
661 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
662 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
663 SDValue buildSqrtEstimateImpl(SDValue Op, bool Recip, SDNodeFlags Flags);
664 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
665 bool Reciprocal);
666 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
667 bool Reciprocal);
668 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
669 bool DemandHighBits = true);
670 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
671 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
672 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
673 bool HasPos, unsigned PosOpcode,
674 unsigned NegOpcode, const SDLoc &DL);
675 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
676 SDValue InnerPos, SDValue InnerNeg, bool FromAdd,
677 bool HasPos, unsigned PosOpcode,
678 unsigned NegOpcode, const SDLoc &DL);
679 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL,
680 bool FromAdd);
681 SDValue MatchLoadCombine(SDNode *N);
682 SDValue mergeTruncStores(StoreSDNode *N);
683 SDValue reduceLoadWidth(SDNode *N);
684 SDValue ReduceLoadOpStoreWidth(SDNode *N);
685 SDValue splitMergedValStore(StoreSDNode *ST);
686 SDValue TransformFPLoadStorePair(SDNode *N);
687 SDValue convertBuildVecExtToExt(SDNode *N);
688 SDValue convertBuildVecZextToBuildVecWithZeros(SDNode *N);
689 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
690 SDValue reduceBuildVecTruncToBitCast(SDNode *N);
691 SDValue reduceBuildVecToShuffle(SDNode *N);
692 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
693 ArrayRef<int> VectorMask, SDValue VecIn1,
694 SDValue VecIn2, unsigned LeftIdx,
695 bool DidSplitVec);
696 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
697
698 /// Walk up chain skipping non-aliasing memory nodes,
699 /// looking for aliasing nodes and adding them to the Aliases vector.
700 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
701 SmallVectorImpl<SDValue> &Aliases);
702
703 /// Return true if there is any possibility that the two addresses overlap.
704 bool mayAlias(SDNode *Op0, SDNode *Op1) const;
705
706 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
707 /// chain (aliasing node.)
708 SDValue FindBetterChain(SDNode *N, SDValue Chain);
709
710 /// Try to replace a store and any possibly adjacent stores on
711 /// consecutive chains with better chains. Return true only if St is
712 /// replaced.
713 ///
714 /// Notice that other chains may still be replaced even if the function
715 /// returns false.
716 bool findBetterNeighborChains(StoreSDNode *St);
717
718 // Helper for findBetterNeighborChains. Walk up store chain add additional
719 // chained stores that do not overlap and can be parallelized.
720 bool parallelizeChainedStores(StoreSDNode *St);
721
722 /// Holds a pointer to an LSBaseSDNode as well as information on where it
723 /// is located in a sequence of memory operations connected by a chain.
724 struct MemOpLink {
725 // Ptr to the mem node.
726 LSBaseSDNode *MemNode;
727
728 // Offset from the base ptr.
729 int64_t OffsetFromBase;
730
731 MemOpLink(LSBaseSDNode *N, int64_t Offset)
732 : MemNode(N), OffsetFromBase(Offset) {}
733 };
734
735 // Classify the origin of a stored value.
736 enum class StoreSource { Unknown, Constant, Extract, Load };
737 StoreSource getStoreSource(SDValue StoreVal) {
738 switch (StoreVal.getOpcode()) {
739 case ISD::Constant:
740 case ISD::ConstantFP:
741 return StoreSource::Constant;
745 return StoreSource::Constant;
746 return StoreSource::Unknown;
749 return StoreSource::Extract;
750 case ISD::LOAD:
751 return StoreSource::Load;
752 default:
753 return StoreSource::Unknown;
754 }
755 }
756
757 /// This is a helper function for visitMUL to check the profitability
758 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
759 /// MulNode is the original multiply, AddNode is (add x, c1),
760 /// and ConstNode is c2.
761 bool isMulAddWithConstProfitable(SDNode *MulNode, SDValue AddNode,
762 SDValue ConstNode);
763
764 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
765 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
766 /// the type of the loaded value to be extended.
767 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
768 EVT LoadResultTy, EVT &ExtVT);
769
770 /// Helper function to calculate whether the given Load/Store can have its
771 /// width reduced to ExtVT.
772 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
773 EVT &MemVT, unsigned ShAmt = 0);
774
775 /// Used by BackwardsPropagateMask to find suitable loads.
776 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
777 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
778 ConstantSDNode *Mask, SDNode *&NodeToMask);
779 /// Attempt to propagate a given AND node back to load leaves so that they
780 /// can be combined into narrow loads.
781 bool BackwardsPropagateMask(SDNode *N);
782
783 /// Helper function for mergeConsecutiveStores which merges the component
784 /// store chains.
785 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
786 unsigned NumStores);
787
788 /// Helper function for mergeConsecutiveStores which checks if all the store
789 /// nodes have the same underlying object. We can still reuse the first
790 /// store's pointer info if all the stores are from the same object.
791 bool hasSameUnderlyingObj(ArrayRef<MemOpLink> StoreNodes);
792
793 /// This is a helper function for mergeConsecutiveStores. When the source
794 /// elements of the consecutive stores are all constants or all extracted
795 /// vector elements, try to merge them into one larger store introducing
796 /// bitcasts if necessary. \return True if a merged store was created.
797 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
798 EVT MemVT, unsigned NumStores,
799 bool IsConstantSrc, bool UseVector,
800 bool UseTrunc);
801
802 /// This is a helper function for mergeConsecutiveStores. Stores that
803 /// potentially may be merged with St are placed in StoreNodes. On success,
804 /// returns a chain predecessor to all store candidates.
805 SDNode *getStoreMergeCandidates(StoreSDNode *St,
806 SmallVectorImpl<MemOpLink> &StoreNodes);
807
808 /// Helper function for mergeConsecutiveStores. Checks if candidate stores
809 /// have indirect dependency through their operands. RootNode is the
810 /// predecessor to all stores calculated by getStoreMergeCandidates and is
811 /// used to prune the dependency check. \return True if safe to merge.
812 bool checkMergeStoreCandidatesForDependencies(
813 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
814 SDNode *RootNode);
815
816 /// Helper function for tryStoreMergeOfLoads. Checks if the load/store
817 /// chain has a call in it. \return True if a call is found.
818 bool hasCallInLdStChain(StoreSDNode *St, LoadSDNode *Ld);
819
820 /// This is a helper function for mergeConsecutiveStores. Given a list of
821 /// store candidates, find the first N that are consecutive in memory.
822 /// Returns 0 if there are not at least 2 consecutive stores to try merging.
823 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
824 int64_t ElementSizeBytes) const;
825
826 /// This is a helper function for mergeConsecutiveStores. It is used for
827 /// store chains that are composed entirely of constant values.
828 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
829 unsigned NumConsecutiveStores,
830 EVT MemVT, SDNode *Root, bool AllowVectors);
831
832 /// This is a helper function for mergeConsecutiveStores. It is used for
833 /// store chains that are composed entirely of extracted vector elements.
834 /// When extracting multiple vector elements, try to store them in one
835 /// vector store rather than a sequence of scalar stores.
836 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
837 unsigned NumConsecutiveStores, EVT MemVT,
838 SDNode *Root);
839
840 /// This is a helper function for mergeConsecutiveStores. It is used for
841 /// store chains that are composed entirely of loaded values.
842 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
843 unsigned NumConsecutiveStores, EVT MemVT,
844 SDNode *Root, bool AllowVectors,
845 bool IsNonTemporalStore, bool IsNonTemporalLoad);
846
847 /// Merge consecutive store operations into a wide store.
848 /// This optimization uses wide integers or vectors when possible.
849 /// \return true if stores were merged.
850 bool mergeConsecutiveStores(StoreSDNode *St);
851
852 /// Try to transform a truncation where C is a constant:
853 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
854 ///
855 /// \p N needs to be a truncation and its first operand an AND. Other
856 /// requirements are checked by the function (e.g. that trunc is
857 /// single-use) and if missed an empty SDValue is returned.
858 SDValue distributeTruncateThroughAnd(SDNode *N);
859
860 /// Helper function to determine whether the target supports operation
861 /// given by \p Opcode for type \p VT, that is, whether the operation
862 /// is legal or custom before legalizing operations, and whether is
863 /// legal (but not custom) after legalization.
864 bool hasOperation(unsigned Opcode, EVT VT) {
865 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
866 }
867
868 bool hasUMin(EVT VT) const {
869 auto LK = TLI.getTypeConversion(*DAG.getContext(), VT);
870 return (LK.first == TargetLoweringBase::TypeLegal ||
872 TLI.isOperationLegalOrCustom(ISD::UMIN, LK.second);
873 }
874
875 public:
876 /// Runs the dag combiner on all nodes in the work list
877 void Run(CombineLevel AtLevel);
878
879 SelectionDAG &getDAG() const { return DAG; }
880
881 /// Convenience wrapper around TargetLowering::getShiftAmountTy.
882 EVT getShiftAmountTy(EVT LHSTy) {
883 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout());
884 }
885
886 /// This method returns true if we are running before type legalization or
887 /// if the specified VT is legal.
888 bool isTypeLegal(const EVT &VT) {
889 if (!LegalTypes) return true;
890 return TLI.isTypeLegal(VT);
891 }
892
893 /// Convenience wrapper around TargetLowering::getSetCCResultType
894 EVT getSetCCResultType(EVT VT) const {
895 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
896 }
897
898 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
899 SDValue OrigLoad, SDValue ExtLoad,
900 ISD::NodeType ExtType);
901 };
902
903/// This class is a DAGUpdateListener that removes any deleted
904/// nodes from the worklist.
905class WorklistRemover : public SelectionDAG::DAGUpdateListener {
906 DAGCombiner &DC;
907
908public:
909 explicit WorklistRemover(DAGCombiner &dc)
910 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
911
912 void NodeDeleted(SDNode *N, SDNode *E) override {
913 DC.removeFromWorklist(N);
914 }
915};
916
917class WorklistInserter : public SelectionDAG::DAGUpdateListener {
918 DAGCombiner &DC;
919
920public:
921 explicit WorklistInserter(DAGCombiner &dc)
922 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
923
924 // FIXME: Ideally we could add N to the worklist, but this causes exponential
925 // compile time costs in large DAGs, e.g. Halide.
926 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
927};
928
929} // end anonymous namespace
930
931//===----------------------------------------------------------------------===//
932// TargetLowering::DAGCombinerInfo implementation
933//===----------------------------------------------------------------------===//
934
936 ((DAGCombiner*)DC)->AddToWorklist(N);
937}
938
940CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
941 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
942}
943
945CombineTo(SDNode *N, SDValue Res, bool AddTo) {
946 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
947}
948
950CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
951 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
952}
953
956 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
957}
958
961 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
962}
963
964//===----------------------------------------------------------------------===//
965// Helper Functions
966//===----------------------------------------------------------------------===//
967
968void DAGCombiner::deleteAndRecombine(SDNode *N) {
969 removeFromWorklist(N);
970
971 // If the operands of this node are only used by the node, they will now be
972 // dead. Make sure to re-visit them and recursively delete dead nodes.
973 for (const SDValue &Op : N->ops())
974 // For an operand generating multiple values, one of the values may
975 // become dead allowing further simplification (e.g. split index
976 // arithmetic from an indexed load).
977 if (Op->hasOneUse() || Op->getNumValues() > 1)
978 AddToWorklist(Op.getNode());
979
980 DAG.DeleteNode(N);
981}
982
983// APInts must be the same size for most operations, this helper
984// function zero extends the shorter of the pair so that they match.
985// We provide an Offset so that we can create bitwidths that won't overflow.
986static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
987 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
988 LHS = LHS.zext(Bits);
989 RHS = RHS.zext(Bits);
990}
991
992// Return true if this node is a setcc, or is a select_cc
993// that selects between the target values used for true and false, making it
994// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
995// the appropriate nodes based on the type of node we are checking. This
996// simplifies life a bit for the callers.
997bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
998 SDValue &CC, bool MatchStrict) const {
999 if (N.getOpcode() == ISD::SETCC) {
1000 LHS = N.getOperand(0);
1001 RHS = N.getOperand(1);
1002 CC = N.getOperand(2);
1003 return true;
1004 }
1005
1006 if (MatchStrict &&
1007 (N.getOpcode() == ISD::STRICT_FSETCC ||
1008 N.getOpcode() == ISD::STRICT_FSETCCS)) {
1009 LHS = N.getOperand(1);
1010 RHS = N.getOperand(2);
1011 CC = N.getOperand(3);
1012 return true;
1013 }
1014
1015 if (N.getOpcode() != ISD::SELECT_CC || !TLI.isConstTrueVal(N.getOperand(2)) ||
1016 !TLI.isConstFalseVal(N.getOperand(3)))
1017 return false;
1018
1019 if (TLI.getBooleanContents(N.getValueType()) ==
1021 return false;
1022
1023 LHS = N.getOperand(0);
1024 RHS = N.getOperand(1);
1025 CC = N.getOperand(4);
1026 return true;
1027}
1028
1029/// Return true if this is a SetCC-equivalent operation with only one use.
1030/// If this is true, it allows the users to invert the operation for free when
1031/// it is profitable to do so.
1032bool DAGCombiner::isOneUseSetCC(SDValue N) const {
1033 SDValue N0, N1, N2;
1034 if (isSetCCEquivalent(N, N0, N1, N2) && N->hasOneUse())
1035 return true;
1036 return false;
1037}
1038
1040 if (!ScalarTy.isSimple())
1041 return false;
1042
1043 uint64_t MaskForTy = 0ULL;
1044 switch (ScalarTy.getSimpleVT().SimpleTy) {
1045 case MVT::i8:
1046 MaskForTy = 0xFFULL;
1047 break;
1048 case MVT::i16:
1049 MaskForTy = 0xFFFFULL;
1050 break;
1051 case MVT::i32:
1052 MaskForTy = 0xFFFFFFFFULL;
1053 break;
1054 default:
1055 return false;
1056 break;
1057 }
1058
1059 APInt Val;
1060 if (ISD::isConstantSplatVector(N, Val))
1061 return Val.getLimitedValue() == MaskForTy;
1062
1063 return false;
1064}
1065
1066// Determines if it is a constant integer or a splat/build vector of constant
1067// integers (and undefs).
1068// Do not permit build vector implicit truncation unless AllowTruncation is set.
1069static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false,
1070 bool AllowTruncation = false) {
1072 return !(Const->isOpaque() && NoOpaques);
1073 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
1074 return false;
1075 unsigned BitWidth = N.getScalarValueSizeInBits();
1076 for (const SDValue &Op : N->op_values()) {
1077 if (Op.isUndef())
1078 continue;
1080 if (!Const || (Const->isOpaque() && NoOpaques))
1081 return false;
1082 // When AllowTruncation is true, allow constants that have been promoted
1083 // during type legalization as long as the value fits in the target type.
1084 if ((AllowTruncation &&
1085 Const->getAPIntValue().getActiveBits() > BitWidth) ||
1086 (!AllowTruncation && Const->getAPIntValue().getBitWidth() != BitWidth))
1087 return false;
1088 }
1089 return true;
1090}
1091
1092// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1093// undef's.
1094static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
1095 if (V.getOpcode() != ISD::BUILD_VECTOR)
1096 return false;
1097 return isConstantOrConstantVector(V, NoOpaques) ||
1099}
1100
1101// Determine if this an indexed load with an opaque target constant index.
1102static bool canSplitIdx(LoadSDNode *LD) {
1103 return MaySplitLoadIndex &&
1104 (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
1105 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
1106}
1107
1108bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
1109 const SDLoc &DL,
1110 SDNode *N,
1111 SDValue N0,
1112 SDValue N1) {
1113 // Currently this only tries to ensure we don't undo the GEP splits done by
1114 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1115 // we check if the following transformation would be problematic:
1116 // (load/store (add, (add, x, offset1), offset2)) ->
1117 // (load/store (add, x, offset1+offset2)).
1118
1119 // (load/store (add, (add, x, y), offset2)) ->
1120 // (load/store (add, (add, x, offset2), y)).
1121
1122 if (!N0.isAnyAdd())
1123 return false;
1124
1125 // Check for vscale addressing modes.
1126 // (load/store (add/sub (add x, y), vscale))
1127 // (load/store (add/sub (add x, y), (lsl vscale, C)))
1128 // (load/store (add/sub (add x, y), (mul vscale, C)))
1129 if ((N1.getOpcode() == ISD::VSCALE ||
1130 ((N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::MUL) &&
1131 N1.getOperand(0).getOpcode() == ISD::VSCALE &&
1133 N1.getValueType().getFixedSizeInBits() <= 64) {
1134 int64_t ScalableOffset = N1.getOpcode() == ISD::VSCALE
1135 ? N1.getConstantOperandVal(0)
1136 : (N1.getOperand(0).getConstantOperandVal(0) *
1137 (N1.getOpcode() == ISD::SHL
1138 ? (1LL << N1.getConstantOperandVal(1))
1139 : N1.getConstantOperandVal(1)));
1140 if (Opc == ISD::SUB)
1141 ScalableOffset = -ScalableOffset;
1142 if (all_of(N->users(), [&](SDNode *Node) {
1143 if (auto *LoadStore = dyn_cast<MemSDNode>(Node);
1144 LoadStore && LoadStore->hasUniqueMemOperand() &&
1145 LoadStore->getBasePtr().getNode() == N) {
1146 TargetLoweringBase::AddrMode AM;
1147 AM.HasBaseReg = true;
1148 AM.ScalableOffset = ScalableOffset;
1149 EVT VT = LoadStore->getMemoryVT();
1150 unsigned AS = LoadStore->getAddressSpace();
1151 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1152 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy,
1153 AS);
1154 }
1155 return false;
1156 }))
1157 return true;
1158 }
1159
1160 if (Opc != ISD::ADD && Opc != ISD::PTRADD)
1161 return false;
1162
1163 auto *C2 = dyn_cast<ConstantSDNode>(N1);
1164 if (!C2)
1165 return false;
1166
1167 const APInt &C2APIntVal = C2->getAPIntValue();
1168 if (C2APIntVal.getSignificantBits() > 64)
1169 return false;
1170
1171 if (auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1172 if (N0.hasOneUse())
1173 return false;
1174
1175 const APInt &C1APIntVal = C1->getAPIntValue();
1176 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
1177 if (CombinedValueIntVal.getSignificantBits() > 64)
1178 return false;
1179 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
1180
1181 for (SDNode *Node : N->users()) {
1182 if (auto *LoadStore = dyn_cast<MemSDNode>(Node)) {
1183 if (!LoadStore->hasUniqueMemOperand())
1184 continue;
1185 // Is x[offset2] already not a legal addressing mode? If so then
1186 // reassociating the constants breaks nothing (we test offset2 because
1187 // that's the one we hope to fold into the load or store).
1188 TargetLoweringBase::AddrMode AM;
1189 AM.HasBaseReg = true;
1190 AM.BaseOffs = C2APIntVal.getSExtValue();
1191 EVT VT = LoadStore->getMemoryVT();
1192 unsigned AS = LoadStore->getAddressSpace();
1193 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1194 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1195 continue;
1196
1197 // Would x[offset1+offset2] still be a legal addressing mode?
1198 AM.BaseOffs = CombinedValue;
1199 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1200 return true;
1201 }
1202 }
1203 } else {
1204 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N0.getOperand(1)))
1205 if (GA->getOpcode() == ISD::GlobalAddress && TLI.isOffsetFoldingLegal(GA))
1206 return false;
1207
1208 for (SDNode *Node : N->users()) {
1209 auto *LoadStore = dyn_cast<MemSDNode>(Node);
1210 if (!LoadStore || !LoadStore->hasUniqueMemOperand())
1211 return false;
1212
1213 // Is x[offset2] a legal addressing mode? If so then
1214 // reassociating the constants breaks address pattern
1215 TargetLoweringBase::AddrMode AM;
1216 AM.HasBaseReg = true;
1217 AM.BaseOffs = C2APIntVal.getSExtValue();
1218 EVT VT = LoadStore->getMemoryVT();
1219 unsigned AS = LoadStore->getAddressSpace();
1220 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
1221 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
1222 return false;
1223 }
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// Helper for DAGCombiner::reassociateOps. Try to reassociate (Opc N0, N1) if
1231/// \p N0 is the same kind of operation as \p Opc.
1232SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
1233 SDValue N0, SDValue N1,
1234 SDNodeFlags Flags) {
1235 EVT VT = N0.getValueType();
1236
1237 if (N0.getOpcode() != Opc)
1238 return SDValue();
1239
1240 SDValue N00 = N0.getOperand(0);
1241 SDValue N01 = N0.getOperand(1);
1242
1244 SDNodeFlags NewFlags;
1245 if (N0.getOpcode() == ISD::ADD && N0->getFlags().hasNoUnsignedWrap() &&
1246 Flags.hasNoUnsignedWrap())
1247 NewFlags |= SDNodeFlags::NoUnsignedWrap;
1248
1250 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1251 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1})) {
1252 NewFlags.setDisjoint(Flags.hasDisjoint() &&
1253 N0->getFlags().hasDisjoint());
1254 return DAG.getNode(Opc, DL, VT, N00, OpNode, NewFlags);
1255 }
1256 return SDValue();
1257 }
1258 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1259 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1260 // iff (op x, c1) has one use
1261 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, NewFlags);
1262 return DAG.getNode(Opc, DL, VT, OpNode, N01, NewFlags);
1263 }
1264 }
1265
1266 // Check for repeated operand logic simplifications.
1267 if (Opc == ISD::AND || Opc == ISD::OR) {
1268 // (N00 & N01) & N00 --> N00 & N01
1269 // (N00 & N01) & N01 --> N00 & N01
1270 // (N00 | N01) | N00 --> N00 | N01
1271 // (N00 | N01) | N01 --> N00 | N01
1272 if (N1 == N00 || N1 == N01)
1273 return N0;
1274 }
1275 if (Opc == ISD::XOR) {
1276 // (N00 ^ N01) ^ N00 --> N01
1277 if (N1 == N00)
1278 return N01;
1279 // (N00 ^ N01) ^ N01 --> N00
1280 if (N1 == N01)
1281 return N00;
1282 }
1283
1284 if (TLI.isReassocProfitable(DAG, N0, N1)) {
1285 if (N1 != N01) {
1286 // Reassociate if (op N00, N1) already exist
1287 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N00, N1})) {
1288 // if Op (Op N00, N1), N01 already exist
1289 // we need to stop reassciate to avoid dead loop
1290 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N01}))
1291 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N01);
1292 }
1293 }
1294
1295 if (N1 != N00) {
1296 // Reassociate if (op N01, N1) already exist
1297 if (SDNode *NE = DAG.getNodeIfExists(Opc, DAG.getVTList(VT), {N01, N1})) {
1298 // if Op (Op N01, N1), N00 already exist
1299 // we need to stop reassciate to avoid dead loop
1300 if (!DAG.doesNodeExist(Opc, DAG.getVTList(VT), {SDValue(NE, 0), N00}))
1301 return DAG.getNode(Opc, DL, VT, SDValue(NE, 0), N00);
1302 }
1303 }
1304
1305 // Reassociate the operands from (OR/AND (OR/AND(N00, N001)), N1) to (OR/AND
1306 // (OR/AND(N00, N1)), N01) when N00 and N1 are comparisons with the same
1307 // predicate or to (OR/AND (OR/AND(N1, N01)), N00) when N01 and N1 are
1308 // comparisons with the same predicate. This enables optimizations as the
1309 // following one:
1310 // CMP(A,C)||CMP(B,C) => CMP(MIN/MAX(A,B), C)
1311 // CMP(A,C)&&CMP(B,C) => CMP(MIN/MAX(A,B), C)
1312 if (Opc == ISD::AND || Opc == ISD::OR) {
1313 if (N1->getOpcode() == ISD::SETCC && N00->getOpcode() == ISD::SETCC &&
1314 N01->getOpcode() == ISD::SETCC) {
1315 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
1316 ISD::CondCode CC00 = cast<CondCodeSDNode>(N00.getOperand(2))->get();
1317 ISD::CondCode CC01 = cast<CondCodeSDNode>(N01.getOperand(2))->get();
1318 if (CC1 == CC00 && CC1 != CC01) {
1319 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1, Flags);
1320 return DAG.getNode(Opc, DL, VT, OpNode, N01, Flags);
1321 }
1322 if (CC1 == CC01 && CC1 != CC00) {
1323 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N01, N1, Flags);
1324 return DAG.getNode(Opc, DL, VT, OpNode, N00, Flags);
1325 }
1326 }
1327 }
1328 }
1329
1330 return SDValue();
1331}
1332
1333/// Try to reassociate commutative (Opc N0, N1) if either \p N0 or \p N1 is the
1334/// same kind of operation as \p Opc.
1335SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
1336 SDValue N1, SDNodeFlags Flags) {
1337 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
1338
1339 // Floating-point reassociation is not allowed without loose FP math.
1340 if (N0.getValueType().isFloatingPoint() ||
1342 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
1343 return SDValue();
1344
1345 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1, Flags))
1346 return Combined;
1347 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0, Flags))
1348 return Combined;
1349 return SDValue();
1350}
1351
1352// Try to fold Opc(vecreduce(x), vecreduce(y)) -> vecreduce(Opc(x, y))
1353// Note that we only expect Flags to be passed from FP operations. For integer
1354// operations they need to be dropped.
1355SDValue DAGCombiner::reassociateReduction(unsigned RedOpc, unsigned Opc,
1356 const SDLoc &DL, EVT VT, SDValue N0,
1357 SDValue N1, SDNodeFlags Flags) {
1358 if (N0.getOpcode() == RedOpc && N1.getOpcode() == RedOpc &&
1359 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1360 N0->hasOneUse() && N1->hasOneUse() &&
1362 TLI.shouldReassociateReduction(RedOpc, N0.getOperand(0).getValueType())) {
1363 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
1364 return DAG.getNode(RedOpc, DL, VT,
1365 DAG.getNode(Opc, DL, N0.getOperand(0).getValueType(),
1366 N0.getOperand(0), N1.getOperand(0)));
1367 }
1368
1369 // Reassociate op(op(vecreduce(a), b), op(vecreduce(c), d)) into
1370 // op(vecreduce(op(a, c)), op(b, d)), to combine the reductions into a
1371 // single node.
1372 SDValue A, B, C, D, RedA, RedB;
1373 if (sd_match(N0,
1375 Opc, m_Value(RedA, m_OneUse(m_UnaryOp(RedOpc, m_Value(A)))),
1376 m_Value(B, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1377 sd_match(N1,
1379 Opc, m_Value(RedB, m_OneUse(m_UnaryOp(RedOpc, m_Value(C)))),
1380 m_Value(D, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) &&
1381 A.getValueType() == C.getValueType() &&
1382 hasOperation(Opc, A.getValueType()) &&
1383 TLI.shouldReassociateReduction(RedOpc, VT)) {
1384 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1385 (!N0->getFlags().hasAllowReassociation() ||
1387 !RedA->getFlags().hasAllowReassociation() ||
1388 !RedB->getFlags().hasAllowReassociation()))
1389 return SDValue();
1390 SelectionDAG::FlagInserter FlagsInserter(
1391 DAG, Flags & N0->getFlags() & N1->getFlags() & RedA->getFlags() &
1392 RedB->getFlags());
1393 SDValue Op = DAG.getNode(Opc, DL, A.getValueType(), A, C);
1394 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1395 SDValue Op2 = DAG.getNode(Opc, DL, VT, B, D);
1396 return DAG.getNode(Opc, DL, VT, Red, Op2);
1397 }
1398
1399 // Reassociate a reduction chain so two reductions become adjacent and the
1400 // folds above can merge them:
1401 // op(vecreduce(X), op(vecreduce(Y), Z))
1402 // -> op(vecreduce(op(X, Y)), Z)
1403 // Applied to fixpoint by the combiner worklist, this collapses an
1404 // arbitrarily long chain of reductions (such as the left-leaning chain SLP
1405 // emits) into a single reduction.
1406 auto FoldReductionChain = [&](SDValue Red0, SDValue Chain) -> SDValue {
1407 SDValue X, Y, Z, RedY;
1408 if (!sd_match(Red0, m_OneUse(m_UnaryOp(RedOpc, m_Value(X)))) ||
1409 !sd_match(
1410 Chain,
1412 Opc, m_Value(RedY, m_OneUse(m_UnaryOp(RedOpc, m_Value(Y)))),
1413 m_Value(Z, m_Unless(m_UnaryOp(RedOpc, m_Value())))))) ||
1414 X.getValueType() != Y.getValueType() ||
1415 !hasOperation(Opc, X.getValueType()) ||
1416 !TLI.shouldReassociateReduction(RedOpc, VT))
1417 return SDValue();
1418 if ((Opc == ISD::FADD || Opc == ISD::FMUL) &&
1419 (!Chain->getFlags().hasAllowReassociation() ||
1420 !Red0->getFlags().hasAllowReassociation() ||
1421 !RedY->getFlags().hasAllowReassociation()))
1422 return SDValue();
1423 SelectionDAG::FlagInserter FlagsInserter(
1424 DAG, Flags & Chain->getFlags() & Red0->getFlags() & RedY->getFlags());
1425 SDValue Op = DAG.getNode(Opc, DL, X.getValueType(), X, Y);
1426 SDValue Red = DAG.getNode(RedOpc, DL, VT, Op);
1427 return DAG.getNode(Opc, DL, VT, Red, Z);
1428 };
1429 if (SDValue V = FoldReductionChain(N0, N1))
1430 return V;
1431 if (SDValue V = FoldReductionChain(N1, N0))
1432 return V;
1433
1434 return SDValue();
1435}
1436
1437SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
1438 bool AddTo) {
1439 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
1440 ++NodesCombined;
1441 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
1442 To[0].dump(&DAG);
1443 dbgs() << " and " << NumTo - 1 << " other values\n");
1444 for (unsigned i = 0, e = NumTo; i != e; ++i)
1445 assert((!To[i].getNode() ||
1446 N->getValueType(i) == To[i].getValueType()) &&
1447 "Cannot combine value to value of different type!");
1448
1449 WorklistRemover DeadNodes(*this);
1450 DAG.ReplaceAllUsesWith(N, To);
1451 if (AddTo) {
1452 // Push the new nodes and any users onto the worklist
1453 for (unsigned i = 0, e = NumTo; i != e; ++i) {
1454 if (To[i].getNode())
1455 AddToWorklistWithUsers(To[i].getNode());
1456 }
1457 }
1458
1459 // Finally, if the node is now dead, remove it from the graph. The node
1460 // may not be dead if the replacement process recursively simplified to
1461 // something else needing this node.
1462 if (N->use_empty())
1463 deleteAndRecombine(N);
1464 return SDValue(N, 0);
1465}
1466
1467void DAGCombiner::
1468CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
1469 // Replace the old value with the new one.
1470 ++NodesCombined;
1471 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.dump(&DAG);
1472 dbgs() << "\nWith: "; TLO.New.dump(&DAG); dbgs() << '\n');
1473
1474 // Replace all uses.
1475 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
1476
1477 // Push the new node and any (possibly new) users onto the worklist.
1478 AddToWorklistWithUsers(TLO.New.getNode());
1479
1480 // Finally, if the node is now dead, remove it from the graph.
1481 recursivelyDeleteUnusedNodes(TLO.Old.getNode());
1482}
1483
1484/// Check the specified integer node value to see if it can be simplified or if
1485/// things it uses can be simplified by bit propagation. If so, return true.
1486bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
1487 const APInt &DemandedElts,
1488 bool AssumeSingleUse) {
1489 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1490 KnownBits Known;
1491 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
1492 AssumeSingleUse))
1493 return false;
1494
1495 // Revisit the node.
1496 AddToWorklist(Op.getNode());
1497
1498 CommitTargetLoweringOpt(TLO);
1499 return true;
1500}
1501
1502/// Check the specified vector node value to see if it can be simplified or
1503/// if things it uses can be simplified as it only uses some of the elements.
1504/// If so, return true.
1505bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
1506 const APInt &DemandedElts,
1507 bool AssumeSingleUse) {
1508 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
1509 APInt KnownUndef, KnownZero;
1510 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
1511 TLO, 0, AssumeSingleUse))
1512 return false;
1513
1514 // Revisit the node.
1515 AddToWorklist(Op.getNode());
1516
1517 CommitTargetLoweringOpt(TLO);
1518 return true;
1519}
1520
1521void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
1522 SDLoc DL(Load);
1523 EVT VT = Load->getValueType(0);
1524 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1525
1526 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
1527 Trunc.dump(&DAG); dbgs() << '\n');
1528
1529 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1530 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1531
1532 AddToWorklist(Trunc.getNode());
1533 recursivelyDeleteUnusedNodes(Load);
1534}
1535
1536SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1537 Replace = false;
1538 SDLoc DL(Op);
1539 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1540 LoadSDNode *LD = cast<LoadSDNode>(Op);
1541 EVT MemVT = LD->getMemoryVT();
1543 : LD->getExtensionType();
1544 Replace = true;
1545 return DAG.getExtLoad(ExtType, DL, PVT,
1546 LD->getChain(), LD->getBasePtr(),
1547 MemVT, LD->getMemOperand());
1548 }
1549
1550 unsigned Opc = Op.getOpcode();
1551 switch (Opc) {
1552 default: break;
1553 case ISD::AssertSext:
1554 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1555 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1556 break;
1557 case ISD::AssertZext:
1558 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1559 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1560 break;
1561 case ISD::Constant: {
1562 unsigned ExtOpc =
1563 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1564 return DAG.getNode(ExtOpc, DL, PVT, Op);
1565 }
1566 }
1567
1568 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1569 return SDValue();
1570 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1571}
1572
1573SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1575 return SDValue();
1576 EVT OldVT = Op.getValueType();
1577 SDLoc DL(Op);
1578 bool Replace = false;
1579 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1580 if (!NewOp.getNode())
1581 return SDValue();
1582 AddToWorklist(NewOp.getNode());
1583
1584 if (Replace)
1585 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1586 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1587 DAG.getValueType(OldVT));
1588}
1589
1590SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1591 EVT OldVT = Op.getValueType();
1592 SDLoc DL(Op);
1593 bool Replace = false;
1594 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1595 if (!NewOp.getNode())
1596 return SDValue();
1597 AddToWorklist(NewOp.getNode());
1598
1599 if (Replace)
1600 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1601 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1602}
1603
1604/// Promote the specified integer binary operation if the target indicates it is
1605/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1606/// i32 since i16 instructions are longer.
1607SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1608 if (!LegalOperations)
1609 return SDValue();
1610
1611 EVT VT = Op.getValueType();
1612 if (VT.isVector() || !VT.isInteger())
1613 return SDValue();
1614
1615 // If operation type is 'undesirable', e.g. i16 on x86, consider
1616 // promoting it.
1617 unsigned Opc = Op.getOpcode();
1618 if (TLI.isTypeDesirableForOp(Opc, VT))
1619 return SDValue();
1620
1621 EVT PVT = VT;
1622 // Consult target whether it is a good idea to promote this operation and
1623 // what's the right type to promote it to.
1624 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1625 assert(PVT != VT && "Don't know what type to promote to!");
1626
1627 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1628
1629 bool Replace0 = false;
1630 SDValue N0 = Op.getOperand(0);
1631 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1632
1633 bool Replace1 = false;
1634 SDValue N1 = Op.getOperand(1);
1635 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1636 SDLoc DL(Op);
1637
1638 SDValue RV =
1639 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1640
1641 // We are always replacing N0/N1's use in N and only need additional
1642 // replacements if there are additional uses.
1643 // Note: We are checking uses of the *nodes* (SDNode) rather than values
1644 // (SDValue) here because the node may reference multiple values
1645 // (for example, the chain value of a load node).
1646 Replace0 &= !N0->hasOneUse();
1647 Replace1 &= (N0 != N1) && !N1->hasOneUse();
1648
1649 // Combine Op here so it is preserved past replacements.
1650 CombineTo(Op.getNode(), RV);
1651
1652 // If operands have a use ordering, make sure we deal with
1653 // predecessor first.
1654 if (Replace0 && Replace1 && N0->isPredecessorOf(N1.getNode())) {
1655 std::swap(N0, N1);
1656 std::swap(NN0, NN1);
1657 }
1658
1659 if (Replace0) {
1660 AddToWorklist(NN0.getNode());
1661 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1662 }
1663 if (Replace1) {
1664 AddToWorklist(NN1.getNode());
1665 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1666 }
1667 return Op;
1668 }
1669 return SDValue();
1670}
1671
1672/// Promote the specified integer shift operation if the target indicates it is
1673/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1674/// i32 since i16 instructions are longer.
1675SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1676 if (!LegalOperations)
1677 return SDValue();
1678
1679 EVT VT = Op.getValueType();
1680 if (VT.isVector() || !VT.isInteger())
1681 return SDValue();
1682
1683 // If operation type is 'undesirable', e.g. i16 on x86, consider
1684 // promoting it.
1685 unsigned Opc = Op.getOpcode();
1686 if (TLI.isTypeDesirableForOp(Opc, VT))
1687 return SDValue();
1688
1689 EVT PVT = VT;
1690 // Consult target whether it is a good idea to promote this operation and
1691 // what's the right type to promote it to.
1692 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1693 assert(PVT != VT && "Don't know what type to promote to!");
1694
1695 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1696
1697 SDNodeFlags TruncFlags;
1698 bool Replace = false;
1699 SDValue N0 = Op.getOperand(0);
1700 if (Opc == ISD::SRA) {
1701 N0 = SExtPromoteOperand(N0, PVT);
1702 } else if (Opc == ISD::SRL) {
1703 N0 = ZExtPromoteOperand(N0, PVT);
1704 } else {
1705 if (Op->getFlags().hasNoUnsignedWrap()) {
1706 N0 = ZExtPromoteOperand(N0, PVT);
1707 TruncFlags = SDNodeFlags::NoUnsignedWrap;
1708 } else if (Op->getFlags().hasNoSignedWrap()) {
1709 N0 = SExtPromoteOperand(N0, PVT);
1710 TruncFlags = SDNodeFlags::NoSignedWrap;
1711 } else {
1712 N0 = PromoteOperand(N0, PVT, Replace);
1713 }
1714 }
1715
1716 if (!N0.getNode())
1717 return SDValue();
1718
1719 SDLoc DL(Op);
1720 SDValue N1 = Op.getOperand(1);
1721 SDValue RV = DAG.getNode(ISD::TRUNCATE, DL, VT,
1722 DAG.getNode(Opc, DL, PVT, N0, N1), TruncFlags);
1723
1724 if (Replace)
1725 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1726
1727 // Deal with Op being deleted.
1728 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1729 return RV;
1730 }
1731 return SDValue();
1732}
1733
1734SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1735 if (!LegalOperations)
1736 return SDValue();
1737
1738 EVT VT = Op.getValueType();
1739 if (VT.isVector() || !VT.isInteger())
1740 return SDValue();
1741
1742 // If operation type is 'undesirable', e.g. i16 on x86, consider
1743 // promoting it.
1744 unsigned Opc = Op.getOpcode();
1745 if (TLI.isTypeDesirableForOp(Opc, VT))
1746 return SDValue();
1747
1748 EVT PVT = VT;
1749 // Consult target whether it is a good idea to promote this operation and
1750 // what's the right type to promote it to.
1751 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1752 assert(PVT != VT && "Don't know what type to promote to!");
1753 // fold (aext (aext x)) -> (aext x)
1754 // fold (aext (zext x)) -> (zext x)
1755 // fold (aext (sext x)) -> (sext x)
1756 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.dump(&DAG));
1757 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1758 }
1759 return SDValue();
1760}
1761
1762bool DAGCombiner::PromoteLoad(SDValue Op) {
1763 if (!LegalOperations)
1764 return false;
1765
1766 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1767 return false;
1768
1769 EVT VT = Op.getValueType();
1770 if (VT.isVector() || !VT.isInteger())
1771 return false;
1772
1773 // If operation type is 'undesirable', e.g. i16 on x86, consider
1774 // promoting it.
1775 unsigned Opc = Op.getOpcode();
1776 if (TLI.isTypeDesirableForOp(Opc, VT))
1777 return false;
1778
1779 EVT PVT = VT;
1780 // Consult target whether it is a good idea to promote this operation and
1781 // what's the right type to promote it to.
1782 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1783 assert(PVT != VT && "Don't know what type to promote to!");
1784
1785 SDLoc DL(Op);
1786 SDNode *N = Op.getNode();
1787 LoadSDNode *LD = cast<LoadSDNode>(N);
1788 EVT MemVT = LD->getMemoryVT();
1790 : LD->getExtensionType();
1791 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1792 LD->getChain(), LD->getBasePtr(),
1793 MemVT, LD->getMemOperand());
1794 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1795
1796 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
1797 Result.dump(&DAG); dbgs() << '\n');
1798
1799 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1800 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1801
1802 AddToWorklist(Result.getNode());
1803 recursivelyDeleteUnusedNodes(N);
1804 return true;
1805 }
1806
1807 return false;
1808}
1809
1810/// Recursively delete a node which has no uses and any operands for
1811/// which it is the only use.
1812///
1813/// Note that this both deletes the nodes and removes them from the worklist.
1814/// It also adds any nodes who have had a user deleted to the worklist as they
1815/// may now have only one use and subject to other combines.
1816bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1817 if (!N->use_empty())
1818 return false;
1819
1820 SmallSetVector<SDNode *, 16> Nodes;
1821 Nodes.insert(N);
1822 do {
1823 N = Nodes.pop_back_val();
1824 if (!N)
1825 continue;
1826
1827 if (N->use_empty()) {
1828 for (const SDValue &ChildN : N->op_values())
1829 Nodes.insert(ChildN.getNode());
1830
1831 removeFromWorklist(N);
1832 DAG.DeleteNode(N);
1833 } else {
1834 AddToWorklist(N);
1835 }
1836 } while (!Nodes.empty());
1837 return true;
1838}
1839
1840//===----------------------------------------------------------------------===//
1841// Main DAG Combiner implementation
1842//===----------------------------------------------------------------------===//
1843
1844void DAGCombiner::Run(CombineLevel AtLevel) {
1845 // set the instance variables, so that the various visit routines may use it.
1846 Level = AtLevel;
1847 LegalDAG = Level >= AfterLegalizeDAG;
1848 LegalOperations = Level >= AfterLegalizeVectorOps;
1849 LegalTypes = Level >= AfterLegalizeTypes;
1850
1851 bool UseTopologicalSorting = EnableTopologicalSorting.getNumOccurrences() > 0
1853 : TLI.useTopologicalSorting();
1854
1855 WorklistInserter AddNodes(*this);
1856
1857 if (UseTopologicalSorting)
1859
1860 // Add all the dag nodes to the worklist.
1861 //
1862 // Note: All nodes are not added to PruningList here, this is because the only
1863 // nodes which can be deleted are those which have no uses and all other nodes
1864 // which would otherwise be added to the worklist by the first call to
1865 // getNextWorklistEntry are already present in it.
1866 if (UseTopologicalSorting) {
1867 for (SDNode &Node : reverse(DAG.allnodes()))
1868 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1869 } else {
1870 for (SDNode &Node : DAG.allnodes())
1871 AddToWorklist(&Node, /* IsCandidateForPruning */ Node.use_empty());
1872 }
1873
1874 // Create a dummy node (which is not added to allnodes), that adds a reference
1875 // to the root node, preventing it from being deleted, and tracking any
1876 // changes of the root.
1877 HandleSDNode Dummy(DAG.getRoot());
1878
1879 // While we have a valid worklist entry node, try to combine it.
1880 while (SDNode *N = getNextWorklistEntry()) {
1881 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1882 // N is deleted from the DAG, since they too may now be dead or may have a
1883 // reduced number of uses, allowing other xforms.
1884 if (recursivelyDeleteUnusedNodes(N))
1885 continue;
1886
1887 WorklistRemover DeadNodes(*this);
1888
1889 // If this combine is running after legalizing the DAG, re-legalize any
1890 // nodes pulled off the worklist.
1891 if (LegalDAG) {
1892 SmallSetVector<SDNode *, 16> UpdatedNodes;
1893 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1894
1895 for (SDNode *LN : UpdatedNodes)
1896 AddToWorklistWithUsers(LN);
1897
1898 if (!NIsValid)
1899 continue;
1900 }
1901
1902 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1903
1904 // Add any operands of the new node which have not yet been combined to the
1905 // worklist as well. getNextWorklistEntry flags nodes that have been
1906 // combined before. Because the worklist uniques things already, this won't
1907 // repeatedly process the same operand.
1908 for (const SDValue &ChildN : N->op_values())
1909 AddToWorklist(ChildN.getNode(), /*IsCandidateForPruning=*/true,
1910 /*SkipIfCombinedBefore=*/true);
1911
1912 SDValue RV = combine(N);
1913
1914 if (!RV.getNode())
1915 continue;
1916
1917 ++NodesCombined;
1918
1919 // Invalidate cached info.
1920 ChainsWithoutMergeableStores.clear();
1921
1922 // If we get back the same node we passed in, rather than a new node or
1923 // zero, we know that the node must have defined multiple values and
1924 // CombineTo was used. Since CombineTo takes care of the worklist
1925 // mechanics for us, we have no work to do in this case.
1926 if (RV.getNode() == N)
1927 continue;
1928
1929 assert(N->getOpcode() != ISD::DELETED_NODE &&
1930 RV.getOpcode() != ISD::DELETED_NODE &&
1931 "Node was deleted but visit returned new node!");
1932
1933 LLVM_DEBUG(dbgs() << " ... into: "; RV.dump(&DAG));
1934
1935 if (N->getNumValues() == RV->getNumValues())
1936 DAG.ReplaceAllUsesWith(N, RV.getNode());
1937 else {
1938 assert(N->getValueType(0) == RV.getValueType() &&
1939 N->getNumValues() == 1 && "Type mismatch");
1940 DAG.ReplaceAllUsesWith(N, &RV);
1941 }
1942
1943 // Push the new node and any users onto the worklist. Omit this if the
1944 // new node is the EntryToken (e.g. if a store managed to get optimized
1945 // out), because re-visiting the EntryToken and its users will not uncover
1946 // any additional opportunities, but there may be a large number of such
1947 // users, potentially causing compile time explosion.
1948 if (RV.getOpcode() != ISD::EntryToken)
1949 AddToWorklistWithUsers(RV.getNode());
1950
1951 // Finally, if the node is now dead, remove it from the graph. The node
1952 // may not be dead if the replacement process recursively simplified to
1953 // something else needing this node. This will also take care of adding any
1954 // operands which have lost a user to the worklist.
1955 recursivelyDeleteUnusedNodes(N);
1956 }
1957
1958 // If the root changed (e.g. it was a dead load, update the root).
1959 DAG.setRoot(Dummy.getValue());
1960 DAG.RemoveDeadNodes();
1961}
1962
1963SDValue DAGCombiner::visit(SDNode *N) {
1964 // clang-format off
1965 switch (N->getOpcode()) {
1966 default: break;
1967 case ISD::TokenFactor: return visitTokenFactor(N);
1968 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1969 case ISD::ADD: return visitADD(N);
1970 case ISD::PTRADD: return visitPTRADD(N);
1971 case ISD::SUB: return visitSUB(N);
1972 case ISD::SADDSAT:
1973 case ISD::UADDSAT: return visitADDSAT(N);
1974 case ISD::SSUBSAT:
1975 case ISD::USUBSAT: return visitSUBSAT(N);
1976 case ISD::ADDC: return visitADDC(N);
1977 case ISD::SADDO:
1978 case ISD::UADDO: return visitADDO(N);
1979 case ISD::SUBC: return visitSUBC(N);
1980 case ISD::SSUBO:
1981 case ISD::USUBO: return visitSUBO(N);
1982 case ISD::ADDE: return visitADDE(N);
1983 case ISD::UADDO_CARRY: return visitUADDO_CARRY(N);
1984 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
1985 case ISD::SUBE: return visitSUBE(N);
1986 case ISD::USUBO_CARRY: return visitUSUBO_CARRY(N);
1987 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
1988 case ISD::SMULFIX:
1989 case ISD::SMULFIXSAT:
1990 case ISD::UMULFIX:
1991 case ISD::UMULFIXSAT: return visitMULFIX(N);
1992 case ISD::MUL: return visitMUL(N);
1993 case ISD::SDIV: return visitSDIV(N);
1994 case ISD::UDIV: return visitUDIV(N);
1995 case ISD::SREM:
1996 case ISD::UREM: return visitREM(N);
1997 case ISD::MULHU: return visitMULHU(N);
1998 case ISD::MULHS: return visitMULHS(N);
1999 case ISD::AVGFLOORS:
2000 case ISD::AVGFLOORU:
2001 case ISD::AVGCEILS:
2002 case ISD::AVGCEILU: return visitAVG(N);
2003 case ISD::ABDS:
2004 case ISD::ABDU: return visitABD(N);
2005 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
2006 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
2007 case ISD::SMULO:
2008 case ISD::UMULO: return visitMULO(N);
2009 case ISD::SMIN:
2010 case ISD::SMAX:
2011 case ISD::UMIN:
2012 case ISD::UMAX: return visitIMINMAX(N);
2013 case ISD::AND: return visitAND(N);
2014 case ISD::OR: return visitOR(N);
2015 case ISD::XOR: return visitXOR(N);
2016 case ISD::SHL: return visitSHL(N);
2017 case ISD::SRA: return visitSRA(N);
2018 case ISD::SRL: return visitSRL(N);
2019 case ISD::ROTR:
2020 case ISD::ROTL: return visitRotate(N);
2021 case ISD::FSHL:
2022 case ISD::FSHR: return visitFunnelShift(N);
2023 case ISD::SSHLSAT:
2024 case ISD::USHLSAT: return visitSHLSAT(N);
2025 case ISD::ABS: return visitABS(N);
2026 case ISD::ABS_MIN_POISON: return visitABS_MIN_POISON(N);
2027 case ISD::CLMUL:
2028 case ISD::CLMULR:
2029 case ISD::CLMULH: return visitCLMUL(N);
2030 case ISD::PEXT: return visitPEXT(N);
2031 case ISD::PDEP: return visitPDEP(N);
2032 case ISD::BSWAP: return visitBSWAP(N);
2033 case ISD::BITREVERSE: return visitBITREVERSE(N);
2034 case ISD::CTLZ: return visitCTLZ(N);
2035 case ISD::CTLZ_ZERO_POISON: return visitCTLZ_ZERO_POISON(N);
2036 case ISD::CTTZ: return visitCTTZ(N);
2037 case ISD::CTTZ_ZERO_POISON: return visitCTTZ_ZERO_POISON(N);
2038 case ISD::CTPOP: return visitCTPOP(N);
2039 case ISD::SELECT: return visitSELECT(N);
2040 case ISD::VSELECT: return visitVSELECT(N);
2041 case ISD::SELECT_CC: return visitSELECT_CC(N);
2042 case ISD::SETCC: return visitSETCC(N);
2043 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
2044 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
2045 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
2046 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
2047 case ISD::AssertSext:
2048 case ISD::AssertZext: return visitAssertExt(N);
2049 case ISD::AssertAlign: return visitAssertAlign(N);
2050 case ISD::IS_FPCLASS: return visitIS_FPCLASS(N);
2051 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
2054 case ISD::ANY_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
2055 case ISD::TRUNCATE: return visitTRUNCATE(N);
2056 case ISD::TRUNCATE_USAT_U: return visitTRUNCATE_USAT_U(N);
2057 case ISD::BITCAST: return visitBITCAST(N);
2058 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
2059 case ISD::FADD: return visitFADD(N);
2060 case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
2061 case ISD::FSUB: return visitFSUB(N);
2062 case ISD::FMUL: return visitFMUL(N);
2063 case ISD::FMA: return visitFMA(N);
2064 case ISD::FMAD: return visitFMAD(N);
2065 case ISD::FMULADD: return visitFMULADD(N);
2066 case ISD::FDIV: return visitFDIV(N);
2067 case ISD::FREM: return visitFREM(N);
2068 case ISD::FSQRT: return visitFSQRT(N);
2069 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
2070 case ISD::FPOW: return visitFPOW(N);
2071 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
2072 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
2073 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
2074 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
2075 case ISD::LROUND:
2076 case ISD::LLROUND:
2077 case ISD::LRINT:
2078 case ISD::LLRINT: return visitXROUND(N);
2079 case ISD::FP_ROUND: return visitFP_ROUND(N);
2080 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
2081 case ISD::FNEG: return visitFNEG(N);
2082 case ISD::FABS: return visitFABS(N);
2083 case ISD::FFLOOR: return visitFFLOOR(N);
2084 case ISD::FMINNUM:
2085 case ISD::FMAXNUM:
2086 case ISD::FMINIMUM:
2087 case ISD::FMAXIMUM:
2088 case ISD::FMINIMUMNUM:
2089 case ISD::FMAXIMUMNUM: return visitFMinMax(N);
2090 case ISD::FCEIL: return visitFCEIL(N);
2091 case ISD::FTRUNC: return visitFTRUNC(N);
2092 case ISD::FFREXP: return visitFFREXP(N);
2093 case ISD::BRCOND: return visitBRCOND(N);
2094 case ISD::BR_CC: return visitBR_CC(N);
2095 case ISD::LOAD: return visitLOAD(N);
2096 case ISD::STORE: return visitSTORE(N);
2097 case ISD::ATOMIC_STORE: return visitATOMIC_STORE(N);
2098 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
2099 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
2100 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
2101 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
2102 case ISD::VECTOR_INTERLEAVE: return visitVECTOR_INTERLEAVE(N);
2103 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
2104 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
2105 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
2106 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
2107 case ISD::MGATHER: return visitMGATHER(N);
2108 case ISD::MLOAD: return visitMLOAD(N);
2109 case ISD::MSCATTER: return visitMSCATTER(N);
2110 case ISD::MSTORE: return visitMSTORE(N);
2111 case ISD::EXPERIMENTAL_VECTOR_HISTOGRAM: return visitMHISTOGRAM(N);
2116 return visitPARTIAL_REDUCE_MLA(N);
2119 return visitLOOP_DEPENDENCE_MASK(N);
2120 case ISD::VECTOR_COMPRESS: return visitVECTOR_COMPRESS(N);
2121 case ISD::LIFETIME_END: return visitLIFETIME_END(N);
2122 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
2123 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
2124 case ISD::FP_TO_BF16: return visitFP_TO_BF16(N);
2125 case ISD::BF16_TO_FP: return visitBF16_TO_FP(N);
2126 case ISD::FREEZE: return visitFREEZE(N);
2127 case ISD::GET_FPENV_MEM: return visitGET_FPENV_MEM(N);
2128 case ISD::SET_FPENV_MEM: return visitSET_FPENV_MEM(N);
2129 case ISD::FCANONICALIZE: return visitFCANONICALIZE(N);
2132 case ISD::VECREDUCE_ADD:
2133 case ISD::VECREDUCE_MUL:
2134 case ISD::VECREDUCE_AND:
2135 case ISD::VECREDUCE_OR:
2136 case ISD::VECREDUCE_XOR:
2146 case ISD::VECREDUCE_FMINIMUMNUM: return visitVECREDUCE(N);
2147#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
2148#include "llvm/IR/VPIntrinsics.def"
2149 return visitVPOp(N);
2150 }
2151 // clang-format on
2152 return SDValue();
2153}
2154
2155SDValue DAGCombiner::combine(SDNode *N) {
2156 if (!DebugCounter::shouldExecute(DAGCombineCounter))
2157 return SDValue();
2158
2159 SDValue RV;
2160 if (!DisableGenericCombines)
2161 RV = visit(N);
2162
2163 // If nothing happened, try a target-specific DAG combine.
2164 if (!RV.getNode()) {
2165 assert(N->getOpcode() != ISD::DELETED_NODE &&
2166 "Node was deleted but visit returned NULL!");
2167
2168 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
2169 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
2170
2171 // Expose the DAG combiner to the target combiner impls.
2172 TargetLowering::DAGCombinerInfo
2173 DagCombineInfo(DAG, Level, false, this);
2174
2175 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
2176 }
2177 }
2178
2179 // If nothing happened still, try promoting the operation.
2180 if (!RV.getNode()) {
2181 switch (N->getOpcode()) {
2182 default: break;
2183 case ISD::ADD:
2184 case ISD::SUB:
2185 case ISD::MUL:
2186 case ISD::AND:
2187 case ISD::OR:
2188 case ISD::XOR:
2189 RV = PromoteIntBinOp(SDValue(N, 0));
2190 break;
2191 case ISD::SHL:
2192 case ISD::SRA:
2193 case ISD::SRL:
2194 RV = PromoteIntShiftOp(SDValue(N, 0));
2195 break;
2196 case ISD::SIGN_EXTEND:
2197 case ISD::ZERO_EXTEND:
2198 case ISD::ANY_EXTEND:
2199 RV = PromoteExtend(SDValue(N, 0));
2200 break;
2201 case ISD::LOAD:
2202 if (PromoteLoad(SDValue(N, 0)))
2203 RV = SDValue(N, 0);
2204 break;
2205 }
2206 }
2207
2208 // If N is a commutative binary node, try to eliminate it if the commuted
2209 // version is already present in the DAG.
2210 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode())) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
2213
2214 // Constant operands are canonicalized to RHS.
2215 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
2216 SDValue Ops[] = {N1, N0};
2217 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
2218 N->getFlags());
2219 if (CSENode)
2220 return SDValue(CSENode, 0);
2221 }
2222 }
2223
2224 return RV;
2225}
2226
2227/// Given a node, return its input chain if it has one, otherwise return a null
2228/// sd operand.
2230 if (unsigned NumOps = N->getNumOperands()) {
2231 if (N->getOperand(0).getValueType() == MVT::Other)
2232 return N->getOperand(0);
2233 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
2234 return N->getOperand(NumOps-1);
2235 for (unsigned i = 1; i < NumOps-1; ++i)
2236 if (N->getOperand(i).getValueType() == MVT::Other)
2237 return N->getOperand(i);
2238 }
2239 return SDValue();
2240}
2241
2242SDValue DAGCombiner::visitFCANONICALIZE(SDNode *N) {
2243 SDValue Operand = N->getOperand(0);
2244 EVT VT = Operand.getValueType();
2245 SDLoc dl(N);
2246
2247 // Canonicalize undef to quiet NaN.
2248 if (Operand.isUndef()) {
2249 APFloat CanonicalQNaN = APFloat::getQNaN(VT.getFltSemantics());
2250 return DAG.getConstantFP(CanonicalQNaN, dl, VT);
2251 }
2252 return SDValue();
2253}
2254
2255SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
2256 // If N has two operands, where one has an input chain equal to the other,
2257 // the 'other' chain is redundant.
2258 if (N->getNumOperands() == 2) {
2259 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
2260 return N->getOperand(0);
2261 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
2262 return N->getOperand(1);
2263 }
2264
2265 // Don't simplify token factors if optnone.
2266 if (OptLevel == CodeGenOptLevel::None)
2267 return SDValue();
2268
2269 // Don't simplify the token factor if the node itself has too many operands.
2270 if (N->getNumOperands() > TokenFactorInlineLimit)
2271 return SDValue();
2272
2273 // If the sole user is a token factor, we should make sure we have a
2274 // chance to merge them together. This prevents TF chains from inhibiting
2275 // optimizations.
2276 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TokenFactor)
2277 AddToWorklist(*(N->user_begin()));
2278
2279 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
2280 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
2281 SmallPtrSet<SDNode*, 16> SeenOps;
2282 bool Changed = false; // If we should replace this token factor.
2283
2284 // Start out with this token factor.
2285 TFs.push_back(N);
2286
2287 // Iterate through token factors. The TFs grows when new token factors are
2288 // encountered.
2289 for (unsigned i = 0; i < TFs.size(); ++i) {
2290 // Limit number of nodes to inline, to avoid quadratic compile times.
2291 // We have to add the outstanding Token Factors to Ops, otherwise we might
2292 // drop Ops from the resulting Token Factors.
2293 if (Ops.size() > TokenFactorInlineLimit) {
2294 for (unsigned j = i; j < TFs.size(); j++)
2295 Ops.emplace_back(TFs[j], 0);
2296 // Drop unprocessed Token Factors from TFs, so we do not add them to the
2297 // combiner worklist later.
2298 TFs.resize(i);
2299 break;
2300 }
2301
2302 SDNode *TF = TFs[i];
2303 // Check each of the operands.
2304 for (const SDValue &Op : TF->op_values()) {
2305 switch (Op.getOpcode()) {
2306 case ISD::EntryToken:
2307 // Entry tokens don't need to be added to the list. They are
2308 // redundant.
2309 Changed = true;
2310 break;
2311
2312 case ISD::TokenFactor:
2313 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
2314 // Queue up for processing.
2315 TFs.push_back(Op.getNode());
2316 Changed = true;
2317 break;
2318 }
2319 [[fallthrough]];
2320
2321 default:
2322 // Only add if it isn't already in the list.
2323 if (SeenOps.insert(Op.getNode()).second)
2324 Ops.push_back(Op);
2325 else
2326 Changed = true;
2327 break;
2328 }
2329 }
2330 }
2331
2332 // Re-visit inlined Token Factors, to clean them up in case they have been
2333 // removed. Skip the first Token Factor, as this is the current node.
2334 for (unsigned i = 1, e = TFs.size(); i < e; i++)
2335 AddToWorklist(TFs[i]);
2336
2337 // Remove Nodes that are chained to another node in the list. Do so
2338 // by walking up chains breath-first stopping when we've seen
2339 // another operand. In general we must climb to the EntryNode, but we can exit
2340 // early if we find all remaining work is associated with just one operand as
2341 // no further pruning is possible.
2342
2343 // List of nodes to search through and original Ops from which they originate.
2345 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
2346 SmallPtrSet<SDNode *, 16> SeenChains;
2347 bool DidPruneOps = false;
2348
2349 unsigned NumLeftToConsider = 0;
2350 for (const SDValue &Op : Ops) {
2351 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
2352 OpWorkCount.push_back(1);
2353 }
2354
2355 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
2356 // If this is an Op, we can remove the op from the list. Remark any
2357 // search associated with it as from the current OpNumber.
2358 if (SeenOps.contains(Op)) {
2359 Changed = true;
2360 DidPruneOps = true;
2361 unsigned OrigOpNumber = 0;
2362 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
2363 OrigOpNumber++;
2364 assert((OrigOpNumber != Ops.size()) &&
2365 "expected to find TokenFactor Operand");
2366 // Re-mark worklist from OrigOpNumber to OpNumber
2367 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
2368 if (Worklist[i].second == OrigOpNumber) {
2369 Worklist[i].second = OpNumber;
2370 }
2371 }
2372 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
2373 OpWorkCount[OrigOpNumber] = 0;
2374 NumLeftToConsider--;
2375 }
2376 // Add if it's a new chain
2377 if (SeenChains.insert(Op).second) {
2378 OpWorkCount[OpNumber]++;
2379 Worklist.push_back(std::make_pair(Op, OpNumber));
2380 }
2381 };
2382
2383 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
2384 // We need at least be consider at least 2 Ops to prune.
2385 if (NumLeftToConsider <= 1)
2386 break;
2387 auto CurNode = Worklist[i].first;
2388 auto CurOpNumber = Worklist[i].second;
2389 assert((OpWorkCount[CurOpNumber] > 0) &&
2390 "Node should not appear in worklist");
2391 switch (CurNode->getOpcode()) {
2392 case ISD::EntryToken:
2393 // Hitting EntryToken is the only way for the search to terminate without
2394 // hitting
2395 // another operand's search. Prevent us from marking this operand
2396 // considered.
2397 NumLeftToConsider++;
2398 break;
2399 case ISD::TokenFactor:
2400 for (const SDValue &Op : CurNode->op_values())
2401 AddToWorklist(i, Op.getNode(), CurOpNumber);
2402 break;
2404 case ISD::LIFETIME_END:
2405 case ISD::CopyFromReg:
2406 case ISD::CopyToReg:
2407 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
2408 break;
2409 default:
2410 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
2411 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
2412 break;
2413 }
2414 OpWorkCount[CurOpNumber]--;
2415 if (OpWorkCount[CurOpNumber] == 0)
2416 NumLeftToConsider--;
2417 }
2418
2419 // If we've changed things around then replace token factor.
2420 if (Changed) {
2422 if (Ops.empty()) {
2423 // The entry token is the only possible outcome.
2424 Result = DAG.getEntryNode();
2425 } else {
2426 if (DidPruneOps) {
2427 SmallVector<SDValue, 8> PrunedOps;
2428 //
2429 for (const SDValue &Op : Ops) {
2430 if (SeenChains.count(Op.getNode()) == 0)
2431 PrunedOps.push_back(Op);
2432 }
2433 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
2434 } else {
2435 Result = DAG.getTokenFactor(SDLoc(N), Ops);
2436 }
2437 }
2438 return Result;
2439 }
2440 return SDValue();
2441}
2442
2443/// MERGE_VALUES can always be eliminated.
2444SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
2445 WorklistRemover DeadNodes(*this);
2446 // Replacing results may cause a different MERGE_VALUES to suddenly
2447 // be CSE'd with N, and carry its uses with it. Iterate until no
2448 // uses remain, to ensure that the node can be safely deleted.
2449 // First add the users of this node to the work list so that they
2450 // can be tried again once they have new operands.
2451 AddUsersToWorklist(N);
2452 do {
2453 // Do as a single replacement to avoid rewalking use lists.
2455 DAG.ReplaceAllUsesWith(N, Ops.data());
2456 } while (!N->use_empty());
2457 deleteAndRecombine(N);
2458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2459}
2460
2461/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2462/// ConstantSDNode pointer else nullptr.
2465 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
2466}
2467
2468// isTruncateOf - If N is a truncate of some other value, return true, record
2469// the value being truncated in Op and which of Op's bits are zero/one in Known.
2470// This function computes KnownBits to avoid a duplicated call to
2471// computeKnownBits in the caller.
2473 KnownBits &Known) {
2474 if (N->getOpcode() == ISD::TRUNCATE) {
2475 Op = N->getOperand(0);
2476 Known = DAG.computeKnownBits(Op);
2477 if (N->getFlags().hasNoUnsignedWrap())
2478 Known.Zero.setBitsFrom(N.getScalarValueSizeInBits());
2479 return true;
2480 }
2481
2482 if (N.getValueType().getScalarType() != MVT::i1 ||
2483 !sd_match(
2485 return false;
2486
2487 Known = DAG.computeKnownBits(Op);
2488 return (Known.Zero | 1).isAllOnes();
2489}
2490
2491/// Return true if 'Use' is a load or a store that uses N as its base pointer
2492/// and that N may be folded in the load / store addressing mode.
2494 const TargetLowering &TLI) {
2495 EVT VT;
2496 unsigned AS;
2497
2498 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
2499 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2500 return false;
2501 VT = LD->getMemoryVT();
2502 AS = LD->getAddressSpace();
2503 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
2504 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2505 return false;
2506 VT = ST->getMemoryVT();
2507 AS = ST->getAddressSpace();
2509 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
2510 return false;
2511 VT = LD->getMemoryVT();
2512 AS = LD->getAddressSpace();
2514 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
2515 return false;
2516 VT = ST->getMemoryVT();
2517 AS = ST->getAddressSpace();
2518 } else {
2519 return false;
2520 }
2521
2523 if (N->isAnyAdd()) {
2524 AM.HasBaseReg = true;
2526 if (Offset)
2527 // [reg +/- imm]
2528 AM.BaseOffs = Offset->getSExtValue();
2529 else
2530 // [reg +/- reg]
2531 AM.Scale = 1;
2532 } else if (N->getOpcode() == ISD::SUB) {
2533 AM.HasBaseReg = true;
2535 if (Offset)
2536 // [reg +/- imm]
2537 AM.BaseOffs = -Offset->getSExtValue();
2538 else
2539 // [reg +/- reg]
2540 AM.Scale = 1;
2541 } else {
2542 return false;
2543 }
2544
2545 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
2546 VT.getTypeForEVT(*DAG.getContext()), AS);
2547}
2548
2549/// This inverts a canonicalization in IR that replaces a variable select arm
2550/// with an identity constant. Codegen improves if we re-use the variable
2551/// operand rather than load a constant. This can also be converted into a
2552/// masked vector operation if the target supports it.
2554 bool ShouldCommuteOperands) {
2555 SDValue N0 = N->getOperand(0);
2556 SDValue N1 = N->getOperand(1);
2557
2558 // Match a select as operand 1. The identity constant that we are looking for
2559 // is only valid as operand 1 of a non-commutative binop.
2560 if (ShouldCommuteOperands)
2561 std::swap(N0, N1);
2562
2563 SDValue Cond, TVal, FVal;
2565 m_Value(FVal)))))
2566 return SDValue();
2567
2568 // We can't hoist all instructions because of immediate UB (not speculatable).
2569 // For example div/rem by zero.
2571 return SDValue();
2572
2573 unsigned SelOpcode = N1.getOpcode();
2574 unsigned Opcode = N->getOpcode();
2575 EVT VT = N->getValueType(0);
2576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2577
2578 // This transform increases uses of N0, so freeze it to be safe.
2579 // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
2580 unsigned OpNo = ShouldCommuteOperands ? 0 : 1;
2581 if (DAG.isIdentityElement(Opcode, N->getFlags(), TVal, OpNo) &&
2582 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2583 FVal)) {
2584 SDValue F0 = DAG.getFreeze(N0);
2585 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
2586 return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
2587 }
2588 // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
2589 if (DAG.isIdentityElement(Opcode, N->getFlags(), FVal, OpNo) &&
2590 TLI.shouldFoldSelectWithIdentityConstant(Opcode, VT, SelOpcode, N0,
2591 TVal)) {
2592 SDValue F0 = DAG.getFreeze(N0);
2593 SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
2594 return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
2595 }
2596
2597 return SDValue();
2598}
2599
2600SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
2603 "Unexpected binary operator");
2604
2605 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
2606 return Sel;
2607
2608 if (TLI.isCommutativeBinOp(BO->getOpcode()))
2609 if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
2610 return Sel;
2611
2612 // Don't do this unless the old select is going away. We want to eliminate the
2613 // binary operator, not replace a binop with a select.
2614 // TODO: Handle ISD::SELECT_CC.
2615 unsigned SelOpNo = 0;
2616 SDValue Sel = BO->getOperand(0);
2617 auto BinOpcode = BO->getOpcode();
2618 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
2619 SelOpNo = 1;
2620 Sel = BO->getOperand(1);
2621
2622 // Peek through trunc to shift amount type.
2623 if ((BinOpcode == ISD::SHL || BinOpcode == ISD::SRA ||
2624 BinOpcode == ISD::SRL) && Sel.hasOneUse()) {
2625 // This is valid when the truncated bits of x are already zero.
2626 SDValue Op;
2627 KnownBits Known;
2628 if (isTruncateOf(DAG, Sel, Op, Known) &&
2629 Known.countMaxActiveBits() < Sel.getScalarValueSizeInBits())
2630 Sel = Op;
2631 }
2632 }
2633
2634 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
2635 return SDValue();
2636
2637 SDValue CT = Sel.getOperand(1);
2638 if (!isConstantOrConstantVector(CT, true) &&
2640 return SDValue();
2641
2642 SDValue CF = Sel.getOperand(2);
2643 if (!isConstantOrConstantVector(CF, true) &&
2645 return SDValue();
2646
2647 // Bail out if any constants are opaque because we can't constant fold those.
2648 // The exception is "and" and "or" with either 0 or -1 in which case we can
2649 // propagate non constant operands into select. I.e.:
2650 // and (select Cond, 0, -1), X --> select Cond, 0, X
2651 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2652 bool CanFoldNonConst =
2653 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
2656
2657 SDValue CBO = BO->getOperand(SelOpNo ^ 1);
2658 if (!CanFoldNonConst &&
2659 !isConstantOrConstantVector(CBO, true) &&
2661 return SDValue();
2662
2663 SDLoc DL(Sel);
2664 SDValue NewCT, NewCF;
2665 EVT VT = BO->getValueType(0);
2666
2667 if (CanFoldNonConst) {
2668 // If CBO is an opaque constant, we can't rely on getNode to constant fold.
2669 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CT)) ||
2670 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CT)))
2671 NewCT = CT;
2672 else
2673 NewCT = CBO;
2674
2675 if ((BinOpcode == ISD::AND && isNullOrNullSplat(CF)) ||
2676 (BinOpcode == ISD::OR && isAllOnesOrAllOnesSplat(CF)))
2677 NewCF = CF;
2678 else
2679 NewCF = CBO;
2680 } else {
2681 // We have a select-of-constants followed by a binary operator with a
2682 // constant. Eliminate the binop by pulling the constant math into the
2683 // select. Example: add (select Cond, CT, CF), CBO --> select Cond, CT +
2684 // CBO, CF + CBO
2685 NewCT = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CT})
2686 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CT, CBO});
2687 if (!NewCT)
2688 return SDValue();
2689
2690 NewCF = SelOpNo ? DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CBO, CF})
2691 : DAG.FoldConstantArithmetic(BinOpcode, DL, VT, {CF, CBO});
2692 if (!NewCF)
2693 return SDValue();
2694 }
2695
2696 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF, BO->getFlags());
2697}
2698
2700 SelectionDAG &DAG) {
2701 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2702 "Expecting add or sub");
2703
2704 // Match a constant operand and a zext operand for the math instruction:
2705 // add Z, C
2706 // sub C, Z
2707 bool IsAdd = N->getOpcode() == ISD::ADD;
2708 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
2709 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
2710 auto *CN = dyn_cast<ConstantSDNode>(C);
2711 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
2712 return SDValue();
2713
2714 // Match the zext operand as a setcc of a boolean.
2715 if (Z.getOperand(0).getValueType() != MVT::i1)
2716 return SDValue();
2717
2718 // Match the compare as: setcc (X & 1), 0, eq.
2719 if (!sd_match(Z.getOperand(0), m_SetCC(m_And(m_Value(), m_One()), m_Zero(),
2721 return SDValue();
2722
2723 // We are adding/subtracting a constant and an inverted low bit. Turn that
2724 // into a subtract/add of the low bit with incremented/decremented constant:
2725 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2726 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2727 EVT VT = C.getValueType();
2728 SDValue LowBit = DAG.getZExtOrTrunc(Z.getOperand(0).getOperand(0), DL, VT);
2729 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT)
2730 : DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
2731 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
2732}
2733
2734// Attempt to form avgceil(A, B) from (A | B) - ((A ^ B) >> 1)
2735SDValue DAGCombiner::foldSubToAvg(SDNode *N, const SDLoc &DL) {
2736 SDValue N0 = N->getOperand(0);
2737 EVT VT = N0.getValueType();
2738 SDValue A, B;
2739
2740 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
2742 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2743 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
2744 }
2745 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
2747 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One())))) {
2748 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
2749 }
2750 return SDValue();
2751}
2752
2753/// Try to fold a pointer arithmetic node.
2754/// This needs to be done separately from normal addition, because pointer
2755/// addition is not commutative.
2756SDValue DAGCombiner::visitPTRADD(SDNode *N) {
2757 SDValue N0 = N->getOperand(0);
2758 SDValue N1 = N->getOperand(1);
2759 EVT PtrVT = N0.getValueType();
2760 EVT IntVT = N1.getValueType();
2761 SDLoc DL(N);
2762
2763 // This is already ensured by an assert in SelectionDAG::getNode(). Several
2764 // combines here depend on this assumption.
2765 assert(PtrVT == IntVT &&
2766 "PTRADD with different operand types is not supported");
2767
2768 // fold (ptradd x, 0) -> x
2769 if (isNullConstant(N1))
2770 return N0;
2771
2772 // fold (ptradd 0, x) -> x
2773 if (PtrVT == IntVT && isNullConstant(N0))
2774 return N1;
2775
2776 if (N0.getOpcode() == ISD::PTRADD &&
2777 !reassociationCanBreakAddressingModePattern(ISD::PTRADD, DL, N, N0, N1)) {
2778 SDValue X = N0.getOperand(0);
2779 SDValue Y = N0.getOperand(1);
2780 SDValue Z = N1;
2781 bool N0OneUse = N0.hasOneUse();
2782 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2783 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2784
2785 // (ptradd (ptradd x, y), z) -> (ptradd x, (add y, z)) if:
2786 // * y is a constant and (ptradd x, y) has one use; or
2787 // * y and z are both constants.
2788 if ((YIsConstant && N0OneUse) || (YIsConstant && ZIsConstant)) {
2789 // If both additions in the original were NUW, the new ones are as well.
2790 SDNodeFlags Flags =
2791 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2792 SDValue Add = DAG.getNode(ISD::ADD, DL, IntVT, {Y, Z}, Flags);
2793 AddToWorklist(Add.getNode());
2794 // We can't set InBounds even if both original ptradds were InBounds and
2795 // NUW: SDAG usually represents pointers as integers, therefore, the
2796 // matched pattern behaves as if it had implicit casts:
2797 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds x, y))), z)
2798 // The outer inbounds ptradd might therefore rely on a provenance that x
2799 // does not have.
2800 return DAG.getMemBasePlusOffset(X, Add, DL, Flags);
2801 }
2802 }
2803
2804 // The following combines can turn in-bounds pointer arithmetic out of bounds.
2805 // That is problematic for settings like AArch64's CPA, which checks that
2806 // intermediate results of pointer arithmetic remain in bounds. The target
2807 // therefore needs to opt-in to enable them.
2809 DAG.getMachineFunction().getFunction(), PtrVT))
2810 return SDValue();
2811
2812 if (N0.getOpcode() == ISD::PTRADD && isa<ConstantSDNode>(N1)) {
2813 // Fold (ptradd (ptradd GA, v), c) -> (ptradd (ptradd GA, c) v) with
2814 // global address GA and constant c, such that c can be folded into GA.
2815 // TODO: Support constant vector splats.
2816 SDValue GAValue = N0.getOperand(0);
2817 if (const GlobalAddressSDNode *GA =
2819 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2820 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2821 // If both additions in the original were NUW, reassociation preserves
2822 // that.
2823 SDNodeFlags Flags =
2824 (N->getFlags() & N0->getFlags()) & SDNodeFlags::NoUnsignedWrap;
2825 // We can't set InBounds even if both original ptradds were InBounds and
2826 // NUW: SDAG usually represents pointers as integers, therefore, the
2827 // matched pattern behaves as if it had implicit casts:
2828 // (ptradd inbounds (inttoptr (ptrtoint (ptradd inbounds GA, v))), c)
2829 // The outer inbounds ptradd might therefore rely on a provenance that
2830 // GA does not have.
2831 SDValue Inner = DAG.getMemBasePlusOffset(GAValue, N1, DL, Flags);
2832 AddToWorklist(Inner.getNode());
2833 return DAG.getMemBasePlusOffset(Inner, N0.getOperand(1), DL, Flags);
2834 }
2835 }
2836 }
2837
2838 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse()) {
2839 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, y), z) if z is a constant,
2840 // y is not, and (add y, z) is used only once.
2841 // (ptradd x, (add y, z)) -> (ptradd (ptradd x, z), y) if y is a constant,
2842 // z is not, and (add y, z) is used only once.
2843 // The goal is to move constant offsets to the outermost ptradd, to create
2844 // more opportunities to fold offsets into memory instructions.
2845 // Together with the another combine above, this also implements
2846 // (ptradd (ptradd x, y), z) -> (ptradd (ptradd x, z), y)).
2847 SDValue X = N0;
2848 SDValue Y = N1.getOperand(0);
2849 SDValue Z = N1.getOperand(1);
2850 bool YIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Y);
2851 bool ZIsConstant = DAG.isConstantIntBuildVectorOrConstantInt(Z);
2852
2853 // If both additions in the original were NUW, reassociation preserves that.
2854 SDNodeFlags CommonFlags = N->getFlags() & N1->getFlags();
2855 SDNodeFlags ReassocFlags = CommonFlags & SDNodeFlags::NoUnsignedWrap;
2856 if (CommonFlags.hasNoUnsignedWrap()) {
2857 // If both operations are NUW and the PTRADD is inbounds, the offests are
2858 // both non-negative, so the reassociated PTRADDs are also inbounds.
2859 ReassocFlags |= N->getFlags() & SDNodeFlags::InBounds;
2860 }
2861
2862 if (ZIsConstant != YIsConstant) {
2863 if (YIsConstant)
2864 std::swap(Y, Z);
2865 SDValue Inner = DAG.getMemBasePlusOffset(X, Y, DL, ReassocFlags);
2866 AddToWorklist(Inner.getNode());
2867 return DAG.getMemBasePlusOffset(Inner, Z, DL, ReassocFlags);
2868 }
2869 }
2870
2871 // Transform (ptradd a, b) -> (or disjoint a, b) if it is equivalent and if
2872 // that transformation can't block an offset folding at any use of the ptradd.
2873 // This should be done late, after legalization, so that it doesn't block
2874 // other ptradd combines that could enable more offset folding.
2875 if (LegalOperations && DAG.haveNoCommonBitsSet(N0, N1)) {
2876 bool TransformCannotBreakAddrMode = none_of(N->users(), [&](SDNode *User) {
2877 return canFoldInAddressingMode(N, User, DAG, TLI);
2878 });
2879
2880 if (TransformCannotBreakAddrMode)
2881 return DAG.getNode(ISD::OR, DL, PtrVT, N0, N1, SDNodeFlags::Disjoint);
2882 }
2883
2884 return SDValue();
2885}
2886
2887/// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2888/// a shift and add with a different constant.
2890 SelectionDAG &DAG) {
2891 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
2892 "Expecting add or sub");
2893
2894 // We need a constant operand for the add/sub, and the other operand is a
2895 // logical shift right: add (srl), C or sub C, (srl).
2896 bool IsAdd = N->getOpcode() == ISD::ADD;
2897 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
2898 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
2899 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
2900 ShiftOp.getOpcode() != ISD::SRL)
2901 return SDValue();
2902
2903 // The shift must be of a 'not' value.
2904 SDValue Not = ShiftOp.getOperand(0);
2905 if (!Not.hasOneUse() || !isBitwiseNot(Not))
2906 return SDValue();
2907
2908 // The shift must be moving the sign bit to the least-significant-bit.
2909 EVT VT = ShiftOp.getValueType();
2910 SDValue ShAmt = ShiftOp.getOperand(1);
2911 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
2912 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
2913 return SDValue();
2914
2915 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2916 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2917 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2918 if (SDValue NewC = DAG.FoldConstantArithmetic(
2919 IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
2920 {ConstantOp, DAG.getConstant(1, DL, VT)})) {
2921 SDValue NewShift = DAG.getNode(IsAdd ? ISD::SRA : ISD::SRL, DL, VT,
2922 Not.getOperand(0), ShAmt);
2923 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
2924 }
2925
2926 return SDValue();
2927}
2928
2929static bool
2931 return (isBitwiseNot(Op0) && Op0.getOperand(0) == Op1) ||
2932 (isBitwiseNot(Op1) && Op1.getOperand(0) == Op0);
2933}
2934
2935/// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2936/// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2937/// are no common bits set in the operands).
2938SDValue DAGCombiner::visitADDLike(SDNode *N) {
2939 SDValue N0 = N->getOperand(0);
2940 SDValue N1 = N->getOperand(1);
2941 EVT VT = N0.getValueType();
2942 SDLoc DL(N);
2943
2944 // fold (add x, undef) -> undef
2945 if (N0.isUndef())
2946 return N0;
2947 if (N1.isUndef())
2948 return N1;
2949
2950 // fold (add c1, c2) -> c1+c2
2951 if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
2952 return C;
2953
2954 // canonicalize constant to RHS
2957 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
2958
2959 if (areBitwiseNotOfEachother(N0, N1))
2960 return DAG.getConstant(APInt::getAllOnes(VT.getScalarSizeInBits()), DL, VT);
2961
2962 // fold vector ops
2963 if (VT.isVector()) {
2964 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
2965 return FoldedVOp;
2966
2967 // fold (add x, 0) -> x, vector edition
2969 return N0;
2970 }
2971
2972 // fold (add x, 0) -> x
2973 if (isNullConstant(N1))
2974 return N0;
2975
2976 if (N0.getOpcode() == ISD::SUB) {
2977 SDValue N00 = N0.getOperand(0);
2978 SDValue N01 = N0.getOperand(1);
2979
2980 // fold ((A-c1)+c2) -> (A+(c2-c1))
2981 if (SDValue Sub = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N01}))
2982 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
2983
2984 // fold ((c1-A)+c2) -> (c1+c2)-A
2985 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N00}))
2986 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
2987 }
2988
2989 // add (sext i1 X), 1 -> zext (not i1 X)
2990 // We don't transform this pattern:
2991 // add (zext i1 X), -1 -> sext (not i1 X)
2992 // because most (?) targets generate better code for the zext form.
2993 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
2994 isOneOrOneSplat(N1)) {
2995 SDValue X = N0.getOperand(0);
2996 if ((!LegalOperations ||
2997 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
2999 X.getScalarValueSizeInBits() == 1) {
3000 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
3001 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
3002 }
3003 }
3004
3005 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1))
3006 // iff (or x, c0) is equivalent to (add x, c0).
3007 // Fold (add (xor x, c0), c1) -> (add x, (c0 + c1))
3008 // iff (xor x, c0) is equivalent to (add x, c0).
3009 if (DAG.isADDLike(N0)) {
3010 SDValue N01 = N0.getOperand(1);
3011 if (SDValue Add = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N01}))
3012 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add);
3013 }
3014
3015 if (SDValue NewSel = foldBinOpIntoSelect(N))
3016 return NewSel;
3017
3018 // reassociate add
3019 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N, N0, N1)) {
3020 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
3021 return RADD;
3022
3023 // (X + Y) + X --> Y + (X + X)
3024 SDValue X, Y, InnerAdd;
3025 if (sd_match(
3026 N, m_Add(m_OneUse(m_Value(InnerAdd, m_Add(m_Value(X), m_Value(Y)))),
3027 m_Deferred(X)))) {
3028 if (X != Y) {
3029 // Redistribute shared NUW flag.
3030 // TODO: If NSW+NUW occurs on both adds, that can be redistributed too.
3031 SDNodeFlags NewFlags =
3032 N->getFlags() & InnerAdd->getFlags() & SDNodeFlags::NoUnsignedWrap;
3033 SDValue X2 = DAG.getNode(ISD::ADD, DL, VT, X, X, NewFlags);
3034 return DAG.getNode(ISD::ADD, DL, VT, Y, X2, NewFlags);
3035 }
3036 }
3037
3038 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
3039 // equivalent to (add x, c).
3040 // Reassociate (add (xor x, c), y) -> (add add(x, y), c)) if (xor x, c) is
3041 // equivalent to (add x, c).
3042 // Do this optimization only when adding c does not introduce instructions
3043 // for adding carries.
3044 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
3045 if (DAG.isADDLike(N0) && N0.hasOneUse() &&
3046 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
3047 // If N0's type does not split or is a sign mask, it does not introduce
3048 // add carry.
3049 auto TyActn = TLI.getTypeAction(*DAG.getContext(), N0.getValueType());
3050 bool NoAddCarry = TyActn == TargetLoweringBase::TypeLegal ||
3053 if (NoAddCarry)
3054 return DAG.getNode(
3055 ISD::ADD, DL, VT,
3056 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
3057 N0.getOperand(1));
3058 }
3059 return SDValue();
3060 };
3061 if (SDValue Add = ReassociateAddOr(N0, N1))
3062 return Add;
3063 if (SDValue Add = ReassociateAddOr(N1, N0))
3064 return Add;
3065
3066 // Fold add(vecreduce(x), vecreduce(y)) -> vecreduce(add(x, y))
3067 if (SDValue SD =
3068 reassociateReduction(ISD::VECREDUCE_ADD, ISD::ADD, DL, VT, N0, N1))
3069 return SD;
3070 }
3071
3072 SDValue A, B, C, D;
3073
3074 // fold ((0-A) + B) -> B-A
3075 if (sd_match(N0, m_Neg(m_Value(A))))
3076 return DAG.getNode(ISD::SUB, DL, VT, N1, A);
3077
3078 // fold (A + (0-B)) -> A-B
3079 if (sd_match(N1, m_Neg(m_Value(B))))
3080 return DAG.getNode(ISD::SUB, DL, VT, N0, B);
3081
3082 // fold (A+(B-A)) -> B
3083 if (sd_match(N1, m_Sub(m_Value(B), m_Specific(N0))))
3084 return B;
3085
3086 // fold ((B-A)+A) -> B
3087 if (sd_match(N0, m_Sub(m_Value(B), m_Specific(N1))))
3088 return B;
3089
3090 // fold ((A-B)+(C-A)) -> (C-B)
3091 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3093 return DAG.getNode(ISD::SUB, DL, VT, C, B);
3094
3095 // fold ((A-B)+(B-C)) -> (A-C)
3096 if (sd_match(N0, m_Sub(m_Value(A), m_Value(B))) &&
3098 return DAG.getNode(ISD::SUB, DL, VT, A, C);
3099
3100 // fold (A+(B-(A+C))) to (B-C)
3101 // fold (A+(B-(C+A))) to (B-C)
3102 if (sd_match(N1, m_Sub(m_Value(B), m_Add(m_Specific(N0), m_Value(C)))))
3103 return DAG.getNode(ISD::SUB, DL, VT, B, C);
3104
3105 // fold (A+((B-A)+or-C)) to (B+or-C)
3106 if (sd_match(N1,
3108 m_Sub(m_Sub(m_Value(B), m_Specific(N0)), m_Value(C)))))
3109 return DAG.getNode(N1.getOpcode(), DL, VT, B, C);
3110
3111 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
3112 if (sd_match(N0, m_OneUse(m_Sub(m_Value(A), m_Value(B)))) &&
3113 sd_match(N1, m_OneUse(m_Sub(m_Value(C), m_Value(D)))) &&
3115 return DAG.getNode(ISD::SUB, DL, VT,
3116 DAG.getNode(ISD::ADD, SDLoc(N0), VT, A, C),
3117 DAG.getNode(ISD::ADD, SDLoc(N1), VT, B, D));
3118
3119 // fold (add (umax X, C), -C) --> (usubsat X, C)
3120 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
3121 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
3122 return (!Max && !Op) ||
3123 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
3124 };
3125 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
3126 /*AllowUndefs*/ true))
3127 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
3128 N0.getOperand(1));
3129 }
3130
3132 return SDValue(N, 0);
3133
3134 if (isOneOrOneSplat(N1)) {
3135 // fold (add (xor a, -1), 1) -> (sub 0, a)
3136 if (isBitwiseNot(N0))
3137 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
3138 N0.getOperand(0));
3139
3140 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
3141 if (N0.getOpcode() == ISD::ADD) {
3142 SDValue A, Xor;
3143
3144 if (isBitwiseNot(N0.getOperand(0))) {
3145 A = N0.getOperand(1);
3146 Xor = N0.getOperand(0);
3147 } else if (isBitwiseNot(N0.getOperand(1))) {
3148 A = N0.getOperand(0);
3149 Xor = N0.getOperand(1);
3150 }
3151
3152 if (Xor)
3153 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
3154 }
3155
3156 // Look for:
3157 // add (add x, y), 1
3158 // And if the target does not like this form then turn into:
3159 // sub y, (xor x, -1)
3160 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3161 N0.hasOneUse() &&
3162 // Limit this to after legalization if the add has wrap flags
3163 (Level >= AfterLegalizeDAG || (!N->getFlags().hasNoUnsignedWrap() &&
3164 !N->getFlags().hasNoSignedWrap()))) {
3165 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3166 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
3167 }
3168 }
3169
3170 // (x - y) + -1 -> add (xor y, -1), x
3171 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
3172 isAllOnesOrAllOnesSplat(N1, /*AllowUndefs=*/true)) {
3173 SDValue Not = DAG.getNOT(DL, N0.getOperand(1), VT);
3174 return DAG.getNode(ISD::ADD, DL, VT, Not, N0.getOperand(0));
3175 }
3176
3177 // Fold add(mul(add(A, CA), CM), CB) -> add(mul(A, CM), CM*CA+CB).
3178 // This can help if the inner add has multiple uses.
3179 APInt CM, CA;
3180 if (ConstantSDNode *CB = dyn_cast<ConstantSDNode>(N1)) {
3181 if (VT.getScalarSizeInBits() <= 64) {
3183 m_ConstInt(CM)))) &&
3185 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3186 SDNodeFlags Flags;
3187 // If all the inputs are nuw, the outputs can be nuw. If all the input
3188 // are _also_ nsw the outputs can be too.
3189 if (N->getFlags().hasNoUnsignedWrap() &&
3190 N0->getFlags().hasNoUnsignedWrap() &&
3193 if (N->getFlags().hasNoSignedWrap() &&
3194 N0->getFlags().hasNoSignedWrap() &&
3197 }
3198 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3199 DAG.getConstant(CM, DL, VT), Flags);
3200 return DAG.getNode(
3201 ISD::ADD, DL, VT, Mul,
3202 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3203 }
3204 // Also look in case there is an intermediate add.
3205 if (sd_match(N0, m_OneUse(m_Add(
3207 m_ConstInt(CM))),
3208 m_Value(B)))) &&
3210 (CA * CM + CB->getAPIntValue()).getSExtValue())) {
3211 SDNodeFlags Flags;
3212 // If all the inputs are nuw, the outputs can be nuw. If all the input
3213 // are _also_ nsw the outputs can be too.
3214 SDValue OMul =
3215 N0.getOperand(0) == B ? N0.getOperand(1) : N0.getOperand(0);
3216 if (N->getFlags().hasNoUnsignedWrap() &&
3217 N0->getFlags().hasNoUnsignedWrap() &&
3218 OMul->getFlags().hasNoUnsignedWrap() &&
3219 OMul.getOperand(0)->getFlags().hasNoUnsignedWrap()) {
3221 if (N->getFlags().hasNoSignedWrap() &&
3222 N0->getFlags().hasNoSignedWrap() &&
3223 OMul->getFlags().hasNoSignedWrap() &&
3224 OMul.getOperand(0)->getFlags().hasNoSignedWrap())
3226 }
3227 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N1), VT, A,
3228 DAG.getConstant(CM, DL, VT), Flags);
3229 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N1), VT, Mul, B, Flags);
3230 return DAG.getNode(
3231 ISD::ADD, DL, VT, Add,
3232 DAG.getConstant(CA * CM + CB->getAPIntValue(), DL, VT), Flags);
3233 }
3234 }
3235 }
3236
3237 if (SDValue Combined = visitADDLikeCommutative(N0, N1, DL))
3238 return Combined;
3239
3240 if (SDValue Combined = visitADDLikeCommutative(N1, N0, DL))
3241 return Combined;
3242
3243 return SDValue();
3244}
3245
3246// Attempt to form avgfloor(A, B) from (A & B) + ((A ^ B) >> 1)
3247// Attempt to form avgfloor(A, B) from ((A >> 1) + (B >> 1)) + (A & B & 1)
3248// Attempt to form avgceil(A, B) from ((A >> 1) + (B >> 1)) + ((A | B) & 1)
3249SDValue DAGCombiner::foldAddToAvg(SDNode *N, const SDLoc &DL) {
3250 SDValue N0 = N->getOperand(0);
3251 EVT VT = N0.getValueType();
3252 SDValue A, B;
3253
3254 if ((!LegalOperations || hasOperation(ISD::AVGFLOORU, VT)) &&
3255 (sd_match(N,
3257 m_Srl(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3260 m_Srl(m_Deferred(A), m_One()),
3261 m_Srl(m_Deferred(B), m_One()))))) {
3262 return DAG.getNode(ISD::AVGFLOORU, DL, VT, A, B);
3263 }
3264 if ((!LegalOperations || hasOperation(ISD::AVGFLOORS, VT)) &&
3265 (sd_match(N,
3267 m_Sra(m_Xor(m_Deferred(A), m_Deferred(B)), m_One()))) ||
3270 m_Sra(m_Deferred(A), m_One()),
3271 m_Sra(m_Deferred(B), m_One()))))) {
3272 return DAG.getNode(ISD::AVGFLOORS, DL, VT, A, B);
3273 }
3274
3275 if ((!LegalOperations || hasOperation(ISD::AVGCEILU, VT)) &&
3276 sd_match(N,
3278 m_Srl(m_Deferred(A), m_One()),
3279 m_Srl(m_Deferred(B), m_One())))) {
3280 return DAG.getNode(ISD::AVGCEILU, DL, VT, A, B);
3281 }
3282 if ((!LegalOperations || hasOperation(ISD::AVGCEILS, VT)) &&
3283 sd_match(N,
3285 m_Sra(m_Deferred(A), m_One()),
3286 m_Sra(m_Deferred(B), m_One())))) {
3287 return DAG.getNode(ISD::AVGCEILS, DL, VT, A, B);
3288 }
3289
3290 return SDValue();
3291}
3292
3293SDValue DAGCombiner::visitADD(SDNode *N) {
3294 SDValue N0 = N->getOperand(0);
3295 SDValue N1 = N->getOperand(1);
3296 EVT VT = N0.getValueType();
3297 SDLoc DL(N);
3298
3299 if (SDValue Combined = visitADDLike(N))
3300 return Combined;
3301
3302 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
3303 return V;
3304
3305 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
3306 return V;
3307
3308 if (SDValue V = MatchRotate(N0, N1, SDLoc(N), /*FromAdd=*/true))
3309 return V;
3310
3311 // Try to match AVGFLOOR fixedwidth pattern
3312 if (SDValue V = foldAddToAvg(N, DL))
3313 return V;
3314
3315 // fold (a+b) -> (a|b) iff a and b share no bits.
3316 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
3317 DAG.haveNoCommonBitsSet(N0, N1))
3318 return DAG.getNode(ISD::OR, DL, VT, N0, N1, SDNodeFlags::Disjoint);
3319
3320 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
3321 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
3322 const APInt &C0 = N0->getConstantOperandAPInt(0);
3323 const APInt &C1 = N1->getConstantOperandAPInt(0);
3324 return DAG.getVScale(DL, VT, C0 + C1);
3325 }
3326
3327 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
3328 if (N0.getOpcode() == ISD::ADD &&
3329 N0.getOperand(1).getOpcode() == ISD::VSCALE &&
3330 N1.getOpcode() == ISD::VSCALE) {
3331 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3332 const APInt &VS1 = N1->getConstantOperandAPInt(0);
3333 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
3334 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
3335 }
3336
3337 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
3338 if (N0.getOpcode() == ISD::STEP_VECTOR &&
3339 N1.getOpcode() == ISD::STEP_VECTOR) {
3340 const APInt &C0 = N0->getConstantOperandAPInt(0);
3341 const APInt &C1 = N1->getConstantOperandAPInt(0);
3342 APInt NewStep = C0 + C1;
3343 return DAG.getStepVector(DL, VT, NewStep);
3344 }
3345
3346 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
3347 if (N0.getOpcode() == ISD::ADD &&
3349 N1.getOpcode() == ISD::STEP_VECTOR) {
3350 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
3351 const APInt &SV1 = N1->getConstantOperandAPInt(0);
3352 APInt NewStep = SV0 + SV1;
3353 SDValue SV = DAG.getStepVector(DL, VT, NewStep);
3354 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
3355 }
3356
3357 return SDValue();
3358}
3359
3360SDValue DAGCombiner::visitADDSAT(SDNode *N) {
3361 unsigned Opcode = N->getOpcode();
3362 SDValue N0 = N->getOperand(0);
3363 SDValue N1 = N->getOperand(1);
3364 EVT VT = N0.getValueType();
3365 bool IsSigned = Opcode == ISD::SADDSAT;
3366 SDLoc DL(N);
3367
3368 // fold (add_sat x, undef) -> -1
3369 if (N0.isUndef() || N1.isUndef())
3370 return DAG.getAllOnesConstant(DL, VT);
3371
3372 // fold (add_sat c1, c2) -> c3
3373 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
3374 return C;
3375
3376 // canonicalize constant to RHS
3379 return DAG.getNode(Opcode, DL, VT, N1, N0);
3380
3381 // fold vector ops
3382 if (VT.isVector()) {
3383 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
3384 return FoldedVOp;
3385
3386 // fold (add_sat x, 0) -> x, vector edition
3388 return N0;
3389 }
3390
3391 // fold (add_sat x, 0) -> x
3392 if (isNullConstant(N1))
3393 return N0;
3394
3395 // If it cannot overflow, transform into an add.
3396 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3397 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
3398
3399 return SDValue();
3400}
3401
3403 bool ForceCarryReconstruction = false) {
3404 bool Masked = false;
3405
3406 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
3407 while (true) {
3408 if (ForceCarryReconstruction && V.getValueType() == MVT::i1)
3409 return V;
3410
3411 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
3412 V = V.getOperand(0);
3413 continue;
3414 }
3415
3416 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
3417 if (ForceCarryReconstruction)
3418 return V;
3419
3420 Masked = true;
3421 V = V.getOperand(0);
3422 continue;
3423 }
3424
3425 break;
3426 }
3427
3428 // If this is not a carry, return.
3429 if (V.getResNo() != 1)
3430 return SDValue();
3431
3432 if (V.getOpcode() != ISD::UADDO_CARRY && V.getOpcode() != ISD::USUBO_CARRY &&
3433 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
3434 return SDValue();
3435
3436 EVT VT = V->getValueType(0);
3437 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
3438 return SDValue();
3439
3440 // If the result is masked, then no matter what kind of bool it is we can
3441 // return. If it isn't, then we need to make sure the bool type is either 0 or
3442 // 1 and not other values.
3443 if (Masked ||
3444 TLI.getBooleanContents(V.getValueType()) ==
3446 return V;
3447
3448 return SDValue();
3449}
3450
3451/// Given the operands of an add/sub operation, see if the 2nd operand is a
3452/// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
3453/// the opcode and bypass the mask operation.
3454static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
3455 SelectionDAG &DAG, const SDLoc &DL) {
3456 if (N1.getOpcode() == ISD::ZERO_EXTEND)
3457 N1 = N1.getOperand(0);
3458
3459 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
3460 return SDValue();
3461
3462 EVT VT = N0.getValueType();
3463 SDValue N10 = N1.getOperand(0);
3464 if (N10.getValueType() != VT && N10.getOpcode() == ISD::TRUNCATE)
3465 N10 = N10.getOperand(0);
3466
3467 if (N10.getValueType() != VT)
3468 return SDValue();
3469
3470 if (DAG.ComputeNumSignBits(N10) != VT.getScalarSizeInBits())
3471 return SDValue();
3472
3473 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
3474 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
3475 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N10);
3476}
3477
3478/// Helper for doing combines based on N0 and N1 being added to each other.
3479SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
3480 const SDLoc &DL) {
3481 EVT VT = N0.getValueType();
3482
3483 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
3484 SDValue Y, N;
3485 if (sd_match(N1, m_Shl(m_Neg(m_Value(Y)), m_Value(N))))
3486 return DAG.getNode(ISD::SUB, DL, VT, N0,
3487 DAG.getNode(ISD::SHL, DL, VT, Y, N));
3488
3489 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
3490 return V;
3491
3492 // Look for:
3493 // add (add x, 1), y
3494 // And if the target does not like this form then turn into:
3495 // sub y, (xor x, -1)
3496 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.getOpcode() == ISD::ADD &&
3497 N0.hasOneUse() && isOneOrOneSplat(N0.getOperand(1)) &&
3498 // Limit this to after legalization if the add has wrap flags
3499 (Level >= AfterLegalizeDAG || (!N0->getFlags().hasNoUnsignedWrap() &&
3500 !N0->getFlags().hasNoSignedWrap()))) {
3501 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
3502 return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
3503 }
3504
3505 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse()) {
3506 // Hoist one-use subtraction by non-opaque constant:
3507 // (x - C) + y -> (x + y) - C
3508 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3509 if (isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
3510 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
3511 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
3512 }
3513 // Hoist one-use subtraction from non-opaque constant:
3514 // (C - x) + y -> (y - x) + C
3515 if (isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
3516 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
3517 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
3518 }
3519 }
3520
3521 // add (mul x, C), x -> mul x, C+1
3522 if (N0.getOpcode() == ISD::MUL && N0.getOperand(0) == N1 &&
3523 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true) &&
3524 N0.hasOneUse()) {
3525 SDValue NewC = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
3526 DAG.getConstant(1, DL, VT));
3527 return DAG.getNode(ISD::MUL, DL, VT, N0.getOperand(0), NewC);
3528 }
3529
3530 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
3531 // rather than 'add 0/-1' (the zext should get folded).
3532 // add (sext i1 Y), X --> sub X, (zext i1 Y)
3533 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
3534 N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
3536 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
3537 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
3538 }
3539
3540 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
3541 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
3542 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
3543 if (TN->getVT() == MVT::i1) {
3544 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
3545 DAG.getConstant(1, DL, VT));
3546 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
3547 }
3548 }
3549
3550 // (add X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3551 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1)) &&
3552 N1.getResNo() == 0)
3553 return DAG.getNode(ISD::UADDO_CARRY, DL, N1->getVTList(),
3554 N0, N1.getOperand(0), N1.getOperand(2));
3555
3556 // (add X, Carry) -> (uaddo_carry X, 0, Carry)
3558 if (SDValue Carry = getAsCarry(TLI, N1))
3559 return DAG.getNode(ISD::UADDO_CARRY, DL,
3560 DAG.getVTList(VT, Carry.getValueType()), N0,
3561 DAG.getConstant(0, DL, VT), Carry);
3562
3563 return SDValue();
3564}
3565
3566SDValue DAGCombiner::visitADDC(SDNode *N) {
3567 SDValue N0 = N->getOperand(0);
3568 SDValue N1 = N->getOperand(1);
3569 EVT VT = N0.getValueType();
3570 SDLoc DL(N);
3571
3572 // If the flag result is dead, turn this into an ADD.
3573 if (!N->hasAnyUseOfValue(1))
3574 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3575 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3576
3577 // canonicalize constant to RHS.
3578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3580 if (N0C && !N1C)
3581 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
3582
3583 // fold (addc x, 0) -> x + no carry out
3584 if (isNullConstant(N1))
3585 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
3586 DL, MVT::Glue));
3587
3588 // If it cannot overflow, transform into an add.
3590 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3591 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
3592
3593 return SDValue();
3594}
3595
3596/**
3597 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
3598 * then the flip also occurs if computing the inverse is the same cost.
3599 * This function returns an empty SDValue in case it cannot flip the boolean
3600 * without increasing the cost of the computation. If you want to flip a boolean
3601 * no matter what, use DAG.getLogicalNOT.
3602 */
3604 const TargetLowering &TLI,
3605 bool Force) {
3606 if (Force && isa<ConstantSDNode>(V))
3607 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3608
3609 if (V.getOpcode() != ISD::XOR)
3610 return SDValue();
3611
3612 if (DAG.isBoolConstant(V.getOperand(1)) == true)
3613 return V.getOperand(0);
3614 if (Force && isConstOrConstSplat(V.getOperand(1), false))
3615 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
3616 return SDValue();
3617}
3618
3619SDValue DAGCombiner::visitADDO(SDNode *N) {
3620 SDValue N0 = N->getOperand(0);
3621 SDValue N1 = N->getOperand(1);
3622 EVT VT = N0.getValueType();
3623 bool IsSigned = (ISD::SADDO == N->getOpcode());
3624
3625 EVT CarryVT = N->getValueType(1);
3626 SDLoc DL(N);
3627
3628 // If the flag result is dead, turn this into an ADD.
3629 if (!N->hasAnyUseOfValue(1))
3630 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3631 DAG.getUNDEF(CarryVT));
3632
3633 // canonicalize constant to RHS.
3636 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
3637
3638 // fold (addo x, 0) -> x + no carry out
3639 if (isNullOrNullSplat(N1))
3640 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
3641
3642 // If it cannot overflow, transform into an add.
3643 if (DAG.willNotOverflowAdd(IsSigned, N0, N1))
3644 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
3645 DAG.getConstant(0, DL, CarryVT));
3646
3647 if (IsSigned) {
3648 // fold (saddo (xor a, -1), 1) -> (ssub 0, a).
3649 if (isBitwiseNot(N0) && isOneOrOneSplat(N1))
3650 return DAG.getNode(ISD::SSUBO, DL, N->getVTList(),
3651 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3652 } else {
3653 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
3654 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
3655 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
3656 DAG.getConstant(0, DL, VT), N0.getOperand(0));
3657 return CombineTo(
3658 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3659 }
3660
3661 if (SDValue Combined = visitUADDOLike(N0, N1, N))
3662 return Combined;
3663
3664 if (SDValue Combined = visitUADDOLike(N1, N0, N))
3665 return Combined;
3666 }
3667
3668 return SDValue();
3669}
3670
3671SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
3672 EVT VT = N0.getValueType();
3673 if (VT.isVector())
3674 return SDValue();
3675
3676 // (uaddo X, (uaddo_carry Y, 0, Carry)) -> (uaddo_carry X, Y, Carry)
3677 // If Y + 1 cannot overflow.
3678 if (N1.getOpcode() == ISD::UADDO_CARRY && isNullConstant(N1.getOperand(1))) {
3679 SDValue Y = N1.getOperand(0);
3680 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
3682 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0, Y,
3683 N1.getOperand(2));
3684 }
3685
3686 // (uaddo X, Carry) -> (uaddo_carry X, 0, Carry)
3688 if (SDValue Carry = getAsCarry(TLI, N1))
3689 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(), N0,
3690 DAG.getConstant(0, SDLoc(N), VT), Carry);
3691
3692 return SDValue();
3693}
3694
3695SDValue DAGCombiner::visitADDE(SDNode *N) {
3696 SDValue N0 = N->getOperand(0);
3697 SDValue N1 = N->getOperand(1);
3698 SDValue CarryIn = N->getOperand(2);
3699
3700 // canonicalize constant to RHS
3701 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3703 if (N0C && !N1C)
3704 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
3705 N1, N0, CarryIn);
3706
3707 // fold (adde x, y, false) -> (addc x, y)
3708 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
3709 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
3710
3711 return SDValue();
3712}
3713
3714SDValue DAGCombiner::visitUADDO_CARRY(SDNode *N) {
3715 SDValue N0 = N->getOperand(0);
3716 SDValue N1 = N->getOperand(1);
3717 SDValue CarryIn = N->getOperand(2);
3718 SDLoc DL(N);
3719
3720 // canonicalize constant to RHS
3721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3723 if (N0C && !N1C)
3724 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
3725
3726 // fold (uaddo_carry x, y, false) -> (uaddo x, y)
3727 if (isNullConstant(CarryIn)) {
3728 if (!LegalOperations ||
3729 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
3730 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
3731 }
3732
3733 // fold (uaddo_carry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
3734 if (isNullConstant(N0) && isNullConstant(N1)) {
3735 EVT VT = N0.getValueType();
3736 EVT CarryVT = CarryIn.getValueType();
3737 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
3738 AddToWorklist(CarryExt.getNode());
3739 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
3740 DAG.getConstant(1, DL, VT)),
3741 DAG.getConstant(0, DL, CarryVT));
3742 }
3743
3744 if (SDValue Combined = visitUADDO_CARRYLike(N0, N1, CarryIn, N))
3745 return Combined;
3746
3747 if (SDValue Combined = visitUADDO_CARRYLike(N1, N0, CarryIn, N))
3748 return Combined;
3749
3750 // We want to avoid useless duplication.
3751 // TODO: This is done automatically for binary operations. As UADDO_CARRY is
3752 // not a binary operation, this is not really possible to leverage this
3753 // existing mechanism for it. However, if more operations require the same
3754 // deduplication logic, then it may be worth generalize.
3755 SDValue Ops[] = {N1, N0, CarryIn};
3756 SDNode *CSENode =
3757 DAG.getNodeIfExists(ISD::UADDO_CARRY, N->getVTList(), Ops, N->getFlags());
3758 if (CSENode)
3759 return SDValue(CSENode, 0);
3760
3761 return SDValue();
3762}
3763
3764/**
3765 * If we are facing some sort of diamond carry propagation pattern try to
3766 * break it up to generate something like:
3767 * (uaddo_carry X, 0, (uaddo_carry A, B, Z):Carry)
3768 *
3769 * The end result is usually an increase in operation required, but because the
3770 * carry is now linearized, other transforms can kick in and optimize the DAG.
3771 *
3772 * Patterns typically look something like
3773 * (uaddo A, B)
3774 * / \
3775 * Carry Sum
3776 * | \
3777 * | (uaddo_carry *, 0, Z)
3778 * | /
3779 * \ Carry
3780 * | /
3781 * (uaddo_carry X, *, *)
3782 *
3783 * But numerous variation exist. Our goal is to identify A, B, X and Z and
3784 * produce a combine with a single path for carry propagation.
3785 */
3787 SelectionDAG &DAG, SDValue X,
3788 SDValue Carry0, SDValue Carry1,
3789 SDNode *N) {
3790 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
3791 return SDValue();
3792 if (Carry1.getOpcode() != ISD::UADDO)
3793 return SDValue();
3794
3795 SDValue Z;
3796
3797 /**
3798 * First look for a suitable Z. It will present itself in the form of
3799 * (uaddo_carry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
3800 */
3801 if (Carry0.getOpcode() == ISD::UADDO_CARRY &&
3802 isNullConstant(Carry0.getOperand(1))) {
3803 Z = Carry0.getOperand(2);
3804 } else if (Carry0.getOpcode() == ISD::UADDO &&
3805 isOneConstant(Carry0.getOperand(1))) {
3806 EVT VT = Carry0->getValueType(1);
3807 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
3808 } else {
3809 // We couldn't find a suitable Z.
3810 return SDValue();
3811 }
3812
3813
3814 auto cancelDiamond = [&](SDValue A,SDValue B) {
3815 SDLoc DL(N);
3816 SDValue NewY =
3817 DAG.getNode(ISD::UADDO_CARRY, DL, Carry0->getVTList(), A, B, Z);
3818 Combiner.AddToWorklist(NewY.getNode());
3819 return DAG.getNode(ISD::UADDO_CARRY, DL, N->getVTList(), X,
3820 DAG.getConstant(0, DL, X.getValueType()),
3821 NewY.getValue(1));
3822 };
3823
3824 /**
3825 * (uaddo A, B)
3826 * |
3827 * Sum
3828 * |
3829 * (uaddo_carry *, 0, Z)
3830 */
3831 if (Carry0.getOperand(0) == Carry1.getValue(0)) {
3832 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
3833 }
3834
3835 /**
3836 * (uaddo_carry A, 0, Z)
3837 * |
3838 * Sum
3839 * |
3840 * (uaddo *, B)
3841 */
3842 if (Carry1.getOperand(0) == Carry0.getValue(0)) {
3843 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
3844 }
3845
3846 if (Carry1.getOperand(1) == Carry0.getValue(0)) {
3847 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
3848 }
3849
3850 return SDValue();
3851}
3852
3853// If we are facing some sort of diamond carry/borrow in/out pattern try to
3854// match patterns like:
3855//
3856// (uaddo A, B) CarryIn
3857// | \ |
3858// | \ |
3859// PartialSum PartialCarryOutX /
3860// | | /
3861// | ____|____________/
3862// | / |
3863// (uaddo *, *) \________
3864// | \ \
3865// | \ |
3866// | PartialCarryOutY |
3867// | \ |
3868// | \ /
3869// AddCarrySum | ______/
3870// | /
3871// CarryOut = (or *, *)
3872//
3873// And generate UADDO_CARRY (or USUBO_CARRY) with two result values:
3874//
3875// {AddCarrySum, CarryOut} = (uaddo_carry A, B, CarryIn)
3876//
3877// Our goal is to identify A, B, and CarryIn and produce UADDO_CARRY/USUBO_CARRY
3878// with a single path for carry/borrow out propagation.
3880 SDValue N0, SDValue N1, SDNode *N) {
3881 SDValue Carry0 = getAsCarry(TLI, N0);
3882 if (!Carry0)
3883 return SDValue();
3884 SDValue Carry1 = getAsCarry(TLI, N1);
3885 if (!Carry1)
3886 return SDValue();
3887
3888 unsigned Opcode = Carry0.getOpcode();
3889 if (Opcode != Carry1.getOpcode())
3890 return SDValue();
3891 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
3892 return SDValue();
3893 // Guarantee identical type of CarryOut
3894 EVT CarryOutType = N->getValueType(0);
3895 if (CarryOutType != Carry0.getValue(1).getValueType() ||
3896 CarryOutType != Carry1.getValue(1).getValueType())
3897 return SDValue();
3898
3899 // Canonicalize the add/sub of A and B (the top node in the above ASCII art)
3900 // as Carry0 and the add/sub of the carry in as Carry1 (the middle node).
3901 if (Carry1.getNode()->isOperandOf(Carry0.getNode()))
3902 std::swap(Carry0, Carry1);
3903
3904 // Check if nodes are connected in expected way.
3905 if (Carry1.getOperand(0) != Carry0.getValue(0) &&
3906 Carry1.getOperand(1) != Carry0.getValue(0))
3907 return SDValue();
3908
3909 // The carry in value must be on the righthand side for subtraction.
3910 unsigned CarryInOperandNum =
3911 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
3912 if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
3913 return SDValue();
3914 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
3915
3916 unsigned NewOp = Opcode == ISD::UADDO ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
3917 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
3918 return SDValue();
3919
3920 // Verify that the carry/borrow in is plausibly a carry/borrow bit.
3921 CarryIn = getAsCarry(TLI, CarryIn, true);
3922 if (!CarryIn)
3923 return SDValue();
3924
3925 SDLoc DL(N);
3926 CarryIn = DAG.getBoolExtOrTrunc(CarryIn, DL, Carry1->getValueType(1),
3927 Carry1->getValueType(0));
3928 SDValue Merged =
3929 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
3930 Carry0.getOperand(1), CarryIn);
3931
3932 // Please note that because we have proven that the result of the UADDO/USUBO
3933 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
3934 // therefore prove that if the first UADDO/USUBO overflows, the second
3935 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
3936 // maximum value.
3937 //
3938 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
3939 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
3940 //
3941 // This is important because it means that OR and XOR can be used to merge
3942 // carry flags; and that AND can return a constant zero.
3943 //
3944 // TODO: match other operations that can merge flags (ADD, etc)
3945 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
3946 if (N->getOpcode() == ISD::AND)
3947 return DAG.getConstant(0, DL, CarryOutType);
3948 return Merged.getValue(1);
3949}
3950
3951// Reconstruct a subtract-with-borrow chain from its canonicalized icmp form:
3952// carry_out = or(icmp ult A, B, and(icmp eq A, B, carry_in))
3953// InstCombine folds usub.with.overflow chains into this, losing the
3954// USUBO_CARRY that lowers to sbb/sbcs.
3956 const TargetLowering &TLI) {
3957 SDValue A, B, CarryIn;
3962 m_Value(CarryIn)))))
3963 return SDValue();
3964
3965 EVT IntVT = A.getValueType();
3966 // Skip vectors: USUBO_CARRY on a vector type has no legalization path and
3967 // would crash.
3968 if (IntVT.isVector() || !TLI.isOperationLegalOrCustom(
3970 *DAG.getContext(), IntVT)))
3971 return SDValue();
3972
3973 SDLoc DL(N);
3974 SDVTList VTs = DAG.getVTList(IntVT, N->getValueType(0));
3975 return DAG.getNode(ISD::USUBO_CARRY, DL, VTs, A, B, CarryIn).getValue(1);
3976}
3977
3978SDValue DAGCombiner::visitUADDO_CARRYLike(SDValue N0, SDValue N1,
3979 SDValue CarryIn, SDNode *N) {
3980 // fold (uaddo_carry (xor a, -1), b, c) -> (usubo_carry b, a, !c) and flip
3981 // carry.
3982 if (isBitwiseNot(N0))
3983 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
3984 SDLoc DL(N);
3985 SDValue Sub = DAG.getNode(ISD::USUBO_CARRY, DL, N->getVTList(), N1,
3986 N0.getOperand(0), NotC);
3987 return CombineTo(
3988 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
3989 }
3990
3991 // Iff the flag result is dead:
3992 // (uaddo_carry (add|uaddo X, Y), 0, Carry) -> (uaddo_carry X, Y, Carry)
3993 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3994 // or the dependency between the instructions.
3995 if ((N0.getOpcode() == ISD::ADD ||
3996 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
3997 N0.getValue(1) != CarryIn)) &&
3998 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
3999 return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), N->getVTList(),
4000 N0.getOperand(0), N0.getOperand(1), CarryIn);
4001
4002 /**
4003 * When one of the uaddo_carry argument is itself a carry, we may be facing
4004 * a diamond carry propagation. In which case we try to transform the DAG
4005 * to ensure linear carry propagation if that is possible.
4006 */
4007 if (auto Y = getAsCarry(TLI, N1)) {
4008 // Because both are carries, Y and Z can be swapped.
4009 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
4010 return R;
4011 if (auto R = combineUADDO_CARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
4012 return R;
4013 }
4014
4015 return SDValue();
4016}
4017
4018SDValue DAGCombiner::visitSADDO_CARRYLike(SDValue N0, SDValue N1,
4019 SDValue CarryIn, SDNode *N) {
4020 // fold (saddo_carry (xor a, -1), b, c) -> (ssubo_carry b, a, !c)
4021 if (isBitwiseNot(N0)) {
4022 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true))
4023 return DAG.getNode(ISD::SSUBO_CARRY, SDLoc(N), N->getVTList(), N1,
4024 N0.getOperand(0), NotC);
4025 }
4026
4027 return SDValue();
4028}
4029
4030SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
4031 SDValue N0 = N->getOperand(0);
4032 SDValue N1 = N->getOperand(1);
4033 SDValue CarryIn = N->getOperand(2);
4034 SDLoc DL(N);
4035
4036 // canonicalize constant to RHS
4037 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4038 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4039 if (N0C && !N1C)
4040 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
4041
4042 // fold (saddo_carry x, y, false) -> (saddo x, y)
4043 if (isNullConstant(CarryIn)) {
4044 if (!LegalOperations ||
4045 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
4046 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
4047 }
4048
4049 if (SDValue Combined = visitSADDO_CARRYLike(N0, N1, CarryIn, N))
4050 return Combined;
4051
4052 if (SDValue Combined = visitSADDO_CARRYLike(N1, N0, CarryIn, N))
4053 return Combined;
4054
4055 return SDValue();
4056}
4057
4058// Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
4059// clamp/truncation if necessary.
4061 SDValue RHS, SelectionDAG &DAG,
4062 const SDLoc &DL) {
4063 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
4064 "Illegal truncation");
4065
4066 if (DstVT == SrcVT)
4067 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4068
4069 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
4070 // clamping RHS.
4072 DstVT.getScalarSizeInBits());
4073 if (!DAG.MaskedValueIsZero(LHS, UpperBits))
4074 return SDValue();
4075
4076 SDValue SatLimit =
4078 DstVT.getScalarSizeInBits()),
4079 DL, SrcVT);
4080 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
4081 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
4082 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
4083 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
4084}
4085
4086// Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
4087// usubsat(a,b), optionally as a truncated type.
4088SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N, const SDLoc &DL) {
4089 if (N->getOpcode() != ISD::SUB ||
4090 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
4091 return SDValue();
4092
4093 EVT SubVT = N->getValueType(0);
4094 SDValue Op0 = N->getOperand(0);
4095 SDValue Op1 = N->getOperand(1);
4096
4097 // Try to find umax(a,b) - b or a - umin(a,b) patterns
4098 // they may be converted to usubsat(a,b).
4099 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4100 SDValue MaxLHS = Op0.getOperand(0);
4101 SDValue MaxRHS = Op0.getOperand(1);
4102 if (MaxLHS == Op1)
4103 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, DL);
4104 if (MaxRHS == Op1)
4105 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, DL);
4106 }
4107
4108 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
4109 SDValue MinLHS = Op1.getOperand(0);
4110 SDValue MinRHS = Op1.getOperand(1);
4111 if (MinLHS == Op0)
4112 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, DL);
4113 if (MinRHS == Op0)
4114 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, DL);
4115 }
4116
4117 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
4118 if (Op1.getOpcode() == ISD::TRUNCATE &&
4119 Op1.getOperand(0).getOpcode() == ISD::UMIN &&
4120 Op1.getOperand(0).hasOneUse()) {
4121 SDValue MinLHS = Op1.getOperand(0).getOperand(0);
4122 SDValue MinRHS = Op1.getOperand(0).getOperand(1);
4123 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
4124 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
4125 DAG, DL);
4126 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
4127 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
4128 DAG, DL);
4129 }
4130
4131 return SDValue();
4132}
4133
4134// Refinement of DAG/Type Legalisation (promotion) when CTLZ is used for
4135// counting leading ones. Broadly, it replaces the substraction with a left
4136// shift.
4137//
4138// * DAG Legalisation Pattern:
4139//
4140// (sub (ctlz (zeroextend (not Src)))
4141// BitWidthDiff)
4142//
4143// if BitWidthDiff == BitWidth(Node) - BitWidth(Src)
4144// -->
4145//
4146// (ctlz_zero_poison (not (shl (anyextend Src)
4147// BitWidthDiff)))
4148//
4149// * Type Legalisation Pattern:
4150//
4151// (sub (ctlz (and (xor Src XorMask)
4152// AndMask))
4153// BitWidthDiff)
4154//
4155// if AndMask has only trailing ones
4156// and MaskBitWidth(AndMask) == BitWidth(Node) - BitWidthDiff
4157// and XorMask has more trailing ones than AndMask
4158// -->
4159//
4160// (ctlz_zero_poison (not (shl Src BitWidthDiff)))
4162 const SDLoc DL(N);
4163 SDValue N0 = N->getOperand(0);
4164 EVT VT = N0.getValueType();
4165 unsigned BitWidth = VT.getScalarSizeInBits();
4166
4167 APInt AndMask;
4168 APInt XorMask;
4169 uint64_t BitWidthDiff;
4170
4171 SDValue CtlzOp;
4172 SDValue Src;
4173
4174 if (!sd_match(N, m_Sub(m_Ctlz(m_Value(CtlzOp)), m_ConstInt(BitWidthDiff))))
4175 return SDValue();
4176
4177 if (sd_match(CtlzOp, m_ZExt(m_Not(m_Value(Src))))) {
4178 // DAG Legalisation Pattern:
4179 // (sub (ctlz (zero_extend (not Op)) BitWidthDiff))
4180 if ((BitWidth - Src.getValueType().getScalarSizeInBits()) != BitWidthDiff)
4181 return SDValue();
4182
4183 Src = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Src);
4184 } else if (sd_match(CtlzOp, m_And(m_Xor(m_Value(Src), m_ConstInt(XorMask)),
4185 m_ConstInt(AndMask)))) {
4186 // Type Legalisation Pattern:
4187 // (sub (ctlz (and (xor Op XorMask) AndMask)) BitWidthDiff)
4188 if (BitWidthDiff >= BitWidth)
4189 return SDValue();
4190 unsigned AndMaskWidth = BitWidth - BitWidthDiff;
4191 if (!(AndMask.isMask(AndMaskWidth) && XorMask.countr_one() >= AndMaskWidth))
4192 return SDValue();
4193 } else
4194 return SDValue();
4195
4196 SDValue ShiftConst = DAG.getShiftAmountConstant(BitWidthDiff, VT, DL);
4197 SDValue LShift = DAG.getNode(ISD::SHL, DL, VT, Src, ShiftConst);
4198 SDValue Not =
4199 DAG.getNode(ISD::XOR, DL, VT, LShift, DAG.getAllOnesConstant(DL, VT));
4200
4201 return DAG.getNode(ISD::CTLZ_ZERO_POISON, DL, VT, Not);
4202}
4203
4204// Fold sub(x, mul(divrem(x,y)[0], y)) to divrem(x, y)[1]
4206 const SDLoc &DL) {
4207 assert(N->getOpcode() == ISD::SUB && "Node must be a SUB");
4208 SDValue Sub0 = N->getOperand(0);
4209 SDValue Sub1 = N->getOperand(1);
4210
4211 auto CheckAndFoldMulCase = [&](SDValue DivRem, SDValue MaybeY) -> SDValue {
4212 if ((DivRem.getOpcode() == ISD::SDIVREM ||
4213 DivRem.getOpcode() == ISD::UDIVREM) &&
4214 DivRem.getResNo() == 0 && DivRem.getOperand(0) == Sub0 &&
4215 DivRem.getOperand(1) == MaybeY) {
4216 return SDValue(DivRem.getNode(), 1);
4217 }
4218 return SDValue();
4219 };
4220
4221 if (Sub1.getOpcode() == ISD::MUL) {
4222 // (sub x, (mul divrem(x,y)[0], y))
4223 SDValue Mul0 = Sub1.getOperand(0);
4224 SDValue Mul1 = Sub1.getOperand(1);
4225
4226 if (SDValue Res = CheckAndFoldMulCase(Mul0, Mul1))
4227 return Res;
4228
4229 if (SDValue Res = CheckAndFoldMulCase(Mul1, Mul0))
4230 return Res;
4231
4232 } else if (Sub1.getOpcode() == ISD::SHL) {
4233 // Handle (sub x, (shl divrem(x,y)[0], C)) where y = 1 << C
4234 SDValue Shl0 = Sub1.getOperand(0);
4235 SDValue Shl1 = Sub1.getOperand(1);
4236 // Check if Shl0 is divrem(x, Y)[0]
4237 if ((Shl0.getOpcode() == ISD::SDIVREM ||
4238 Shl0.getOpcode() == ISD::UDIVREM) &&
4239 Shl0.getResNo() == 0 && Shl0.getOperand(0) == Sub0) {
4240
4241 SDValue Divisor = Shl0.getOperand(1);
4242
4243 ConstantSDNode *DivC = isConstOrConstSplat(Divisor);
4245 if (!DivC || !ShC)
4246 return SDValue();
4247
4248 if (DivC->getAPIntValue().isPowerOf2() &&
4249 DivC->getAPIntValue().logBase2() == ShC->getAPIntValue())
4250 return SDValue(Shl0.getNode(), 1);
4251 }
4252 }
4253 return SDValue();
4254}
4255
4256// Since it may not be valid to emit a fold to zero for vector initializers
4257// check if we can before folding.
4258static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
4259 SelectionDAG &DAG, bool LegalOperations) {
4260 if (!VT.isVector())
4261 return DAG.getConstant(0, DL, VT);
4262 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
4263 return DAG.getConstant(0, DL, VT);
4264 return SDValue();
4265}
4266
4267SDValue DAGCombiner::visitSUB(SDNode *N) {
4268 SDValue N0 = N->getOperand(0);
4269 SDValue N1 = N->getOperand(1);
4270 EVT VT = N0.getValueType();
4271 unsigned BitWidth = VT.getScalarSizeInBits();
4272 SDLoc DL(N);
4273
4274 if (SDValue V = foldSubCtlzNot(N, DAG))
4275 return V;
4276
4277 // fold (sub x, x) -> 0
4278 if (N0 == N1)
4279 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
4280
4281 // fold (sub c1, c2) -> c3
4282 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
4283 return C;
4284
4285 // fold vector ops
4286 if (VT.isVector()) {
4287 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4288 return FoldedVOp;
4289
4290 // fold (sub x, 0) -> x, vector edition
4292 return N0;
4293 }
4294
4295 // (sub x, ([v]select (ult x, y), 0, y)) -> (umin x, (sub x, y))
4296 // (sub x, ([v]select (uge x, y), y, 0)) -> (umin x, (sub x, y))
4297 if (N1.hasOneUse() && hasUMin(VT)) {
4298 SDValue Y;
4299 auto MS0 = m_Specific(N0);
4300 auto MVY = m_Value(Y);
4301 auto MZ = m_Zero();
4302 auto MCC1 = m_SpecificCondCode(ISD::SETULT);
4303 auto MCC2 = m_SpecificCondCode(ISD::SETUGE);
4304
4305 if (sd_match(N1, m_SelectCCLike(MS0, MVY, MZ, m_Deferred(Y), MCC1)) ||
4306 sd_match(N1, m_SelectCCLike(MS0, MVY, m_Deferred(Y), MZ, MCC2)) ||
4307 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC1), MZ, m_Deferred(Y))) ||
4308 sd_match(N1, m_VSelect(m_SetCC(MS0, MVY, MCC2), m_Deferred(Y), MZ)))
4309
4310 return DAG.getNode(ISD::UMIN, DL, VT, N0,
4311 DAG.getNode(ISD::SUB, DL, VT, N0, Y));
4312 }
4313
4314 if (SDValue NewSel = foldBinOpIntoSelect(N))
4315 return NewSel;
4316
4317 // fold (sub x, c) -> (add x, -c)
4318 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4319 return DAG.getNode(ISD::ADD, DL, VT, N0,
4320 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4321
4322 if (isNullOrNullSplat(N0)) {
4323 // Right-shifting everything out but the sign bit followed by negation is
4324 // the same as flipping arithmetic/logical shift type without the negation:
4325 // -(X >>u 31) -> (X >>s 31)
4326 // -(X >>s 31) -> (X >>u 31)
4327 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
4328 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
4329 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
4330 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
4331 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
4332 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
4333 }
4334 }
4335
4336 // 0 - X --> 0 if the sub is NUW.
4337 if (N->getFlags().hasNoUnsignedWrap())
4338 return N0;
4339
4341 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
4342 // N1 must be 0 because negating the minimum signed value is undefined.
4343 if (N->getFlags().hasNoSignedWrap())
4344 return N0;
4345
4346 // 0 - X --> X if X is 0 or the minimum signed value.
4347 return N1;
4348 }
4349
4350 // Convert 0 - abs(x).
4351 if (ISD::isAbsOpcode(N1.getOpcode()) && N1.hasOneUse() &&
4352 !TLI.isOperationLegalOrCustom(N1.getOpcode(), VT))
4353 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
4354 return Result;
4355
4356 // Similar to the previous rule, but this time targeting an expanded abs.
4357 // (sub 0, (max X, (sub 0, X))) --> (min X, (sub 0, X))
4358 // as well as
4359 // (sub 0, (min X, (sub 0, X))) --> (max X, (sub 0, X))
4360 // Note that these two are applicable to both signed and unsigned min/max.
4361 SDValue X;
4362 SDValue S0;
4363 auto NegPat = m_Value(S0, m_Neg(m_Deferred(X)));
4364 if (sd_match(N1, m_OneUse(m_AnyOf(m_SMax(m_Value(X), NegPat),
4365 m_UMax(m_Value(X), NegPat),
4366 m_SMin(m_Value(X), NegPat),
4367 m_UMin(m_Value(X), NegPat))))) {
4368 unsigned NewOpc = ISD::getInverseMinMaxOpcode(N1->getOpcode());
4369 if (hasOperation(NewOpc, VT))
4370 return DAG.getNode(NewOpc, DL, VT, X, S0);
4371 }
4372
4373 // Fold neg(splat(neg(x)) -> splat(x)
4374 if (VT.isVector()) {
4375 SDValue N1S = DAG.getSplatValue(N1, true);
4376 if (N1S && N1S.getOpcode() == ISD::SUB &&
4377 isNullConstant(N1S.getOperand(0)))
4378 return DAG.getSplat(VT, DL, N1S.getOperand(1));
4379 }
4380
4381 // sub 0, (and x, 1) --> SIGN_EXTEND_INREG x, i1
4382 if (N1.getOpcode() == ISD::AND && N1.hasOneUse() &&
4383 isOneOrOneSplat(N1->getOperand(1))) {
4384 EVT ExtVT = VT.changeElementType(*DAG.getContext(), MVT::i1);
4387 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N1->getOperand(0),
4388 DAG.getValueType(ExtVT));
4389 }
4390 }
4391 }
4392
4393 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
4395 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4396
4397 // fold (A - (0-B)) -> A+B
4398 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
4399 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
4400
4401 // fold A-(A-B) -> B
4402 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
4403 return N1.getOperand(1);
4404
4405 // fold (A+B)-A -> B
4406 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
4407 return N0.getOperand(1);
4408
4409 // fold (A+B)-B -> A
4410 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
4411 return N0.getOperand(0);
4412
4413 // fold (A+C1)-C2 -> A+(C1-C2)
4414 if (N0.getOpcode() == ISD::ADD) {
4415 SDValue N01 = N0.getOperand(1);
4416 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N01, N1}))
4417 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
4418 }
4419
4420 // fold C2-(A+C1) -> (C2-C1)-A
4421 if (N1.getOpcode() == ISD::ADD) {
4422 SDValue N11 = N1.getOperand(1);
4423 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}))
4424 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
4425 }
4426
4427 // fold (A-C1)-C2 -> A-(C1+C2)
4428 if (N0.getOpcode() == ISD::SUB) {
4429 SDValue N01 = N0.getOperand(1);
4430 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N01, N1}))
4431 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
4432 }
4433
4434 // fold (c1-A)-c2 -> (c1-c2)-A
4435 if (N0.getOpcode() == ISD::SUB) {
4436 SDValue N00 = N0.getOperand(0);
4437 if (SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N00, N1}))
4438 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
4439 }
4440
4441 SDValue A, B, C;
4442
4443 // fold ((A+(B+C))-B) -> A+C
4444 if (sd_match(N0, m_Add(m_Value(A), m_Add(m_Specific(N1), m_Value(C)))))
4445 return DAG.getNode(ISD::ADD, DL, VT, A, C);
4446
4447 // fold ((A+(B-C))-B) -> A-C
4448 if (sd_match(N0, m_Add(m_Value(A), m_Sub(m_Specific(N1), m_Value(C)))))
4449 return DAG.getNode(ISD::SUB, DL, VT, A, C);
4450
4451 // fold ((A-(B-C))-C) -> A-B
4452 if (sd_match(N0, m_Sub(m_Value(A), m_Sub(m_Value(B), m_Specific(N1)))))
4453 return DAG.getNode(ISD::SUB, DL, VT, A, B);
4454
4455 // fold (A-(B-C)) -> A+(C-B)
4456 if (sd_match(N1, m_OneUse(m_Sub(m_Value(B), m_Value(C)))))
4457 return DAG.getNode(ISD::ADD, DL, VT, N0,
4458 DAG.getNode(ISD::SUB, DL, VT, C, B));
4459
4460 // A - (A & B) -> A & (~B)
4461 if (sd_match(N1, m_And(m_Specific(N0), m_Value(B))) &&
4462 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true)))
4463 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getNOT(DL, B, VT));
4464
4465 // fold (A - (-B * C)) -> (A + (B * C))
4466 if (sd_match(N1, m_OneUse(m_Mul(m_Neg(m_Value(B)), m_Value(C)))))
4467 return DAG.getNode(ISD::ADD, DL, VT, N0,
4468 DAG.getNode(ISD::MUL, DL, VT, B, C));
4469
4470 // If either operand of a sub is undef, the result is undef
4471 if (N0.isUndef())
4472 return N0;
4473 if (N1.isUndef())
4474 return N1;
4475
4476 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DL, DAG))
4477 return V;
4478
4479 if (SDValue V = foldAddSubOfSignBit(N, DL, DAG))
4480 return V;
4481
4482 // Try to match AVGCEIL fixedwidth pattern
4483 if (SDValue V = foldSubToAvg(N, DL))
4484 return V;
4485
4486 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, DL))
4487 return V;
4488
4489 if (SDValue V = foldSubToUSubSat(VT, N, DL))
4490 return V;
4491
4492 if (SDValue V = foldRemainderIdiom(N, DAG, DL))
4493 return V;
4494
4495 // (A - B) - 1 -> add (xor B, -1), A
4497 m_One(/*AllowUndefs=*/true))))
4498 return DAG.getNode(ISD::ADD, DL, VT, A, DAG.getNOT(DL, B, VT));
4499
4500 // Look for:
4501 // sub y, (xor x, -1)
4502 // And if the target does not like this form then turn into:
4503 // add (add x, y), 1
4504 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
4505 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
4506 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
4507 }
4508
4509 // Hoist one-use addition by non-opaque constant:
4510 // (x + C) - y -> (x - y) + C
4511 if (!reassociationCanBreakAddressingModePattern(ISD::SUB, DL, N, N0, N1) &&
4512 N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
4513 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4514 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4515 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
4516 }
4517 // y - (x + C) -> (y - x) - C
4518 if (N1.getOpcode() == ISD::ADD && N1.hasOneUse() &&
4519 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
4520 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
4521 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
4522 }
4523 // (x - C) - y -> (x - y) - C
4524 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
4525 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4526 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
4527 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
4528 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
4529 }
4530 // (C - x) - y -> C - (x + y)
4531 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
4532 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
4533 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
4534 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
4535 }
4536
4537 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
4538 // rather than 'sub 0/1' (the sext should get folded).
4539 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
4540 if (N1.getOpcode() == ISD::ZERO_EXTEND &&
4541 N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
4542 TLI.getBooleanContents(VT) ==
4544 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
4545 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
4546 }
4547
4548 // fold B = sra (A, size(A)-1); sub (xor (A, B), B) -> (abs A)
4549 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
4551 sd_match(N0, m_Xor(m_Specific(A), m_Specific(N1))))
4552 return DAG.getNode(ISD::ABS, DL, VT, A);
4553
4554 // If the relocation model supports it, consider symbol offsets.
4555 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
4556 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
4557 // fold (sub Sym+c1, Sym+c2) -> c1-c2
4558 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
4559 if (GA->getGlobal() == GB->getGlobal())
4560 return DAG.getConstant(
4561 APInt(VT.getScalarSizeInBits(), GA->getOffset() - GB->getOffset(),
4562 /*isSigned=*/false, /*implicitTrunc=*/true),
4563 DL, VT);
4564 }
4565
4566 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
4567 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
4568 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
4569 if (TN->getVT() == MVT::i1) {
4570 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
4571 DAG.getConstant(1, DL, VT));
4572 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
4573 }
4574 }
4575
4576 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C)) if this is the
4577 // only use of the vscale value or if (vscale * -C) is a valid add immediate.
4578 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
4579 if (N1.getOpcode() == ISD::VSCALE) {
4580 const APInt &IntVal = N1.getConstantOperandAPInt(0);
4581 if ((N1.hasOneUse() ||
4582 TLI.isLegalAddScalableImmediate(-IntVal.getSExtValue())) &&
4583 (!IntVal.isPowerOf2() ||
4584 hasOperation(ISD::MUL, N1.getOperand(0).getValueType())))
4585 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
4586 }
4587
4588 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
4589 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
4590 APInt NewStep = -N1.getConstantOperandAPInt(0);
4591 return DAG.getNode(ISD::ADD, DL, VT, N0,
4592 DAG.getStepVector(DL, VT, NewStep));
4593 }
4594
4595 // Prefer an add for more folding potential and possibly better codegen:
4596 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
4597 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
4598 SDValue ShAmt = N1.getOperand(1);
4599 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
4600 if (ShAmtC && ShAmtC->getAPIntValue() == (BitWidth - 1)) {
4601 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
4602 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
4603 }
4604 }
4605
4606 // As with the previous fold, prefer add for more folding potential.
4607 // Subtracting SMIN/0 is the same as adding SMIN/0:
4608 // N0 - (X << BW-1) --> N0 + (X << BW-1)
4609 if (N1.getOpcode() == ISD::SHL) {
4610 ConstantSDNode *ShlC = isConstOrConstSplat(N1.getOperand(1));
4611 if (ShlC && ShlC->getAPIntValue() == (BitWidth - 1))
4612 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
4613 }
4614
4615 // (sub (usubo_carry X, 0, Carry), Y) -> (usubo_carry X, Y, Carry)
4616 if (N0.getOpcode() == ISD::USUBO_CARRY && isNullConstant(N0.getOperand(1)) &&
4617 N0.getResNo() == 0 && N0.hasOneUse())
4618 return DAG.getNode(ISD::USUBO_CARRY, DL, N0->getVTList(),
4619 N0.getOperand(0), N1, N0.getOperand(2));
4620
4622 // (sub Carry, X) -> (uaddo_carry (sub 0, X), 0, Carry)
4623 if (SDValue Carry = getAsCarry(TLI, N0)) {
4624 SDValue X = N1;
4625 SDValue Zero = DAG.getConstant(0, DL, VT);
4626 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
4627 return DAG.getNode(ISD::UADDO_CARRY, DL,
4628 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
4629 Carry);
4630 }
4631 }
4632
4633 if (ConstantSDNode *C0 = isConstOrConstSplat(N0)) {
4634 const APInt &C0Val = C0->getAPIntValue();
4635
4636 // sub nuw C, x --> xor x, C when C is a mask (2^k - 1)
4637 if (N->getFlags().hasNoUnsignedWrap() && C0Val.isMask())
4638 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4639
4640 // If there's no chance of borrowing from adjacent bits, then sub is xor:
4641 // sub C0, X --> xor X, C0
4642 if (!C0->isOpaque()) {
4643 const APInt &MaybeOnes = ~DAG.computeKnownBits(N1).Zero;
4644 if ((C0Val - MaybeOnes) == (C0Val ^ MaybeOnes))
4645 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
4646 }
4647 }
4648
4649 // smax(a,b) - smin(a,b) --> abds(a,b)
4650 if ((!LegalOperations || hasOperation(ISD::ABDS, VT)) &&
4651 sd_match(N0, &DAG, m_SMaxLike(m_Value(A), m_Value(B))) &&
4652 sd_match(N1, &DAG, m_SMinLike(m_Specific(A), m_Specific(B))))
4653 return DAG.getNode(ISD::ABDS, DL, VT, A, B);
4654
4655 // smin(a,b) - smax(a,b) --> neg(abds(a,b))
4656 if (hasOperation(ISD::ABDS, VT) &&
4657 sd_match(N0, &DAG, m_SMinLike(m_Value(A), m_Value(B))) &&
4658 sd_match(N1, &DAG, m_SMaxLike(m_Specific(A), m_Specific(B))))
4659 return DAG.getNegative(DAG.getNode(ISD::ABDS, DL, VT, A, B), DL, VT);
4660
4661 // umax(a,b) - umin(a,b) --> abdu(a,b)
4662 if ((!LegalOperations || hasOperation(ISD::ABDU, VT)) &&
4663 sd_match(N0, &DAG, m_UMaxLike(m_Value(A), m_Value(B))) &&
4664 sd_match(N1, &DAG, m_UMinLike(m_Specific(A), m_Specific(B))))
4665 return DAG.getNode(ISD::ABDU, DL, VT, A, B);
4666
4667 // umin(a,b) - umax(a,b) --> neg(abdu(a,b))
4668 if (hasOperation(ISD::ABDU, VT) &&
4669 sd_match(N0, &DAG, m_UMinLike(m_Value(A), m_Value(B))) &&
4670 sd_match(N1, &DAG, m_UMaxLike(m_Specific(A), m_Specific(B))))
4671 return DAG.getNegative(DAG.getNode(ISD::ABDU, DL, VT, A, B), DL, VT);
4672
4673 return SDValue();
4674}
4675
4676SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
4677 unsigned Opcode = N->getOpcode();
4678 SDValue N0 = N->getOperand(0);
4679 SDValue N1 = N->getOperand(1);
4680 EVT VT = N0.getValueType();
4681 bool IsSigned = Opcode == ISD::SSUBSAT;
4682 SDLoc DL(N);
4683
4684 // fold (sub_sat x, undef) -> 0
4685 if (N0.isUndef() || N1.isUndef())
4686 return DAG.getConstant(0, DL, VT);
4687
4688 // fold (sub_sat x, x) -> 0
4689 if (N0 == N1)
4690 return DAG.getConstant(0, DL, VT);
4691
4692 // fold (sub_sat c1, c2) -> c3
4693 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
4694 return C;
4695
4696 // fold vector ops
4697 if (VT.isVector()) {
4698 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4699 return FoldedVOp;
4700
4701 // fold (sub_sat x, 0) -> x, vector edition
4703 return N0;
4704 }
4705
4706 // fold (sub_sat x, 0) -> x
4707 if (isNullConstant(N1))
4708 return N0;
4709
4710 // If it cannot overflow, transform into an sub.
4711 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4712 return DAG.getNode(ISD::SUB, DL, VT, N0, N1);
4713
4714 // Narrow a vXiN USUBSAT to a smaller type when both operands are known
4715 // to fit in fewer bits. This allows targets with native narrow USUBSAT
4716 // (e.g. vpsubusb/vpsubusw) to avoid emulation with vpmaxu + vsub.
4717 if (!IsSigned && VT.isVector() && VT.isSimple()) {
4718 unsigned ScalarBits = VT.getScalarSizeInBits();
4719 if (ScalarBits > 8 && isPowerOf2_32(ScalarBits) &&
4720 !TLI.isOperationLegal(ISD::USUBSAT, VT)) {
4721 KnownBits Known0 = DAG.computeKnownBits(N0);
4722 unsigned ActiveBits = Known0.countMaxActiveBits();
4723 for (unsigned NarrowBits = PowerOf2Ceil(ActiveBits);
4724 NarrowBits != 0 && NarrowBits < ScalarBits; NarrowBits *= 2) {
4725 unsigned Scale = ScalarBits / NarrowBits;
4726 unsigned NumElts = VT.getVectorNumElements() * Scale;
4727 MVT NarrowSVT = MVT::getIntegerVT(NarrowBits);
4728 MVT NarrowVT = MVT::getVectorVT(NarrowSVT, NumElts);
4729
4730 if (!TLI.isOperationLegalOrCustom(ISD::USUBSAT, NarrowVT))
4731 continue;
4732 KnownBits Known1 = DAG.computeKnownBits(N1);
4733 if (Known1.countMaxActiveBits() <= NarrowBits) {
4734 SDValue NarrowN0 = DAG.getBitcast(NarrowVT, N0);
4735 SDValue NarrowN1 = DAG.getBitcast(NarrowVT, N1);
4736 SDValue NarrowSub =
4737 DAG.getNode(ISD::USUBSAT, DL, NarrowVT, NarrowN0, NarrowN1);
4738 return DAG.getBitcast(VT, NarrowSub);
4739 }
4740 // TODO: If N1 doesn't fit in NarrowBits, we could OR the upper bits
4741 // of N1 with 1s to force saturation in those lanes, allowing the
4742 // narrow USUBSAT to still be used. This requires a TLI hook to check
4743 // whether the constant can be folded as a broadcast memory operand
4744 // (profitable on AVX512, not on SSE/AVX), to avoid introducing an
4745 // extra register and instruction on non-AVX512 targets.
4746 break;
4747 }
4748 }
4749 }
4750 return SDValue();
4751}
4752
4753SDValue DAGCombiner::visitSUBC(SDNode *N) {
4754 SDValue N0 = N->getOperand(0);
4755 SDValue N1 = N->getOperand(1);
4756 EVT VT = N0.getValueType();
4757 SDLoc DL(N);
4758
4759 // If the flag result is dead, turn this into an SUB.
4760 if (!N->hasAnyUseOfValue(1))
4761 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4762 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4763
4764 // fold (subc x, x) -> 0 + no borrow
4765 if (N0 == N1)
4766 return CombineTo(N, DAG.getConstant(0, DL, VT),
4767 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4768
4769 // fold (subc x, 0) -> x + no borrow
4770 if (isNullConstant(N1))
4771 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4772
4773 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4774 if (isAllOnesConstant(N0))
4775 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4776 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
4777
4778 return SDValue();
4779}
4780
4781SDValue DAGCombiner::visitSUBO(SDNode *N) {
4782 SDValue N0 = N->getOperand(0);
4783 SDValue N1 = N->getOperand(1);
4784 EVT VT = N0.getValueType();
4785 bool IsSigned = (ISD::SSUBO == N->getOpcode());
4786
4787 EVT CarryVT = N->getValueType(1);
4788 SDLoc DL(N);
4789
4790 // If the flag result is dead, turn this into an SUB.
4791 if (!N->hasAnyUseOfValue(1))
4792 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4793 DAG.getUNDEF(CarryVT));
4794
4795 // fold (subo x, x) -> 0 + no borrow
4796 if (N0 == N1)
4797 return CombineTo(N, DAG.getConstant(0, DL, VT),
4798 DAG.getConstant(0, DL, CarryVT));
4799
4800 // fold (subox, c) -> (addo x, -c)
4801 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1))
4802 if (IsSigned && !N1C->isMinSignedValue())
4803 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
4804 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
4805
4806 // fold (subo x, 0) -> x + no borrow
4807 if (isNullOrNullSplat(N1))
4808 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
4809
4810 // If it cannot overflow, transform into an sub.
4811 if (DAG.willNotOverflowSub(IsSigned, N0, N1))
4812 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
4813 DAG.getConstant(0, DL, CarryVT));
4814
4815 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
4816 if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
4817 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
4818 DAG.getConstant(0, DL, CarryVT));
4819
4820 return SDValue();
4821}
4822
4823SDValue DAGCombiner::visitSUBE(SDNode *N) {
4824 SDValue N0 = N->getOperand(0);
4825 SDValue N1 = N->getOperand(1);
4826 SDValue CarryIn = N->getOperand(2);
4827
4828 // fold (sube x, y, false) -> (subc x, y)
4829 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
4830 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
4831
4832 return SDValue();
4833}
4834
4835SDValue DAGCombiner::visitUSUBO_CARRY(SDNode *N) {
4836 SDValue N0 = N->getOperand(0);
4837 SDValue N1 = N->getOperand(1);
4838 SDValue CarryIn = N->getOperand(2);
4839
4840 // fold (usubo_carry x, y, false) -> (usubo x, y)
4841 if (isNullConstant(CarryIn)) {
4842 if (!LegalOperations ||
4843 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
4844 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
4845 }
4846
4847 // Iff the flag result is dead:
4848 // (usubo_carry (sub X, Y), 0, Carry) -> (usubo_carry X, Y, Carry)
4849 if (N0.getOpcode() == ISD::SUB && isNullConstant(N1) &&
4850 !N->hasAnyUseOfValue(1))
4851 return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), N->getVTList(),
4852 N0.getOperand(0), N0.getOperand(1), CarryIn);
4853
4854 return SDValue();
4855}
4856
4857SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
4858 SDValue N0 = N->getOperand(0);
4859 SDValue N1 = N->getOperand(1);
4860 SDValue CarryIn = N->getOperand(2);
4861
4862 // fold (ssubo_carry x, y, false) -> (ssubo x, y)
4863 if (isNullConstant(CarryIn)) {
4864 if (!LegalOperations ||
4865 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
4866 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
4867 }
4868
4869 return SDValue();
4870}
4871
4872// Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
4873// UMULFIXSAT here.
4874SDValue DAGCombiner::visitMULFIX(SDNode *N) {
4875 SDValue N0 = N->getOperand(0);
4876 SDValue N1 = N->getOperand(1);
4877 SDValue Scale = N->getOperand(2);
4878 EVT VT = N0.getValueType();
4879
4880 // fold (mulfix x, undef, scale) -> 0
4881 if (N0.isUndef() || N1.isUndef())
4882 return DAG.getConstant(0, SDLoc(N), VT);
4883
4884 // Canonicalize constant to RHS (vector doesn't have to splat)
4887 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
4888
4889 // fold (mulfix x, 0, scale) -> 0
4890 if (isNullConstant(N1))
4891 return DAG.getConstant(0, SDLoc(N), VT);
4892
4893 return SDValue();
4894}
4895
4896SDValue DAGCombiner::visitMUL(SDNode *N) {
4897 SDValue N0 = N->getOperand(0);
4898 SDValue N1 = N->getOperand(1);
4899 EVT VT = N0.getValueType();
4900 unsigned BitWidth = VT.getScalarSizeInBits();
4901 SDLoc DL(N);
4902
4903 // fold (mul x, undef) -> 0
4904 if (N0.isUndef() || N1.isUndef())
4905 return DAG.getConstant(0, DL, VT);
4906
4907 // fold (mul c1, c2) -> c1*c2
4908 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, DL, VT, {N0, N1}))
4909 return C;
4910
4911 // canonicalize constant to RHS (vector doesn't have to splat)
4914 return DAG.getNode(ISD::MUL, DL, VT, N1, N0);
4915
4916 bool N1IsConst = false;
4917 bool N1IsOpaqueConst = false;
4918 APInt ConstValue1;
4919
4920 // fold vector ops
4921 if (VT.isVector()) {
4922 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
4923 return FoldedVOp;
4924
4925 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
4926 assert((!N1IsConst || ConstValue1.getBitWidth() == BitWidth) &&
4927 "Splat APInt should be element width");
4928 } else {
4929 N1IsConst = isa<ConstantSDNode>(N1);
4930 if (N1IsConst) {
4931 ConstValue1 = N1->getAsAPIntVal();
4932 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
4933 }
4934 }
4935
4936 // fold (mul x, 0) -> 0
4937 if (N1IsConst && ConstValue1.isZero())
4938 return N1;
4939
4940 // fold (mul x, 1) -> x
4941 if (N1IsConst && ConstValue1.isOne())
4942 return N0;
4943
4944 if (SDValue NewSel = foldBinOpIntoSelect(N))
4945 return NewSel;
4946
4947 // fold (mul x, -1) -> 0-x
4948 if (N1IsConst && ConstValue1.isAllOnes())
4949 return DAG.getNegative(N0, DL, VT);
4950
4951 // fold (mul x, (1 << c)) -> x << c
4952 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
4953 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
4954 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
4955 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
4956 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
4957 SDNodeFlags Flags;
4958 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap());
4959 // Preserve nsw when the shift amount is strictly less than BitWidth - 1,
4960 // i.e. the multiplier is not the signed minimum value.
4961 if (N->getFlags().hasNoSignedWrap() && N1IsConst &&
4962 ConstValue1.logBase2() < BitWidth - 1)
4963 Flags.setNoSignedWrap(true);
4964 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc, Flags);
4965 }
4966 }
4967
4968 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
4969 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
4970 unsigned Log2Val = (-ConstValue1).logBase2();
4971
4972 // FIXME: If the input is something that is easily negated (e.g. a
4973 // single-use add), we should put the negate there.
4974 return DAG.getNode(
4975 ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4976 DAG.getNode(ISD::SHL, DL, VT, N0,
4977 DAG.getShiftAmountConstant(Log2Val, VT, DL)));
4978 }
4979
4980 // Attempt to reuse an existing umul_lohi/smul_lohi node, but only if the
4981 // hi result is in use in case we hit this mid-legalization.
4982 for (unsigned LoHiOpc : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
4983 if (!LegalOperations || TLI.isOperationLegalOrCustom(LoHiOpc, VT)) {
4984 SDVTList LoHiVT = DAG.getVTList(VT, VT);
4985 // TODO: Can we match commutable operands with getNodeIfExists?
4986 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N0, N1}))
4987 if (LoHi->hasAnyUseOfValue(1))
4988 return SDValue(LoHi, 0);
4989 if (SDNode *LoHi = DAG.getNodeIfExists(LoHiOpc, LoHiVT, {N1, N0}))
4990 if (LoHi->hasAnyUseOfValue(1))
4991 return SDValue(LoHi, 0);
4992 }
4993 }
4994
4995 // Try to transform:
4996 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
4997 // mul x, (2^N + 1) --> add (shl x, N), x
4998 // mul x, (2^N - 1) --> sub (shl x, N), x
4999 // Examples: x * 33 --> (x << 5) + x
5000 // x * 15 --> (x << 4) - x
5001 // x * -33 --> -((x << 5) + x)
5002 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
5003 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
5004 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
5005 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
5006 // Examples: x * 0x8800 --> (x << 15) + (x << 11)
5007 // x * 0xf800 --> (x << 16) - (x << 11)
5008 // x * -0x8800 --> -((x << 15) + (x << 11))
5009 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
5010 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
5011 // TODO: We could handle more general decomposition of any constant by
5012 // having the target set a limit on number of ops and making a
5013 // callback to determine that sequence (similar to sqrt expansion).
5014 unsigned MathOp = ISD::DELETED_NODE;
5015 APInt MulC = ConstValue1.abs();
5016 // The constant `2` should be treated as (2^0 + 1).
5017 unsigned TZeros = MulC == 2 ? 0 : MulC.countr_zero();
5018 MulC.lshrInPlace(TZeros);
5019 if ((MulC - 1).isPowerOf2())
5020 MathOp = ISD::ADD;
5021 else if ((MulC + 1).isPowerOf2())
5022 MathOp = ISD::SUB;
5023
5024 if (MathOp != ISD::DELETED_NODE) {
5025 unsigned ShAmt =
5026 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
5027 ShAmt += TZeros;
5028 assert(ShAmt < BitWidth &&
5029 "multiply-by-constant generated out of bounds shift");
5030 SDValue Shl =
5031 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
5032 SDValue R =
5033 TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
5034 DAG.getNode(ISD::SHL, DL, VT, N0,
5035 DAG.getConstant(TZeros, DL, VT)))
5036 : DAG.getNode(MathOp, DL, VT, Shl, N0);
5037 if (ConstValue1.isNegative())
5038 R = DAG.getNegative(R, DL, VT);
5039 return R;
5040 }
5041 }
5042
5043 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
5044 {
5045 SDValue X, C1;
5046 if (sd_match(N0, m_Shl(m_Value(X), m_Value(C1))))
5047 if (SDValue C3 = DAG.FoldConstantArithmetic(ISD::SHL, DL, VT, {N1, C1}))
5048 return DAG.getNode(ISD::MUL, DL, VT, X, C3);
5049 }
5050
5051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
5052 // use.
5053 {
5054 SDValue X, C, Y;
5055 if (sd_match(N,
5058 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, X, Y);
5059 return DAG.getNode(ISD::SHL, DL, VT, Mul, C);
5060 }
5061 }
5062
5063 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
5067 return DAG.getNode(
5068 ISD::ADD, DL, VT,
5069 DAG.getNode(ISD::MUL, SDLoc(N0), VT, N0.getOperand(0), N1),
5070 DAG.getNode(ISD::MUL, SDLoc(N1), VT, N0.getOperand(1), N1));
5071
5072 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
5073 // avoid if ISD::MUL handling is poor and ISD::SHL isn't an option.
5074 ConstantSDNode *NC1 = isConstOrConstSplat(N1);
5075 if (N0.getOpcode() == ISD::VSCALE && NC1) {
5076 const APInt &C0 = N0.getConstantOperandAPInt(0);
5077 const APInt &C1 = NC1->getAPIntValue();
5078 if (!C0.isPowerOf2() || C1.isPowerOf2() ||
5079 hasOperation(ISD::MUL, NC1->getValueType(0)))
5080 return DAG.getVScale(DL, VT, C0 * C1);
5081 }
5082
5083 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5084 APInt MulVal;
5085 if (N0.getOpcode() == ISD::STEP_VECTOR &&
5086 ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
5087 const APInt &C0 = N0.getConstantOperandAPInt(0);
5088 APInt NewStep = C0 * MulVal;
5089 return DAG.getStepVector(DL, VT, NewStep);
5090 }
5091
5092 // Fold Y = sra (X, size(X)-1); mul (or (Y, 1), X) -> (abs X)
5093 SDValue X;
5094 if ((!LegalOperations || hasOperation(ISD::ABS, VT)) &&
5096 m_One()),
5097 m_Deferred(X)))) {
5098 return DAG.getNode(ISD::ABS, DL, VT, X);
5099 }
5100
5101 // Fold ((mul x, 0/undef) -> 0,
5102 // (mul x, 1) -> x) -> x)
5103 // -> and(x, mask)
5104 // We can replace vectors with '0' and '1' factors with a clearing mask.
5105 if (VT.isFixedLengthVector()) {
5106 unsigned NumElts = VT.getVectorNumElements();
5107 SmallBitVector ClearMask;
5108 ClearMask.reserve(NumElts);
5109 auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
5110 if (!V || V->isZero()) {
5111 ClearMask.push_back(true);
5112 return true;
5113 }
5114 ClearMask.push_back(false);
5115 return V->isOne();
5116 };
5117 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
5118 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
5119 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
5120 EVT LegalSVT = N1.getOperand(0).getValueType();
5121 SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
5122 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
5124 for (unsigned I = 0; I != NumElts; ++I)
5125 if (ClearMask[I])
5126 Mask[I] = Zero;
5127 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
5128 }
5129 }
5130
5131 // reassociate mul
5132 if (SDValue RMUL = reassociateOps(ISD::MUL, DL, N0, N1, N->getFlags()))
5133 return RMUL;
5134
5135 // Fold mul(vecreduce(x), vecreduce(y)) -> vecreduce(mul(x, y))
5136 if (SDValue SD =
5137 reassociateReduction(ISD::VECREDUCE_MUL, ISD::MUL, DL, VT, N0, N1))
5138 return SD;
5139
5140 // Simplify the operands using demanded-bits information.
5142 return SDValue(N, 0);
5143
5144 return SDValue();
5145}
5146
5147/// Return true if divmod libcall is available.
5149 const SelectionDAG &DAG) {
5150 RTLIB::Libcall LC;
5151 EVT NodeType = Node->getValueType(0);
5152 if (!NodeType.isSimple())
5153 return false;
5154 switch (NodeType.getSimpleVT().SimpleTy) {
5155 default: return false; // No libcall for vector types.
5156 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
5157 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
5158 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
5159 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
5160 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
5161 }
5162
5163 return DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported;
5164}
5165
5166/// Issue divrem if both quotient and remainder are needed.
5167SDValue DAGCombiner::useDivRem(SDNode *Node) {
5168 if (Node->use_empty())
5169 return SDValue(); // This is a dead node, leave it alone.
5170
5171 unsigned Opcode = Node->getOpcode();
5172 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
5173 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
5174
5175 // DivMod lib calls can still work on non-legal types if using lib-calls.
5176 EVT VT = Node->getValueType(0);
5177 if (VT.isVector() || !VT.isInteger())
5178 return SDValue();
5179
5180 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
5181 return SDValue();
5182
5183 // If DIVREM is going to get expanded into a libcall,
5184 // but there is no libcall available, then don't combine.
5185 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
5187 return SDValue();
5188
5189 // If div is legal, it's better to do the normal expansion
5190 unsigned OtherOpcode = 0;
5191 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
5192 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
5193 if (TLI.isOperationLegalOrCustom(Opcode, VT))
5194 return SDValue();
5195 } else {
5196 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5197 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
5198 return SDValue();
5199 }
5200
5201 SDValue Op0 = Node->getOperand(0);
5202 SDValue Op1 = Node->getOperand(1);
5203 SDValue combined;
5204 for (SDNode *User : Op0->users()) {
5205 if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
5206 User->use_empty())
5207 continue;
5208 // Convert the other matching node(s), too;
5209 // otherwise, the DIVREM may get target-legalized into something
5210 // target-specific that we won't be able to recognize.
5211 unsigned UserOpc = User->getOpcode();
5212 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
5213 User->getOperand(0) == Op0 &&
5214 User->getOperand(1) == Op1) {
5215 if (!combined) {
5216 if (UserOpc == OtherOpcode) {
5217 SDVTList VTs = DAG.getVTList(VT, VT);
5218 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
5219 } else if (UserOpc == DivRemOpc) {
5220 combined = SDValue(User, 0);
5221 } else {
5222 assert(UserOpc == Opcode);
5223 continue;
5224 }
5225 }
5226 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
5227 CombineTo(User, combined);
5228 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
5229 CombineTo(User, combined.getValue(1));
5230 }
5231 }
5232 return combined;
5233}
5234
5236 SDValue N0 = N->getOperand(0);
5237 SDValue N1 = N->getOperand(1);
5238 EVT VT = N->getValueType(0);
5239 SDLoc DL(N);
5240
5241 unsigned Opc = N->getOpcode();
5242 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
5243
5244 // X / undef -> undef
5245 // X % undef -> undef
5246 // X / 0 -> undef
5247 // X % 0 -> undef
5248 // NOTE: This includes vectors where any divisor element is zero/undef.
5249 if (DAG.isUndef(Opc, {N0, N1}))
5250 return DAG.getUNDEF(VT);
5251
5252 // undef / X -> 0
5253 // undef % X -> 0
5254 if (N0.isUndef())
5255 return DAG.getConstant(0, DL, VT);
5256
5257 // 0 / X -> 0
5258 // 0 % X -> 0
5260 if (N0C && N0C->isZero())
5261 return N0;
5262
5263 // X / X -> 1
5264 // X % X -> 0
5265 if (N0 == N1)
5266 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
5267
5268 // X / 1 -> X
5269 // X % 1 -> 0
5270 // If this is a boolean op (single-bit element type), we can't have
5271 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
5272 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
5273 // it's a 1.
5274 if (isOneOrOneSplat(N1) || (VT.getScalarType() == MVT::i1))
5275 return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
5276
5277 return SDValue();
5278}
5279
5280SDValue DAGCombiner::visitSDIV(SDNode *N) {
5281 SDValue N0 = N->getOperand(0);
5282 SDValue N1 = N->getOperand(1);
5283 EVT VT = N->getValueType(0);
5284 EVT CCVT = getSetCCResultType(VT);
5285 SDLoc DL(N);
5286
5287 // fold (sdiv c1, c2) -> c1/c2
5288 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
5289 return C;
5290
5291 // fold vector ops
5292 if (VT.isVector())
5293 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5294 return FoldedVOp;
5295
5296 // fold (sdiv X, -1) -> 0-X
5297 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5298 if (N1C && N1C->isAllOnes())
5299 return DAG.getNegative(N0, DL, VT);
5300
5301 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
5302 if (N1C && N1C->isMinSignedValue())
5303 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5304 DAG.getConstant(1, DL, VT),
5305 DAG.getConstant(0, DL, VT));
5306
5307 if (SDValue V = simplifyDivRem(N, DAG))
5308 return V;
5309
5310 if (SDValue NewSel = foldBinOpIntoSelect(N))
5311 return NewSel;
5312
5313 // If we know the sign bits of both operands are zero, strength reduce to a
5314 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
5315 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5316 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
5317
5318 if (SDValue V = visitSDIVLike(N0, N1, N)) {
5319 // If the corresponding remainder node exists, update its users with
5320 // (Dividend - (Quotient * Divisor).
5321 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
5322 { N0, N1 })) {
5323 // If the sdiv has the exact flag we shouldn't propagate it to the
5324 // remainder node.
5325 if (!N->getFlags().hasExact()) {
5326 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5327 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5328 AddToWorklist(Mul.getNode());
5329 AddToWorklist(Sub.getNode());
5330 CombineTo(RemNode, Sub);
5331 }
5332 }
5333 return V;
5334 }
5335
5336 // sdiv, srem -> sdivrem
5337 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5338 // true. Otherwise, we break the simplification logic in visitREM().
5339 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5340 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5341 if (SDValue DivRem = useDivRem(N))
5342 return DivRem;
5343
5344 return SDValue();
5345}
5346
5347static bool isDivisorPowerOfTwo(SDValue Divisor) {
5348 // Helper for determining whether a value is a power-2 constant scalar or a
5349 // vector of such elements.
5350 auto IsPowerOfTwo = [](ConstantSDNode *C) {
5351 if (C->isZero() || C->isOpaque())
5352 return false;
5353 if (C->getAPIntValue().isPowerOf2())
5354 return true;
5355 if (C->getAPIntValue().isNegatedPowerOf2())
5356 return true;
5357 return false;
5358 };
5359
5360 return ISD::matchUnaryPredicate(Divisor, IsPowerOfTwo, /*AllowUndefs=*/false,
5361 /*AllowTruncation=*/true);
5362}
5363
5364SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5365 SDLoc DL(N);
5366 EVT VT = N->getValueType(0);
5367 EVT CCVT = getSetCCResultType(VT);
5368 unsigned BitWidth = VT.getScalarSizeInBits();
5369 unsigned MaxLegalDivRemBitWidth = TLI.getMaxDivRemBitWidthSupported();
5370
5371 // fold (sdiv X, pow2) -> simple ops after legalize
5372 // FIXME: We check for the exact bit here because the generic lowering gives
5373 // better results in that case. The target-specific lowering should learn how
5374 // to handle exact sdivs efficiently. An exception is made for large bitwidths
5375 // exceeding what the target can natively support, as division expansion was
5376 // skipped in favor of this optimization.
5377 if ((!N->getFlags().hasExact() || BitWidth > MaxLegalDivRemBitWidth) &&
5378 isDivisorPowerOfTwo(N1)) {
5379 // Target-specific implementation of sdiv x, pow2.
5380 if (SDValue Res = BuildSDIVPow2(N))
5381 return Res;
5382
5383 // Create constants that are functions of the shift amount value.
5384 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
5385 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
5386 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
5387 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
5388 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
5389 if (!isConstantOrConstantVector(Inexact))
5390 return SDValue();
5391
5392 // Splat the sign bit into the register
5393 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
5394 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
5395 AddToWorklist(Sign.getNode());
5396
5397 // Add (N0 < 0) ? abs2 - 1 : 0;
5398 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
5399 AddToWorklist(Srl.getNode());
5400 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
5401 AddToWorklist(Add.getNode());
5402 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
5403 AddToWorklist(Sra.getNode());
5404
5405 // Special case: (sdiv X, 1) -> X
5406 // Special Case: (sdiv X, -1) -> 0-X
5407 SDValue One = DAG.getConstant(1, DL, VT);
5409 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
5410 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
5411 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
5412 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
5413
5414 // If dividing by a positive value, we're done. Otherwise, the result must
5415 // be negated.
5416 SDValue Zero = DAG.getConstant(0, DL, VT);
5417 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
5418
5419 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
5420 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
5421 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
5422 return Res;
5423 }
5424
5425 // If integer divide is expensive and we satisfy the requirements, emit an
5426 // alternate sequence. Targets may check function attributes for size/speed
5427 // trade-offs.
5428 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5429 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5430 /*AllowTruncation=*/true) &&
5431 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5432 if (SDValue Op = BuildSDIV(N))
5433 return Op;
5434
5435 return SDValue();
5436}
5437
5438SDValue DAGCombiner::visitUDIV(SDNode *N) {
5439 SDValue N0 = N->getOperand(0);
5440 SDValue N1 = N->getOperand(1);
5441 EVT VT = N->getValueType(0);
5442 EVT CCVT = getSetCCResultType(VT);
5443 SDLoc DL(N);
5444
5445 // fold (udiv c1, c2) -> c1/c2
5446 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
5447 return C;
5448
5449 // fold vector ops
5450 if (VT.isVector())
5451 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5452 return FoldedVOp;
5453
5454 // fold (udiv X, -1) -> select(X == -1, 1, 0)
5455 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5456 if (N1C && N1C->isAllOnes() && CCVT.isVector() == VT.isVector()) {
5457 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
5458 DAG.getConstant(1, DL, VT),
5459 DAG.getConstant(0, DL, VT));
5460 }
5461
5462 if (SDValue V = simplifyDivRem(N, DAG))
5463 return V;
5464
5465 if (SDValue NewSel = foldBinOpIntoSelect(N))
5466 return NewSel;
5467
5468 if (SDValue V = visitUDIVLike(N0, N1, N)) {
5469 // If the corresponding remainder node exists, update its users with
5470 // (Dividend - (Quotient * Divisor).
5471 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
5472 { N0, N1 })) {
5473 // If the udiv has the exact flag we shouldn't propagate it to the
5474 // remainder node.
5475 if (!N->getFlags().hasExact()) {
5476 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
5477 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5478 AddToWorklist(Mul.getNode());
5479 AddToWorklist(Sub.getNode());
5480 CombineTo(RemNode, Sub);
5481 }
5482 }
5483 return V;
5484 }
5485
5486 // sdiv, srem -> sdivrem
5487 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
5488 // true. Otherwise, we break the simplification logic in visitREM().
5489 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5490 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
5491 if (SDValue DivRem = useDivRem(N))
5492 return DivRem;
5493
5494 // Simplify the operands using demanded-bits information.
5495 // We don't have demanded bits support for UDIV so this just enables constant
5496 // folding based on known bits.
5498 return SDValue(N, 0);
5499
5500 return SDValue();
5501}
5502
5503SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
5504 SDLoc DL(N);
5505 EVT VT = N->getValueType(0);
5506
5507 // fold (udiv x, (1 << c)) -> x >>u c
5508 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5509 /*AllowTruncation=*/true)) {
5510 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5511 AddToWorklist(LogBase2.getNode());
5512
5513 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5514 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
5515 AddToWorklist(Trunc.getNode());
5516 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5517 }
5518 }
5519
5520 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
5521 if (N1.getOpcode() == ISD::SHL) {
5522 SDValue N10 = N1.getOperand(0);
5523 if (isConstantOrConstantVector(N10, /*NoOpaques=*/true,
5524 /*AllowTruncation=*/true)) {
5525 if (SDValue LogBase2 = BuildLogBase2(N10, DL)) {
5526 AddToWorklist(LogBase2.getNode());
5527
5528 EVT ADDVT = N1.getOperand(1).getValueType();
5529 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
5530 AddToWorklist(Trunc.getNode());
5531 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
5532 AddToWorklist(Add.getNode());
5533 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
5534 }
5535 }
5536 }
5537
5538 // fold (udiv x, c) -> alternate
5539 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5540 if (isConstantOrConstantVector(N1, /*NoOpaques=*/false,
5541 /*AllowTruncation=*/true) &&
5542 !TLI.isIntDivCheap(N->getValueType(0), Attr))
5543 if (SDValue Op = BuildUDIV(N))
5544 return Op;
5545
5546 return SDValue();
5547}
5548
5549SDValue DAGCombiner::buildOptimizedSREM(SDValue N0, SDValue N1, SDNode *N) {
5550 if (!N->getFlags().hasExact() && isDivisorPowerOfTwo(N1) &&
5551 !DAG.doesNodeExist(ISD::SDIV, N->getVTList(), {N0, N1})) {
5552 // Target-specific implementation of srem x, pow2.
5553 if (SDValue Res = BuildSREMPow2(N))
5554 return Res;
5555 }
5556 return SDValue();
5557}
5558
5559// handles ISD::SREM and ISD::UREM
5560SDValue DAGCombiner::visitREM(SDNode *N) {
5561 unsigned Opcode = N->getOpcode();
5562 SDValue N0 = N->getOperand(0);
5563 SDValue N1 = N->getOperand(1);
5564 EVT VT = N->getValueType(0);
5565 EVT CCVT = getSetCCResultType(VT);
5566
5567 bool isSigned = (Opcode == ISD::SREM);
5568 SDLoc DL(N);
5569
5570 // fold (rem c1, c2) -> c1%c2
5571 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5572 return C;
5573
5574 // fold (urem X, -1) -> select(FX == -1, 0, FX)
5575 // Freeze the numerator to avoid a miscompile with an undefined value.
5576 if (!isSigned && llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false) &&
5577 CCVT.isVector() == VT.isVector()) {
5578 SDValue F0 = DAG.getFreeze(N0);
5579 SDValue EqualsNeg1 = DAG.getSetCC(DL, CCVT, F0, N1, ISD::SETEQ);
5580 return DAG.getSelect(DL, VT, EqualsNeg1, DAG.getConstant(0, DL, VT), F0);
5581 }
5582
5583 if (SDValue V = simplifyDivRem(N, DAG))
5584 return V;
5585
5586 if (SDValue NewSel = foldBinOpIntoSelect(N))
5587 return NewSel;
5588
5589 if (isSigned) {
5590 // If we know the sign bits of both operands are zero, strength reduce to a
5591 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
5592 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
5593 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
5594 } else {
5595 if (DAG.isKnownToBeAPowerOfTwo(N1, /*OrZero=*/true)) {
5596 // fold (urem x, pow2) -> (and x, pow2-1)
5597 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
5598 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
5599 AddToWorklist(Add.getNode());
5600 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
5601 }
5602 }
5603
5604 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5605
5606 // If X/C can be simplified by the division-by-constant logic, lower
5607 // X%C to the equivalent of X-X/C*C.
5608 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
5609 // speculative DIV must not cause a DIVREM conversion. We guard against this
5610 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
5611 // combine will not return a DIVREM. Regardless, checking cheapness here
5612 // makes sense since the simplification results in fatter code.
5613 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
5614 if (isSigned) {
5615 // check if we can build faster implementation for srem
5616 if (SDValue OptimizedRem = buildOptimizedSREM(N0, N1, N))
5617 return OptimizedRem;
5618 }
5619
5620 SDValue OptimizedDiv =
5621 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
5622 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
5623 // If the equivalent Div node also exists, update its users.
5624 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
5625 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
5626 { N0, N1 }))
5627 CombineTo(DivNode, OptimizedDiv);
5628 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
5629 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
5630 AddToWorklist(OptimizedDiv.getNode());
5631 AddToWorklist(Mul.getNode());
5632 return Sub;
5633 }
5634 }
5635
5636 // sdiv, srem -> sdivrem
5637 if (SDValue DivRem = useDivRem(N))
5638 return DivRem.getValue(1);
5639
5640 // fold urem(urem(A, BCst), Op1Cst) -> urem(A, Op1Cst)
5641 // iff urem(BCst, Op1Cst) == 0
5642 SDValue A;
5643 APInt Op1Cst, BCst;
5644 if (sd_match(N, m_URem(m_URem(m_Value(A), m_ConstInt(BCst)),
5645 m_ConstInt(Op1Cst))) &&
5646 BCst.urem(Op1Cst).isZero()) {
5647 return DAG.getNode(ISD::UREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5648 }
5649
5650 // fold srem(srem(A, BCst), Op1Cst) -> srem(A, Op1Cst)
5651 // iff srem(BCst, Op1Cst) == 0 && Op1Cst != 1
5652 if (sd_match(N, m_SRem(m_SRem(m_Value(A), m_ConstInt(BCst)),
5653 m_ConstInt(Op1Cst))) &&
5654 BCst.srem(Op1Cst).isZero() && !Op1Cst.isAllOnes()) {
5655 return DAG.getNode(ISD::SREM, DL, VT, A, DAG.getConstant(Op1Cst, DL, VT));
5656 }
5657
5658 return SDValue();
5659}
5660
5661SDValue DAGCombiner::visitMULHS(SDNode *N) {
5662 SDValue N0 = N->getOperand(0);
5663 SDValue N1 = N->getOperand(1);
5664 EVT VT = N->getValueType(0);
5665 SDLoc DL(N);
5666
5667 // fold (mulhs c1, c2)
5668 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
5669 return C;
5670
5671 // canonicalize constant to RHS.
5674 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
5675
5676 if (VT.isVector()) {
5677 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5678 return FoldedVOp;
5679
5680 // fold (mulhs x, 0) -> 0
5681 // do not return N1, because undef node may exist.
5683 return DAG.getConstant(0, DL, VT);
5684 }
5685
5686 // fold (mulhs x, 0) -> 0
5687 if (isNullConstant(N1))
5688 return N1;
5689
5690 // fold (mulhs x, 1) -> (sra x, size(x)-1)
5691 if (isOneConstant(N1))
5692 return DAG.getNode(
5693 ISD::SRA, DL, VT, N0,
5695
5696 // fold (mulhs x, undef) -> 0
5697 if (N0.isUndef() || N1.isUndef())
5698 return DAG.getConstant(0, DL, VT);
5699
5700 // If the type twice as wide is legal, transform the mulhs to a wider multiply
5701 // plus a shift.
5702 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
5703 !VT.isVector()) {
5704 MVT Simple = VT.getSimpleVT();
5705 unsigned SimpleSize = Simple.getSizeInBits();
5706 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5707 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5708 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
5709 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
5710 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5711 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5712 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5713 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5714 }
5715 }
5716
5717 return SDValue();
5718}
5719
5720SDValue DAGCombiner::visitMULHU(SDNode *N) {
5721 SDValue N0 = N->getOperand(0);
5722 SDValue N1 = N->getOperand(1);
5723 EVT VT = N->getValueType(0);
5724 SDLoc DL(N);
5725
5726 // fold (mulhu c1, c2)
5727 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
5728 return C;
5729
5730 // canonicalize constant to RHS.
5733 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
5734
5735 if (VT.isVector()) {
5736 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5737 return FoldedVOp;
5738
5739 // fold (mulhu x, 0) -> 0
5740 // do not return N1, because undef node may exist.
5742 return DAG.getConstant(0, DL, VT);
5743 }
5744
5745 // fold (mulhu x, 0) -> 0
5746 if (isNullConstant(N1))
5747 return N1;
5748
5749 // fold (mulhu x, 1) -> 0
5750 if (isOneConstant(N1))
5751 return DAG.getConstant(0, DL, VT);
5752
5753 // fold (mulhu x, undef) -> 0
5754 if (N0.isUndef() || N1.isUndef())
5755 return DAG.getConstant(0, DL, VT);
5756
5757 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
5758 if (isConstantOrConstantVector(N1, /*NoOpaques=*/true,
5759 /*AllowTruncation=*/true) &&
5760 (!LegalOperations || hasOperation(ISD::SRL, VT))) {
5761 if (SDValue LogBase2 = BuildLogBase2(N1, DL)) {
5762 unsigned NumEltBits = VT.getScalarSizeInBits();
5763 SDValue SRLAmt = DAG.getNode(
5764 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
5765 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
5766 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
5767 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
5768 }
5769 }
5770
5771 // If the type twice as wide is legal, transform the mulhu to a wider multiply
5772 // plus a shift.
5773 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
5774 !VT.isVector()) {
5775 MVT Simple = VT.getSimpleVT();
5776 unsigned SimpleSize = Simple.getSizeInBits();
5777 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
5778 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
5779 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
5780 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
5781 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
5782 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
5783 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
5784 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
5785 }
5786 }
5787
5788 // Simplify the operands using demanded-bits information.
5789 // We don't have demanded bits support for MULHU so this just enables constant
5790 // folding based on known bits.
5792 return SDValue(N, 0);
5793
5794 return SDValue();
5795}
5796
5797SDValue DAGCombiner::visitAVG(SDNode *N) {
5798 unsigned Opcode = N->getOpcode();
5799 SDValue N0 = N->getOperand(0);
5800 SDValue N1 = N->getOperand(1);
5801 EVT VT = N->getValueType(0);
5802 SDLoc DL(N);
5803 bool IsSigned = Opcode == ISD::AVGCEILS || Opcode == ISD::AVGFLOORS;
5804
5805 // fold (avg c1, c2)
5806 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5807 return C;
5808
5809 // canonicalize constant to RHS.
5812 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5813
5814 if (VT.isVector())
5815 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5816 return FoldedVOp;
5817
5818 // fold (avg x, undef) -> x
5819 if (N0.isUndef())
5820 return N1;
5821 if (N1.isUndef())
5822 return N0;
5823
5824 // fold (avg x, x) --> x
5825 if (N0 == N1 && Level >= AfterLegalizeTypes)
5826 return N0;
5827
5828 // fold (avgfloor x, 0) -> x >> 1
5829 SDValue X, Y;
5831 return DAG.getNode(ISD::SRA, DL, VT, X,
5832 DAG.getShiftAmountConstant(1, VT, DL));
5834 return DAG.getNode(ISD::SRL, DL, VT, X,
5835 DAG.getShiftAmountConstant(1, VT, DL));
5836
5837 // fold avgu(zext(x), zext(y)) -> zext(avgu(x, y))
5838 // fold avgs(sext(x), sext(y)) -> sext(avgs(x, y))
5839 if (!IsSigned &&
5840 sd_match(N, m_BinOp(Opcode, m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
5841 X.getValueType() == Y.getValueType() &&
5842 hasOperation(Opcode, X.getValueType())) {
5843 SDValue AvgU = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5844 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, AvgU);
5845 }
5846 if (IsSigned &&
5847 sd_match(N, m_BinOp(Opcode, m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
5848 X.getValueType() == Y.getValueType() &&
5849 hasOperation(Opcode, X.getValueType())) {
5850 SDValue AvgS = DAG.getNode(Opcode, DL, X.getValueType(), X, Y);
5851 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, AvgS);
5852 }
5853
5854 // Fold avgflooru(x,y) -> avgceilu(x,y-1) iff y != 0
5855 // Fold avgflooru(x,y) -> avgceilu(x-1,y) iff x != 0
5856 // Check if avgflooru isn't legal/custom but avgceilu is.
5857 if (Opcode == ISD::AVGFLOORU && !hasOperation(ISD::AVGFLOORU, VT) &&
5858 (!LegalOperations || hasOperation(ISD::AVGCEILU, VT))) {
5859 if (DAG.isKnownNeverZero(N1))
5860 return DAG.getNode(
5861 ISD::AVGCEILU, DL, VT, N0,
5862 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getAllOnesConstant(DL, VT)));
5863 if (DAG.isKnownNeverZero(N0))
5864 return DAG.getNode(
5865 ISD::AVGCEILU, DL, VT, N1,
5866 DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getAllOnesConstant(DL, VT)));
5867 }
5868
5869 // Fold avgfloor((add nw x,y), 1) -> avgceil(x,y)
5870 // Fold avgfloor((add nw x,1), y) -> avgceil(x,y)
5871 if ((Opcode == ISD::AVGFLOORU && hasOperation(ISD::AVGCEILU, VT)) ||
5872 (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGCEILS, VT))) {
5873 SDValue Add;
5874 if (sd_match(N,
5875 m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_Value(Y))),
5876 m_One())) ||
5877 sd_match(N, m_c_BinOp(Opcode, m_Value(Add, m_Add(m_Value(X), m_One())),
5878 m_Value(Y)))) {
5879
5880 if (IsSigned && Add->getFlags().hasNoSignedWrap())
5881 return DAG.getNode(ISD::AVGCEILS, DL, VT, X, Y);
5882
5883 if (!IsSigned && Add->getFlags().hasNoUnsignedWrap())
5884 return DAG.getNode(ISD::AVGCEILU, DL, VT, X, Y);
5885 }
5886 }
5887
5888 // Fold avgfloors(x,y) -> avgflooru(x,y) if both x and y are non-negative
5889 if (Opcode == ISD::AVGFLOORS && hasOperation(ISD::AVGFLOORU, VT)) {
5890 if (DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5891 return DAG.getNode(ISD::AVGFLOORU, DL, VT, N0, N1);
5892 }
5893
5894 return SDValue();
5895}
5896
5897SDValue DAGCombiner::visitABD(SDNode *N) {
5898 unsigned Opcode = N->getOpcode();
5899 SDValue N0 = N->getOperand(0);
5900 SDValue N1 = N->getOperand(1);
5901 EVT VT = N->getValueType(0);
5902 SDLoc DL(N);
5903
5904 // fold (abd c1, c2)
5905 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
5906 return C;
5907
5908 // canonicalize constant to RHS.
5911 return DAG.getNode(Opcode, DL, N->getVTList(), N1, N0);
5912
5913 if (VT.isVector())
5914 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
5915 return FoldedVOp;
5916
5917 // fold (abd x, undef) -> 0
5918 if (N0.isUndef() || N1.isUndef())
5919 return DAG.getConstant(0, DL, VT);
5920
5921 // fold (abd x, x) -> 0
5922 if (N0 == N1)
5923 return DAG.getConstant(0, DL, VT);
5924
5925 SDValue X, Y;
5926
5927 // fold (abds x, 0) -> abs x
5929 (!LegalOperations || hasOperation(ISD::ABS, VT)))
5930 return DAG.getNode(ISD::ABS, DL, VT, X);
5931
5932 // fold (abdu x, 0) -> x
5934 return X;
5935
5936 // fold (abds x, y) -> (abdu x, y) iff both args are known positive
5937 if (Opcode == ISD::ABDS && hasOperation(ISD::ABDU, VT) &&
5938 DAG.SignBitIsZero(N0) && DAG.SignBitIsZero(N1))
5939 return DAG.getNode(ISD::ABDU, DL, VT, N1, N0);
5940
5941 // fold (abd? (?ext x), (?ext y)) -> (zext (abd? x, y))
5944 EVT SmallVT = X.getScalarValueSizeInBits() > Y.getScalarValueSizeInBits()
5945 ? X.getValueType()
5946 : Y.getValueType();
5947 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5948 SDValue ExtedX = DAG.getExtOrTrunc(X, SDLoc(X), SmallVT, N0->getOpcode());
5949 SDValue ExtedY = DAG.getExtOrTrunc(Y, SDLoc(Y), SmallVT, N0->getOpcode());
5950 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {ExtedX, ExtedY});
5951 SDValue ZExted = DAG.getZExtOrTrunc(SmallABD, DL, VT);
5952 return ZExted;
5953 }
5954 }
5955
5956 // fold (abd? (?ext ty:x), small_const:c) -> (zext (abd? x, c))
5959 EVT SmallVT = X.getValueType();
5960 if (!LegalOperations || hasOperation(Opcode, SmallVT)) {
5961 uint64_t Bits = SmallVT.getScalarSizeInBits();
5962 unsigned RelevantBits =
5963 (Opcode == ISD::ABDS) ? DAG.ComputeMaxSignificantBits(Y)
5965 bool TruncatingYIsCheap = TLI.isTruncateFree(Y, SmallVT) ||
5967 Y,
5968 [&](auto *C) {
5969 if (!C)
5970 return true;
5971 const APInt &YConst = C->getAsAPIntVal();
5972 return (Opcode == ISD::ABDS)
5973 ? YConst.isSignedIntN(Bits)
5974 : YConst.isIntN(Bits);
5975 },
5976 /*AllowUndefs=*/true);
5977
5978 if (RelevantBits <= Bits && TruncatingYIsCheap) {
5979 SDValue NewY = DAG.getNode(ISD::TRUNCATE, SDLoc(Y), SmallVT, Y);
5980 SDValue SmallABD = DAG.getNode(Opcode, DL, SmallVT, {X, NewY});
5981 return DAG.getZExtOrTrunc(SmallABD, DL, VT);
5982 }
5983 }
5984 }
5985
5986 return SDValue();
5987}
5988
5989/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
5990/// give the opcodes for the two computations that are being performed. Return
5991/// true if a simplification was made.
5992SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
5993 unsigned HiOp) {
5994 // If the high half is not needed, just compute the low half.
5995 bool HiExists = N->hasAnyUseOfValue(1);
5996 if (!HiExists && (!LegalOperations ||
5997 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
5998 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
5999 return CombineTo(N, Res, Res);
6000 }
6001
6002 // If the low half is not needed, just compute the high half.
6003 bool LoExists = N->hasAnyUseOfValue(0);
6004 if (!LoExists && (!LegalOperations ||
6005 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
6006 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
6007 return CombineTo(N, Res, Res);
6008 }
6009
6010 // If both halves are used, return as it is.
6011 if (LoExists && HiExists)
6012 return SDValue();
6013
6014 // If the two computed results can be simplified separately, separate them.
6015 if (LoExists) {
6016 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
6017 AddToWorklist(Lo.getNode());
6018 SDValue LoOpt = combine(Lo.getNode());
6019 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
6020 (!LegalOperations ||
6021 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
6022 return CombineTo(N, LoOpt, LoOpt);
6023 }
6024
6025 if (HiExists) {
6026 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
6027 AddToWorklist(Hi.getNode());
6028 SDValue HiOpt = combine(Hi.getNode());
6029 if (HiOpt.getNode() && HiOpt != Hi &&
6030 (!LegalOperations ||
6031 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
6032 return CombineTo(N, HiOpt, HiOpt);
6033 }
6034
6035 return SDValue();
6036}
6037
6038SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
6039 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
6040 return Res;
6041
6042 SDValue N0 = N->getOperand(0);
6043 SDValue N1 = N->getOperand(1);
6044 EVT VT = N->getValueType(0);
6045 SDLoc DL(N);
6046
6047 // Constant fold.
6049 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N0, N1);
6050
6051 // canonicalize constant to RHS (vector doesn't have to splat)
6054 return DAG.getNode(ISD::SMUL_LOHI, DL, N->getVTList(), N1, N0);
6055
6056 // If the type is twice as wide is legal, transform the mulhu to a wider
6057 // multiply plus a shift.
6058 if (VT.isSimple() && !VT.isVector()) {
6059 MVT Simple = VT.getSimpleVT();
6060 unsigned SimpleSize = Simple.getSizeInBits();
6061 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6062 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6063 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
6064 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
6065 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6066 // Compute the high part as N1.
6067 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6068 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6069 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6070 // Compute the low part as N0.
6071 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6072 return CombineTo(N, Lo, Hi);
6073 }
6074 }
6075
6076 return SDValue();
6077}
6078
6079SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
6080 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
6081 return Res;
6082
6083 SDValue N0 = N->getOperand(0);
6084 SDValue N1 = N->getOperand(1);
6085 EVT VT = N->getValueType(0);
6086 SDLoc DL(N);
6087
6088 // Constant fold.
6090 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N0, N1);
6091
6092 // canonicalize constant to RHS (vector doesn't have to splat)
6095 return DAG.getNode(ISD::UMUL_LOHI, DL, N->getVTList(), N1, N0);
6096
6097 // (umul_lohi N0, 0) -> (0, 0)
6098 if (isNullConstant(N1)) {
6099 SDValue Zero = DAG.getConstant(0, DL, VT);
6100 return CombineTo(N, Zero, Zero);
6101 }
6102
6103 // (umul_lohi N0, 1) -> (N0, 0)
6104 if (isOneConstant(N1)) {
6105 SDValue Zero = DAG.getConstant(0, DL, VT);
6106 return CombineTo(N, N0, Zero);
6107 }
6108
6109 // If the type is twice as wide is legal, transform the mulhu to a wider
6110 // multiply plus a shift.
6111 if (VT.isSimple() && !VT.isVector()) {
6112 MVT Simple = VT.getSimpleVT();
6113 unsigned SimpleSize = Simple.getSizeInBits();
6114 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
6115 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
6116 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
6117 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
6118 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
6119 // Compute the high part as N1.
6120 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
6121 DAG.getShiftAmountConstant(SimpleSize, NewVT, DL));
6122 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
6123 // Compute the low part as N0.
6124 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
6125 return CombineTo(N, Lo, Hi);
6126 }
6127 }
6128
6129 return SDValue();
6130}
6131
6132SDValue DAGCombiner::visitMULO(SDNode *N) {
6133 SDValue N0 = N->getOperand(0);
6134 SDValue N1 = N->getOperand(1);
6135 EVT VT = N0.getValueType();
6136 bool IsSigned = (ISD::SMULO == N->getOpcode());
6137
6138 EVT CarryVT = N->getValueType(1);
6139 SDLoc DL(N);
6140
6141 ConstantSDNode *N0C = isConstOrConstSplat(N0);
6142 ConstantSDNode *N1C = isConstOrConstSplat(N1);
6143
6144 // fold operation with constant operands.
6145 // TODO: Move this to FoldConstantArithmetic when it supports nodes with
6146 // multiple results.
6147 if (N0C && N1C) {
6148 bool Overflow;
6149 APInt Result =
6150 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
6151 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
6152 return CombineTo(N, DAG.getConstant(Result, DL, VT),
6153 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
6154 }
6155
6156 // canonicalize constant to RHS.
6159 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
6160
6161 // fold (mulo x, 0) -> 0 + no carry out
6162 if (isNullOrNullSplat(N1))
6163 return CombineTo(N, DAG.getConstant(0, DL, VT),
6164 DAG.getConstant(0, DL, CarryVT));
6165
6166 // (mulo x, 2) -> (addo x, x)
6167 // FIXME: This needs a freeze.
6168 if (N1C && N1C->getAPIntValue() == 2 &&
6169 (!IsSigned || VT.getScalarSizeInBits() > 2))
6170 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
6171 N->getVTList(), N0, N0);
6172
6173 // A 1 bit SMULO overflows if both inputs are 1.
6174 if (IsSigned && VT.getScalarSizeInBits() == 1) {
6175 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
6176 SDValue Cmp = DAG.getSetCC(DL, CarryVT, And,
6177 DAG.getConstant(0, DL, VT), ISD::SETNE);
6178 return CombineTo(N, And, Cmp);
6179 }
6180
6181 // If it cannot overflow, transform into a mul.
6182 if (DAG.willNotOverflowMul(IsSigned, N0, N1))
6183 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
6184 DAG.getConstant(0, DL, CarryVT));
6185 return SDValue();
6186}
6187
6188// Function to calculate whether the Min/Max pair of SDNodes (potentially
6189// swapped around) make a signed saturate pattern, clamping to between a signed
6190// saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
6191// Returns the node being clamped and the bitwidth of the clamp in BW. Should
6192// work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
6193// same as SimplifySelectCC. N0<N1 ? N2 : N3.
6195 SDValue N3, ISD::CondCode CC, unsigned &BW,
6196 bool &Unsigned, SelectionDAG &DAG) {
6197 auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
6198 ISD::CondCode CC) {
6199 // The compare and select operand should be the same or the select operands
6200 // should be truncated versions of the comparison.
6201 if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
6202 return 0;
6203 // The constants need to be the same or a truncated version of each other.
6206 if (!N1C || !N3C)
6207 return 0;
6208 const APInt &C1 = N1C->getAPIntValue().trunc(N1.getScalarValueSizeInBits());
6209 const APInt &C2 = N3C->getAPIntValue().trunc(N3.getScalarValueSizeInBits());
6210 if (C1.getBitWidth() < C2.getBitWidth() || C1 != C2.sext(C1.getBitWidth()))
6211 return 0;
6212 return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
6213 };
6214
6215 // Check the initial value is a SMIN/SMAX equivalent.
6216 unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
6217 if (!Opcode0)
6218 return SDValue();
6219
6220 // We could only need one range check, if the fptosi could never produce
6221 // the upper value.
6222 if (N0.getOpcode() == ISD::FP_TO_SINT && Opcode0 == ISD::SMAX) {
6223 if (isNullOrNullSplat(N3)) {
6224 EVT IntVT = N0.getValueType().getScalarType();
6225 EVT FPVT = N0.getOperand(0).getValueType().getScalarType();
6226 if (FPVT.isSimple()) {
6227 Type *InputTy = FPVT.getTypeForEVT(*DAG.getContext());
6228 const fltSemantics &Semantics = InputTy->getFltSemantics();
6229 uint32_t MinBitWidth =
6230 APFloatBase::semanticsIntSizeInBits(Semantics, /*isSigned*/ true);
6231 if (IntVT.getSizeInBits() >= MinBitWidth) {
6232 Unsigned = true;
6233 BW = PowerOf2Ceil(MinBitWidth);
6234 return N0;
6235 }
6236 }
6237 }
6238 }
6239
6240 SDValue N00, N01, N02, N03;
6241 ISD::CondCode N0CC;
6242 switch (N0.getOpcode()) {
6243 case ISD::SMIN:
6244 case ISD::SMAX:
6245 N00 = N02 = N0.getOperand(0);
6246 N01 = N03 = N0.getOperand(1);
6247 N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
6248 break;
6249 case ISD::SELECT_CC:
6250 N00 = N0.getOperand(0);
6251 N01 = N0.getOperand(1);
6252 N02 = N0.getOperand(2);
6253 N03 = N0.getOperand(3);
6254 N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
6255 break;
6256 case ISD::SELECT:
6257 case ISD::VSELECT:
6258 if (N0.getOperand(0).getOpcode() != ISD::SETCC)
6259 return SDValue();
6260 N00 = N0.getOperand(0).getOperand(0);
6261 N01 = N0.getOperand(0).getOperand(1);
6262 N02 = N0.getOperand(1);
6263 N03 = N0.getOperand(2);
6264 N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
6265 break;
6266 default:
6267 return SDValue();
6268 }
6269
6270 unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
6271 if (!Opcode1 || Opcode0 == Opcode1)
6272 return SDValue();
6273
6274 ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
6275 ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
6276 if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
6277 return SDValue();
6278
6279 const APInt &MinC = MinCOp->getAPIntValue();
6280 const APInt &MaxC = MaxCOp->getAPIntValue();
6281 APInt MinCPlus1 = MinC + 1;
6282 if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
6283 BW = MinCPlus1.exactLogBase2() + 1;
6284 Unsigned = false;
6285 return N02;
6286 }
6287
6288 if (MaxC == 0 && MinC != 0 && MinCPlus1.isPowerOf2()) {
6289 BW = MinCPlus1.exactLogBase2();
6290 Unsigned = true;
6291 return N02;
6292 }
6293
6294 return SDValue();
6295}
6296
6298 SDValue N3, ISD::CondCode CC,
6299 SelectionDAG &DAG) {
6300 unsigned BW;
6301 bool Unsigned;
6302 SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned, DAG);
6303 if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
6304 return SDValue();
6305 EVT FPVT = Fp.getOperand(0).getValueType();
6306 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6307 EVT::getIntegerVT(*DAG.getContext(), BW));
6308 unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
6309 if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
6310 return SDValue();
6311 SDLoc DL(Fp);
6312 SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
6313 DAG.getValueType(NewVT.getScalarType()));
6314 return DAG.getExtOrTrunc(!Unsigned, Sat, DL, N2->getValueType(0));
6315}
6316
6318 SDValue N3, ISD::CondCode CC,
6319 SelectionDAG &DAG) {
6320 // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
6321 // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
6322 // be truncated versions of the setcc (N0/N1).
6323 if ((N0 != N2 &&
6324 (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
6325 N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
6326 return SDValue();
6329 if (!N1C || !N3C)
6330 return SDValue();
6331 const APInt &C1 = N1C->getAPIntValue();
6332 const APInt &C3 = N3C->getAPIntValue();
6333 if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
6334 C1 != C3.zext(C1.getBitWidth()))
6335 return SDValue();
6336
6337 unsigned BW = (C1 + 1).exactLogBase2();
6338 EVT FPVT = N0.getOperand(0).getValueType();
6339 EVT NewVT = FPVT.changeElementType(*DAG.getContext(),
6340 EVT::getIntegerVT(*DAG.getContext(), BW));
6342 FPVT, NewVT))
6343 return SDValue();
6344
6345 SDValue Sat =
6346 DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
6347 DAG.getValueType(NewVT.getScalarType()));
6348 return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
6349}
6350
6351// Fold a NaN-guard select of fp_to_sint/fp_to_uint into the saturating
6352// variant, which returns 0 for NaN.
6354 EVT VT = N->getValueType(0);
6355 SDLoc DL(N);
6356
6357 // Match an isnan-guarded select, requiring the compare to be single-use.
6358 // The guarded value is fp_to_sint/fp_to_uint of X, optionally masked by an
6359 // AND:
6360 // select (setcc X, 0.0, uno), 0, (fp_to_sint/uint X)
6361 // select (setcc X, 0.0, ord), (fp_to_sint/uint X), 0
6362 // select (setcc X, 0.0, uno), 0, (and (fp_to_sint/uint X), M)
6363 // select (setcc X, 0.0, ord), (and (fp_to_sint/uint X), M), 0
6364 SDValue X, GuardedVal;
6365 if (!sd_match(N,
6368 m_Zero(), m_Value(GuardedVal))) &&
6369 !sd_match(N,
6372 m_Value(GuardedVal), m_Zero())))
6373 return SDValue();
6374
6375 // The guarded value must be fp_to_sint/fp_to_uint of the same X, optionally
6376 // masked by a (commutative) AND.
6377 SDValue Mask;
6378 unsigned NewOpc;
6379 if (sd_match(GuardedVal, m_FPToSI(m_Specific(X))) ||
6380 sd_match(GuardedVal, m_And(m_FPToSI(m_Specific(X)), m_Value(Mask))))
6381 NewOpc = ISD::FP_TO_SINT_SAT;
6382 else if (sd_match(GuardedVal, m_FPToUI(m_Specific(X))) ||
6383 sd_match(GuardedVal, m_And(m_FPToUI(m_Specific(X)), m_Value(Mask))))
6384 NewOpc = ISD::FP_TO_UINT_SAT;
6385 else
6386 return SDValue();
6387
6389 X.getValueType(), VT))
6390 return SDValue();
6391
6392 SDValue Sat =
6393 DAG.getNode(NewOpc, DL, VT, X, DAG.getValueType(VT.getScalarType()));
6394 if (Mask) {
6395 // For NaN inputs the saturating conversion yields 0, so (and 0, Mask) must
6396 // stay 0 to match the original select. A poison Mask would make it poison,
6397 // so freeze Mask to guarantee a defined value.
6398 Sat = DAG.getNode(ISD::AND, DL, VT, Sat, DAG.getFreeze(Mask));
6399 }
6400 return Sat;
6401}
6402
6403SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
6404 SDValue N0 = N->getOperand(0);
6405 SDValue N1 = N->getOperand(1);
6406 EVT VT = N0.getValueType();
6407 unsigned Opcode = N->getOpcode();
6408 SDLoc DL(N);
6409
6410 // fold operation with constant operands.
6411 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
6412 return C;
6413
6414 // If the operands are the same, this is a no-op.
6415 if (N0 == N1)
6416 return N0;
6417
6418 // canonicalize constant to RHS
6421 return DAG.getNode(Opcode, DL, VT, N1, N0);
6422
6423 // fold vector ops
6424 if (VT.isVector())
6425 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
6426 return FoldedVOp;
6427
6428 // reassociate minmax
6429 if (SDValue RMINMAX = reassociateOps(Opcode, DL, N0, N1, N->getFlags()))
6430 return RMINMAX;
6431
6432 // Fold sign-extension masks using arithmetic shift:
6433 // smax(X, -1) -> or(X, ashr(X, BW-1))
6434 // smin(X, 0) -> and(X, ashr(X, BW-1))
6435 // ashr(X, BW-1) sign-extends the sign bit: 0 for X>=0, -1 for X<0.
6436 // OR with X yields X (non-negative) or -1 (negative) = smax(X,-1).
6437 // AND with X yields 0 (non-negative) or X (negative) = smin(X, 0).
6438 // Both reduce to two instructions vs. a compare+cmov on x86-64.
6439 // Only fold when the target has no native SMAX/SMIN instruction for this
6440 // type (isOperationExpand), the type is legal (not needing splitting),
6441 // the operand is not a min/max chain (preserving target combine patterns
6442 // that fold smax(smin(x,C),D) into a single saturation instruction), and
6443 // for smax(X,-1) the operand is not a sign extension (doubling its use
6444 // count can cause the target to lower the extension less efficiently).
6445 APInt C;
6446 if (TLI.isTypeLegal(VT) &&
6448 sd_match(N1, m_ConstInt(C))) {
6449 if (Opcode == ISD::SMAX && TLI.isOperationExpand(ISD::SMAX, VT) &&
6450 N0.getOpcode() != ISD::SMIN && N0.getOpcode() != ISD::SIGN_EXTEND &&
6451 C.isAllOnes()) {
6452 SDValue ShiftAmt =
6454 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6455 return DAG.getNode(ISD::OR, DL, VT, N0, Shift);
6456 }
6457 if (Opcode == ISD::SMIN && TLI.isOperationExpand(ISD::SMIN, VT) &&
6458 N0.getOpcode() != ISD::SMAX && C.isZero()) {
6459 SDValue ShiftAmt =
6461 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, N0, ShiftAmt);
6462 return DAG.getNode(ISD::AND, DL, VT, N0, Shift);
6463 }
6464 }
6465
6466 // If both operands are known to have the same sign (both non-negative or both
6467 // negative), flip between UMIN/UMAX and SMIN/SMAX.
6468 // Only do this if:
6469 // 1. The current op isn't legal and the flipped is.
6470 // 2. The saturation pattern is broken by canonicalization in InstCombine.
6471 bool IsOpIllegal = !TLI.isOperationLegal(Opcode, VT);
6472 bool IsSatBroken = Opcode == ISD::UMIN && N0.getOpcode() == ISD::SMAX;
6473
6474 if (IsSatBroken || IsOpIllegal) {
6475 auto HasKnownSameSign = [&](SDValue A, SDValue B) {
6476 if (A.isUndef() || B.isUndef())
6477 return true;
6478
6479 KnownBits KA = DAG.computeKnownBits(A);
6480 if (!KA.isNonNegative() && !KA.isNegative())
6481 return false;
6482
6483 KnownBits KB = DAG.computeKnownBits(B);
6484 if (KA.isNonNegative())
6485 return KB.isNonNegative();
6486 return KB.isNegative();
6487 };
6488
6489 if (HasKnownSameSign(N0, N1)) {
6490 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
6491 if ((IsSatBroken && IsOpIllegal) || TLI.isOperationLegal(AltOpcode, VT))
6492 return DAG.getNode(AltOpcode, DL, VT, N0, N1);
6493 }
6494 }
6495
6496 if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
6498 N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
6499 return S;
6500 if (Opcode == ISD::UMIN)
6501 if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
6502 return S;
6503
6504 // Fold min/max(vecreduce(x), vecreduce(y)) -> vecreduce(min/max(x, y))
6505 auto ReductionOpcode = [](unsigned Opcode) {
6506 switch (Opcode) {
6507 case ISD::SMIN:
6508 return ISD::VECREDUCE_SMIN;
6509 case ISD::SMAX:
6510 return ISD::VECREDUCE_SMAX;
6511 case ISD::UMIN:
6512 return ISD::VECREDUCE_UMIN;
6513 case ISD::UMAX:
6514 return ISD::VECREDUCE_UMAX;
6515 default:
6516 llvm_unreachable("Unexpected opcode");
6517 }
6518 };
6519 if (SDValue SD = reassociateReduction(ReductionOpcode(Opcode), Opcode,
6520 SDLoc(N), VT, N0, N1))
6521 return SD;
6522
6523 // Fold operation with vscale operands.
6524 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
6525 uint64_t C0 = N0->getConstantOperandVal(0);
6526 uint64_t C1 = N1->getConstantOperandVal(0);
6527 if (Opcode == ISD::UMAX)
6528 return C0 > C1 ? N0 : N1;
6529 else if (Opcode == ISD::UMIN)
6530 return C0 > C1 ? N1 : N0;
6531 }
6532
6533 // If we know the range of vscale, see if we can fold it given a constant.
6534 if (N0.getOpcode() == ISD::VSCALE) {
6535 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
6536 bool ForSigned = (Opcode == ISD::SMAX || Opcode == ISD::SMIN);
6537 ConstantRange Range = DAG.computeConstantRange(N0, ForSigned);
6538
6539 const APInt &C1V = C1->getAPIntValue();
6540 if ((Opcode == ISD::UMAX && Range.getUnsignedMax().ule(C1V)) ||
6541 (Opcode == ISD::UMIN && Range.getUnsignedMin().uge(C1V)) ||
6542 (Opcode == ISD::SMAX && Range.getSignedMax().sle(C1V)) ||
6543 (Opcode == ISD::SMIN && Range.getSignedMin().sge(C1V))) {
6544 return N1;
6545 }
6546 }
6547 }
6548
6549 // Simplify the operands using demanded-bits information.
6551 return SDValue(N, 0);
6552
6553 return SDValue();
6554}
6555
6556/// If this is a bitwise logic instruction and both operands have the same
6557/// opcode, try to sink the other opcode after the logic instruction.
6558SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
6559 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
6560 EVT VT = N0.getValueType();
6561 unsigned LogicOpcode = N->getOpcode();
6562 unsigned HandOpcode = N0.getOpcode();
6563 assert(ISD::isBitwiseLogicOp(LogicOpcode) && "Expected logic opcode");
6564 assert(HandOpcode == N1.getOpcode() && "Bad input!");
6565
6566 // Bail early if none of these transforms apply.
6567 if (N0.getNumOperands() == 0)
6568 return SDValue();
6569
6570 // FIXME: We should check number of uses of the operands to not increase
6571 // the instruction count for all transforms.
6572
6573 // Handle size-changing casts (or sign_extend_inreg).
6574 SDValue X = N0.getOperand(0);
6575 SDValue Y = N1.getOperand(0);
6576 EVT XVT = X.getValueType();
6577 SDLoc DL(N);
6578 if (ISD::isExtOpcode(HandOpcode) || ISD::isExtVecInRegOpcode(HandOpcode) ||
6579 (HandOpcode == ISD::SIGN_EXTEND_INREG &&
6580 N0.getOperand(1) == N1.getOperand(1))) {
6581 // If both operands have other uses, this transform would create extra
6582 // instructions without eliminating anything.
6583 if (!N0.hasOneUse() && !N1.hasOneUse())
6584 return SDValue();
6585 // We need matching integer source types.
6586 if (XVT != Y.getValueType())
6587 return SDValue();
6588 // Don't create an illegal op during or after legalization. Don't ever
6589 // create an unsupported vector op.
6590 if ((VT.isVector() || LegalOperations) &&
6591 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
6592 return SDValue();
6593 // Avoid infinite looping with PromoteIntBinOp.
6594 // TODO: Should we apply desirable/legal constraints to all opcodes?
6595 if ((HandOpcode == ISD::ANY_EXTEND ||
6596 HandOpcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
6597 LegalTypes && !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
6598 return SDValue();
6599 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
6600 SDNodeFlags LogicFlags;
6601 LogicFlags.setDisjoint(N->getFlags().hasDisjoint() &&
6602 ISD::isExtOpcode(HandOpcode));
6603 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y, LogicFlags);
6604 if (HandOpcode == ISD::SIGN_EXTEND_INREG)
6605 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6606 return DAG.getNode(HandOpcode, DL, VT, Logic);
6607 }
6608
6609 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
6610 if (HandOpcode == ISD::TRUNCATE) {
6611 // If both operands have other uses, this transform would create extra
6612 // instructions without eliminating anything.
6613 if (!N0.hasOneUse() && !N1.hasOneUse())
6614 return SDValue();
6615 // We need matching source types.
6616 if (XVT != Y.getValueType())
6617 return SDValue();
6618 // Don't create an illegal op during or after legalization.
6619 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
6620 return SDValue();
6621 // Be extra careful sinking truncate. If it's free, there's no benefit in
6622 // widening a binop. Also, don't create a logic op on an illegal type.
6623 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
6624 return SDValue();
6625 if (!TLI.isTypeLegal(XVT))
6626 return SDValue();
6627 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6628 return DAG.getNode(HandOpcode, DL, VT, Logic);
6629 }
6630
6631 // For binops SHL/SRL/SRA/AND:
6632 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
6633 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
6634 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
6635 N0.getOperand(1) == N1.getOperand(1)) {
6636 // If either operand has other uses, this transform is not an improvement.
6637 if (!N0.hasOneUse() || !N1.hasOneUse())
6638 return SDValue();
6639 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6640 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
6641 }
6642
6643 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
6644 if (HandOpcode == ISD::BSWAP) {
6645 // If either operand has other uses, this transform is not an improvement.
6646 if (!N0.hasOneUse() || !N1.hasOneUse())
6647 return SDValue();
6648 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6649 return DAG.getNode(HandOpcode, DL, VT, Logic);
6650 }
6651
6652 // For funnel shifts FSHL/FSHR:
6653 // logic_op (OP x, x1, s), (OP y, y1, s) -->
6654 // --> OP (logic_op x, y), (logic_op, x1, y1), s
6655 if ((HandOpcode == ISD::FSHL || HandOpcode == ISD::FSHR) &&
6656 N0.getOperand(2) == N1.getOperand(2)) {
6657 if (!N0.hasOneUse() || !N1.hasOneUse())
6658 return SDValue();
6659 SDValue X1 = N0.getOperand(1);
6660 SDValue Y1 = N1.getOperand(1);
6661 SDValue S = N0.getOperand(2);
6662 SDValue Logic0 = DAG.getNode(LogicOpcode, DL, VT, X, Y);
6663 SDValue Logic1 = DAG.getNode(LogicOpcode, DL, VT, X1, Y1);
6664 return DAG.getNode(HandOpcode, DL, VT, Logic0, Logic1, S);
6665 }
6666
6667 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
6668 // Only perform this optimization up until type legalization, before
6669 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
6670 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
6671 // we don't want to undo this promotion.
6672 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
6673 // on scalars.
6674 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
6675 Level <= AfterLegalizeTypes) {
6676 // Input types must be integer and the same.
6677 if (XVT.isInteger() && XVT == Y.getValueType() &&
6678 !(VT.isVector() && TLI.isTypeLegal(VT) &&
6679 !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
6680 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
6681 return DAG.getNode(HandOpcode, DL, VT, Logic);
6682 }
6683 }
6684
6685 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
6686 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
6687 // If both shuffles use the same mask, and both shuffle within a single
6688 // vector, then it is worthwhile to move the swizzle after the operation.
6689 // The type-legalizer generates this pattern when loading illegal
6690 // vector types from memory. In many cases this allows additional shuffle
6691 // optimizations.
6692 // There are other cases where moving the shuffle after the xor/and/or
6693 // is profitable even if shuffles don't perform a swizzle.
6694 // If both shuffles use the same mask, and both shuffles have the same first
6695 // or second operand, then it might still be profitable to move the shuffle
6696 // after the xor/and/or operation.
6697 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
6698 auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
6699 auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
6700 assert(X.getValueType() == Y.getValueType() &&
6701 "Inputs to shuffles are not the same type");
6702
6703 // Check that both shuffles use the same mask. The masks are known to be of
6704 // the same length because the result vector type is the same.
6705 // Check also that shuffles have only one use to avoid introducing extra
6706 // instructions.
6707 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
6708 !SVN0->getMask().equals(SVN1->getMask()))
6709 return SDValue();
6710
6711 // Don't try to fold this node if it requires introducing a
6712 // build vector of all zeros that might be illegal at this stage.
6713 SDValue ShOp = N0.getOperand(1);
6714 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6715 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6716
6717 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
6718 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
6719 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
6720 N0.getOperand(0), N1.getOperand(0));
6721 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
6722 }
6723
6724 // Don't try to fold this node if it requires introducing a
6725 // build vector of all zeros that might be illegal at this stage.
6726 ShOp = N0.getOperand(0);
6727 if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
6728 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
6729
6730 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
6731 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
6732 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
6733 N1.getOperand(1));
6734 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
6735 }
6736 }
6737
6738 return SDValue();
6739}
6740
6741/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
6742SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
6743 const SDLoc &DL) {
6744 SDValue LL, LR, RL, RR, N0CC, N1CC;
6745 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
6746 !isSetCCEquivalent(N1, RL, RR, N1CC))
6747 return SDValue();
6748
6749 assert(N0.getValueType() == N1.getValueType() &&
6750 "Unexpected operand types for bitwise logic op");
6751 assert(LL.getValueType() == LR.getValueType() &&
6752 RL.getValueType() == RR.getValueType() &&
6753 "Unexpected operand types for setcc");
6754
6755 // If we're here post-legalization or the logic op type is not i1, the logic
6756 // op type must match a setcc result type. Also, all folds require new
6757 // operations on the left and right operands, so those types must match.
6758 EVT VT = N0.getValueType();
6759 EVT OpVT = LL.getValueType();
6760 if (LegalOperations || VT.getScalarType() != MVT::i1)
6761 if (VT != getSetCCResultType(OpVT))
6762 return SDValue();
6763 if (OpVT != RL.getValueType())
6764 return SDValue();
6765
6766 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
6767 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
6768 bool IsInteger = OpVT.isInteger();
6769 if (LR == RR && CC0 == CC1 && IsInteger) {
6770 bool IsZero = isNullOrNullSplat(LR);
6771 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
6772
6773 // All bits clear?
6774 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
6775 // All sign bits clear?
6776 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
6777 // Any bits set?
6778 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
6779 // Any sign bits set?
6780 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
6781
6782 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
6783 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
6784 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
6785 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
6786 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
6787 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
6788 AddToWorklist(Or.getNode());
6789 return DAG.getSetCC(DL, VT, Or, LR, CC1);
6790 }
6791
6792 // All bits set?
6793 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
6794 // All sign bits set?
6795 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
6796 // Any bits clear?
6797 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
6798 // Any sign bits clear?
6799 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
6800
6801 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
6802 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
6803 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
6804 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
6805 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
6806 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
6807 AddToWorklist(And.getNode());
6808 return DAG.getSetCC(DL, VT, And, LR, CC1);
6809 }
6810 }
6811
6812 // (and (setne (and X, LL1), 0), (setne (and X, RL1), 0))
6813 // --> (seteq (and X, (LL1|RL1)), (LL1|RL1))
6814 // (or (seteq (and X, LL1), 0), (seteq (and X, RL1), 0))
6815 // --> (setne (and X, (LL1|RL1)), (LL1|RL1))
6816 if (LL.getOpcode() == ISD::AND && RL.getOpcode() == ISD::AND &&
6817 isNullConstant(LR) && isNullConstant(RR) && CC0 == CC1 &&
6818 (CC0 == ISD::SETNE || CC0 == ISD::SETEQ)) {
6819 SDValue LL0, LL1, RL0, RL1;
6820 LL0 = LL.getOperand(0);
6821 RL0 = RL.getOperand(0);
6822 LL1 = LL.getOperand(1);
6823 RL1 = RL.getOperand(1);
6824 if (LL0 == RL0 && DAG.isKnownToBeAPowerOfTwo(LL1) &&
6825 DAG.isKnownToBeAPowerOfTwo(RL1)) {
6826 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL1, RL1);
6827 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL0, Or);
6828 return DAG.getSetCC(DL, VT, And, Or, IsAnd ? ISD::SETEQ : ISD::SETNE);
6829 }
6830 }
6831
6832 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
6833 // (or (seteq X, 0), (seteq X, -1)) --> (setult (add X, 1), 2)
6834 if (LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && IsInteger &&
6835 ((IsAnd && CC0 == ISD::SETNE) || (!IsAnd && CC0 == ISD::SETEQ)) &&
6836 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
6837 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
6838 SDValue One = DAG.getConstant(1, DL, OpVT);
6839 SDValue Two = DAG.getConstant(2, DL, OpVT);
6840 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
6841 AddToWorklist(Add.getNode());
6842 return DAG.getSetCC(DL, VT, Add, Two, IsAnd ? ISD::SETUGE : ISD::SETULT);
6843 }
6844
6845 // Try more general transforms if the predicates match and the only user of
6846 // the compares is the 'and' or 'or'.
6847 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
6848 N0.hasOneUse() && N1.hasOneUse()) {
6849 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
6850 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
6851 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
6852 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
6853 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
6854 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
6855 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6856 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
6857 }
6858
6859 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
6860 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
6861 // Match a shared variable operand and 2 non-opaque constant operands.
6862 auto MatchDiffPow2 = [&](ConstantSDNode *C0, ConstantSDNode *C1) {
6863 // The difference of the constants must be a single bit.
6864 const APInt &CMax =
6865 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
6866 const APInt &CMin =
6867 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
6868 return !C0->isOpaque() && !C1->isOpaque() && (CMax - CMin).isPowerOf2();
6869 };
6870 if (LL == RL && ISD::matchBinaryPredicate(LR, RR, MatchDiffPow2)) {
6871 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
6872 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
6873 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
6874 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
6875 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
6876 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
6877 SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
6878 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
6879 SDValue Zero = DAG.getConstant(0, DL, OpVT);
6880 return DAG.getSetCC(DL, VT, And, Zero, CC0);
6881 }
6882 }
6883 }
6884
6885 // Canonicalize equivalent operands to LL == RL.
6886 if (LL == RR && LR == RL) {
6888 std::swap(RL, RR);
6889 }
6890
6891 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6892 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
6893 if (LL == RL && LR == RR) {
6894 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
6895 : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
6896 if (NewCC != ISD::SETCC_INVALID &&
6897 (!LegalOperations ||
6898 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
6899 TLI.isOperationLegal(ISD::SETCC, OpVT))))
6900 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
6901 }
6902
6903 return SDValue();
6904}
6905
6906static bool arebothOperandsNotSNan(SDValue Operand1, SDValue Operand2,
6907 SelectionDAG &DAG) {
6908 return DAG.isKnownNeverSNaN(Operand2) && DAG.isKnownNeverSNaN(Operand1);
6909}
6910
6911static bool arebothOperandsNotNan(SDValue Operand1, SDValue Operand2,
6912 SelectionDAG &DAG) {
6913 return DAG.isKnownNeverNaN(Operand2) && DAG.isKnownNeverNaN(Operand1);
6914}
6915
6916/// Returns an appropriate FP min/max opcode for clamping operations.
6917static unsigned getMinMaxOpcodeForClamp(bool IsMin, SDValue Operand1,
6918 SDValue Operand2, SelectionDAG &DAG,
6919 const TargetLowering &TLI) {
6920 EVT VT = Operand1.getValueType();
6921 unsigned IEEEOp = IsMin ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6922 if (TLI.isOperationLegalOrCustom(IEEEOp, VT) &&
6923 arebothOperandsNotNan(Operand1, Operand2, DAG))
6924 return IEEEOp;
6925 unsigned PreferredOp = IsMin ? ISD::FMINNUM : ISD::FMAXNUM;
6926 if (TLI.isOperationLegalOrCustom(PreferredOp, VT))
6927 return PreferredOp;
6928 return ISD::DELETED_NODE;
6929}
6930
6931// FIXME: use FMINIMUMNUM if possible, such as for RISC-V.
6933 SDValue Operand1, SDValue Operand2, bool SetCCNoNaNs, ISD::CondCode CC,
6934 unsigned OrAndOpcode, SelectionDAG &DAG, bool isFMAXNUMFMINNUM_IEEE,
6935 bool isFMAXNUMFMINNUM) {
6936 // The optimization cannot be applied for all the predicates because
6937 // of the way FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle
6938 // NaNs. For FMINNUM_IEEE/FMAXNUM_IEEE, the optimization cannot be
6939 // applied at all if one of the operands is a signaling NaN.
6940
6941 // It is safe to use FMINNUM_IEEE/FMAXNUM_IEEE if all the operands
6942 // are non NaN values.
6943 if (((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::OR)) ||
6944 ((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::AND))) {
6945 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6946 isFMAXNUMFMINNUM_IEEE
6949 }
6950
6951 if (((CC == ISD::SETGT || CC == ISD::SETGE) && (OrAndOpcode == ISD::OR)) ||
6952 ((CC == ISD::SETLT || CC == ISD::SETLE) && (OrAndOpcode == ISD::AND))) {
6953 return (SetCCNoNaNs || arebothOperandsNotNan(Operand1, Operand2, DAG)) &&
6954 isFMAXNUMFMINNUM_IEEE
6957 }
6958
6959 // Both FMINNUM/FMAXNUM and FMINNUM_IEEE/FMAXNUM_IEEE handle quiet
6960 // NaNs in the same way. But, FMINNUM/FMAXNUM and FMINNUM_IEEE/
6961 // FMAXNUM_IEEE handle signaling NaNs differently. If we cannot prove
6962 // that there are not any sNaNs, then the optimization is not valid
6963 // for FMINNUM_IEEE/FMAXNUM_IEEE. In the presence of sNaNs, we apply
6964 // the optimization using FMINNUM/FMAXNUM for the following cases. If
6965 // we can prove that we do not have any sNaNs, then we can do the
6966 // optimization using FMINNUM_IEEE/FMAXNUM_IEEE for the following
6967 // cases.
6968 if (((CC == ISD::SETOLT || CC == ISD::SETOLE) && (OrAndOpcode == ISD::OR)) ||
6969 ((CC == ISD::SETUGT || CC == ISD::SETUGE) && (OrAndOpcode == ISD::AND))) {
6970 return isFMAXNUMFMINNUM ? ISD::FMINNUM
6971 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6972 isFMAXNUMFMINNUM_IEEE
6975 }
6976
6977 if (((CC == ISD::SETOGT || CC == ISD::SETOGE) && (OrAndOpcode == ISD::OR)) ||
6978 ((CC == ISD::SETULT || CC == ISD::SETULE) && (OrAndOpcode == ISD::AND))) {
6979 return isFMAXNUMFMINNUM ? ISD::FMAXNUM
6980 : arebothOperandsNotSNan(Operand1, Operand2, DAG) &&
6981 isFMAXNUMFMINNUM_IEEE
6984 }
6985
6986 return ISD::DELETED_NODE;
6987}
6988
6991 assert(
6992 (LogicOp->getOpcode() == ISD::AND || LogicOp->getOpcode() == ISD::OR) &&
6993 "Invalid Op to combine SETCC with");
6994
6995 // TODO: Search past casts/truncates.
6996 SDValue LHS = LogicOp->getOperand(0);
6997 SDValue RHS = LogicOp->getOperand(1);
6998 if (LHS->getOpcode() != ISD::SETCC || RHS->getOpcode() != ISD::SETCC ||
6999 !LHS->hasOneUse() || !RHS->hasOneUse())
7000 return SDValue();
7001
7002 SDNodeFlags LHSSetCCFlags = LHS->getFlags();
7003 SDNodeFlags RHSSetCCFlags = RHS->getFlags();
7004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7006 LogicOp, LHS.getNode(), RHS.getNode());
7007
7008 SDValue LHS0 = LHS->getOperand(0);
7009 SDValue RHS0 = RHS->getOperand(0);
7010 SDValue LHS1 = LHS->getOperand(1);
7011 SDValue RHS1 = RHS->getOperand(1);
7012 // TODO: We don't actually need a splat here, for vectors we just need the
7013 // invariants to hold for each element.
7014 auto *LHS1C = isConstOrConstSplat(LHS1);
7015 auto *RHS1C = isConstOrConstSplat(RHS1);
7016 ISD::CondCode CCL = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7017 ISD::CondCode CCR = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7018 EVT VT = LogicOp->getValueType(0);
7019 EVT OpVT = LHS0.getValueType();
7020 SDLoc DL(LogicOp);
7021
7022 // Check if the operands of an and/or operation are comparisons and if they
7023 // compare against the same value. Replace the and/or-cmp-cmp sequence with
7024 // min/max cmp sequence. If LHS1 is equal to RHS1, then the or-cmp-cmp
7025 // sequence will be replaced with min-cmp sequence:
7026 // (LHS0 < LHS1) | (RHS0 < RHS1) -> min(LHS0, RHS0) < LHS1
7027 // and and-cmp-cmp will be replaced with max-cmp sequence:
7028 // (LHS0 < LHS1) & (RHS0 < RHS1) -> max(LHS0, RHS0) < LHS1
7029 // The optimization does not work for `==` or `!=` .
7030 // The two comparisons should have either the same predicate or the
7031 // predicate of one of the comparisons is the opposite of the other one.
7032 bool isFMAXNUMFMINNUM_IEEE = TLI.isOperationLegal(ISD::FMAXNUM_IEEE, OpVT) &&
7034 bool isFMAXNUMFMINNUM = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, OpVT) &&
7036 if (((OpVT.isInteger() && TLI.isOperationLegal(ISD::UMAX, OpVT) &&
7037 TLI.isOperationLegal(ISD::SMAX, OpVT) &&
7038 TLI.isOperationLegal(ISD::UMIN, OpVT) &&
7039 TLI.isOperationLegal(ISD::SMIN, OpVT)) ||
7040 (OpVT.isFloatingPoint() &&
7041 (isFMAXNUMFMINNUM_IEEE || isFMAXNUMFMINNUM))) &&
7043 CCL != ISD::SETFALSE && CCL != ISD::SETO && CCL != ISD::SETUO &&
7044 CCL != ISD::SETTRUE &&
7045 (CCL == CCR || CCL == ISD::getSetCCSwappedOperands(CCR))) {
7046
7047 SDValue CommonValue, Operand1, Operand2;
7049 if (CCL == CCR) {
7050 if (LHS0 == RHS0) {
7051 CommonValue = LHS0;
7052 Operand1 = LHS1;
7053 Operand2 = RHS1;
7055 } else if (LHS1 == RHS1) {
7056 CommonValue = LHS1;
7057 Operand1 = LHS0;
7058 Operand2 = RHS0;
7059 CC = CCL;
7060 }
7061 } else {
7062 assert(CCL == ISD::getSetCCSwappedOperands(CCR) && "Unexpected CC");
7063 if (LHS0 == RHS1) {
7064 CommonValue = LHS0;
7065 Operand1 = LHS1;
7066 Operand2 = RHS0;
7067 CC = CCR;
7068 } else if (RHS0 == LHS1) {
7069 CommonValue = LHS1;
7070 Operand1 = LHS0;
7071 Operand2 = RHS1;
7072 CC = CCL;
7073 }
7074 }
7075
7076 // Don't do this transform for sign bit tests. Let foldLogicOfSetCCs
7077 // handle it using OR/AND.
7078 if (CC == ISD::SETLT && isNullOrNullSplat(CommonValue))
7079 CC = ISD::SETCC_INVALID;
7080 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CommonValue))
7081 CC = ISD::SETCC_INVALID;
7082
7083 if (CC != ISD::SETCC_INVALID) {
7084 unsigned NewOpcode = ISD::DELETED_NODE;
7085 bool IsSigned = isSignedIntSetCC(CC);
7086 if (OpVT.isInteger()) {
7087 bool IsLess = (CC == ISD::SETLE || CC == ISD::SETULE ||
7088 CC == ISD::SETLT || CC == ISD::SETULT);
7089 bool IsOr = (LogicOp->getOpcode() == ISD::OR);
7090 if (IsLess == IsOr)
7091 NewOpcode = IsSigned ? ISD::SMIN : ISD::UMIN;
7092 else
7093 NewOpcode = IsSigned ? ISD::SMAX : ISD::UMAX;
7094 } else if (OpVT.isFloatingPoint())
7096 Operand1, Operand2,
7097 LHSSetCCFlags.hasNoNaNs() && RHSSetCCFlags.hasNoNaNs(), CC,
7098 LogicOp->getOpcode(), DAG, isFMAXNUMFMINNUM_IEEE, isFMAXNUMFMINNUM);
7099
7100 if (NewOpcode != ISD::DELETED_NODE) {
7101 // Propagate fast-math flags from setcc.
7102 SDNodeFlags Flags = LHS->getFlags() & RHS->getFlags();
7103 SDValue MinMaxValue =
7104 DAG.getNode(NewOpcode, DL, OpVT, Operand1, Operand2, Flags);
7105 return DAG.getSetCC(DL, VT, MinMaxValue, CommonValue, CC, /*Chain=*/{},
7106 /*IsSignaling=*/false, Flags);
7107 }
7108 }
7109 }
7110
7111 if (LHS0 == LHS1 && RHS0 == RHS1 && CCL == CCR &&
7112 LHS0.getValueType() == RHS0.getValueType() &&
7113 ((LogicOp->getOpcode() == ISD::AND && CCL == ISD::SETO) ||
7114 (LogicOp->getOpcode() == ISD::OR && CCL == ISD::SETUO)))
7115 return DAG.getSetCC(DL, VT, LHS0, RHS0, CCL);
7116
7117 if (TargetPreference == AndOrSETCCFoldKind::None)
7118 return SDValue();
7119
7120 if (CCL == CCR &&
7121 CCL == (LogicOp->getOpcode() == ISD::AND ? ISD::SETNE : ISD::SETEQ) &&
7122 LHS0 == RHS0 && LHS1C && RHS1C && OpVT.isInteger()) {
7123 const APInt &APLhs = LHS1C->getAPIntValue();
7124 const APInt &APRhs = RHS1C->getAPIntValue();
7125
7126 // Preference is to use ISD::ABS or we already have an ISD::ABS (in which
7127 // case this is just a compare).
7128 if (APLhs == (-APRhs) &&
7129 ((TargetPreference & AndOrSETCCFoldKind::ABS) ||
7130 DAG.doesNodeExist(ISD::ABS, DAG.getVTList(OpVT), {LHS0}))) {
7131 const APInt &C = APLhs.isNegative() ? APRhs : APLhs;
7132 // (icmp eq A, C) | (icmp eq A, -C)
7133 // -> (icmp eq Abs(A), C)
7134 // (icmp ne A, C) & (icmp ne A, -C)
7135 // -> (icmp ne Abs(A), C)
7136 SDValue AbsOp = DAG.getNode(ISD::ABS, DL, OpVT, LHS0);
7137 return DAG.getNode(ISD::SETCC, DL, VT, AbsOp,
7138 DAG.getConstant(C, DL, OpVT), LHS.getOperand(2));
7139 } else if (TargetPreference &
7141
7142 // AndOrSETCCFoldKind::AddAnd:
7143 // A == C0 | A == C1
7144 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7145 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) == 0
7146 // A != C0 & A != C1
7147 // IF IsPow2(smax(C0, C1)-smin(C0, C1))
7148 // -> ((A - smin(C0, C1)) & ~(smax(C0, C1)-smin(C0, C1))) != 0
7149
7150 // AndOrSETCCFoldKind::NotAnd:
7151 // A == C0 | A == C1
7152 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7153 // -> ~A & smin(C0, C1) == 0
7154 // A != C0 & A != C1
7155 // IF smax(C0, C1) == -1 AND IsPow2(smax(C0, C1) - smin(C0, C1))
7156 // -> ~A & smin(C0, C1) != 0
7157
7158 const APInt &MaxC = APIntOps::smax(APRhs, APLhs);
7159 const APInt &MinC = APIntOps::smin(APRhs, APLhs);
7160 APInt Dif = MaxC - MinC;
7161 if (!Dif.isZero() && Dif.isPowerOf2()) {
7162 if (MaxC.isAllOnes() &&
7163 (TargetPreference & AndOrSETCCFoldKind::NotAnd)) {
7164 SDValue NotOp = DAG.getNOT(DL, LHS0, OpVT);
7165 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, NotOp,
7166 DAG.getConstant(MinC, DL, OpVT));
7167 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7168 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7169 } else if (TargetPreference & AndOrSETCCFoldKind::AddAnd) {
7170
7171 SDValue AddOp = DAG.getNode(ISD::ADD, DL, OpVT, LHS0,
7172 DAG.getConstant(-MinC, DL, OpVT));
7173 SDValue AndOp = DAG.getNode(ISD::AND, DL, OpVT, AddOp,
7174 DAG.getConstant(~Dif, DL, OpVT));
7175 return DAG.getNode(ISD::SETCC, DL, VT, AndOp,
7176 DAG.getConstant(0, DL, OpVT), LHS.getOperand(2));
7177 }
7178 }
7179 }
7180 }
7181
7182 return SDValue();
7183}
7184
7185// Combine `(select c, (X & 1), 0)` -> `(and (zext c), X)`.
7186// We canonicalize to the `select` form in the middle end, but the `and` form
7187// gets better codegen and all tested targets (arm, x86, riscv)
7189 const SDLoc &DL, SelectionDAG &DAG) {
7190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7191 if (!isNullConstant(F))
7192 return SDValue();
7193
7194 EVT CondVT = Cond.getValueType();
7195 if (TLI.getBooleanContents(CondVT) !=
7197 return SDValue();
7198
7199 if (T.getOpcode() != ISD::AND)
7200 return SDValue();
7201
7202 if (!isOneConstant(T.getOperand(1)))
7203 return SDValue();
7204
7205 EVT OpVT = T.getValueType();
7206
7207 SDValue CondMask =
7208 OpVT == CondVT ? Cond : DAG.getBoolExtOrTrunc(Cond, DL, OpVT, CondVT);
7209 return DAG.getNode(ISD::AND, DL, OpVT, CondMask, T.getOperand(0));
7210}
7211
7212/// This contains all DAGCombine rules which reduce two values combined by
7213/// an And operation to a single value. This makes them reusable in the context
7214/// of visitSELECT(). Rules involving constants are not included as
7215/// visitSELECT() already handles those cases.
7216SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
7217 EVT VT = N1.getValueType();
7218 SDLoc DL(N);
7219
7220 // fold (and x, undef) -> 0
7221 if (N0.isUndef() || N1.isUndef())
7222 return DAG.getConstant(0, DL, VT);
7223
7224 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
7225 return V;
7226
7227 // Canonicalize:
7228 // and(x, add) -> and(add, x)
7229 if (N1.getOpcode() == ISD::ADD)
7230 std::swap(N0, N1);
7231
7232 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
7233 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
7234 VT.isScalarInteger() && VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
7235 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7236 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
7237 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
7238 // immediate for an add, but it is legal if its top c2 bits are set,
7239 // transform the ADD so the immediate doesn't need to be materialized
7240 // in a register.
7241 APInt ADDC = ADDI->getAPIntValue();
7242 APInt SRLC = SRLI->getAPIntValue();
7243 if (ADDC.getSignificantBits() <= 64 && SRLC.ult(VT.getSizeInBits()) &&
7244 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7246 SRLC.getZExtValue());
7247 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
7248 ADDC |= Mask;
7249 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
7250 SDLoc DL0(N0);
7251 SDValue NewAdd =
7252 DAG.getNode(ISD::ADD, DL0, VT,
7253 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
7254 CombineTo(N0.getNode(), NewAdd);
7255 // Return N so it doesn't get rechecked!
7256 return SDValue(N, 0);
7257 }
7258 }
7259 }
7260 }
7261 }
7262 }
7263
7264 return SDValue();
7265}
7266
7267bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
7268 EVT LoadResultTy, EVT &ExtVT) {
7269 if (!AndC->getAPIntValue().isMask())
7270 return false;
7271
7272 unsigned ActiveBits = AndC->getAPIntValue().countr_one();
7273
7274 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7275 EVT LoadedVT = LoadN->getMemoryVT();
7276
7277 if (ExtVT == LoadedVT &&
7278 (!LegalOperations ||
7279 TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7280 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))) {
7281 // ZEXTLOAD will match without needing to change the size of the value being
7282 // loaded.
7283 return true;
7284 }
7285
7286 // Do not change the width of a volatile or atomic loads.
7287 if (!LoadN->isSimple())
7288 return false;
7289
7290 // Do not generate loads of non-round integer types since these can
7291 // be expensive (and would be wrong if the type is not byte sized).
7292 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
7293 return false;
7294
7295 if (LegalOperations &&
7296 !TLI.isLoadLegal(LoadResultTy, ExtVT, LoadN->getAlign(),
7297 LoadN->getAddressSpace(), ISD::ZEXTLOAD, false))
7298 return false;
7299
7300 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT, /*ByteOffset=*/0))
7301 return false;
7302
7303 return true;
7304}
7305
7306bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
7307 ISD::LoadExtType ExtType, EVT &MemVT,
7308 unsigned ShAmt) {
7309 if (!LDST)
7310 return false;
7311
7312 // Only allow byte offsets.
7313 if (ShAmt % 8)
7314 return false;
7315 const unsigned ByteShAmt = ShAmt / 8;
7316
7317 // Do not generate loads of non-round integer types since these can
7318 // be expensive (and would be wrong if the type is not byte sized).
7319 if (!MemVT.isRound())
7320 return false;
7321
7322 // Don't change the width of a volatile or atomic loads.
7323 if (!LDST->isSimple())
7324 return false;
7325
7326 EVT LdStMemVT = LDST->getMemoryVT();
7327
7328 // Bail out when changing the scalable property, since we can't be sure that
7329 // we're actually narrowing here.
7330 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
7331 return false;
7332
7333 // Verify that we are actually reducing a load width here.
7334 if (LdStMemVT.bitsLT(MemVT))
7335 return false;
7336
7337 // Ensure that this isn't going to produce an unsupported memory access.
7338 if (ShAmt) {
7339 const Align LDSTAlign = LDST->getAlign();
7340 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
7341 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7342 LDST->getAddressSpace(), NarrowAlign,
7343 LDST->getMemOperand()->getFlags()))
7344 return false;
7345 }
7346
7347 // It's not possible to generate a constant of extended or untyped type.
7348 EVT PtrType = LDST->getBasePtr().getValueType();
7349 if (PtrType == MVT::Untyped || PtrType.isExtended())
7350 return false;
7351
7352 if (isa<LoadSDNode>(LDST)) {
7353 LoadSDNode *Load = cast<LoadSDNode>(LDST);
7354 // Don't transform one with multiple uses, this would require adding a new
7355 // load.
7356 if (!SDValue(Load, 0).hasOneUse())
7357 return false;
7358
7359 if (LegalOperations &&
7360 !TLI.isLoadLegal(Load->getValueType(0), MemVT, Load->getAlign(),
7361 Load->getAddressSpace(), ExtType, false))
7362 return false;
7363
7364 // For the transform to be legal, the load must produce only two values
7365 // (the value loaded and the chain). Don't transform a pre-increment
7366 // load, for example, which produces an extra value. Otherwise the
7367 // transformation is not equivalent, and the downstream logic to replace
7368 // uses gets things wrong.
7369 if (Load->getNumValues() > 2)
7370 return false;
7371
7372 // If the load that we're shrinking is an extload and we're not just
7373 // discarding the extension we can't simply shrink the load. Bail.
7374 // TODO: It would be possible to merge the extensions in some cases.
7375 if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
7376 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7377 return false;
7378
7379 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT, ByteShAmt))
7380 return false;
7381 } else {
7382 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
7383 StoreSDNode *Store = cast<StoreSDNode>(LDST);
7384 // Can't write outside the original store
7385 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
7386 return false;
7387
7388 if (LegalOperations &&
7389 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT,
7390 Store->getAlign(), Store->getAddressSpace()))
7391 return false;
7392 }
7393 return true;
7394}
7395
7396bool DAGCombiner::SearchForAndLoads(SDNode *N,
7397 SmallVectorImpl<LoadSDNode*> &Loads,
7398 SmallPtrSetImpl<SDNode*> &NodesWithConsts,
7399 ConstantSDNode *Mask,
7400 SDNode *&NodeToMask) {
7401 // Recursively search for the operands, looking for loads which can be
7402 // narrowed.
7403 for (SDValue Op : N->op_values()) {
7404 if (Op.getValueType().isVector())
7405 return false;
7406
7407 // Some constants may need fixing up later if they are too large.
7408 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
7409 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
7410 "Expected bitwise logic operation");
7411 if (!C->getAPIntValue().isSubsetOf(Mask->getAPIntValue()))
7412 NodesWithConsts.insert(N);
7413 continue;
7414 }
7415
7416 if (!Op.hasOneUse())
7417 return false;
7418
7419 switch(Op.getOpcode()) {
7420 case ISD::LOAD: {
7421 auto *Load = cast<LoadSDNode>(Op);
7422 EVT ExtVT;
7423 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
7424 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
7425
7426 // ZEXTLOAD is already small enough.
7427 if (Load->getExtensionType() == ISD::ZEXTLOAD &&
7428 ExtVT.bitsGE(Load->getMemoryVT()))
7429 continue;
7430
7431 // Use LE to convert equal sized loads to zext.
7432 if (ExtVT.bitsLE(Load->getMemoryVT()))
7433 Loads.push_back(Load);
7434
7435 continue;
7436 }
7437 return false;
7438 }
7439 case ISD::ZERO_EXTEND:
7440 case ISD::AssertZext: {
7441 unsigned ActiveBits = Mask->getAPIntValue().countr_one();
7442 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
7443 EVT VT = Op.getOpcode() == ISD::AssertZext ?
7444 cast<VTSDNode>(Op.getOperand(1))->getVT() :
7445 Op.getOperand(0).getValueType();
7446
7447 // We can accept extending nodes if the mask is wider or an equal
7448 // width to the original type.
7449 if (ExtVT.bitsGE(VT))
7450 continue;
7451 break;
7452 }
7453 case ISD::OR:
7454 case ISD::XOR:
7455 case ISD::AND:
7456 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
7457 NodeToMask))
7458 return false;
7459 continue;
7460 }
7461
7462 // Allow one node which will masked along with any loads found.
7463 if (NodeToMask)
7464 return false;
7465
7466 // Also ensure that the node to be masked only produces one data result.
7467 NodeToMask = Op.getNode();
7468 if (NodeToMask->getNumValues() > 1) {
7469 bool HasValue = false;
7470 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
7471 MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
7472 if (VT != MVT::Glue && VT != MVT::Other) {
7473 if (HasValue) {
7474 NodeToMask = nullptr;
7475 return false;
7476 }
7477 HasValue = true;
7478 }
7479 }
7480 assert(HasValue && "Node to be masked has no data result?");
7481 }
7482 }
7483 return true;
7484}
7485
7486bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
7487 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
7488 if (!Mask)
7489 return false;
7490
7491 if (!Mask->getAPIntValue().isMask())
7492 return false;
7493
7494 // No need to do anything if the and directly uses a load.
7495 if (isa<LoadSDNode>(N->getOperand(0)))
7496 return false;
7497
7499 SmallPtrSet<SDNode*, 2> NodesWithConsts;
7500 SDNode *FixupNode = nullptr;
7501 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
7502 if (Loads.empty())
7503 return false;
7504
7505 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
7506 SDValue MaskOp = N->getOperand(1);
7507
7508 // If it exists, fixup the single node we allow in the tree that needs
7509 // masking.
7510 if (FixupNode) {
7511 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
7512 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
7513 FixupNode->getValueType(0),
7514 SDValue(FixupNode, 0), MaskOp);
7515 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
7516 if (And.getOpcode() == ISD ::AND)
7517 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
7518 }
7519
7520 // Narrow any constants that need it.
7521 for (auto *LogicN : NodesWithConsts) {
7522 SDValue Op0 = LogicN->getOperand(0);
7523 SDValue Op1 = LogicN->getOperand(1);
7524
7525 // We only need to fix AND if both inputs are constants. And we only need
7526 // to fix one of the constants.
7527 if (LogicN->getOpcode() == ISD::AND &&
7529 continue;
7530
7531 if (isa<ConstantSDNode>(Op0) && LogicN->getOpcode() != ISD::AND)
7532 Op0 =
7533 DAG.getNode(ISD::AND, SDLoc(Op0), Op0.getValueType(), Op0, MaskOp);
7534
7535 if (isa<ConstantSDNode>(Op1))
7536 Op1 =
7537 DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), Op1, MaskOp);
7538
7539 if (isa<ConstantSDNode>(Op0) && !isa<ConstantSDNode>(Op1))
7540 std::swap(Op0, Op1);
7541
7542 DAG.UpdateNodeOperands(LogicN, Op0, Op1);
7543 }
7544
7545 // Create narrow loads.
7546 for (auto *Load : Loads) {
7547 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
7548 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
7549 SDValue(Load, 0), MaskOp);
7551 if (And.getOpcode() == ISD ::AND)
7552 And = SDValue(
7553 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
7554 SDValue NewLoad = reduceLoadWidth(And.getNode());
7555 assert(NewLoad &&
7556 "Shouldn't be masking the load if it can't be narrowed");
7557 CombineTo(Load, NewLoad, NewLoad.getValue(1));
7558 }
7559 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
7560 return true;
7561 }
7562 return false;
7563}
7564
7565// Unfold
7566// x & (-1 'logical shift' y)
7567// To
7568// (x 'opposite logical shift' y) 'logical shift' y
7569// if it is better for performance.
7570SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
7571 assert(N->getOpcode() == ISD::AND);
7572
7573 SDValue N0 = N->getOperand(0);
7574 SDValue N1 = N->getOperand(1);
7575
7576 // Do we actually prefer shifts over mask?
7578 return SDValue();
7579
7580 // Try to match (-1 '[outer] logical shift' y)
7581 unsigned OuterShift;
7582 unsigned InnerShift; // The opposite direction to the OuterShift.
7583 SDValue Y; // Shift amount.
7584 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
7585 if (!M.hasOneUse())
7586 return false;
7587 OuterShift = M->getOpcode();
7588 if (OuterShift == ISD::SHL)
7589 InnerShift = ISD::SRL;
7590 else if (OuterShift == ISD::SRL)
7591 InnerShift = ISD::SHL;
7592 else
7593 return false;
7594 if (!isAllOnesConstant(M->getOperand(0)))
7595 return false;
7596 Y = M->getOperand(1);
7597 return true;
7598 };
7599
7600 SDValue X;
7601 if (matchMask(N1))
7602 X = N0;
7603 else if (matchMask(N0))
7604 X = N1;
7605 else
7606 return SDValue();
7607
7608 SDLoc DL(N);
7609 EVT VT = N->getValueType(0);
7610
7611 // tmp = x 'opposite logical shift' y
7612 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
7613 // ret = tmp 'logical shift' y
7614 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
7615
7616 return T1;
7617}
7618
7619/// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
7620/// For a target with a bit test, this is expected to become test + set and save
7621/// at least 1 instruction.
7623 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
7624
7625 // Look through an optional extension.
7626 SDValue And0 = And->getOperand(0), And1 = And->getOperand(1);
7627 if (And0.getOpcode() == ISD::ANY_EXTEND && And0.hasOneUse())
7628 And0 = And0.getOperand(0);
7629 if (!isOneConstant(And1) || !And0.hasOneUse())
7630 return SDValue();
7631
7632 SDValue Src = And0;
7633
7634 // Attempt to find a 'not' op.
7635 // TODO: Should we favor test+set even without the 'not' op?
7636 bool FoundNot = false;
7637 if (isBitwiseNot(Src)) {
7638 FoundNot = true;
7639 Src = Src.getOperand(0);
7640
7641 // Look though an optional truncation. The source operand may not be the
7642 // same type as the original 'and', but that is ok because we are masking
7643 // off everything but the low bit.
7644 if (Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse())
7645 Src = Src.getOperand(0);
7646 }
7647
7648 // Match a shift-right by constant.
7649 if (Src.getOpcode() != ISD::SRL || !Src.hasOneUse())
7650 return SDValue();
7651
7652 // This is probably not worthwhile without a supported type.
7653 EVT SrcVT = Src.getValueType();
7654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7655 if (!TLI.isTypeLegal(SrcVT))
7656 return SDValue();
7657
7658 // We might have looked through casts that make this transform invalid.
7659 unsigned BitWidth = SrcVT.getScalarSizeInBits();
7660 SDValue ShiftAmt = Src.getOperand(1);
7661 auto *ShiftAmtC = dyn_cast<ConstantSDNode>(ShiftAmt);
7662 if (!ShiftAmtC || !ShiftAmtC->getAPIntValue().ult(BitWidth))
7663 return SDValue();
7664
7665 // Set source to shift source.
7666 Src = Src.getOperand(0);
7667
7668 // Try again to find a 'not' op.
7669 // TODO: Should we favor test+set even with two 'not' ops?
7670 if (!FoundNot) {
7671 if (!isBitwiseNot(Src))
7672 return SDValue();
7673 Src = Src.getOperand(0);
7674 }
7675
7676 if (!TLI.hasBitTest(Src, ShiftAmt))
7677 return SDValue();
7678
7679 // Turn this into a bit-test pattern using mask op + setcc:
7680 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
7681 // and (srl (not X), C)), 1 --> (and X, 1<<C) == 0
7682 SDLoc DL(And);
7683 SDValue X = DAG.getZExtOrTrunc(Src, DL, SrcVT);
7684 EVT CCVT =
7685 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7686 SDValue Mask = DAG.getConstant(
7687 APInt::getOneBitSet(BitWidth, ShiftAmtC->getZExtValue()), DL, SrcVT);
7688 SDValue NewAnd = DAG.getNode(ISD::AND, DL, SrcVT, X, Mask);
7689 SDValue Zero = DAG.getConstant(0, DL, SrcVT);
7690 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
7691 return DAG.getZExtOrTrunc(Setcc, DL, And->getValueType(0));
7692}
7693
7694/// For targets that support usubsat, match a bit-hack form of that operation
7695/// that ends in 'and' and convert it.
7697 EVT VT = N->getValueType(0);
7698 unsigned BitWidth = VT.getScalarSizeInBits();
7699 APInt SignMask = APInt::getSignMask(BitWidth);
7700
7701 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
7702 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
7703 // xor/add with SMIN (signmask) are logically equivalent.
7704 SDValue X;
7705 if (!sd_match(N, m_And(m_OneUse(m_Xor(m_Value(X), m_SpecificInt(SignMask))),
7707 m_SpecificInt(BitWidth - 1))))) &&
7710 m_SpecificInt(BitWidth - 1))))))
7711 return SDValue();
7712
7713 return DAG.getNode(ISD::USUBSAT, DL, VT, X,
7714 DAG.getConstant(SignMask, DL, VT));
7715}
7716
7717/// Given a bitwise logic operation N with a matching bitwise logic operand,
7718/// fold a pattern where 2 of the source operands are identically shifted
7719/// values. For example:
7720/// ((X0 << Y) | Z) | (X1 << Y) --> ((X0 | X1) << Y) | Z
7722 SelectionDAG &DAG) {
7723 unsigned LogicOpcode = N->getOpcode();
7724 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7725 "Expected bitwise logic operation");
7726
7727 if (!LogicOp.hasOneUse() || !ShiftOp.hasOneUse())
7728 return SDValue();
7729
7730 // Match another bitwise logic op and a shift.
7731 unsigned ShiftOpcode = ShiftOp.getOpcode();
7732 if (LogicOp.getOpcode() != LogicOpcode ||
7733 !(ShiftOpcode == ISD::SHL || ShiftOpcode == ISD::SRL ||
7734 ShiftOpcode == ISD::SRA))
7735 return SDValue();
7736
7737 // Match another shift op inside the first logic operand. Handle both commuted
7738 // possibilities.
7739 // LOGIC (LOGIC (SH X0, Y), Z), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7740 // LOGIC (LOGIC Z, (SH X0, Y)), (SH X1, Y) --> LOGIC (SH (LOGIC X0, X1), Y), Z
7741 SDValue X1 = ShiftOp.getOperand(0);
7742 SDValue Y = ShiftOp.getOperand(1);
7743 SDValue X0, Z;
7744 if (LogicOp.getOperand(0).getOpcode() == ShiftOpcode &&
7745 LogicOp.getOperand(0).getOperand(1) == Y) {
7746 X0 = LogicOp.getOperand(0).getOperand(0);
7747 Z = LogicOp.getOperand(1);
7748 } else if (LogicOp.getOperand(1).getOpcode() == ShiftOpcode &&
7749 LogicOp.getOperand(1).getOperand(1) == Y) {
7750 X0 = LogicOp.getOperand(1).getOperand(0);
7751 Z = LogicOp.getOperand(0);
7752 } else {
7753 return SDValue();
7754 }
7755
7756 EVT VT = N->getValueType(0);
7757 SDLoc DL(N);
7758 SDValue LogicX = DAG.getNode(LogicOpcode, DL, VT, X0, X1);
7759 SDValue NewShift = DAG.getNode(ShiftOpcode, DL, VT, LogicX, Y);
7760 return DAG.getNode(LogicOpcode, DL, VT, NewShift, Z);
7761}
7762
7763/// Given a tree of logic operations with shape like
7764/// (LOGIC (LOGIC (X, Y), LOGIC (Z, Y)))
7765/// try to match and fold shift operations with the same shift amount.
7766/// For example:
7767/// LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W) -->
7768/// --> LOGIC (SH (LOGIC X0, X1), Y), (LOGIC Z, W)
7770 SDValue RightHand, SelectionDAG &DAG) {
7771 unsigned LogicOpcode = N->getOpcode();
7772 assert(ISD::isBitwiseLogicOp(LogicOpcode) &&
7773 "Expected bitwise logic operation");
7774 if (LeftHand.getOpcode() != LogicOpcode ||
7775 RightHand.getOpcode() != LogicOpcode)
7776 return SDValue();
7777 if (!LeftHand.hasOneUse() || !RightHand.hasOneUse())
7778 return SDValue();
7779
7780 // Try to match one of following patterns:
7781 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC (SH X1, Y), W)
7782 // LOGIC (LOGIC (SH X0, Y), Z), (LOGIC W, (SH X1, Y))
7783 // Note that foldLogicOfShifts will handle commuted versions of the left hand
7784 // itself.
7785 SDValue CombinedShifts, W;
7786 SDValue R0 = RightHand.getOperand(0);
7787 SDValue R1 = RightHand.getOperand(1);
7788 if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R0, DAG)))
7789 W = R1;
7790 else if ((CombinedShifts = foldLogicOfShifts(N, LeftHand, R1, DAG)))
7791 W = R0;
7792 else
7793 return SDValue();
7794
7795 EVT VT = N->getValueType(0);
7796 SDLoc DL(N);
7797 return DAG.getNode(LogicOpcode, DL, VT, CombinedShifts, W);
7798}
7799
7800/// Fold "masked merge" expressions like `(m & x) | (~m & y)` and its DeMorgan
7801/// variant `(~m | x) & (m | y)` into the equivalent `((x ^ y) & m) ^ y)`
7802/// pattern. This is typically a better representation for targets without a
7803/// fused "and-not" operation.
7805 const TargetLowering &TLI, const SDLoc &DL) {
7806 // Note that masked-merge variants using XOR or ADD expressions are
7807 // normalized to OR by InstCombine so we only check for OR or AND.
7808 assert((Node->getOpcode() == ISD::OR || Node->getOpcode() == ISD::AND) &&
7809 "Must be called with ISD::OR or ISD::AND node");
7810
7811 // If the target supports and-not, don't fold this.
7812 if (TLI.hasAndNot(SDValue(Node, 0)))
7813 return SDValue();
7814
7815 SDValue M, X, Y;
7816
7817 if (sd_match(Node,
7819 m_OneUse(m_And(m_Deferred(M), m_Value(X))))) ||
7820 sd_match(Node,
7822 m_OneUse(m_Or(m_Deferred(M), m_Value(Y)))))) {
7823 EVT VT = M.getValueType();
7824 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, Y);
7825 SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor, M);
7826 return DAG.getNode(ISD::XOR, DL, VT, And, Y);
7827 }
7828 return SDValue();
7829}
7830
7831SDValue DAGCombiner::visitAND(SDNode *N) {
7832 SDValue N0 = N->getOperand(0);
7833 SDValue N1 = N->getOperand(1);
7834 EVT VT = N1.getValueType();
7835 SDLoc DL(N);
7836
7837 // x & x --> x
7838 if (N0 == N1)
7839 return N0;
7840
7841 // fold (and c1, c2) -> c1&c2
7842 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, DL, VT, {N0, N1}))
7843 return C;
7844
7845 // canonicalize constant to RHS
7848 return DAG.getNode(ISD::AND, DL, VT, N1, N0);
7849
7850 if (areBitwiseNotOfEachother(N0, N1))
7851 return DAG.getConstant(APInt::getZero(VT.getScalarSizeInBits()), DL, VT);
7852
7853 // fold vector ops
7854 if (VT.isVector()) {
7855 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
7856 return FoldedVOp;
7857
7858 // fold (and x, 0) -> 0, vector edition
7860 // do not return N1, because undef node may exist in N1
7862 N1.getValueType());
7863
7864 // fold (and x, -1) -> x, vector edition
7866 return N0;
7867
7868 // fold (and buildvector(x,0,-1,w), buildvector(0,y,z,w))
7869 // --> buildvector(0,0,z,w)