1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
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
7 //===----------------------------------------------------------------------===//
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.
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.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntervalMap.h"
23 #include "llvm/ADT/None.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/CodeGen/DAGCombine.h"
34 #include "llvm/CodeGen/ISDOpcodes.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CodeGen.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/KnownBits.h"
61 #include "llvm/Support/MachineValueType.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetOptions.h"
77 #define DEBUG_TYPE "dagcombine"
79 STATISTIC(NodesCombined
, "Number of dag nodes combined");
80 STATISTIC(PreIndexedNodes
, "Number of pre-indexed nodes created");
81 STATISTIC(PostIndexedNodes
, "Number of post-indexed nodes created");
82 STATISTIC(OpsNarrowed
, "Number of load/op/store narrowed");
83 STATISTIC(LdStFP2Int
, "Number of fp load/store pairs transformed to int");
84 STATISTIC(SlicedLoads
, "Number of load sliced");
85 STATISTIC(NumFPLogicOpsConv
, "Number of logic ops converted to fp ops");
88 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden
,
89 cl::desc("Enable DAG combiner's use of IR alias analysis"));
92 UseTBAA("combiner-use-tbaa", cl::Hidden
, cl::init(true),
93 cl::desc("Enable DAG combiner's use of TBAA"));
96 static cl::opt
<std::string
>
97 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden
,
98 cl::desc("Only use DAG-combiner alias analysis in this"
102 /// Hidden option to stress test load slicing, i.e., when this option
103 /// is enabled, load slicing bypasses most of its profitability guards.
105 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden
,
106 cl::desc("Bypass the profitability model of load slicing"),
110 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden
, cl::init(true),
111 cl::desc("DAG combiner may split indexing from loads"));
114 EnableStoreMerging("combiner-store-merging", cl::Hidden
, cl::init(true),
115 cl::desc("DAG combiner enable merging multiple stores "
116 "into a wider store"));
118 static cl::opt
<unsigned> TokenFactorInlineLimit(
119 "combiner-tokenfactor-inline-limit", cl::Hidden
, cl::init(2048),
120 cl::desc("Limit the number of operands to inline for Token Factors"));
122 static cl::opt
<unsigned> StoreMergeDependenceLimit(
123 "combiner-store-merge-dependence-limit", cl::Hidden
, cl::init(10),
124 cl::desc("Limit the number of times for the same StoreNode and RootNode "
125 "to bail out in store merging dependence check"));
131 const TargetLowering
&TLI
;
133 CodeGenOpt::Level OptLevel
;
134 bool LegalOperations
= false;
135 bool LegalTypes
= false;
138 /// Worklist of all of the nodes that need to be simplified.
140 /// This must behave as a stack -- new nodes to process are pushed onto the
141 /// back and when processing we pop off of the back.
143 /// The worklist will not contain duplicates but may contain null entries
144 /// due to nodes being deleted from the underlying DAG.
145 SmallVector
<SDNode
*, 64> Worklist
;
147 /// Mapping from an SDNode to its position on the worklist.
149 /// This is used to find and remove nodes from the worklist (by nulling
150 /// them) when they are deleted from the underlying DAG. It relies on
151 /// stable indices of nodes within the worklist.
152 DenseMap
<SDNode
*, unsigned> WorklistMap
;
153 /// This records all nodes attempted to add to the worklist since we
154 /// considered a new worklist entry. As we keep do not add duplicate nodes
155 /// in the worklist, this is different from the tail of the worklist.
156 SmallSetVector
<SDNode
*, 32> PruningList
;
158 /// Set of nodes which have been combined (at least once).
160 /// This is used to allow us to reliably add any operands of a DAG node
161 /// which have not yet been combined to the worklist.
162 SmallPtrSet
<SDNode
*, 32> CombinedNodes
;
164 /// Map from candidate StoreNode to the pair of RootNode and count.
165 /// The count is used to track how many times we have seen the StoreNode
166 /// with the same RootNode bail out in dependence check. If we have seen
167 /// the bail out for the same pair many times over a limit, we won't
168 /// consider the StoreNode with the same RootNode as store merging
170 DenseMap
<SDNode
*, std::pair
<SDNode
*, unsigned>> StoreRootCountMap
;
172 // AA - Used for DAG load/store alias analysis.
175 /// When an instruction is simplified, add all users of the instruction to
176 /// the work lists because they might get more simplified now.
177 void AddUsersToWorklist(SDNode
*N
) {
178 for (SDNode
*Node
: N
->uses())
182 // Prune potentially dangling nodes. This is called after
183 // any visit to a node, but should also be called during a visit after any
184 // failed combine which may have created a DAG node.
185 void clearAddedDanglingWorklistEntries() {
186 // Check any nodes added to the worklist to see if they are prunable.
187 while (!PruningList
.empty()) {
188 auto *N
= PruningList
.pop_back_val();
190 recursivelyDeleteUnusedNodes(N
);
194 SDNode
*getNextWorklistEntry() {
195 // Before we do any work, remove nodes that are not in use.
196 clearAddedDanglingWorklistEntries();
198 // The Worklist holds the SDNodes in order, but it may contain null
200 while (!N
&& !Worklist
.empty()) {
201 N
= Worklist
.pop_back_val();
205 bool GoodWorklistEntry
= WorklistMap
.erase(N
);
206 (void)GoodWorklistEntry
;
207 assert(GoodWorklistEntry
&&
208 "Found a worklist entry without a corresponding map entry!");
213 /// Call the node-specific routine that folds each particular type of node.
214 SDValue
visit(SDNode
*N
);
217 DAGCombiner(SelectionDAG
&D
, AliasAnalysis
*AA
, CodeGenOpt::Level OL
)
218 : DAG(D
), TLI(D
.getTargetLoweringInfo()), Level(BeforeLegalizeTypes
),
219 OptLevel(OL
), AA(AA
) {
220 ForCodeSize
= DAG
.getMachineFunction().getFunction().hasOptSize();
222 MaximumLegalStoreInBits
= 0;
223 for (MVT VT
: MVT::all_valuetypes())
224 if (EVT(VT
).isSimple() && VT
!= MVT::Other
&&
225 TLI
.isTypeLegal(EVT(VT
)) &&
226 VT
.getSizeInBits() >= MaximumLegalStoreInBits
)
227 MaximumLegalStoreInBits
= VT
.getSizeInBits();
230 void ConsiderForPruning(SDNode
*N
) {
231 // Mark this for potential pruning.
232 PruningList
.insert(N
);
235 /// Add to the worklist making sure its instance is at the back (next to be
237 void AddToWorklist(SDNode
*N
) {
238 assert(N
->getOpcode() != ISD::DELETED_NODE
&&
239 "Deleted Node added to Worklist");
241 // Skip handle nodes as they can't usefully be combined and confuse the
242 // zero-use deletion strategy.
243 if (N
->getOpcode() == ISD::HANDLENODE
)
246 ConsiderForPruning(N
);
248 if (WorklistMap
.insert(std::make_pair(N
, Worklist
.size())).second
)
249 Worklist
.push_back(N
);
252 /// Remove all instances of N from the worklist.
253 void removeFromWorklist(SDNode
*N
) {
254 CombinedNodes
.erase(N
);
255 PruningList
.remove(N
);
256 StoreRootCountMap
.erase(N
);
258 auto It
= WorklistMap
.find(N
);
259 if (It
== WorklistMap
.end())
260 return; // Not in the worklist.
262 // Null out the entry rather than erasing it to avoid a linear operation.
263 Worklist
[It
->second
] = nullptr;
264 WorklistMap
.erase(It
);
267 void deleteAndRecombine(SDNode
*N
);
268 bool recursivelyDeleteUnusedNodes(SDNode
*N
);
270 /// Replaces all uses of the results of one DAG node with new values.
271 SDValue
CombineTo(SDNode
*N
, const SDValue
*To
, unsigned NumTo
,
274 /// Replaces all uses of the results of one DAG node with new values.
275 SDValue
CombineTo(SDNode
*N
, SDValue Res
, bool AddTo
= true) {
276 return CombineTo(N
, &Res
, 1, AddTo
);
279 /// Replaces all uses of the results of one DAG node with new values.
280 SDValue
CombineTo(SDNode
*N
, SDValue Res0
, SDValue Res1
,
282 SDValue To
[] = { Res0
, Res1
};
283 return CombineTo(N
, To
, 2, AddTo
);
286 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt
&TLO
);
289 unsigned MaximumLegalStoreInBits
;
291 /// Check the specified integer node value to see if it can be simplified or
292 /// if things it uses can be simplified by bit propagation.
293 /// If so, return true.
294 bool SimplifyDemandedBits(SDValue Op
) {
295 unsigned BitWidth
= Op
.getScalarValueSizeInBits();
296 APInt DemandedBits
= APInt::getAllOnesValue(BitWidth
);
297 return SimplifyDemandedBits(Op
, DemandedBits
);
300 bool SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
) {
301 EVT VT
= Op
.getValueType();
302 unsigned NumElts
= VT
.isVector() ? VT
.getVectorNumElements() : 1;
303 APInt DemandedElts
= APInt::getAllOnesValue(NumElts
);
304 return SimplifyDemandedBits(Op
, DemandedBits
, DemandedElts
);
307 /// Check the specified vector node value to see if it can be simplified or
308 /// if things it uses can be simplified as it only uses some of the
309 /// elements. If so, return true.
310 bool SimplifyDemandedVectorElts(SDValue Op
) {
311 unsigned NumElts
= Op
.getValueType().getVectorNumElements();
312 APInt DemandedElts
= APInt::getAllOnesValue(NumElts
);
313 return SimplifyDemandedVectorElts(Op
, DemandedElts
);
316 bool SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
317 const APInt
&DemandedElts
);
318 bool SimplifyDemandedVectorElts(SDValue Op
, const APInt
&DemandedElts
,
319 bool AssumeSingleUse
= false);
321 bool CombineToPreIndexedLoadStore(SDNode
*N
);
322 bool CombineToPostIndexedLoadStore(SDNode
*N
);
323 SDValue
SplitIndexingFromLoad(LoadSDNode
*LD
);
324 bool SliceUpLoad(SDNode
*N
);
326 // Scalars have size 0 to distinguish from singleton vectors.
327 SDValue
ForwardStoreValueToDirectLoad(LoadSDNode
*LD
);
328 bool getTruncatedStoreValue(StoreSDNode
*ST
, SDValue
&Val
);
329 bool extendLoadedValueToExtension(LoadSDNode
*LD
, SDValue
&Val
);
331 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
334 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
335 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
336 /// \param EltNo index of the vector element to load.
337 /// \param OriginalLoad load that EVE came from to be replaced.
338 /// \returns EVE on success SDValue() on failure.
339 SDValue
scalarizeExtractedVectorLoad(SDNode
*EVE
, EVT InVecVT
,
341 LoadSDNode
*OriginalLoad
);
342 void ReplaceLoadWithPromotedLoad(SDNode
*Load
, SDNode
*ExtLoad
);
343 SDValue
PromoteOperand(SDValue Op
, EVT PVT
, bool &Replace
);
344 SDValue
SExtPromoteOperand(SDValue Op
, EVT PVT
);
345 SDValue
ZExtPromoteOperand(SDValue Op
, EVT PVT
);
346 SDValue
PromoteIntBinOp(SDValue Op
);
347 SDValue
PromoteIntShiftOp(SDValue Op
);
348 SDValue
PromoteExtend(SDValue Op
);
349 bool PromoteLoad(SDValue Op
);
351 /// Call the node-specific routine that knows how to fold each
352 /// particular type of node. If that doesn't do anything, try the
353 /// target-specific DAG combines.
354 SDValue
combine(SDNode
*N
);
356 // Visitation implementation - Implement dag node combining for different
357 // node types. The semantics are as follows:
359 // SDValue.getNode() == 0 - No change was made
360 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
361 // otherwise - N should be replaced by the returned Operand.
363 SDValue
visitTokenFactor(SDNode
*N
);
364 SDValue
visitMERGE_VALUES(SDNode
*N
);
365 SDValue
visitADD(SDNode
*N
);
366 SDValue
visitADDLike(SDNode
*N
);
367 SDValue
visitADDLikeCommutative(SDValue N0
, SDValue N1
, SDNode
*LocReference
);
368 SDValue
visitSUB(SDNode
*N
);
369 SDValue
visitADDSAT(SDNode
*N
);
370 SDValue
visitSUBSAT(SDNode
*N
);
371 SDValue
visitADDC(SDNode
*N
);
372 SDValue
visitADDO(SDNode
*N
);
373 SDValue
visitUADDOLike(SDValue N0
, SDValue N1
, SDNode
*N
);
374 SDValue
visitSUBC(SDNode
*N
);
375 SDValue
visitSUBO(SDNode
*N
);
376 SDValue
visitADDE(SDNode
*N
);
377 SDValue
visitADDCARRY(SDNode
*N
);
378 SDValue
visitADDCARRYLike(SDValue N0
, SDValue N1
, SDValue CarryIn
, SDNode
*N
);
379 SDValue
visitSUBE(SDNode
*N
);
380 SDValue
visitSUBCARRY(SDNode
*N
);
381 SDValue
visitMUL(SDNode
*N
);
382 SDValue
visitMULFIX(SDNode
*N
);
383 SDValue
useDivRem(SDNode
*N
);
384 SDValue
visitSDIV(SDNode
*N
);
385 SDValue
visitSDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
);
386 SDValue
visitUDIV(SDNode
*N
);
387 SDValue
visitUDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
);
388 SDValue
visitREM(SDNode
*N
);
389 SDValue
visitMULHU(SDNode
*N
);
390 SDValue
visitMULHS(SDNode
*N
);
391 SDValue
visitSMUL_LOHI(SDNode
*N
);
392 SDValue
visitUMUL_LOHI(SDNode
*N
);
393 SDValue
visitMULO(SDNode
*N
);
394 SDValue
visitIMINMAX(SDNode
*N
);
395 SDValue
visitAND(SDNode
*N
);
396 SDValue
visitANDLike(SDValue N0
, SDValue N1
, SDNode
*N
);
397 SDValue
visitOR(SDNode
*N
);
398 SDValue
visitORLike(SDValue N0
, SDValue N1
, SDNode
*N
);
399 SDValue
visitXOR(SDNode
*N
);
400 SDValue
SimplifyVBinOp(SDNode
*N
);
401 SDValue
visitSHL(SDNode
*N
);
402 SDValue
visitSRA(SDNode
*N
);
403 SDValue
visitSRL(SDNode
*N
);
404 SDValue
visitFunnelShift(SDNode
*N
);
405 SDValue
visitRotate(SDNode
*N
);
406 SDValue
visitABS(SDNode
*N
);
407 SDValue
visitBSWAP(SDNode
*N
);
408 SDValue
visitBITREVERSE(SDNode
*N
);
409 SDValue
visitCTLZ(SDNode
*N
);
410 SDValue
visitCTLZ_ZERO_UNDEF(SDNode
*N
);
411 SDValue
visitCTTZ(SDNode
*N
);
412 SDValue
visitCTTZ_ZERO_UNDEF(SDNode
*N
);
413 SDValue
visitCTPOP(SDNode
*N
);
414 SDValue
visitSELECT(SDNode
*N
);
415 SDValue
visitVSELECT(SDNode
*N
);
416 SDValue
visitSELECT_CC(SDNode
*N
);
417 SDValue
visitSETCC(SDNode
*N
);
418 SDValue
visitSETCCCARRY(SDNode
*N
);
419 SDValue
visitSIGN_EXTEND(SDNode
*N
);
420 SDValue
visitZERO_EXTEND(SDNode
*N
);
421 SDValue
visitANY_EXTEND(SDNode
*N
);
422 SDValue
visitAssertExt(SDNode
*N
);
423 SDValue
visitSIGN_EXTEND_INREG(SDNode
*N
);
424 SDValue
visitSIGN_EXTEND_VECTOR_INREG(SDNode
*N
);
425 SDValue
visitZERO_EXTEND_VECTOR_INREG(SDNode
*N
);
426 SDValue
visitTRUNCATE(SDNode
*N
);
427 SDValue
visitBITCAST(SDNode
*N
);
428 SDValue
visitBUILD_PAIR(SDNode
*N
);
429 SDValue
visitFADD(SDNode
*N
);
430 SDValue
visitFSUB(SDNode
*N
);
431 SDValue
visitFMUL(SDNode
*N
);
432 SDValue
visitFMA(SDNode
*N
);
433 SDValue
visitFDIV(SDNode
*N
);
434 SDValue
visitFREM(SDNode
*N
);
435 SDValue
visitFSQRT(SDNode
*N
);
436 SDValue
visitFCOPYSIGN(SDNode
*N
);
437 SDValue
visitFPOW(SDNode
*N
);
438 SDValue
visitSINT_TO_FP(SDNode
*N
);
439 SDValue
visitUINT_TO_FP(SDNode
*N
);
440 SDValue
visitFP_TO_SINT(SDNode
*N
);
441 SDValue
visitFP_TO_UINT(SDNode
*N
);
442 SDValue
visitFP_ROUND(SDNode
*N
);
443 SDValue
visitFP_ROUND_INREG(SDNode
*N
);
444 SDValue
visitFP_EXTEND(SDNode
*N
);
445 SDValue
visitFNEG(SDNode
*N
);
446 SDValue
visitFABS(SDNode
*N
);
447 SDValue
visitFCEIL(SDNode
*N
);
448 SDValue
visitFTRUNC(SDNode
*N
);
449 SDValue
visitFFLOOR(SDNode
*N
);
450 SDValue
visitFMINNUM(SDNode
*N
);
451 SDValue
visitFMAXNUM(SDNode
*N
);
452 SDValue
visitFMINIMUM(SDNode
*N
);
453 SDValue
visitFMAXIMUM(SDNode
*N
);
454 SDValue
visitBRCOND(SDNode
*N
);
455 SDValue
visitBR_CC(SDNode
*N
);
456 SDValue
visitLOAD(SDNode
*N
);
458 SDValue
replaceStoreChain(StoreSDNode
*ST
, SDValue BetterChain
);
459 SDValue
replaceStoreOfFPConstant(StoreSDNode
*ST
);
461 SDValue
visitSTORE(SDNode
*N
);
462 SDValue
visitLIFETIME_END(SDNode
*N
);
463 SDValue
visitINSERT_VECTOR_ELT(SDNode
*N
);
464 SDValue
visitEXTRACT_VECTOR_ELT(SDNode
*N
);
465 SDValue
visitBUILD_VECTOR(SDNode
*N
);
466 SDValue
visitCONCAT_VECTORS(SDNode
*N
);
467 SDValue
visitEXTRACT_SUBVECTOR(SDNode
*N
);
468 SDValue
visitVECTOR_SHUFFLE(SDNode
*N
);
469 SDValue
visitSCALAR_TO_VECTOR(SDNode
*N
);
470 SDValue
visitINSERT_SUBVECTOR(SDNode
*N
);
471 SDValue
visitMLOAD(SDNode
*N
);
472 SDValue
visitMSTORE(SDNode
*N
);
473 SDValue
visitMGATHER(SDNode
*N
);
474 SDValue
visitMSCATTER(SDNode
*N
);
475 SDValue
visitFP_TO_FP16(SDNode
*N
);
476 SDValue
visitFP16_TO_FP(SDNode
*N
);
477 SDValue
visitVECREDUCE(SDNode
*N
);
479 SDValue
visitFADDForFMACombine(SDNode
*N
);
480 SDValue
visitFSUBForFMACombine(SDNode
*N
);
481 SDValue
visitFMULForFMADistributiveCombine(SDNode
*N
);
483 SDValue
XformToShuffleWithZero(SDNode
*N
);
484 bool reassociationCanBreakAddressingModePattern(unsigned Opc
,
485 const SDLoc
&DL
, SDValue N0
,
487 SDValue
reassociateOpsCommutative(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
489 SDValue
reassociateOps(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
490 SDValue N1
, SDNodeFlags Flags
);
492 SDValue
visitShiftByConstant(SDNode
*N
, ConstantSDNode
*Amt
);
494 SDValue
foldSelectOfConstants(SDNode
*N
);
495 SDValue
foldVSelectOfConstants(SDNode
*N
);
496 SDValue
foldBinOpIntoSelect(SDNode
*BO
);
497 bool SimplifySelectOps(SDNode
*SELECT
, SDValue LHS
, SDValue RHS
);
498 SDValue
hoistLogicOpWithSameOpcodeHands(SDNode
*N
);
499 SDValue
SimplifySelect(const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
);
500 SDValue
SimplifySelectCC(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
501 SDValue N2
, SDValue N3
, ISD::CondCode CC
,
502 bool NotExtCompare
= false);
503 SDValue
convertSelectOfFPConstantsToLoadOffset(
504 const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
, SDValue N3
,
506 SDValue
foldSelectCCToShiftAnd(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
507 SDValue N2
, SDValue N3
, ISD::CondCode CC
);
508 SDValue
foldLogicOfSetCCs(bool IsAnd
, SDValue N0
, SDValue N1
,
510 SDValue
unfoldMaskedMerge(SDNode
*N
);
511 SDValue
unfoldExtremeBitClearingToShifts(SDNode
*N
);
512 SDValue
SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
,
513 const SDLoc
&DL
, bool foldBooleans
);
514 SDValue
rebuildSetCC(SDValue N
);
516 bool isSetCCEquivalent(SDValue N
, SDValue
&LHS
, SDValue
&RHS
,
518 bool isOneUseSetCC(SDValue N
) const;
520 SDValue
SimplifyNodeWithTwoResults(SDNode
*N
, unsigned LoOp
,
522 SDValue
CombineConsecutiveLoads(SDNode
*N
, EVT VT
);
523 SDValue
CombineExtLoad(SDNode
*N
);
524 SDValue
CombineZExtLogicopShiftLoad(SDNode
*N
);
525 SDValue
combineRepeatedFPDivisors(SDNode
*N
);
526 SDValue
combineInsertEltToShuffle(SDNode
*N
, unsigned InsIndex
);
527 SDValue
ConstantFoldBITCASTofBUILD_VECTOR(SDNode
*, EVT
);
528 SDValue
BuildSDIV(SDNode
*N
);
529 SDValue
BuildSDIVPow2(SDNode
*N
);
530 SDValue
BuildUDIV(SDNode
*N
);
531 SDValue
BuildLogBase2(SDValue V
, const SDLoc
&DL
);
532 SDValue
BuildReciprocalEstimate(SDValue Op
, SDNodeFlags Flags
);
533 SDValue
buildRsqrtEstimate(SDValue Op
, SDNodeFlags Flags
);
534 SDValue
buildSqrtEstimate(SDValue Op
, SDNodeFlags Flags
);
535 SDValue
buildSqrtEstimateImpl(SDValue Op
, SDNodeFlags Flags
, bool Recip
);
536 SDValue
buildSqrtNROneConst(SDValue Arg
, SDValue Est
, unsigned Iterations
,
537 SDNodeFlags Flags
, bool Reciprocal
);
538 SDValue
buildSqrtNRTwoConst(SDValue Arg
, SDValue Est
, unsigned Iterations
,
539 SDNodeFlags Flags
, bool Reciprocal
);
540 SDValue
MatchBSwapHWordLow(SDNode
*N
, SDValue N0
, SDValue N1
,
541 bool DemandHighBits
= true);
542 SDValue
MatchBSwapHWord(SDNode
*N
, SDValue N0
, SDValue N1
);
543 SDNode
*MatchRotatePosNeg(SDValue Shifted
, SDValue Pos
, SDValue Neg
,
544 SDValue InnerPos
, SDValue InnerNeg
,
545 unsigned PosOpcode
, unsigned NegOpcode
,
547 SDNode
*MatchRotate(SDValue LHS
, SDValue RHS
, const SDLoc
&DL
);
548 SDValue
MatchLoadCombine(SDNode
*N
);
549 SDValue
MatchStoreCombine(StoreSDNode
*N
);
550 SDValue
ReduceLoadWidth(SDNode
*N
);
551 SDValue
ReduceLoadOpStoreWidth(SDNode
*N
);
552 SDValue
splitMergedValStore(StoreSDNode
*ST
);
553 SDValue
TransformFPLoadStorePair(SDNode
*N
);
554 SDValue
convertBuildVecZextToZext(SDNode
*N
);
555 SDValue
reduceBuildVecExtToExtBuildVec(SDNode
*N
);
556 SDValue
reduceBuildVecToShuffle(SDNode
*N
);
557 SDValue
createBuildVecShuffle(const SDLoc
&DL
, SDNode
*N
,
558 ArrayRef
<int> VectorMask
, SDValue VecIn1
,
559 SDValue VecIn2
, unsigned LeftIdx
,
561 SDValue
matchVSelectOpSizesWithSetCC(SDNode
*Cast
);
563 /// Walk up chain skipping non-aliasing memory nodes,
564 /// looking for aliasing nodes and adding them to the Aliases vector.
565 void GatherAllAliases(SDNode
*N
, SDValue OriginalChain
,
566 SmallVectorImpl
<SDValue
> &Aliases
);
568 /// Return true if there is any possibility that the two addresses overlap.
569 bool isAlias(SDNode
*Op0
, SDNode
*Op1
) const;
571 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
572 /// chain (aliasing node.)
573 SDValue
FindBetterChain(SDNode
*N
, SDValue Chain
);
575 /// Try to replace a store and any possibly adjacent stores on
576 /// consecutive chains with better chains. Return true only if St is
579 /// Notice that other chains may still be replaced even if the function
581 bool findBetterNeighborChains(StoreSDNode
*St
);
583 // Helper for findBetterNeighborChains. Walk up store chain add additional
584 // chained stores that do not overlap and can be parallelized.
585 bool parallelizeChainedStores(StoreSDNode
*St
);
587 /// Holds a pointer to an LSBaseSDNode as well as information on where it
588 /// is located in a sequence of memory operations connected by a chain.
590 // Ptr to the mem node.
591 LSBaseSDNode
*MemNode
;
593 // Offset from the base ptr.
594 int64_t OffsetFromBase
;
596 MemOpLink(LSBaseSDNode
*N
, int64_t Offset
)
597 : MemNode(N
), OffsetFromBase(Offset
) {}
600 /// This is a helper function for visitMUL to check the profitability
601 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
602 /// MulNode is the original multiply, AddNode is (add x, c1),
603 /// and ConstNode is c2.
604 bool isMulAddWithConstProfitable(SDNode
*MulNode
,
608 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
609 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
610 /// the type of the loaded value to be extended.
611 bool isAndLoadExtLoad(ConstantSDNode
*AndC
, LoadSDNode
*LoadN
,
612 EVT LoadResultTy
, EVT
&ExtVT
);
614 /// Helper function to calculate whether the given Load/Store can have its
615 /// width reduced to ExtVT.
616 bool isLegalNarrowLdSt(LSBaseSDNode
*LDSTN
, ISD::LoadExtType ExtType
,
617 EVT
&MemVT
, unsigned ShAmt
= 0);
619 /// Used by BackwardsPropagateMask to find suitable loads.
620 bool SearchForAndLoads(SDNode
*N
, SmallVectorImpl
<LoadSDNode
*> &Loads
,
621 SmallPtrSetImpl
<SDNode
*> &NodesWithConsts
,
622 ConstantSDNode
*Mask
, SDNode
*&NodeToMask
);
623 /// Attempt to propagate a given AND node back to load leaves so that they
624 /// can be combined into narrow loads.
625 bool BackwardsPropagateMask(SDNode
*N
, SelectionDAG
&DAG
);
627 /// Helper function for MergeConsecutiveStores which merges the
628 /// component store chains.
629 SDValue
getMergeStoreChains(SmallVectorImpl
<MemOpLink
> &StoreNodes
,
632 /// This is a helper function for MergeConsecutiveStores. When the
633 /// source elements of the consecutive stores are all constants or
634 /// all extracted vector elements, try to merge them into one
635 /// larger store introducing bitcasts if necessary. \return True
636 /// if a merged store was created.
637 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl
<MemOpLink
> &StoreNodes
,
638 EVT MemVT
, unsigned NumStores
,
639 bool IsConstantSrc
, bool UseVector
,
642 /// This is a helper function for MergeConsecutiveStores. Stores
643 /// that potentially may be merged with St are placed in
644 /// StoreNodes. RootNode is a chain predecessor to all store
646 void getStoreMergeCandidates(StoreSDNode
*St
,
647 SmallVectorImpl
<MemOpLink
> &StoreNodes
,
650 /// Helper function for MergeConsecutiveStores. Checks if
651 /// candidate stores have indirect dependency through their
652 /// operands. RootNode is the predecessor to all stores calculated
653 /// by getStoreMergeCandidates and is used to prune the dependency check.
654 /// \return True if safe to merge.
655 bool checkMergeStoreCandidatesForDependencies(
656 SmallVectorImpl
<MemOpLink
> &StoreNodes
, unsigned NumStores
,
659 /// Merge consecutive store operations into a wide store.
660 /// This optimization uses wide integers or vectors when possible.
661 /// \return number of stores that were merged into a merged store (the
662 /// affected nodes are stored as a prefix in \p StoreNodes).
663 bool MergeConsecutiveStores(StoreSDNode
*St
);
665 /// Try to transform a truncation where C is a constant:
666 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
668 /// \p N needs to be a truncation and its first operand an AND. Other
669 /// requirements are checked by the function (e.g. that trunc is
670 /// single-use) and if missed an empty SDValue is returned.
671 SDValue
distributeTruncateThroughAnd(SDNode
*N
);
673 /// Helper function to determine whether the target supports operation
674 /// given by \p Opcode for type \p VT, that is, whether the operation
675 /// is legal or custom before legalizing operations, and whether is
676 /// legal (but not custom) after legalization.
677 bool hasOperation(unsigned Opcode
, EVT VT
) {
679 return TLI
.isOperationLegal(Opcode
, VT
);
680 return TLI
.isOperationLegalOrCustom(Opcode
, VT
);
684 /// Runs the dag combiner on all nodes in the work list
685 void Run(CombineLevel AtLevel
);
687 SelectionDAG
&getDAG() const { return DAG
; }
689 /// Returns a type large enough to hold any valid shift amount - before type
690 /// legalization these can be huge.
691 EVT
getShiftAmountTy(EVT LHSTy
) {
692 assert(LHSTy
.isInteger() && "Shift amount is not an integer type!");
693 return TLI
.getShiftAmountTy(LHSTy
, DAG
.getDataLayout(), LegalTypes
);
696 /// This method returns true if we are running before type legalization or
697 /// if the specified VT is legal.
698 bool isTypeLegal(const EVT
&VT
) {
699 if (!LegalTypes
) return true;
700 return TLI
.isTypeLegal(VT
);
703 /// Convenience wrapper around TargetLowering::getSetCCResultType
704 EVT
getSetCCResultType(EVT VT
) const {
705 return TLI
.getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
708 void ExtendSetCCUses(const SmallVectorImpl
<SDNode
*> &SetCCs
,
709 SDValue OrigLoad
, SDValue ExtLoad
,
710 ISD::NodeType ExtType
);
713 /// This class is a DAGUpdateListener that removes any deleted
714 /// nodes from the worklist.
715 class WorklistRemover
: public SelectionDAG::DAGUpdateListener
{
719 explicit WorklistRemover(DAGCombiner
&dc
)
720 : SelectionDAG::DAGUpdateListener(dc
.getDAG()), DC(dc
) {}
722 void NodeDeleted(SDNode
*N
, SDNode
*E
) override
{
723 DC
.removeFromWorklist(N
);
727 class WorklistInserter
: public SelectionDAG::DAGUpdateListener
{
731 explicit WorklistInserter(DAGCombiner
&dc
)
732 : SelectionDAG::DAGUpdateListener(dc
.getDAG()), DC(dc
) {}
734 // FIXME: Ideally we could add N to the worklist, but this causes exponential
735 // compile time costs in large DAGs, e.g. Halide.
736 void NodeInserted(SDNode
*N
) override
{ DC
.ConsiderForPruning(N
); }
739 } // end anonymous namespace
741 //===----------------------------------------------------------------------===//
742 // TargetLowering::DAGCombinerInfo implementation
743 //===----------------------------------------------------------------------===//
745 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode
*N
) {
746 ((DAGCombiner
*)DC
)->AddToWorklist(N
);
749 SDValue
TargetLowering::DAGCombinerInfo::
750 CombineTo(SDNode
*N
, ArrayRef
<SDValue
> To
, bool AddTo
) {
751 return ((DAGCombiner
*)DC
)->CombineTo(N
, &To
[0], To
.size(), AddTo
);
754 SDValue
TargetLowering::DAGCombinerInfo::
755 CombineTo(SDNode
*N
, SDValue Res
, bool AddTo
) {
756 return ((DAGCombiner
*)DC
)->CombineTo(N
, Res
, AddTo
);
759 SDValue
TargetLowering::DAGCombinerInfo::
760 CombineTo(SDNode
*N
, SDValue Res0
, SDValue Res1
, bool AddTo
) {
761 return ((DAGCombiner
*)DC
)->CombineTo(N
, Res0
, Res1
, AddTo
);
764 void TargetLowering::DAGCombinerInfo::
765 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt
&TLO
) {
766 return ((DAGCombiner
*)DC
)->CommitTargetLoweringOpt(TLO
);
769 //===----------------------------------------------------------------------===//
771 //===----------------------------------------------------------------------===//
773 void DAGCombiner::deleteAndRecombine(SDNode
*N
) {
774 removeFromWorklist(N
);
776 // If the operands of this node are only used by the node, they will now be
777 // dead. Make sure to re-visit them and recursively delete dead nodes.
778 for (const SDValue
&Op
: N
->ops())
779 // For an operand generating multiple values, one of the values may
780 // become dead allowing further simplification (e.g. split index
781 // arithmetic from an indexed load).
782 if (Op
->hasOneUse() || Op
->getNumValues() > 1)
783 AddToWorklist(Op
.getNode());
788 /// Return 1 if we can compute the negated form of the specified expression for
789 /// the same cost as the expression itself, or 2 if we can compute the negated
790 /// form more cheaply than the expression itself.
791 static char isNegatibleForFree(SDValue Op
, bool LegalOperations
,
792 const TargetLowering
&TLI
,
793 const TargetOptions
*Options
,
795 unsigned Depth
= 0) {
796 // fneg is removable even if it has multiple uses.
797 if (Op
.getOpcode() == ISD::FNEG
)
800 // Don't allow anything with multiple uses unless we know it is free.
801 EVT VT
= Op
.getValueType();
802 const SDNodeFlags Flags
= Op
->getFlags();
803 if (!Op
.hasOneUse() &&
804 !(Op
.getOpcode() == ISD::FP_EXTEND
&&
805 TLI
.isFPExtFree(VT
, Op
.getOperand(0).getValueType())))
808 // Don't recurse exponentially.
812 switch (Op
.getOpcode()) {
813 default: return false;
814 case ISD::ConstantFP
: {
815 if (!LegalOperations
)
818 // Don't invert constant FP values after legalization unless the target says
819 // the negated constant is legal.
820 return TLI
.isOperationLegal(ISD::ConstantFP
, VT
) ||
821 TLI
.isFPImmLegal(neg(cast
<ConstantFPSDNode
>(Op
)->getValueAPF()), VT
,
824 case ISD::BUILD_VECTOR
: {
825 // Only permit BUILD_VECTOR of constants.
826 if (llvm::any_of(Op
->op_values(), [&](SDValue N
) {
827 return !N
.isUndef() && !isa
<ConstantFPSDNode
>(N
);
830 if (!LegalOperations
)
832 if (TLI
.isOperationLegal(ISD::ConstantFP
, VT
) &&
833 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
835 return llvm::all_of(Op
->op_values(), [&](SDValue N
) {
836 return N
.isUndef() ||
837 TLI
.isFPImmLegal(neg(cast
<ConstantFPSDNode
>(N
)->getValueAPF()), VT
,
842 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
845 // After operation legalization, it might not be legal to create new FSUBs.
846 if (LegalOperations
&& !TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
))
849 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
850 if (char V
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
,
851 Options
, ForCodeSize
, Depth
+ 1))
853 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
854 return isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
, Options
,
855 ForCodeSize
, Depth
+ 1);
857 // We can't turn -(A-B) into B-A when we honor signed zeros.
858 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
861 // fold (fneg (fsub A, B)) -> (fsub B, A)
866 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
867 if (char V
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
,
868 Options
, ForCodeSize
, Depth
+ 1))
871 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
872 if (auto *C
= isConstOrConstSplatFP(Op
.getOperand(1)))
873 if (C
->isExactlyValue(2.0) && Op
.getOpcode() == ISD::FMUL
)
876 return isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
, Options
,
877 ForCodeSize
, Depth
+ 1);
881 if (!Options
->NoSignedZerosFPMath
&& !Flags
.hasNoSignedZeros())
884 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
885 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
886 char V2
= isNegatibleForFree(Op
.getOperand(2), LegalOperations
, TLI
,
887 Options
, ForCodeSize
, Depth
+ 1);
891 // One of Op0/Op1 must be cheaply negatible, then select the cheapest.
892 char V0
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
,
893 Options
, ForCodeSize
, Depth
+ 1);
894 char V1
= isNegatibleForFree(Op
.getOperand(1), LegalOperations
, TLI
,
895 Options
, ForCodeSize
, Depth
+ 1);
896 char V01
= std::max(V0
, V1
);
897 return V01
? std::max(V01
, V2
) : 0;
903 return isNegatibleForFree(Op
.getOperand(0), LegalOperations
, TLI
, Options
,
904 ForCodeSize
, Depth
+ 1);
908 /// If isNegatibleForFree returns true, return the newly negated expression.
909 static SDValue
GetNegatedExpression(SDValue Op
, SelectionDAG
&DAG
,
910 bool LegalOperations
, bool ForCodeSize
,
911 unsigned Depth
= 0) {
912 // fneg is removable even if it has multiple uses.
913 if (Op
.getOpcode() == ISD::FNEG
)
914 return Op
.getOperand(0);
916 assert(Depth
<= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
917 const TargetOptions
&Options
= DAG
.getTarget().Options
;
918 const SDNodeFlags Flags
= Op
->getFlags();
920 switch (Op
.getOpcode()) {
921 default: llvm_unreachable("Unknown code");
922 case ISD::ConstantFP
: {
923 APFloat V
= cast
<ConstantFPSDNode
>(Op
)->getValueAPF();
925 return DAG
.getConstantFP(V
, SDLoc(Op
), Op
.getValueType());
927 case ISD::BUILD_VECTOR
: {
928 SmallVector
<SDValue
, 4> Ops
;
929 for (SDValue C
: Op
->op_values()) {
934 APFloat V
= cast
<ConstantFPSDNode
>(C
)->getValueAPF();
936 Ops
.push_back(DAG
.getConstantFP(V
, SDLoc(Op
), C
.getValueType()));
938 return DAG
.getBuildVector(Op
.getValueType(), SDLoc(Op
), Ops
);
941 assert((Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros()) &&
942 "Expected NSZ fp-flag");
944 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
945 if (isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
946 DAG
.getTargetLoweringInfo(), &Options
, ForCodeSize
,
948 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
949 GetNegatedExpression(Op
.getOperand(0), DAG
,
950 LegalOperations
, ForCodeSize
,
952 Op
.getOperand(1), Flags
);
953 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
954 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
955 GetNegatedExpression(Op
.getOperand(1), DAG
,
956 LegalOperations
, ForCodeSize
,
958 Op
.getOperand(0), Flags
);
960 // fold (fneg (fsub 0, B)) -> B
961 if (ConstantFPSDNode
*N0CFP
=
962 isConstOrConstSplatFP(Op
.getOperand(0), /*AllowUndefs*/ true))
964 return Op
.getOperand(1);
966 // fold (fneg (fsub A, B)) -> (fsub B, A)
967 return DAG
.getNode(ISD::FSUB
, SDLoc(Op
), Op
.getValueType(),
968 Op
.getOperand(1), Op
.getOperand(0), Flags
);
972 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
973 if (isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
974 DAG
.getTargetLoweringInfo(), &Options
, ForCodeSize
,
976 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
977 GetNegatedExpression(Op
.getOperand(0), DAG
,
978 LegalOperations
, ForCodeSize
,
980 Op
.getOperand(1), Flags
);
982 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
983 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
985 GetNegatedExpression(Op
.getOperand(1), DAG
,
986 LegalOperations
, ForCodeSize
,
991 assert((Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros()) &&
992 "Expected NSZ fp-flag");
994 SDValue Neg2
= GetNegatedExpression(Op
.getOperand(2), DAG
, LegalOperations
,
995 ForCodeSize
, Depth
+ 1);
997 char V0
= isNegatibleForFree(Op
.getOperand(0), LegalOperations
,
998 DAG
.getTargetLoweringInfo(), &Options
,
999 ForCodeSize
, Depth
+ 1);
1000 char V1
= isNegatibleForFree(Op
.getOperand(1), LegalOperations
,
1001 DAG
.getTargetLoweringInfo(), &Options
,
1002 ForCodeSize
, Depth
+ 1);
1004 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
1005 SDValue Neg0
= GetNegatedExpression(
1006 Op
.getOperand(0), DAG
, LegalOperations
, ForCodeSize
, Depth
+ 1);
1007 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(), Neg0
,
1008 Op
.getOperand(1), Neg2
, Flags
);
1011 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
1012 SDValue Neg1
= GetNegatedExpression(Op
.getOperand(1), DAG
, LegalOperations
,
1013 ForCodeSize
, Depth
+ 1);
1014 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
1015 Op
.getOperand(0), Neg1
, Neg2
, Flags
);
1018 case ISD::FP_EXTEND
:
1020 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), Op
.getValueType(),
1021 GetNegatedExpression(Op
.getOperand(0), DAG
,
1022 LegalOperations
, ForCodeSize
,
1025 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(Op
), Op
.getValueType(),
1026 GetNegatedExpression(Op
.getOperand(0), DAG
,
1027 LegalOperations
, ForCodeSize
,
1033 // APInts must be the same size for most operations, this helper
1034 // function zero extends the shorter of the pair so that they match.
1035 // We provide an Offset so that we can create bitwidths that won't overflow.
1036 static void zeroExtendToMatch(APInt
&LHS
, APInt
&RHS
, unsigned Offset
= 0) {
1037 unsigned Bits
= Offset
+ std::max(LHS
.getBitWidth(), RHS
.getBitWidth());
1038 LHS
= LHS
.zextOrSelf(Bits
);
1039 RHS
= RHS
.zextOrSelf(Bits
);
1042 // Return true if this node is a setcc, or is a select_cc
1043 // that selects between the target values used for true and false, making it
1044 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
1045 // the appropriate nodes based on the type of node we are checking. This
1046 // simplifies life a bit for the callers.
1047 bool DAGCombiner::isSetCCEquivalent(SDValue N
, SDValue
&LHS
, SDValue
&RHS
,
1048 SDValue
&CC
) const {
1049 if (N
.getOpcode() == ISD::SETCC
) {
1050 LHS
= N
.getOperand(0);
1051 RHS
= N
.getOperand(1);
1052 CC
= N
.getOperand(2);
1056 if (N
.getOpcode() != ISD::SELECT_CC
||
1057 !TLI
.isConstTrueVal(N
.getOperand(2).getNode()) ||
1058 !TLI
.isConstFalseVal(N
.getOperand(3).getNode()))
1061 if (TLI
.getBooleanContents(N
.getValueType()) ==
1062 TargetLowering::UndefinedBooleanContent
)
1065 LHS
= N
.getOperand(0);
1066 RHS
= N
.getOperand(1);
1067 CC
= N
.getOperand(4);
1071 /// Return true if this is a SetCC-equivalent operation with only one use.
1072 /// If this is true, it allows the users to invert the operation for free when
1073 /// it is profitable to do so.
1074 bool DAGCombiner::isOneUseSetCC(SDValue N
) const {
1076 if (isSetCCEquivalent(N
, N0
, N1
, N2
) && N
.getNode()->hasOneUse())
1081 // Returns the SDNode if it is a constant float BuildVector
1082 // or constant float.
1083 static SDNode
*isConstantFPBuildVectorOrConstantFP(SDValue N
) {
1084 if (isa
<ConstantFPSDNode
>(N
))
1086 if (ISD::isBuildVectorOfConstantFPSDNodes(N
.getNode()))
1091 // Determines if it is a constant integer or a build vector of constant
1092 // integers (and undefs).
1093 // Do not permit build vector implicit truncation.
1094 static bool isConstantOrConstantVector(SDValue N
, bool NoOpaques
= false) {
1095 if (ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(N
))
1096 return !(Const
->isOpaque() && NoOpaques
);
1097 if (N
.getOpcode() != ISD::BUILD_VECTOR
)
1099 unsigned BitWidth
= N
.getScalarValueSizeInBits();
1100 for (const SDValue
&Op
: N
->op_values()) {
1103 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(Op
);
1104 if (!Const
|| Const
->getAPIntValue().getBitWidth() != BitWidth
||
1105 (Const
->isOpaque() && NoOpaques
))
1111 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
1113 static bool isAnyConstantBuildVector(SDValue V
, bool NoOpaques
= false) {
1114 if (V
.getOpcode() != ISD::BUILD_VECTOR
)
1116 return isConstantOrConstantVector(V
, NoOpaques
) ||
1117 ISD::isBuildVectorOfConstantFPSDNodes(V
.getNode());
1120 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc
,
1124 // Currently this only tries to ensure we don't undo the GEP splits done by
1125 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
1126 // we check if the following transformation would be problematic:
1127 // (load/store (add, (add, x, offset1), offset2)) ->
1128 // (load/store (add, x, offset1+offset2)).
1130 if (Opc
!= ISD::ADD
|| N0
.getOpcode() != ISD::ADD
)
1136 auto *C1
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
1137 auto *C2
= dyn_cast
<ConstantSDNode
>(N1
);
1141 const APInt
&C1APIntVal
= C1
->getAPIntValue();
1142 const APInt
&C2APIntVal
= C2
->getAPIntValue();
1143 if (C1APIntVal
.getBitWidth() > 64 || C2APIntVal
.getBitWidth() > 64)
1146 const APInt CombinedValueIntVal
= C1APIntVal
+ C2APIntVal
;
1147 if (CombinedValueIntVal
.getBitWidth() > 64)
1149 const int64_t CombinedValue
= CombinedValueIntVal
.getSExtValue();
1151 for (SDNode
*Node
: N0
->uses()) {
1152 auto LoadStore
= dyn_cast
<MemSDNode
>(Node
);
1154 // Is x[offset2] already not a legal addressing mode? If so then
1155 // reassociating the constants breaks nothing (we test offset2 because
1156 // that's the one we hope to fold into the load or store).
1157 TargetLoweringBase::AddrMode AM
;
1158 AM
.HasBaseReg
= true;
1159 AM
.BaseOffs
= C2APIntVal
.getSExtValue();
1160 EVT VT
= LoadStore
->getMemoryVT();
1161 unsigned AS
= LoadStore
->getAddressSpace();
1162 Type
*AccessTy
= VT
.getTypeForEVT(*DAG
.getContext());
1163 if (!TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
, AccessTy
, AS
))
1166 // Would x[offset1+offset2] still be a legal addressing mode?
1167 AM
.BaseOffs
= CombinedValue
;
1168 if (!TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
, AccessTy
, AS
))
1176 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
1177 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
1178 SDValue
DAGCombiner::reassociateOpsCommutative(unsigned Opc
, const SDLoc
&DL
,
1179 SDValue N0
, SDValue N1
) {
1180 EVT VT
= N0
.getValueType();
1182 if (N0
.getOpcode() != Opc
)
1185 // Don't reassociate reductions.
1186 if (N0
->getFlags().hasVectorReduction())
1189 if (SDNode
*C1
= DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1))) {
1190 if (SDNode
*C2
= DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
1191 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
1192 if (SDValue OpNode
= DAG
.FoldConstantArithmetic(Opc
, DL
, VT
, C1
, C2
))
1193 return DAG
.getNode(Opc
, DL
, VT
, N0
.getOperand(0), OpNode
);
1196 if (N0
.hasOneUse()) {
1197 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
1198 // iff (op x, c1) has one use
1199 SDValue OpNode
= DAG
.getNode(Opc
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
1200 if (!OpNode
.getNode())
1202 return DAG
.getNode(Opc
, DL
, VT
, OpNode
, N0
.getOperand(1));
1208 // Try to reassociate commutative binops.
1209 SDValue
DAGCombiner::reassociateOps(unsigned Opc
, const SDLoc
&DL
, SDValue N0
,
1210 SDValue N1
, SDNodeFlags Flags
) {
1211 assert(TLI
.isCommutativeBinOp(Opc
) && "Operation not commutative.");
1212 // Don't reassociate reductions.
1213 if (Flags
.hasVectorReduction())
1216 // Floating-point reassociation is not allowed without loose FP math.
1217 if (N0
.getValueType().isFloatingPoint() ||
1218 N1
.getValueType().isFloatingPoint())
1219 if (!Flags
.hasAllowReassociation() || !Flags
.hasNoSignedZeros())
1222 if (SDValue Combined
= reassociateOpsCommutative(Opc
, DL
, N0
, N1
))
1224 if (SDValue Combined
= reassociateOpsCommutative(Opc
, DL
, N1
, N0
))
1229 SDValue
DAGCombiner::CombineTo(SDNode
*N
, const SDValue
*To
, unsigned NumTo
,
1231 assert(N
->getNumValues() == NumTo
&& "Broken CombineTo call!");
1233 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N
->dump(&DAG
); dbgs() << "\nWith: ";
1234 To
[0].getNode()->dump(&DAG
);
1235 dbgs() << " and " << NumTo
- 1 << " other values\n");
1236 for (unsigned i
= 0, e
= NumTo
; i
!= e
; ++i
)
1237 assert((!To
[i
].getNode() ||
1238 N
->getValueType(i
) == To
[i
].getValueType()) &&
1239 "Cannot combine value to value of different type!");
1241 WorklistRemover
DeadNodes(*this);
1242 DAG
.ReplaceAllUsesWith(N
, To
);
1244 // Push the new nodes and any users onto the worklist
1245 for (unsigned i
= 0, e
= NumTo
; i
!= e
; ++i
) {
1246 if (To
[i
].getNode()) {
1247 AddToWorklist(To
[i
].getNode());
1248 AddUsersToWorklist(To
[i
].getNode());
1253 // Finally, if the node is now dead, remove it from the graph. The node
1254 // may not be dead if the replacement process recursively simplified to
1255 // something else needing this node.
1257 deleteAndRecombine(N
);
1258 return SDValue(N
, 0);
1262 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt
&TLO
) {
1263 // Replace all uses. If any nodes become isomorphic to other nodes and
1264 // are deleted, make sure to remove them from our worklist.
1265 WorklistRemover
DeadNodes(*this);
1266 DAG
.ReplaceAllUsesOfValueWith(TLO
.Old
, TLO
.New
);
1268 // Push the new node and any (possibly new) users onto the worklist.
1269 AddToWorklist(TLO
.New
.getNode());
1270 AddUsersToWorklist(TLO
.New
.getNode());
1272 // Finally, if the node is now dead, remove it from the graph. The node
1273 // may not be dead if the replacement process recursively simplified to
1274 // something else needing this node.
1275 if (TLO
.Old
.getNode()->use_empty())
1276 deleteAndRecombine(TLO
.Old
.getNode());
1279 /// Check the specified integer node value to see if it can be simplified or if
1280 /// things it uses can be simplified by bit propagation. If so, return true.
1281 bool DAGCombiner::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
1282 const APInt
&DemandedElts
) {
1283 TargetLowering::TargetLoweringOpt
TLO(DAG
, LegalTypes
, LegalOperations
);
1285 if (!TLI
.SimplifyDemandedBits(Op
, DemandedBits
, DemandedElts
, Known
, TLO
))
1288 // Revisit the node.
1289 AddToWorklist(Op
.getNode());
1291 // Replace the old value with the new one.
1293 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO
.Old
.getNode()->dump(&DAG
);
1294 dbgs() << "\nWith: "; TLO
.New
.getNode()->dump(&DAG
);
1297 CommitTargetLoweringOpt(TLO
);
1301 /// Check the specified vector node value to see if it can be simplified or
1302 /// if things it uses can be simplified as it only uses some of the elements.
1303 /// If so, return true.
1304 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op
,
1305 const APInt
&DemandedElts
,
1306 bool AssumeSingleUse
) {
1307 TargetLowering::TargetLoweringOpt
TLO(DAG
, LegalTypes
, LegalOperations
);
1308 APInt KnownUndef
, KnownZero
;
1309 if (!TLI
.SimplifyDemandedVectorElts(Op
, DemandedElts
, KnownUndef
, KnownZero
,
1310 TLO
, 0, AssumeSingleUse
))
1313 // Revisit the node.
1314 AddToWorklist(Op
.getNode());
1316 // Replace the old value with the new one.
1318 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO
.Old
.getNode()->dump(&DAG
);
1319 dbgs() << "\nWith: "; TLO
.New
.getNode()->dump(&DAG
);
1322 CommitTargetLoweringOpt(TLO
);
1326 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode
*Load
, SDNode
*ExtLoad
) {
1328 EVT VT
= Load
->getValueType(0);
1329 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, SDValue(ExtLoad
, 0));
1331 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load
->dump(&DAG
); dbgs() << "\nWith: ";
1332 Trunc
.getNode()->dump(&DAG
); dbgs() << '\n');
1333 WorklistRemover
DeadNodes(*this);
1334 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 0), Trunc
);
1335 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 1), SDValue(ExtLoad
, 1));
1336 deleteAndRecombine(Load
);
1337 AddToWorklist(Trunc
.getNode());
1340 SDValue
DAGCombiner::PromoteOperand(SDValue Op
, EVT PVT
, bool &Replace
) {
1343 if (ISD::isUNINDEXEDLoad(Op
.getNode())) {
1344 LoadSDNode
*LD
= cast
<LoadSDNode
>(Op
);
1345 EVT MemVT
= LD
->getMemoryVT();
1346 ISD::LoadExtType ExtType
= ISD::isNON_EXTLoad(LD
) ? ISD::EXTLOAD
1347 : LD
->getExtensionType();
1349 return DAG
.getExtLoad(ExtType
, DL
, PVT
,
1350 LD
->getChain(), LD
->getBasePtr(),
1351 MemVT
, LD
->getMemOperand());
1354 unsigned Opc
= Op
.getOpcode();
1357 case ISD::AssertSext
:
1358 if (SDValue Op0
= SExtPromoteOperand(Op
.getOperand(0), PVT
))
1359 return DAG
.getNode(ISD::AssertSext
, DL
, PVT
, Op0
, Op
.getOperand(1));
1361 case ISD::AssertZext
:
1362 if (SDValue Op0
= ZExtPromoteOperand(Op
.getOperand(0), PVT
))
1363 return DAG
.getNode(ISD::AssertZext
, DL
, PVT
, Op0
, Op
.getOperand(1));
1365 case ISD::Constant
: {
1367 Op
.getValueType().isByteSized() ? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
1368 return DAG
.getNode(ExtOpc
, DL
, PVT
, Op
);
1372 if (!TLI
.isOperationLegal(ISD::ANY_EXTEND
, PVT
))
1374 return DAG
.getNode(ISD::ANY_EXTEND
, DL
, PVT
, Op
);
1377 SDValue
DAGCombiner::SExtPromoteOperand(SDValue Op
, EVT PVT
) {
1378 if (!TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
, PVT
))
1380 EVT OldVT
= Op
.getValueType();
1382 bool Replace
= false;
1383 SDValue NewOp
= PromoteOperand(Op
, PVT
, Replace
);
1384 if (!NewOp
.getNode())
1386 AddToWorklist(NewOp
.getNode());
1389 ReplaceLoadWithPromotedLoad(Op
.getNode(), NewOp
.getNode());
1390 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, DL
, NewOp
.getValueType(), NewOp
,
1391 DAG
.getValueType(OldVT
));
1394 SDValue
DAGCombiner::ZExtPromoteOperand(SDValue Op
, EVT PVT
) {
1395 EVT OldVT
= Op
.getValueType();
1397 bool Replace
= false;
1398 SDValue NewOp
= PromoteOperand(Op
, PVT
, Replace
);
1399 if (!NewOp
.getNode())
1401 AddToWorklist(NewOp
.getNode());
1404 ReplaceLoadWithPromotedLoad(Op
.getNode(), NewOp
.getNode());
1405 return DAG
.getZeroExtendInReg(NewOp
, DL
, OldVT
);
1408 /// Promote the specified integer binary operation if the target indicates it is
1409 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1410 /// i32 since i16 instructions are longer.
1411 SDValue
DAGCombiner::PromoteIntBinOp(SDValue Op
) {
1412 if (!LegalOperations
)
1415 EVT VT
= Op
.getValueType();
1416 if (VT
.isVector() || !VT
.isInteger())
1419 // If operation type is 'undesirable', e.g. i16 on x86, consider
1421 unsigned Opc
= Op
.getOpcode();
1422 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1426 // Consult target whether it is a good idea to promote this operation and
1427 // what's the right type to promote it to.
1428 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1429 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1431 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1433 bool Replace0
= false;
1434 SDValue N0
= Op
.getOperand(0);
1435 SDValue NN0
= PromoteOperand(N0
, PVT
, Replace0
);
1437 bool Replace1
= false;
1438 SDValue N1
= Op
.getOperand(1);
1439 SDValue NN1
= PromoteOperand(N1
, PVT
, Replace1
);
1443 DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, DAG
.getNode(Opc
, DL
, PVT
, NN0
, NN1
));
1445 // We are always replacing N0/N1's use in N and only need
1446 // additional replacements if there are additional uses.
1447 Replace0
&= !N0
->hasOneUse();
1448 Replace1
&= (N0
!= N1
) && !N1
->hasOneUse();
1450 // Combine Op here so it is preserved past replacements.
1451 CombineTo(Op
.getNode(), RV
);
1453 // If operands have a use ordering, make sure we deal with
1454 // predecessor first.
1455 if (Replace0
&& Replace1
&& N0
.getNode()->isPredecessorOf(N1
.getNode())) {
1457 std::swap(NN0
, NN1
);
1461 AddToWorklist(NN0
.getNode());
1462 ReplaceLoadWithPromotedLoad(N0
.getNode(), NN0
.getNode());
1465 AddToWorklist(NN1
.getNode());
1466 ReplaceLoadWithPromotedLoad(N1
.getNode(), NN1
.getNode());
1473 /// Promote the specified integer shift operation if the target indicates it is
1474 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1475 /// i32 since i16 instructions are longer.
1476 SDValue
DAGCombiner::PromoteIntShiftOp(SDValue Op
) {
1477 if (!LegalOperations
)
1480 EVT VT
= Op
.getValueType();
1481 if (VT
.isVector() || !VT
.isInteger())
1484 // If operation type is 'undesirable', e.g. i16 on x86, consider
1486 unsigned Opc
= Op
.getOpcode();
1487 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1491 // Consult target whether it is a good idea to promote this operation and
1492 // what's the right type to promote it to.
1493 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1494 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1496 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1498 bool Replace
= false;
1499 SDValue N0
= Op
.getOperand(0);
1500 SDValue N1
= Op
.getOperand(1);
1501 if (Opc
== ISD::SRA
)
1502 N0
= SExtPromoteOperand(N0
, PVT
);
1503 else if (Opc
== ISD::SRL
)
1504 N0
= ZExtPromoteOperand(N0
, PVT
);
1506 N0
= PromoteOperand(N0
, PVT
, Replace
);
1513 DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, DAG
.getNode(Opc
, DL
, PVT
, N0
, N1
));
1516 ReplaceLoadWithPromotedLoad(Op
.getOperand(0).getNode(), N0
.getNode());
1518 // Deal with Op being deleted.
1519 if (Op
&& Op
.getOpcode() != ISD::DELETED_NODE
)
1525 SDValue
DAGCombiner::PromoteExtend(SDValue Op
) {
1526 if (!LegalOperations
)
1529 EVT VT
= Op
.getValueType();
1530 if (VT
.isVector() || !VT
.isInteger())
1533 // If operation type is 'undesirable', e.g. i16 on x86, consider
1535 unsigned Opc
= Op
.getOpcode();
1536 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1540 // Consult target whether it is a good idea to promote this operation and
1541 // what's the right type to promote it to.
1542 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1543 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1544 // fold (aext (aext x)) -> (aext x)
1545 // fold (aext (zext x)) -> (zext x)
1546 // fold (aext (sext x)) -> (sext x)
1547 LLVM_DEBUG(dbgs() << "\nPromoting "; Op
.getNode()->dump(&DAG
));
1548 return DAG
.getNode(Op
.getOpcode(), SDLoc(Op
), VT
, Op
.getOperand(0));
1553 bool DAGCombiner::PromoteLoad(SDValue Op
) {
1554 if (!LegalOperations
)
1557 if (!ISD::isUNINDEXEDLoad(Op
.getNode()))
1560 EVT VT
= Op
.getValueType();
1561 if (VT
.isVector() || !VT
.isInteger())
1564 // If operation type is 'undesirable', e.g. i16 on x86, consider
1566 unsigned Opc
= Op
.getOpcode();
1567 if (TLI
.isTypeDesirableForOp(Opc
, VT
))
1571 // Consult target whether it is a good idea to promote this operation and
1572 // what's the right type to promote it to.
1573 if (TLI
.IsDesirableToPromoteOp(Op
, PVT
)) {
1574 assert(PVT
!= VT
&& "Don't know what type to promote to!");
1577 SDNode
*N
= Op
.getNode();
1578 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
1579 EVT MemVT
= LD
->getMemoryVT();
1580 ISD::LoadExtType ExtType
= ISD::isNON_EXTLoad(LD
) ? ISD::EXTLOAD
1581 : LD
->getExtensionType();
1582 SDValue NewLD
= DAG
.getExtLoad(ExtType
, DL
, PVT
,
1583 LD
->getChain(), LD
->getBasePtr(),
1584 MemVT
, LD
->getMemOperand());
1585 SDValue Result
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, NewLD
);
1587 LLVM_DEBUG(dbgs() << "\nPromoting "; N
->dump(&DAG
); dbgs() << "\nTo: ";
1588 Result
.getNode()->dump(&DAG
); dbgs() << '\n');
1589 WorklistRemover
DeadNodes(*this);
1590 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
);
1591 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), NewLD
.getValue(1));
1592 deleteAndRecombine(N
);
1593 AddToWorklist(Result
.getNode());
1599 /// Recursively delete a node which has no uses and any operands for
1600 /// which it is the only use.
1602 /// Note that this both deletes the nodes and removes them from the worklist.
1603 /// It also adds any nodes who have had a user deleted to the worklist as they
1604 /// may now have only one use and subject to other combines.
1605 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode
*N
) {
1606 if (!N
->use_empty())
1609 SmallSetVector
<SDNode
*, 16> Nodes
;
1612 N
= Nodes
.pop_back_val();
1616 if (N
->use_empty()) {
1617 for (const SDValue
&ChildN
: N
->op_values())
1618 Nodes
.insert(ChildN
.getNode());
1620 removeFromWorklist(N
);
1625 } while (!Nodes
.empty());
1629 //===----------------------------------------------------------------------===//
1630 // Main DAG Combiner implementation
1631 //===----------------------------------------------------------------------===//
1633 void DAGCombiner::Run(CombineLevel AtLevel
) {
1634 // set the instance variables, so that the various visit routines may use it.
1636 LegalOperations
= Level
>= AfterLegalizeVectorOps
;
1637 LegalTypes
= Level
>= AfterLegalizeTypes
;
1639 WorklistInserter
AddNodes(*this);
1641 // Add all the dag nodes to the worklist.
1642 for (SDNode
&Node
: DAG
.allnodes())
1643 AddToWorklist(&Node
);
1645 // Create a dummy node (which is not added to allnodes), that adds a reference
1646 // to the root node, preventing it from being deleted, and tracking any
1647 // changes of the root.
1648 HandleSDNode
Dummy(DAG
.getRoot());
1650 // While we have a valid worklist entry node, try to combine it.
1651 while (SDNode
*N
= getNextWorklistEntry()) {
1652 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1653 // N is deleted from the DAG, since they too may now be dead or may have a
1654 // reduced number of uses, allowing other xforms.
1655 if (recursivelyDeleteUnusedNodes(N
))
1658 WorklistRemover
DeadNodes(*this);
1660 // If this combine is running after legalizing the DAG, re-legalize any
1661 // nodes pulled off the worklist.
1662 if (Level
== AfterLegalizeDAG
) {
1663 SmallSetVector
<SDNode
*, 16> UpdatedNodes
;
1664 bool NIsValid
= DAG
.LegalizeOp(N
, UpdatedNodes
);
1666 for (SDNode
*LN
: UpdatedNodes
) {
1668 AddUsersToWorklist(LN
);
1674 LLVM_DEBUG(dbgs() << "\nCombining: "; N
->dump(&DAG
));
1676 // Add any operands of the new node which have not yet been combined to the
1677 // worklist as well. Because the worklist uniques things already, this
1678 // won't repeatedly process the same operand.
1679 CombinedNodes
.insert(N
);
1680 for (const SDValue
&ChildN
: N
->op_values())
1681 if (!CombinedNodes
.count(ChildN
.getNode()))
1682 AddToWorklist(ChildN
.getNode());
1684 SDValue RV
= combine(N
);
1691 // If we get back the same node we passed in, rather than a new node or
1692 // zero, we know that the node must have defined multiple values and
1693 // CombineTo was used. Since CombineTo takes care of the worklist
1694 // mechanics for us, we have no work to do in this case.
1695 if (RV
.getNode() == N
)
1698 assert(N
->getOpcode() != ISD::DELETED_NODE
&&
1699 RV
.getOpcode() != ISD::DELETED_NODE
&&
1700 "Node was deleted but visit returned new node!");
1702 LLVM_DEBUG(dbgs() << " ... into: "; RV
.getNode()->dump(&DAG
));
1704 if (N
->getNumValues() == RV
.getNode()->getNumValues())
1705 DAG
.ReplaceAllUsesWith(N
, RV
.getNode());
1707 assert(N
->getValueType(0) == RV
.getValueType() &&
1708 N
->getNumValues() == 1 && "Type mismatch");
1709 DAG
.ReplaceAllUsesWith(N
, &RV
);
1712 // Push the new node and any users onto the worklist
1713 AddToWorklist(RV
.getNode());
1714 AddUsersToWorklist(RV
.getNode());
1716 // Finally, if the node is now dead, remove it from the graph. The node
1717 // may not be dead if the replacement process recursively simplified to
1718 // something else needing this node. This will also take care of adding any
1719 // operands which have lost a user to the worklist.
1720 recursivelyDeleteUnusedNodes(N
);
1723 // If the root changed (e.g. it was a dead load, update the root).
1724 DAG
.setRoot(Dummy
.getValue());
1725 DAG
.RemoveDeadNodes();
1728 SDValue
DAGCombiner::visit(SDNode
*N
) {
1729 switch (N
->getOpcode()) {
1731 case ISD::TokenFactor
: return visitTokenFactor(N
);
1732 case ISD::MERGE_VALUES
: return visitMERGE_VALUES(N
);
1733 case ISD::ADD
: return visitADD(N
);
1734 case ISD::SUB
: return visitSUB(N
);
1736 case ISD::UADDSAT
: return visitADDSAT(N
);
1738 case ISD::USUBSAT
: return visitSUBSAT(N
);
1739 case ISD::ADDC
: return visitADDC(N
);
1741 case ISD::UADDO
: return visitADDO(N
);
1742 case ISD::SUBC
: return visitSUBC(N
);
1744 case ISD::USUBO
: return visitSUBO(N
);
1745 case ISD::ADDE
: return visitADDE(N
);
1746 case ISD::ADDCARRY
: return visitADDCARRY(N
);
1747 case ISD::SUBE
: return visitSUBE(N
);
1748 case ISD::SUBCARRY
: return visitSUBCARRY(N
);
1750 case ISD::SMULFIXSAT
:
1751 case ISD::UMULFIX
: return visitMULFIX(N
);
1752 case ISD::MUL
: return visitMUL(N
);
1753 case ISD::SDIV
: return visitSDIV(N
);
1754 case ISD::UDIV
: return visitUDIV(N
);
1756 case ISD::UREM
: return visitREM(N
);
1757 case ISD::MULHU
: return visitMULHU(N
);
1758 case ISD::MULHS
: return visitMULHS(N
);
1759 case ISD::SMUL_LOHI
: return visitSMUL_LOHI(N
);
1760 case ISD::UMUL_LOHI
: return visitUMUL_LOHI(N
);
1762 case ISD::UMULO
: return visitMULO(N
);
1766 case ISD::UMAX
: return visitIMINMAX(N
);
1767 case ISD::AND
: return visitAND(N
);
1768 case ISD::OR
: return visitOR(N
);
1769 case ISD::XOR
: return visitXOR(N
);
1770 case ISD::SHL
: return visitSHL(N
);
1771 case ISD::SRA
: return visitSRA(N
);
1772 case ISD::SRL
: return visitSRL(N
);
1774 case ISD::ROTL
: return visitRotate(N
);
1776 case ISD::FSHR
: return visitFunnelShift(N
);
1777 case ISD::ABS
: return visitABS(N
);
1778 case ISD::BSWAP
: return visitBSWAP(N
);
1779 case ISD::BITREVERSE
: return visitBITREVERSE(N
);
1780 case ISD::CTLZ
: return visitCTLZ(N
);
1781 case ISD::CTLZ_ZERO_UNDEF
: return visitCTLZ_ZERO_UNDEF(N
);
1782 case ISD::CTTZ
: return visitCTTZ(N
);
1783 case ISD::CTTZ_ZERO_UNDEF
: return visitCTTZ_ZERO_UNDEF(N
);
1784 case ISD::CTPOP
: return visitCTPOP(N
);
1785 case ISD::SELECT
: return visitSELECT(N
);
1786 case ISD::VSELECT
: return visitVSELECT(N
);
1787 case ISD::SELECT_CC
: return visitSELECT_CC(N
);
1788 case ISD::SETCC
: return visitSETCC(N
);
1789 case ISD::SETCCCARRY
: return visitSETCCCARRY(N
);
1790 case ISD::SIGN_EXTEND
: return visitSIGN_EXTEND(N
);
1791 case ISD::ZERO_EXTEND
: return visitZERO_EXTEND(N
);
1792 case ISD::ANY_EXTEND
: return visitANY_EXTEND(N
);
1793 case ISD::AssertSext
:
1794 case ISD::AssertZext
: return visitAssertExt(N
);
1795 case ISD::SIGN_EXTEND_INREG
: return visitSIGN_EXTEND_INREG(N
);
1796 case ISD::SIGN_EXTEND_VECTOR_INREG
: return visitSIGN_EXTEND_VECTOR_INREG(N
);
1797 case ISD::ZERO_EXTEND_VECTOR_INREG
: return visitZERO_EXTEND_VECTOR_INREG(N
);
1798 case ISD::TRUNCATE
: return visitTRUNCATE(N
);
1799 case ISD::BITCAST
: return visitBITCAST(N
);
1800 case ISD::BUILD_PAIR
: return visitBUILD_PAIR(N
);
1801 case ISD::FADD
: return visitFADD(N
);
1802 case ISD::FSUB
: return visitFSUB(N
);
1803 case ISD::FMUL
: return visitFMUL(N
);
1804 case ISD::FMA
: return visitFMA(N
);
1805 case ISD::FDIV
: return visitFDIV(N
);
1806 case ISD::FREM
: return visitFREM(N
);
1807 case ISD::FSQRT
: return visitFSQRT(N
);
1808 case ISD::FCOPYSIGN
: return visitFCOPYSIGN(N
);
1809 case ISD::FPOW
: return visitFPOW(N
);
1810 case ISD::SINT_TO_FP
: return visitSINT_TO_FP(N
);
1811 case ISD::UINT_TO_FP
: return visitUINT_TO_FP(N
);
1812 case ISD::FP_TO_SINT
: return visitFP_TO_SINT(N
);
1813 case ISD::FP_TO_UINT
: return visitFP_TO_UINT(N
);
1814 case ISD::FP_ROUND
: return visitFP_ROUND(N
);
1815 case ISD::FP_ROUND_INREG
: return visitFP_ROUND_INREG(N
);
1816 case ISD::FP_EXTEND
: return visitFP_EXTEND(N
);
1817 case ISD::FNEG
: return visitFNEG(N
);
1818 case ISD::FABS
: return visitFABS(N
);
1819 case ISD::FFLOOR
: return visitFFLOOR(N
);
1820 case ISD::FMINNUM
: return visitFMINNUM(N
);
1821 case ISD::FMAXNUM
: return visitFMAXNUM(N
);
1822 case ISD::FMINIMUM
: return visitFMINIMUM(N
);
1823 case ISD::FMAXIMUM
: return visitFMAXIMUM(N
);
1824 case ISD::FCEIL
: return visitFCEIL(N
);
1825 case ISD::FTRUNC
: return visitFTRUNC(N
);
1826 case ISD::BRCOND
: return visitBRCOND(N
);
1827 case ISD::BR_CC
: return visitBR_CC(N
);
1828 case ISD::LOAD
: return visitLOAD(N
);
1829 case ISD::STORE
: return visitSTORE(N
);
1830 case ISD::INSERT_VECTOR_ELT
: return visitINSERT_VECTOR_ELT(N
);
1831 case ISD::EXTRACT_VECTOR_ELT
: return visitEXTRACT_VECTOR_ELT(N
);
1832 case ISD::BUILD_VECTOR
: return visitBUILD_VECTOR(N
);
1833 case ISD::CONCAT_VECTORS
: return visitCONCAT_VECTORS(N
);
1834 case ISD::EXTRACT_SUBVECTOR
: return visitEXTRACT_SUBVECTOR(N
);
1835 case ISD::VECTOR_SHUFFLE
: return visitVECTOR_SHUFFLE(N
);
1836 case ISD::SCALAR_TO_VECTOR
: return visitSCALAR_TO_VECTOR(N
);
1837 case ISD::INSERT_SUBVECTOR
: return visitINSERT_SUBVECTOR(N
);
1838 case ISD::MGATHER
: return visitMGATHER(N
);
1839 case ISD::MLOAD
: return visitMLOAD(N
);
1840 case ISD::MSCATTER
: return visitMSCATTER(N
);
1841 case ISD::MSTORE
: return visitMSTORE(N
);
1842 case ISD::LIFETIME_END
: return visitLIFETIME_END(N
);
1843 case ISD::FP_TO_FP16
: return visitFP_TO_FP16(N
);
1844 case ISD::FP16_TO_FP
: return visitFP16_TO_FP(N
);
1845 case ISD::VECREDUCE_FADD
:
1846 case ISD::VECREDUCE_FMUL
:
1847 case ISD::VECREDUCE_ADD
:
1848 case ISD::VECREDUCE_MUL
:
1849 case ISD::VECREDUCE_AND
:
1850 case ISD::VECREDUCE_OR
:
1851 case ISD::VECREDUCE_XOR
:
1852 case ISD::VECREDUCE_SMAX
:
1853 case ISD::VECREDUCE_SMIN
:
1854 case ISD::VECREDUCE_UMAX
:
1855 case ISD::VECREDUCE_UMIN
:
1856 case ISD::VECREDUCE_FMAX
:
1857 case ISD::VECREDUCE_FMIN
: return visitVECREDUCE(N
);
1862 SDValue
DAGCombiner::combine(SDNode
*N
) {
1863 SDValue RV
= visit(N
);
1865 // If nothing happened, try a target-specific DAG combine.
1866 if (!RV
.getNode()) {
1867 assert(N
->getOpcode() != ISD::DELETED_NODE
&&
1868 "Node was deleted but visit returned NULL!");
1870 if (N
->getOpcode() >= ISD::BUILTIN_OP_END
||
1871 TLI
.hasTargetDAGCombine((ISD::NodeType
)N
->getOpcode())) {
1873 // Expose the DAG combiner to the target combiner impls.
1874 TargetLowering::DAGCombinerInfo
1875 DagCombineInfo(DAG
, Level
, false, this);
1877 RV
= TLI
.PerformDAGCombine(N
, DagCombineInfo
);
1881 // If nothing happened still, try promoting the operation.
1882 if (!RV
.getNode()) {
1883 switch (N
->getOpcode()) {
1891 RV
= PromoteIntBinOp(SDValue(N
, 0));
1896 RV
= PromoteIntShiftOp(SDValue(N
, 0));
1898 case ISD::SIGN_EXTEND
:
1899 case ISD::ZERO_EXTEND
:
1900 case ISD::ANY_EXTEND
:
1901 RV
= PromoteExtend(SDValue(N
, 0));
1904 if (PromoteLoad(SDValue(N
, 0)))
1910 // If N is a commutative binary node, try to eliminate it if the commuted
1911 // version is already present in the DAG.
1912 if (!RV
.getNode() && TLI
.isCommutativeBinOp(N
->getOpcode()) &&
1913 N
->getNumValues() == 1) {
1914 SDValue N0
= N
->getOperand(0);
1915 SDValue N1
= N
->getOperand(1);
1917 // Constant operands are canonicalized to RHS.
1918 if (N0
!= N1
&& (isa
<ConstantSDNode
>(N0
) || !isa
<ConstantSDNode
>(N1
))) {
1919 SDValue Ops
[] = {N1
, N0
};
1920 SDNode
*CSENode
= DAG
.getNodeIfExists(N
->getOpcode(), N
->getVTList(), Ops
,
1923 return SDValue(CSENode
, 0);
1930 /// Given a node, return its input chain if it has one, otherwise return a null
1932 static SDValue
getInputChainForNode(SDNode
*N
) {
1933 if (unsigned NumOps
= N
->getNumOperands()) {
1934 if (N
->getOperand(0).getValueType() == MVT::Other
)
1935 return N
->getOperand(0);
1936 if (N
->getOperand(NumOps
-1).getValueType() == MVT::Other
)
1937 return N
->getOperand(NumOps
-1);
1938 for (unsigned i
= 1; i
< NumOps
-1; ++i
)
1939 if (N
->getOperand(i
).getValueType() == MVT::Other
)
1940 return N
->getOperand(i
);
1945 SDValue
DAGCombiner::visitTokenFactor(SDNode
*N
) {
1946 // If N has two operands, where one has an input chain equal to the other,
1947 // the 'other' chain is redundant.
1948 if (N
->getNumOperands() == 2) {
1949 if (getInputChainForNode(N
->getOperand(0).getNode()) == N
->getOperand(1))
1950 return N
->getOperand(0);
1951 if (getInputChainForNode(N
->getOperand(1).getNode()) == N
->getOperand(0))
1952 return N
->getOperand(1);
1955 // Don't simplify token factors if optnone.
1956 if (OptLevel
== CodeGenOpt::None
)
1959 // If the sole user is a token factor, we should make sure we have a
1960 // chance to merge them together. This prevents TF chains from inhibiting
1962 if (N
->hasOneUse() && N
->use_begin()->getOpcode() == ISD::TokenFactor
)
1963 AddToWorklist(*(N
->use_begin()));
1965 SmallVector
<SDNode
*, 8> TFs
; // List of token factors to visit.
1966 SmallVector
<SDValue
, 8> Ops
; // Ops for replacing token factor.
1967 SmallPtrSet
<SDNode
*, 16> SeenOps
;
1968 bool Changed
= false; // If we should replace this token factor.
1970 // Start out with this token factor.
1973 // Iterate through token factors. The TFs grows when new token factors are
1975 for (unsigned i
= 0; i
< TFs
.size(); ++i
) {
1976 // Limit number of nodes to inline, to avoid quadratic compile times.
1977 // We have to add the outstanding Token Factors to Ops, otherwise we might
1978 // drop Ops from the resulting Token Factors.
1979 if (Ops
.size() > TokenFactorInlineLimit
) {
1980 for (unsigned j
= i
; j
< TFs
.size(); j
++)
1981 Ops
.emplace_back(TFs
[j
], 0);
1982 // Drop unprocessed Token Factors from TFs, so we do not add them to the
1983 // combiner worklist later.
1988 SDNode
*TF
= TFs
[i
];
1989 // Check each of the operands.
1990 for (const SDValue
&Op
: TF
->op_values()) {
1991 switch (Op
.getOpcode()) {
1992 case ISD::EntryToken
:
1993 // Entry tokens don't need to be added to the list. They are
1998 case ISD::TokenFactor
:
1999 if (Op
.hasOneUse() && !is_contained(TFs
, Op
.getNode())) {
2000 // Queue up for processing.
2001 TFs
.push_back(Op
.getNode());
2008 // Only add if it isn't already in the list.
2009 if (SeenOps
.insert(Op
.getNode()).second
)
2018 // Re-visit inlined Token Factors, to clean them up in case they have been
2019 // removed. Skip the first Token Factor, as this is the current node.
2020 for (unsigned i
= 1, e
= TFs
.size(); i
< e
; i
++)
2021 AddToWorklist(TFs
[i
]);
2023 // Remove Nodes that are chained to another node in the list. Do so
2024 // by walking up chains breath-first stopping when we've seen
2025 // another operand. In general we must climb to the EntryNode, but we can exit
2026 // early if we find all remaining work is associated with just one operand as
2027 // no further pruning is possible.
2029 // List of nodes to search through and original Ops from which they originate.
2030 SmallVector
<std::pair
<SDNode
*, unsigned>, 8> Worklist
;
2031 SmallVector
<unsigned, 8> OpWorkCount
; // Count of work for each Op.
2032 SmallPtrSet
<SDNode
*, 16> SeenChains
;
2033 bool DidPruneOps
= false;
2035 unsigned NumLeftToConsider
= 0;
2036 for (const SDValue
&Op
: Ops
) {
2037 Worklist
.push_back(std::make_pair(Op
.getNode(), NumLeftToConsider
++));
2038 OpWorkCount
.push_back(1);
2041 auto AddToWorklist
= [&](unsigned CurIdx
, SDNode
*Op
, unsigned OpNumber
) {
2042 // If this is an Op, we can remove the op from the list. Remark any
2043 // search associated with it as from the current OpNumber.
2044 if (SeenOps
.count(Op
) != 0) {
2047 unsigned OrigOpNumber
= 0;
2048 while (OrigOpNumber
< Ops
.size() && Ops
[OrigOpNumber
].getNode() != Op
)
2050 assert((OrigOpNumber
!= Ops
.size()) &&
2051 "expected to find TokenFactor Operand");
2052 // Re-mark worklist from OrigOpNumber to OpNumber
2053 for (unsigned i
= CurIdx
+ 1; i
< Worklist
.size(); ++i
) {
2054 if (Worklist
[i
].second
== OrigOpNumber
) {
2055 Worklist
[i
].second
= OpNumber
;
2058 OpWorkCount
[OpNumber
] += OpWorkCount
[OrigOpNumber
];
2059 OpWorkCount
[OrigOpNumber
] = 0;
2060 NumLeftToConsider
--;
2062 // Add if it's a new chain
2063 if (SeenChains
.insert(Op
).second
) {
2064 OpWorkCount
[OpNumber
]++;
2065 Worklist
.push_back(std::make_pair(Op
, OpNumber
));
2069 for (unsigned i
= 0; i
< Worklist
.size() && i
< 1024; ++i
) {
2070 // We need at least be consider at least 2 Ops to prune.
2071 if (NumLeftToConsider
<= 1)
2073 auto CurNode
= Worklist
[i
].first
;
2074 auto CurOpNumber
= Worklist
[i
].second
;
2075 assert((OpWorkCount
[CurOpNumber
] > 0) &&
2076 "Node should not appear in worklist");
2077 switch (CurNode
->getOpcode()) {
2078 case ISD::EntryToken
:
2079 // Hitting EntryToken is the only way for the search to terminate without
2081 // another operand's search. Prevent us from marking this operand
2083 NumLeftToConsider
++;
2085 case ISD::TokenFactor
:
2086 for (const SDValue
&Op
: CurNode
->op_values())
2087 AddToWorklist(i
, Op
.getNode(), CurOpNumber
);
2089 case ISD::LIFETIME_START
:
2090 case ISD::LIFETIME_END
:
2091 case ISD::CopyFromReg
:
2092 case ISD::CopyToReg
:
2093 AddToWorklist(i
, CurNode
->getOperand(0).getNode(), CurOpNumber
);
2096 if (auto *MemNode
= dyn_cast
<MemSDNode
>(CurNode
))
2097 AddToWorklist(i
, MemNode
->getChain().getNode(), CurOpNumber
);
2100 OpWorkCount
[CurOpNumber
]--;
2101 if (OpWorkCount
[CurOpNumber
] == 0)
2102 NumLeftToConsider
--;
2105 // If we've changed things around then replace token factor.
2109 // The entry token is the only possible outcome.
2110 Result
= DAG
.getEntryNode();
2113 SmallVector
<SDValue
, 8> PrunedOps
;
2115 for (const SDValue
&Op
: Ops
) {
2116 if (SeenChains
.count(Op
.getNode()) == 0)
2117 PrunedOps
.push_back(Op
);
2119 Result
= DAG
.getTokenFactor(SDLoc(N
), PrunedOps
);
2121 Result
= DAG
.getTokenFactor(SDLoc(N
), Ops
);
2129 /// MERGE_VALUES can always be eliminated.
2130 SDValue
DAGCombiner::visitMERGE_VALUES(SDNode
*N
) {
2131 WorklistRemover
DeadNodes(*this);
2132 // Replacing results may cause a different MERGE_VALUES to suddenly
2133 // be CSE'd with N, and carry its uses with it. Iterate until no
2134 // uses remain, to ensure that the node can be safely deleted.
2135 // First add the users of this node to the work list so that they
2136 // can be tried again once they have new operands.
2137 AddUsersToWorklist(N
);
2139 // Do as a single replacement to avoid rewalking use lists.
2140 SmallVector
<SDValue
, 8> Ops
;
2141 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
)
2142 Ops
.push_back(N
->getOperand(i
));
2143 DAG
.ReplaceAllUsesWith(N
, Ops
.data());
2144 } while (!N
->use_empty());
2145 deleteAndRecombine(N
);
2146 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
2149 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
2150 /// ConstantSDNode pointer else nullptr.
2151 static ConstantSDNode
*getAsNonOpaqueConstant(SDValue N
) {
2152 ConstantSDNode
*Const
= dyn_cast
<ConstantSDNode
>(N
);
2153 return Const
!= nullptr && !Const
->isOpaque() ? Const
: nullptr;
2156 SDValue
DAGCombiner::foldBinOpIntoSelect(SDNode
*BO
) {
2157 assert(TLI
.isBinOp(BO
->getOpcode()) && BO
->getNumValues() == 1 &&
2158 "Unexpected binary operator");
2160 // Don't do this unless the old select is going away. We want to eliminate the
2161 // binary operator, not replace a binop with a select.
2162 // TODO: Handle ISD::SELECT_CC.
2163 unsigned SelOpNo
= 0;
2164 SDValue Sel
= BO
->getOperand(0);
2165 if (Sel
.getOpcode() != ISD::SELECT
|| !Sel
.hasOneUse()) {
2167 Sel
= BO
->getOperand(1);
2170 if (Sel
.getOpcode() != ISD::SELECT
|| !Sel
.hasOneUse())
2173 SDValue CT
= Sel
.getOperand(1);
2174 if (!isConstantOrConstantVector(CT
, true) &&
2175 !isConstantFPBuildVectorOrConstantFP(CT
))
2178 SDValue CF
= Sel
.getOperand(2);
2179 if (!isConstantOrConstantVector(CF
, true) &&
2180 !isConstantFPBuildVectorOrConstantFP(CF
))
2183 // Bail out if any constants are opaque because we can't constant fold those.
2184 // The exception is "and" and "or" with either 0 or -1 in which case we can
2185 // propagate non constant operands into select. I.e.:
2186 // and (select Cond, 0, -1), X --> select Cond, 0, X
2187 // or X, (select Cond, -1, 0) --> select Cond, -1, X
2188 auto BinOpcode
= BO
->getOpcode();
2189 bool CanFoldNonConst
=
2190 (BinOpcode
== ISD::AND
|| BinOpcode
== ISD::OR
) &&
2191 (isNullOrNullSplat(CT
) || isAllOnesOrAllOnesSplat(CT
)) &&
2192 (isNullOrNullSplat(CF
) || isAllOnesOrAllOnesSplat(CF
));
2194 SDValue CBO
= BO
->getOperand(SelOpNo
^ 1);
2195 if (!CanFoldNonConst
&&
2196 !isConstantOrConstantVector(CBO
, true) &&
2197 !isConstantFPBuildVectorOrConstantFP(CBO
))
2200 EVT VT
= Sel
.getValueType();
2202 // In case of shift value and shift amount may have different VT. For instance
2203 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have
2204 // swapped operands and value types do not match. NB: x86 is fine if operands
2205 // are not swapped with shift amount VT being not bigger than shifted value.
2206 // TODO: that is possible to check for a shift operation, correct VTs and
2207 // still perform optimization on x86 if needed.
2208 if (SelOpNo
&& VT
!= CBO
.getValueType())
2211 // We have a select-of-constants followed by a binary operator with a
2212 // constant. Eliminate the binop by pulling the constant math into the select.
2213 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
2215 SDValue NewCT
= SelOpNo
? DAG
.getNode(BinOpcode
, DL
, VT
, CBO
, CT
)
2216 : DAG
.getNode(BinOpcode
, DL
, VT
, CT
, CBO
);
2217 if (!CanFoldNonConst
&& !NewCT
.isUndef() &&
2218 !isConstantOrConstantVector(NewCT
, true) &&
2219 !isConstantFPBuildVectorOrConstantFP(NewCT
))
2222 SDValue NewCF
= SelOpNo
? DAG
.getNode(BinOpcode
, DL
, VT
, CBO
, CF
)
2223 : DAG
.getNode(BinOpcode
, DL
, VT
, CF
, CBO
);
2224 if (!CanFoldNonConst
&& !NewCF
.isUndef() &&
2225 !isConstantOrConstantVector(NewCF
, true) &&
2226 !isConstantFPBuildVectorOrConstantFP(NewCF
))
2229 SDValue SelectOp
= DAG
.getSelect(DL
, VT
, Sel
.getOperand(0), NewCT
, NewCF
);
2230 SelectOp
->setFlags(BO
->getFlags());
2234 static SDValue
foldAddSubBoolOfMaskedVal(SDNode
*N
, SelectionDAG
&DAG
) {
2235 assert((N
->getOpcode() == ISD::ADD
|| N
->getOpcode() == ISD::SUB
) &&
2236 "Expecting add or sub");
2238 // Match a constant operand and a zext operand for the math instruction:
2241 bool IsAdd
= N
->getOpcode() == ISD::ADD
;
2242 SDValue C
= IsAdd
? N
->getOperand(1) : N
->getOperand(0);
2243 SDValue Z
= IsAdd
? N
->getOperand(0) : N
->getOperand(1);
2244 auto *CN
= dyn_cast
<ConstantSDNode
>(C
);
2245 if (!CN
|| Z
.getOpcode() != ISD::ZERO_EXTEND
)
2248 // Match the zext operand as a setcc of a boolean.
2249 if (Z
.getOperand(0).getOpcode() != ISD::SETCC
||
2250 Z
.getOperand(0).getValueType() != MVT::i1
)
2253 // Match the compare as: setcc (X & 1), 0, eq.
2254 SDValue SetCC
= Z
.getOperand(0);
2255 ISD::CondCode CC
= cast
<CondCodeSDNode
>(SetCC
->getOperand(2))->get();
2256 if (CC
!= ISD::SETEQ
|| !isNullConstant(SetCC
.getOperand(1)) ||
2257 SetCC
.getOperand(0).getOpcode() != ISD::AND
||
2258 !isOneConstant(SetCC
.getOperand(0).getOperand(1)))
2261 // We are adding/subtracting a constant and an inverted low bit. Turn that
2262 // into a subtract/add of the low bit with incremented/decremented constant:
2263 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
2264 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
2265 EVT VT
= C
.getValueType();
2267 SDValue LowBit
= DAG
.getZExtOrTrunc(SetCC
.getOperand(0), DL
, VT
);
2268 SDValue C1
= IsAdd
? DAG
.getConstant(CN
->getAPIntValue() + 1, DL
, VT
) :
2269 DAG
.getConstant(CN
->getAPIntValue() - 1, DL
, VT
);
2270 return DAG
.getNode(IsAdd
? ISD::SUB
: ISD::ADD
, DL
, VT
, C1
, LowBit
);
2273 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
2274 /// a shift and add with a different constant.
2275 static SDValue
foldAddSubOfSignBit(SDNode
*N
, SelectionDAG
&DAG
) {
2276 assert((N
->getOpcode() == ISD::ADD
|| N
->getOpcode() == ISD::SUB
) &&
2277 "Expecting add or sub");
2279 // We need a constant operand for the add/sub, and the other operand is a
2280 // logical shift right: add (srl), C or sub C, (srl).
2281 // TODO - support non-uniform vector amounts.
2282 bool IsAdd
= N
->getOpcode() == ISD::ADD
;
2283 SDValue ConstantOp
= IsAdd
? N
->getOperand(1) : N
->getOperand(0);
2284 SDValue ShiftOp
= IsAdd
? N
->getOperand(0) : N
->getOperand(1);
2285 ConstantSDNode
*C
= isConstOrConstSplat(ConstantOp
);
2286 if (!C
|| ShiftOp
.getOpcode() != ISD::SRL
)
2289 // The shift must be of a 'not' value.
2290 SDValue Not
= ShiftOp
.getOperand(0);
2291 if (!Not
.hasOneUse() || !isBitwiseNot(Not
))
2294 // The shift must be moving the sign bit to the least-significant-bit.
2295 EVT VT
= ShiftOp
.getValueType();
2296 SDValue ShAmt
= ShiftOp
.getOperand(1);
2297 ConstantSDNode
*ShAmtC
= isConstOrConstSplat(ShAmt
);
2298 if (!ShAmtC
|| ShAmtC
->getAPIntValue() != (VT
.getScalarSizeInBits() - 1))
2301 // Eliminate the 'not' by adjusting the shift and add/sub constant:
2302 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
2303 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
2305 auto ShOpcode
= IsAdd
? ISD::SRA
: ISD::SRL
;
2306 SDValue NewShift
= DAG
.getNode(ShOpcode
, DL
, VT
, Not
.getOperand(0), ShAmt
);
2307 APInt NewC
= IsAdd
? C
->getAPIntValue() + 1 : C
->getAPIntValue() - 1;
2308 return DAG
.getNode(ISD::ADD
, DL
, VT
, NewShift
, DAG
.getConstant(NewC
, DL
, VT
));
2311 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
2312 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
2313 /// are no common bits set in the operands).
2314 SDValue
DAGCombiner::visitADDLike(SDNode
*N
) {
2315 SDValue N0
= N
->getOperand(0);
2316 SDValue N1
= N
->getOperand(1);
2317 EVT VT
= N0
.getValueType();
2321 if (VT
.isVector()) {
2322 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
2325 // fold (add x, 0) -> x, vector edition
2326 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
2328 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
2332 // fold (add x, undef) -> undef
2339 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
2340 // canonicalize constant to RHS
2341 if (!DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2342 return DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, N0
);
2343 // fold (add c1, c2) -> c1+c2
2344 return DAG
.FoldConstantArithmetic(ISD::ADD
, DL
, VT
, N0
.getNode(),
2348 // fold (add x, 0) -> x
2349 if (isNullConstant(N1
))
2352 if (isConstantOrConstantVector(N1
, /* NoOpaque */ true)) {
2353 // fold ((A-c1)+c2) -> (A+(c2-c1))
2354 if (N0
.getOpcode() == ISD::SUB
&&
2355 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaque */ true)) {
2356 SDValue Sub
= DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N1
.getNode(),
2357 N0
.getOperand(1).getNode());
2358 assert(Sub
&& "Constant folding failed");
2359 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), Sub
);
2362 // fold ((c1-A)+c2) -> (c1+c2)-A
2363 if (N0
.getOpcode() == ISD::SUB
&&
2364 isConstantOrConstantVector(N0
.getOperand(0), /* NoOpaque */ true)) {
2365 SDValue Add
= DAG
.FoldConstantArithmetic(ISD::ADD
, DL
, VT
, N1
.getNode(),
2366 N0
.getOperand(0).getNode());
2367 assert(Add
&& "Constant folding failed");
2368 return DAG
.getNode(ISD::SUB
, DL
, VT
, Add
, N0
.getOperand(1));
2371 // add (sext i1 X), 1 -> zext (not i1 X)
2372 // We don't transform this pattern:
2373 // add (zext i1 X), -1 -> sext (not i1 X)
2374 // because most (?) targets generate better code for the zext form.
2375 if (N0
.getOpcode() == ISD::SIGN_EXTEND
&& N0
.hasOneUse() &&
2376 isOneOrOneSplat(N1
)) {
2377 SDValue X
= N0
.getOperand(0);
2378 if ((!LegalOperations
||
2379 (TLI
.isOperationLegal(ISD::XOR
, X
.getValueType()) &&
2380 TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
))) &&
2381 X
.getScalarValueSizeInBits() == 1) {
2382 SDValue Not
= DAG
.getNOT(DL
, X
, X
.getValueType());
2383 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Not
);
2387 // Undo the add -> or combine to merge constant offsets from a frame index.
2388 if (N0
.getOpcode() == ISD::OR
&&
2389 isa
<FrameIndexSDNode
>(N0
.getOperand(0)) &&
2390 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
2391 DAG
.haveNoCommonBitsSet(N0
.getOperand(0), N0
.getOperand(1))) {
2392 SDValue Add0
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, N0
.getOperand(1));
2393 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), Add0
);
2397 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
2401 if (!reassociationCanBreakAddressingModePattern(ISD::ADD
, DL
, N0
, N1
)) {
2402 if (SDValue RADD
= reassociateOps(ISD::ADD
, DL
, N0
, N1
, N
->getFlags()))
2405 // fold ((0-A) + B) -> B-A
2406 if (N0
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N0
.getOperand(0)))
2407 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, N0
.getOperand(1));
2409 // fold (A + (0-B)) -> A-B
2410 if (N1
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N1
.getOperand(0)))
2411 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
.getOperand(1));
2413 // fold (A+(B-A)) -> B
2414 if (N1
.getOpcode() == ISD::SUB
&& N0
== N1
.getOperand(1))
2415 return N1
.getOperand(0);
2417 // fold ((B-A)+A) -> B
2418 if (N0
.getOpcode() == ISD::SUB
&& N1
== N0
.getOperand(1))
2419 return N0
.getOperand(0);
2421 // fold ((A-B)+(C-A)) -> (C-B)
2422 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
&&
2423 N0
.getOperand(0) == N1
.getOperand(1))
2424 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2427 // fold ((A-B)+(B-C)) -> (A-C)
2428 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
&&
2429 N0
.getOperand(1) == N1
.getOperand(0))
2430 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0),
2433 // fold (A+(B-(A+C))) to (B-C)
2434 if (N1
.getOpcode() == ISD::SUB
&& N1
.getOperand(1).getOpcode() == ISD::ADD
&&
2435 N0
== N1
.getOperand(1).getOperand(0))
2436 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2437 N1
.getOperand(1).getOperand(1));
2439 // fold (A+(B-(C+A))) to (B-C)
2440 if (N1
.getOpcode() == ISD::SUB
&& N1
.getOperand(1).getOpcode() == ISD::ADD
&&
2441 N0
== N1
.getOperand(1).getOperand(1))
2442 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(0),
2443 N1
.getOperand(1).getOperand(0));
2445 // fold (A+((B-A)+or-C)) to (B+or-C)
2446 if ((N1
.getOpcode() == ISD::SUB
|| N1
.getOpcode() == ISD::ADD
) &&
2447 N1
.getOperand(0).getOpcode() == ISD::SUB
&&
2448 N0
== N1
.getOperand(0).getOperand(1))
2449 return DAG
.getNode(N1
.getOpcode(), DL
, VT
, N1
.getOperand(0).getOperand(0),
2452 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
2453 if (N0
.getOpcode() == ISD::SUB
&& N1
.getOpcode() == ISD::SUB
) {
2454 SDValue N00
= N0
.getOperand(0);
2455 SDValue N01
= N0
.getOperand(1);
2456 SDValue N10
= N1
.getOperand(0);
2457 SDValue N11
= N1
.getOperand(1);
2459 if (isConstantOrConstantVector(N00
) || isConstantOrConstantVector(N10
))
2460 return DAG
.getNode(ISD::SUB
, DL
, VT
,
2461 DAG
.getNode(ISD::ADD
, SDLoc(N0
), VT
, N00
, N10
),
2462 DAG
.getNode(ISD::ADD
, SDLoc(N1
), VT
, N01
, N11
));
2465 // fold (add (umax X, C), -C) --> (usubsat X, C)
2466 if (N0
.getOpcode() == ISD::UMAX
&& hasOperation(ISD::USUBSAT
, VT
)) {
2467 auto MatchUSUBSAT
= [](ConstantSDNode
*Max
, ConstantSDNode
*Op
) {
2468 return (!Max
&& !Op
) ||
2469 (Max
&& Op
&& Max
->getAPIntValue() == (-Op
->getAPIntValue()));
2471 if (ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchUSUBSAT
,
2472 /*AllowUndefs*/ true))
2473 return DAG
.getNode(ISD::USUBSAT
, DL
, VT
, N0
.getOperand(0),
2477 if (SimplifyDemandedBits(SDValue(N
, 0)))
2478 return SDValue(N
, 0);
2480 if (isOneOrOneSplat(N1
)) {
2481 // fold (add (xor a, -1), 1) -> (sub 0, a)
2482 if (isBitwiseNot(N0
))
2483 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
),
2486 // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
2487 if (N0
.getOpcode() == ISD::ADD
||
2488 N0
.getOpcode() == ISD::UADDO
||
2489 N0
.getOpcode() == ISD::SADDO
) {
2492 if (isBitwiseNot(N0
.getOperand(0))) {
2493 A
= N0
.getOperand(1);
2494 Xor
= N0
.getOperand(0);
2495 } else if (isBitwiseNot(N0
.getOperand(1))) {
2496 A
= N0
.getOperand(0);
2497 Xor
= N0
.getOperand(1);
2501 return DAG
.getNode(ISD::SUB
, DL
, VT
, A
, Xor
.getOperand(0));
2505 // add (add x, y), 1
2506 // And if the target does not like this form then turn into:
2507 // sub y, (xor x, -1)
2508 if (!TLI
.preferIncOfAddToSubOfNot(VT
) && N0
.hasOneUse() &&
2509 N0
.getOpcode() == ISD::ADD
) {
2510 SDValue Not
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(0),
2511 DAG
.getAllOnesConstant(DL
, VT
));
2512 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(1), Not
);
2516 // (x - y) + -1 -> add (xor y, -1), x
2517 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2518 isAllOnesOrAllOnesSplat(N1
)) {
2519 SDValue Xor
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(1), N1
);
2520 return DAG
.getNode(ISD::ADD
, DL
, VT
, Xor
, N0
.getOperand(0));
2523 if (SDValue Combined
= visitADDLikeCommutative(N0
, N1
, N
))
2526 if (SDValue Combined
= visitADDLikeCommutative(N1
, N0
, N
))
2532 SDValue
DAGCombiner::visitADD(SDNode
*N
) {
2533 SDValue N0
= N
->getOperand(0);
2534 SDValue N1
= N
->getOperand(1);
2535 EVT VT
= N0
.getValueType();
2538 if (SDValue Combined
= visitADDLike(N
))
2541 if (SDValue V
= foldAddSubBoolOfMaskedVal(N
, DAG
))
2544 if (SDValue V
= foldAddSubOfSignBit(N
, DAG
))
2547 // fold (a+b) -> (a|b) iff a and b share no bits.
2548 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::OR
, VT
)) &&
2549 DAG
.haveNoCommonBitsSet(N0
, N1
))
2550 return DAG
.getNode(ISD::OR
, DL
, VT
, N0
, N1
);
2555 SDValue
DAGCombiner::visitADDSAT(SDNode
*N
) {
2556 unsigned Opcode
= N
->getOpcode();
2557 SDValue N0
= N
->getOperand(0);
2558 SDValue N1
= N
->getOperand(1);
2559 EVT VT
= N0
.getValueType();
2563 if (VT
.isVector()) {
2564 // TODO SimplifyVBinOp
2566 // fold (add_sat x, 0) -> x, vector edition
2567 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
2569 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
2573 // fold (add_sat x, undef) -> -1
2574 if (N0
.isUndef() || N1
.isUndef())
2575 return DAG
.getAllOnesConstant(DL
, VT
);
2577 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
2578 // canonicalize constant to RHS
2579 if (!DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2580 return DAG
.getNode(Opcode
, DL
, VT
, N1
, N0
);
2581 // fold (add_sat c1, c2) -> c3
2582 return DAG
.FoldConstantArithmetic(Opcode
, DL
, VT
, N0
.getNode(),
2586 // fold (add_sat x, 0) -> x
2587 if (isNullConstant(N1
))
2590 // If it cannot overflow, transform into an add.
2591 if (Opcode
== ISD::UADDSAT
)
2592 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2593 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
);
2598 static SDValue
getAsCarry(const TargetLowering
&TLI
, SDValue V
) {
2599 bool Masked
= false;
2601 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
2603 if (V
.getOpcode() == ISD::TRUNCATE
|| V
.getOpcode() == ISD::ZERO_EXTEND
) {
2604 V
= V
.getOperand(0);
2608 if (V
.getOpcode() == ISD::AND
&& isOneConstant(V
.getOperand(1))) {
2610 V
= V
.getOperand(0);
2617 // If this is not a carry, return.
2618 if (V
.getResNo() != 1)
2621 if (V
.getOpcode() != ISD::ADDCARRY
&& V
.getOpcode() != ISD::SUBCARRY
&&
2622 V
.getOpcode() != ISD::UADDO
&& V
.getOpcode() != ISD::USUBO
)
2625 EVT VT
= V
.getNode()->getValueType(0);
2626 if (!TLI
.isOperationLegalOrCustom(V
.getOpcode(), VT
))
2629 // If the result is masked, then no matter what kind of bool it is we can
2630 // return. If it isn't, then we need to make sure the bool type is either 0 or
2631 // 1 and not other values.
2633 TLI
.getBooleanContents(V
.getValueType()) ==
2634 TargetLoweringBase::ZeroOrOneBooleanContent
)
2640 /// Given the operands of an add/sub operation, see if the 2nd operand is a
2641 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
2642 /// the opcode and bypass the mask operation.
2643 static SDValue
foldAddSubMasked1(bool IsAdd
, SDValue N0
, SDValue N1
,
2644 SelectionDAG
&DAG
, const SDLoc
&DL
) {
2645 if (N1
.getOpcode() != ISD::AND
|| !isOneOrOneSplat(N1
->getOperand(1)))
2648 EVT VT
= N0
.getValueType();
2649 if (DAG
.ComputeNumSignBits(N1
.getOperand(0)) != VT
.getScalarSizeInBits())
2652 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
2653 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
2654 return DAG
.getNode(IsAdd
? ISD::SUB
: ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(0));
2657 /// Helper for doing combines based on N0 and N1 being added to each other.
2658 SDValue
DAGCombiner::visitADDLikeCommutative(SDValue N0
, SDValue N1
,
2659 SDNode
*LocReference
) {
2660 EVT VT
= N0
.getValueType();
2661 SDLoc
DL(LocReference
);
2663 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2664 if (N1
.getOpcode() == ISD::SHL
&& N1
.getOperand(0).getOpcode() == ISD::SUB
&&
2665 isNullOrNullSplat(N1
.getOperand(0).getOperand(0)))
2666 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
,
2667 DAG
.getNode(ISD::SHL
, DL
, VT
,
2668 N1
.getOperand(0).getOperand(1),
2671 if (SDValue V
= foldAddSubMasked1(true, N0
, N1
, DAG
, DL
))
2675 // add (add x, 1), y
2676 // And if the target does not like this form then turn into:
2677 // sub y, (xor x, -1)
2678 if (!TLI
.preferIncOfAddToSubOfNot(VT
) && N0
.hasOneUse() &&
2679 N0
.getOpcode() == ISD::ADD
&& isOneOrOneSplat(N0
.getOperand(1))) {
2680 SDValue Not
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(0),
2681 DAG
.getAllOnesConstant(DL
, VT
));
2682 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, Not
);
2685 // Hoist one-use subtraction by non-opaque constant:
2686 // (x - C) + y -> (x + y) - C
2687 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
2688 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2689 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
2690 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), N1
);
2691 return DAG
.getNode(ISD::SUB
, DL
, VT
, Add
, N0
.getOperand(1));
2693 // Hoist one-use subtraction from non-opaque constant:
2694 // (C - x) + y -> (y - x) + C
2695 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
2696 isConstantOrConstantVector(N0
.getOperand(0), /*NoOpaques=*/true)) {
2697 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, N0
.getOperand(1));
2698 return DAG
.getNode(ISD::ADD
, DL
, VT
, Sub
, N0
.getOperand(0));
2701 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
2702 // rather than 'add 0/-1' (the zext should get folded).
2703 // add (sext i1 Y), X --> sub X, (zext i1 Y)
2704 if (N0
.getOpcode() == ISD::SIGN_EXTEND
&&
2705 N0
.getOperand(0).getScalarValueSizeInBits() == 1 &&
2706 TLI
.getBooleanContents(VT
) == TargetLowering::ZeroOrOneBooleanContent
) {
2707 SDValue ZExt
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
.getOperand(0));
2708 return DAG
.getNode(ISD::SUB
, DL
, VT
, N1
, ZExt
);
2711 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2712 if (N1
.getOpcode() == ISD::SIGN_EXTEND_INREG
) {
2713 VTSDNode
*TN
= cast
<VTSDNode
>(N1
.getOperand(1));
2714 if (TN
->getVT() == MVT::i1
) {
2715 SDValue ZExt
= DAG
.getNode(ISD::AND
, DL
, VT
, N1
.getOperand(0),
2716 DAG
.getConstant(1, DL
, VT
));
2717 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, ZExt
);
2721 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2722 if (N1
.getOpcode() == ISD::ADDCARRY
&& isNullConstant(N1
.getOperand(1)) &&
2724 return DAG
.getNode(ISD::ADDCARRY
, DL
, N1
->getVTList(),
2725 N0
, N1
.getOperand(0), N1
.getOperand(2));
2727 // (add X, Carry) -> (addcarry X, 0, Carry)
2728 if (TLI
.isOperationLegalOrCustom(ISD::ADDCARRY
, VT
))
2729 if (SDValue Carry
= getAsCarry(TLI
, N1
))
2730 return DAG
.getNode(ISD::ADDCARRY
, DL
,
2731 DAG
.getVTList(VT
, Carry
.getValueType()), N0
,
2732 DAG
.getConstant(0, DL
, VT
), Carry
);
2737 SDValue
DAGCombiner::visitADDC(SDNode
*N
) {
2738 SDValue N0
= N
->getOperand(0);
2739 SDValue N1
= N
->getOperand(1);
2740 EVT VT
= N0
.getValueType();
2743 // If the flag result is dead, turn this into an ADD.
2744 if (!N
->hasAnyUseOfValue(1))
2745 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2746 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
2748 // canonicalize constant to RHS.
2749 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2750 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2752 return DAG
.getNode(ISD::ADDC
, DL
, N
->getVTList(), N1
, N0
);
2754 // fold (addc x, 0) -> x + no carry out
2755 if (isNullConstant(N1
))
2756 return CombineTo(N
, N0
, DAG
.getNode(ISD::CARRY_FALSE
,
2759 // If it cannot overflow, transform into an add.
2760 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2761 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2762 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
2767 static SDValue
flipBoolean(SDValue V
, const SDLoc
&DL
,
2768 SelectionDAG
&DAG
, const TargetLowering
&TLI
) {
2769 EVT VT
= V
.getValueType();
2772 switch (TLI
.getBooleanContents(VT
)) {
2773 case TargetLowering::ZeroOrOneBooleanContent
:
2774 case TargetLowering::UndefinedBooleanContent
:
2775 Cst
= DAG
.getConstant(1, DL
, VT
);
2777 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2778 Cst
= DAG
.getAllOnesConstant(DL
, VT
);
2782 return DAG
.getNode(ISD::XOR
, DL
, VT
, V
, Cst
);
2786 * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
2787 * then the flip also occurs if computing the inverse is the same cost.
2788 * This function returns an empty SDValue in case it cannot flip the boolean
2789 * without increasing the cost of the computation. If you want to flip a boolean
2790 * no matter what, use flipBoolean.
2792 static SDValue
extractBooleanFlip(SDValue V
, SelectionDAG
&DAG
,
2793 const TargetLowering
&TLI
,
2795 if (Force
&& isa
<ConstantSDNode
>(V
))
2796 return flipBoolean(V
, SDLoc(V
), DAG
, TLI
);
2798 if (V
.getOpcode() != ISD::XOR
)
2801 ConstantSDNode
*Const
= isConstOrConstSplat(V
.getOperand(1), false);
2805 EVT VT
= V
.getValueType();
2807 bool IsFlip
= false;
2808 switch(TLI
.getBooleanContents(VT
)) {
2809 case TargetLowering::ZeroOrOneBooleanContent
:
2810 IsFlip
= Const
->isOne();
2812 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2813 IsFlip
= Const
->isAllOnesValue();
2815 case TargetLowering::UndefinedBooleanContent
:
2816 IsFlip
= (Const
->getAPIntValue() & 0x01) == 1;
2821 return V
.getOperand(0);
2823 return flipBoolean(V
, SDLoc(V
), DAG
, TLI
);
2827 SDValue
DAGCombiner::visitADDO(SDNode
*N
) {
2828 SDValue N0
= N
->getOperand(0);
2829 SDValue N1
= N
->getOperand(1);
2830 EVT VT
= N0
.getValueType();
2831 bool IsSigned
= (ISD::SADDO
== N
->getOpcode());
2833 EVT CarryVT
= N
->getValueType(1);
2836 // If the flag result is dead, turn this into an ADD.
2837 if (!N
->hasAnyUseOfValue(1))
2838 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2839 DAG
.getUNDEF(CarryVT
));
2841 // canonicalize constant to RHS.
2842 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
2843 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
2844 return DAG
.getNode(N
->getOpcode(), DL
, N
->getVTList(), N1
, N0
);
2846 // fold (addo x, 0) -> x + no carry out
2847 if (isNullOrNullSplat(N1
))
2848 return CombineTo(N
, N0
, DAG
.getConstant(0, DL
, CarryVT
));
2851 // If it cannot overflow, transform into an add.
2852 if (DAG
.computeOverflowKind(N0
, N1
) == SelectionDAG::OFK_Never
)
2853 return CombineTo(N
, DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
),
2854 DAG
.getConstant(0, DL
, CarryVT
));
2856 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
2857 if (isBitwiseNot(N0
) && isOneOrOneSplat(N1
)) {
2858 SDValue Sub
= DAG
.getNode(ISD::USUBO
, DL
, N
->getVTList(),
2859 DAG
.getConstant(0, DL
, VT
), N0
.getOperand(0));
2860 return CombineTo(N
, Sub
,
2861 flipBoolean(Sub
.getValue(1), DL
, DAG
, TLI
));
2864 if (SDValue Combined
= visitUADDOLike(N0
, N1
, N
))
2867 if (SDValue Combined
= visitUADDOLike(N1
, N0
, N
))
2874 SDValue
DAGCombiner::visitUADDOLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
2875 EVT VT
= N0
.getValueType();
2879 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2880 // If Y + 1 cannot overflow.
2881 if (N1
.getOpcode() == ISD::ADDCARRY
&& isNullConstant(N1
.getOperand(1))) {
2882 SDValue Y
= N1
.getOperand(0);
2883 SDValue One
= DAG
.getConstant(1, SDLoc(N
), Y
.getValueType());
2884 if (DAG
.computeOverflowKind(Y
, One
) == SelectionDAG::OFK_Never
)
2885 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(), N0
, Y
,
2889 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2890 if (TLI
.isOperationLegalOrCustom(ISD::ADDCARRY
, VT
))
2891 if (SDValue Carry
= getAsCarry(TLI
, N1
))
2892 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(), N0
,
2893 DAG
.getConstant(0, SDLoc(N
), VT
), Carry
);
2898 SDValue
DAGCombiner::visitADDE(SDNode
*N
) {
2899 SDValue N0
= N
->getOperand(0);
2900 SDValue N1
= N
->getOperand(1);
2901 SDValue CarryIn
= N
->getOperand(2);
2903 // canonicalize constant to RHS
2904 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2905 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2907 return DAG
.getNode(ISD::ADDE
, SDLoc(N
), N
->getVTList(),
2910 // fold (adde x, y, false) -> (addc x, y)
2911 if (CarryIn
.getOpcode() == ISD::CARRY_FALSE
)
2912 return DAG
.getNode(ISD::ADDC
, SDLoc(N
), N
->getVTList(), N0
, N1
);
2917 SDValue
DAGCombiner::visitADDCARRY(SDNode
*N
) {
2918 SDValue N0
= N
->getOperand(0);
2919 SDValue N1
= N
->getOperand(1);
2920 SDValue CarryIn
= N
->getOperand(2);
2923 // canonicalize constant to RHS
2924 ConstantSDNode
*N0C
= dyn_cast
<ConstantSDNode
>(N0
);
2925 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
2927 return DAG
.getNode(ISD::ADDCARRY
, DL
, N
->getVTList(), N1
, N0
, CarryIn
);
2929 // fold (addcarry x, y, false) -> (uaddo x, y)
2930 if (isNullConstant(CarryIn
)) {
2931 if (!LegalOperations
||
2932 TLI
.isOperationLegalOrCustom(ISD::UADDO
, N
->getValueType(0)))
2933 return DAG
.getNode(ISD::UADDO
, DL
, N
->getVTList(), N0
, N1
);
2936 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2937 if (isNullConstant(N0
) && isNullConstant(N1
)) {
2938 EVT VT
= N0
.getValueType();
2939 EVT CarryVT
= CarryIn
.getValueType();
2940 SDValue CarryExt
= DAG
.getBoolExtOrTrunc(CarryIn
, DL
, VT
, CarryVT
);
2941 AddToWorklist(CarryExt
.getNode());
2942 return CombineTo(N
, DAG
.getNode(ISD::AND
, DL
, VT
, CarryExt
,
2943 DAG
.getConstant(1, DL
, VT
)),
2944 DAG
.getConstant(0, DL
, CarryVT
));
2947 if (SDValue Combined
= visitADDCARRYLike(N0
, N1
, CarryIn
, N
))
2950 if (SDValue Combined
= visitADDCARRYLike(N1
, N0
, CarryIn
, N
))
2957 * If we are facing some sort of diamond carry propapagtion pattern try to
2958 * break it up to generate something like:
2959 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2961 * The end result is usually an increase in operation required, but because the
2962 * carry is now linearized, other tranforms can kick in and optimize the DAG.
2964 * Patterns typically look something like
2969 * | (addcarry *, 0, Z)
2973 * (addcarry X, *, *)
2975 * But numerous variation exist. Our goal is to identify A, B, X and Z and
2976 * produce a combine with a single path for carry propagation.
2978 static SDValue
combineADDCARRYDiamond(DAGCombiner
&Combiner
, SelectionDAG
&DAG
,
2979 SDValue X
, SDValue Carry0
, SDValue Carry1
,
2981 if (Carry1
.getResNo() != 1 || Carry0
.getResNo() != 1)
2983 if (Carry1
.getOpcode() != ISD::UADDO
)
2989 * First look for a suitable Z. It will present itself in the form of
2990 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
2992 if (Carry0
.getOpcode() == ISD::ADDCARRY
&&
2993 isNullConstant(Carry0
.getOperand(1))) {
2994 Z
= Carry0
.getOperand(2);
2995 } else if (Carry0
.getOpcode() == ISD::UADDO
&&
2996 isOneConstant(Carry0
.getOperand(1))) {
2997 EVT VT
= Combiner
.getSetCCResultType(Carry0
.getValueType());
2998 Z
= DAG
.getConstant(1, SDLoc(Carry0
.getOperand(1)), VT
);
3000 // We couldn't find a suitable Z.
3005 auto cancelDiamond
= [&](SDValue A
,SDValue B
) {
3007 SDValue NewY
= DAG
.getNode(ISD::ADDCARRY
, DL
, Carry0
->getVTList(), A
, B
, Z
);
3008 Combiner
.AddToWorklist(NewY
.getNode());
3009 return DAG
.getNode(ISD::ADDCARRY
, DL
, N
->getVTList(), X
,
3010 DAG
.getConstant(0, DL
, X
.getValueType()),
3019 * (addcarry *, 0, Z)
3021 if (Carry0
.getOperand(0) == Carry1
.getValue(0)) {
3022 return cancelDiamond(Carry1
.getOperand(0), Carry1
.getOperand(1));
3026 * (addcarry A, 0, Z)
3032 if (Carry1
.getOperand(0) == Carry0
.getValue(0)) {
3033 return cancelDiamond(Carry0
.getOperand(0), Carry1
.getOperand(1));
3036 if (Carry1
.getOperand(1) == Carry0
.getValue(0)) {
3037 return cancelDiamond(Carry1
.getOperand(0), Carry0
.getOperand(0));
3043 SDValue
DAGCombiner::visitADDCARRYLike(SDValue N0
, SDValue N1
, SDValue CarryIn
,
3045 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
3046 if (isBitwiseNot(N0
))
3047 if (SDValue NotC
= extractBooleanFlip(CarryIn
, DAG
, TLI
, true)) {
3049 SDValue Sub
= DAG
.getNode(ISD::SUBCARRY
, DL
, N
->getVTList(), N1
,
3050 N0
.getOperand(0), NotC
);
3051 return CombineTo(N
, Sub
,
3052 flipBoolean(Sub
.getValue(1), DL
, DAG
, TLI
));
3055 // Iff the flag result is dead:
3056 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
3057 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
3058 // or the dependency between the instructions.
3059 if ((N0
.getOpcode() == ISD::ADD
||
3060 (N0
.getOpcode() == ISD::UADDO
&& N0
.getResNo() == 0 &&
3061 N0
.getValue(1) != CarryIn
)) &&
3062 isNullConstant(N1
) && !N
->hasAnyUseOfValue(1))
3063 return DAG
.getNode(ISD::ADDCARRY
, SDLoc(N
), N
->getVTList(),
3064 N0
.getOperand(0), N0
.getOperand(1), CarryIn
);
3067 * When one of the addcarry argument is itself a carry, we may be facing
3068 * a diamond carry propagation. In which case we try to transform the DAG
3069 * to ensure linear carry propagation if that is possible.
3071 if (auto Y
= getAsCarry(TLI
, N1
)) {
3072 // Because both are carries, Y and Z can be swapped.
3073 if (auto R
= combineADDCARRYDiamond(*this, DAG
, N0
, Y
, CarryIn
, N
))
3075 if (auto R
= combineADDCARRYDiamond(*this, DAG
, N0
, CarryIn
, Y
, N
))
3082 // Since it may not be valid to emit a fold to zero for vector initializers
3083 // check if we can before folding.
3084 static SDValue
tryFoldToZero(const SDLoc
&DL
, const TargetLowering
&TLI
, EVT VT
,
3085 SelectionDAG
&DAG
, bool LegalOperations
) {
3087 return DAG
.getConstant(0, DL
, VT
);
3088 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
3089 return DAG
.getConstant(0, DL
, VT
);
3093 SDValue
DAGCombiner::visitSUB(SDNode
*N
) {
3094 SDValue N0
= N
->getOperand(0);
3095 SDValue N1
= N
->getOperand(1);
3096 EVT VT
= N0
.getValueType();
3100 if (VT
.isVector()) {
3101 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3104 // fold (sub x, 0) -> x, vector edition
3105 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
3109 // fold (sub x, x) -> 0
3110 // FIXME: Refactor this and xor and other similar operations together.
3112 return tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
3113 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3114 DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
3115 // fold (sub c1, c2) -> c1-c2
3116 return DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N0
.getNode(),
3120 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3123 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
3125 // fold (sub x, c) -> (add x, -c)
3127 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
,
3128 DAG
.getConstant(-N1C
->getAPIntValue(), DL
, VT
));
3131 if (isNullOrNullSplat(N0
)) {
3132 unsigned BitWidth
= VT
.getScalarSizeInBits();
3133 // Right-shifting everything out but the sign bit followed by negation is
3134 // the same as flipping arithmetic/logical shift type without the negation:
3135 // -(X >>u 31) -> (X >>s 31)
3136 // -(X >>s 31) -> (X >>u 31)
3137 if (N1
->getOpcode() == ISD::SRA
|| N1
->getOpcode() == ISD::SRL
) {
3138 ConstantSDNode
*ShiftAmt
= isConstOrConstSplat(N1
.getOperand(1));
3139 if (ShiftAmt
&& ShiftAmt
->getAPIntValue() == (BitWidth
- 1)) {
3140 auto NewSh
= N1
->getOpcode() == ISD::SRA
? ISD::SRL
: ISD::SRA
;
3141 if (!LegalOperations
|| TLI
.isOperationLegal(NewSh
, VT
))
3142 return DAG
.getNode(NewSh
, DL
, VT
, N1
.getOperand(0), N1
.getOperand(1));
3146 // 0 - X --> 0 if the sub is NUW.
3147 if (N
->getFlags().hasNoUnsignedWrap())
3150 if (DAG
.MaskedValueIsZero(N1
, ~APInt::getSignMask(BitWidth
))) {
3151 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
3152 // N1 must be 0 because negating the minimum signed value is undefined.
3153 if (N
->getFlags().hasNoSignedWrap())
3156 // 0 - X --> X if X is 0 or the minimum signed value.
3161 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
3162 if (isAllOnesOrAllOnesSplat(N0
))
3163 return DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
);
3165 // fold (A - (0-B)) -> A+B
3166 if (N1
.getOpcode() == ISD::SUB
&& isNullOrNullSplat(N1
.getOperand(0)))
3167 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(1));
3169 // fold A-(A-B) -> B
3170 if (N1
.getOpcode() == ISD::SUB
&& N0
== N1
.getOperand(0))
3171 return N1
.getOperand(1);
3173 // fold (A+B)-A -> B
3174 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(0) == N1
)
3175 return N0
.getOperand(1);
3177 // fold (A+B)-B -> A
3178 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1) == N1
)
3179 return N0
.getOperand(0);
3181 // fold (A+C1)-C2 -> A+(C1-C2)
3182 if (N0
.getOpcode() == ISD::ADD
&&
3183 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3184 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3185 SDValue NewC
= DAG
.FoldConstantArithmetic(
3186 ISD::SUB
, DL
, VT
, N0
.getOperand(1).getNode(), N1
.getNode());
3187 assert(NewC
&& "Constant folding failed");
3188 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0), NewC
);
3191 // fold C2-(A+C1) -> (C2-C1)-A
3192 if (N1
.getOpcode() == ISD::ADD
) {
3193 SDValue N11
= N1
.getOperand(1);
3194 if (isConstantOrConstantVector(N0
, /* NoOpaques */ true) &&
3195 isConstantOrConstantVector(N11
, /* NoOpaques */ true)) {
3196 SDValue NewC
= DAG
.FoldConstantArithmetic(ISD::SUB
, DL
, VT
, N0
.getNode(),
3198 assert(NewC
&& "Constant folding failed");
3199 return DAG
.getNode(ISD::SUB
, DL
, VT
, NewC
, N1
.getOperand(0));
3203 // fold (A-C1)-C2 -> A-(C1+C2)
3204 if (N0
.getOpcode() == ISD::SUB
&&
3205 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3206 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3207 SDValue NewC
= DAG
.FoldConstantArithmetic(
3208 ISD::ADD
, DL
, VT
, N0
.getOperand(1).getNode(), N1
.getNode());
3209 assert(NewC
&& "Constant folding failed");
3210 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), NewC
);
3213 // fold (c1-A)-c2 -> (c1-c2)-A
3214 if (N0
.getOpcode() == ISD::SUB
&&
3215 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3216 isConstantOrConstantVector(N0
.getOperand(0), /* NoOpaques */ true)) {
3217 SDValue NewC
= DAG
.FoldConstantArithmetic(
3218 ISD::SUB
, DL
, VT
, N0
.getOperand(0).getNode(), N1
.getNode());
3219 assert(NewC
&& "Constant folding failed");
3220 return DAG
.getNode(ISD::SUB
, DL
, VT
, NewC
, N0
.getOperand(1));
3223 // fold ((A+(B+or-C))-B) -> A+or-C
3224 if (N0
.getOpcode() == ISD::ADD
&&
3225 (N0
.getOperand(1).getOpcode() == ISD::SUB
||
3226 N0
.getOperand(1).getOpcode() == ISD::ADD
) &&
3227 N0
.getOperand(1).getOperand(0) == N1
)
3228 return DAG
.getNode(N0
.getOperand(1).getOpcode(), DL
, VT
, N0
.getOperand(0),
3229 N0
.getOperand(1).getOperand(1));
3231 // fold ((A+(C+B))-B) -> A+C
3232 if (N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1).getOpcode() == ISD::ADD
&&
3233 N0
.getOperand(1).getOperand(1) == N1
)
3234 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(0),
3235 N0
.getOperand(1).getOperand(0));
3237 // fold ((A-(B-C))-C) -> A-B
3238 if (N0
.getOpcode() == ISD::SUB
&& N0
.getOperand(1).getOpcode() == ISD::SUB
&&
3239 N0
.getOperand(1).getOperand(1) == N1
)
3240 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0),
3241 N0
.getOperand(1).getOperand(0));
3243 // fold (A-(B-C)) -> A+(C-B)
3244 if (N1
.getOpcode() == ISD::SUB
&& N1
.hasOneUse())
3245 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
,
3246 DAG
.getNode(ISD::SUB
, DL
, VT
, N1
.getOperand(1),
3249 // fold (X - (-Y * Z)) -> (X + (Y * Z))
3250 if (N1
.getOpcode() == ISD::MUL
&& N1
.hasOneUse()) {
3251 if (N1
.getOperand(0).getOpcode() == ISD::SUB
&&
3252 isNullOrNullSplat(N1
.getOperand(0).getOperand(0))) {
3253 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
,
3254 N1
.getOperand(0).getOperand(1),
3256 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Mul
);
3258 if (N1
.getOperand(1).getOpcode() == ISD::SUB
&&
3259 isNullOrNullSplat(N1
.getOperand(1).getOperand(0))) {
3260 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
,
3262 N1
.getOperand(1).getOperand(1));
3263 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Mul
);
3267 // If either operand of a sub is undef, the result is undef
3273 if (SDValue V
= foldAddSubBoolOfMaskedVal(N
, DAG
))
3276 if (SDValue V
= foldAddSubOfSignBit(N
, DAG
))
3279 if (SDValue V
= foldAddSubMasked1(false, N0
, N1
, DAG
, SDLoc(N
)))
3282 // (x - y) - 1 -> add (xor y, -1), x
3283 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&& isOneOrOneSplat(N1
)) {
3284 SDValue Xor
= DAG
.getNode(ISD::XOR
, DL
, VT
, N0
.getOperand(1),
3285 DAG
.getAllOnesConstant(DL
, VT
));
3286 return DAG
.getNode(ISD::ADD
, DL
, VT
, Xor
, N0
.getOperand(0));
3290 // sub y, (xor x, -1)
3291 // And if the target does not like this form then turn into:
3292 // add (add x, y), 1
3293 if (TLI
.preferIncOfAddToSubOfNot(VT
) && N1
.hasOneUse() && isBitwiseNot(N1
)) {
3294 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, N1
.getOperand(0));
3295 return DAG
.getNode(ISD::ADD
, DL
, VT
, Add
, DAG
.getConstant(1, DL
, VT
));
3298 // Hoist one-use addition by non-opaque constant:
3299 // (x + C) - y -> (x - y) + C
3300 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::ADD
&&
3301 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
3302 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), N1
);
3303 return DAG
.getNode(ISD::ADD
, DL
, VT
, Sub
, N0
.getOperand(1));
3305 // y - (x + C) -> (y - x) - C
3306 if (N1
.hasOneUse() && N1
.getOpcode() == ISD::ADD
&&
3307 isConstantOrConstantVector(N1
.getOperand(1), /*NoOpaques=*/true)) {
3308 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
.getOperand(0));
3309 return DAG
.getNode(ISD::SUB
, DL
, VT
, Sub
, N1
.getOperand(1));
3311 // (x - C) - y -> (x - y) - C
3312 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
3313 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
3314 isConstantOrConstantVector(N0
.getOperand(1), /*NoOpaques=*/true)) {
3315 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), N1
);
3316 return DAG
.getNode(ISD::SUB
, DL
, VT
, Sub
, N0
.getOperand(1));
3318 // (C - x) - y -> C - (x + y)
3319 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::SUB
&&
3320 isConstantOrConstantVector(N0
.getOperand(0), /*NoOpaques=*/true)) {
3321 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(1), N1
);
3322 return DAG
.getNode(ISD::SUB
, DL
, VT
, N0
.getOperand(0), Add
);
3325 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
3326 // rather than 'sub 0/1' (the sext should get folded).
3327 // sub X, (zext i1 Y) --> add X, (sext i1 Y)
3328 if (N1
.getOpcode() == ISD::ZERO_EXTEND
&&
3329 N1
.getOperand(0).getScalarValueSizeInBits() == 1 &&
3330 TLI
.getBooleanContents(VT
) ==
3331 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
3332 SDValue SExt
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, N1
.getOperand(0));
3333 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, SExt
);
3336 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
3337 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
)) {
3338 if (N0
.getOpcode() == ISD::XOR
&& N1
.getOpcode() == ISD::SRA
) {
3339 SDValue X0
= N0
.getOperand(0), X1
= N0
.getOperand(1);
3340 SDValue S0
= N1
.getOperand(0);
3341 if ((X0
== S0
&& X1
== N1
) || (X0
== N1
&& X1
== S0
)) {
3342 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
3343 if (ConstantSDNode
*C
= isConstOrConstSplat(N1
.getOperand(1)))
3344 if (C
->getAPIntValue() == (OpSizeInBits
- 1))
3345 return DAG
.getNode(ISD::ABS
, SDLoc(N
), VT
, S0
);
3350 // If the relocation model supports it, consider symbol offsets.
3351 if (GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(N0
))
3352 if (!LegalOperations
&& TLI
.isOffsetFoldingLegal(GA
)) {
3353 // fold (sub Sym, c) -> Sym-c
3354 if (N1C
&& GA
->getOpcode() == ISD::GlobalAddress
)
3355 return DAG
.getGlobalAddress(GA
->getGlobal(), SDLoc(N1C
), VT
,
3357 (uint64_t)N1C
->getSExtValue());
3358 // fold (sub Sym+c1, Sym+c2) -> c1-c2
3359 if (GlobalAddressSDNode
*GB
= dyn_cast
<GlobalAddressSDNode
>(N1
))
3360 if (GA
->getGlobal() == GB
->getGlobal())
3361 return DAG
.getConstant((uint64_t)GA
->getOffset() - GB
->getOffset(),
3365 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
3366 if (N1
.getOpcode() == ISD::SIGN_EXTEND_INREG
) {
3367 VTSDNode
*TN
= cast
<VTSDNode
>(N1
.getOperand(1));
3368 if (TN
->getVT() == MVT::i1
) {
3369 SDValue ZExt
= DAG
.getNode(ISD::AND
, DL
, VT
, N1
.getOperand(0),
3370 DAG
.getConstant(1, DL
, VT
));
3371 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, ZExt
);
3375 // Prefer an add for more folding potential and possibly better codegen:
3376 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
3377 if (!LegalOperations
&& N1
.getOpcode() == ISD::SRL
&& N1
.hasOneUse()) {
3378 SDValue ShAmt
= N1
.getOperand(1);
3379 ConstantSDNode
*ShAmtC
= isConstOrConstSplat(ShAmt
);
3381 ShAmtC
->getAPIntValue() == (N1
.getScalarValueSizeInBits() - 1)) {
3382 SDValue SRA
= DAG
.getNode(ISD::SRA
, DL
, VT
, N1
.getOperand(0), ShAmt
);
3383 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, SRA
);
3390 SDValue
DAGCombiner::visitSUBSAT(SDNode
*N
) {
3391 SDValue N0
= N
->getOperand(0);
3392 SDValue N1
= N
->getOperand(1);
3393 EVT VT
= N0
.getValueType();
3397 if (VT
.isVector()) {
3398 // TODO SimplifyVBinOp
3400 // fold (sub_sat x, 0) -> x, vector edition
3401 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
3405 // fold (sub_sat x, undef) -> 0
3406 if (N0
.isUndef() || N1
.isUndef())
3407 return DAG
.getConstant(0, DL
, VT
);
3409 // fold (sub_sat x, x) -> 0
3411 return DAG
.getConstant(0, DL
, VT
);
3413 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3414 DAG
.isConstantIntBuildVectorOrConstantInt(N1
)) {
3415 // fold (sub_sat c1, c2) -> c3
3416 return DAG
.FoldConstantArithmetic(N
->getOpcode(), DL
, VT
, N0
.getNode(),
3420 // fold (sub_sat x, 0) -> x
3421 if (isNullConstant(N1
))
3427 SDValue
DAGCombiner::visitSUBC(SDNode
*N
) {
3428 SDValue N0
= N
->getOperand(0);
3429 SDValue N1
= N
->getOperand(1);
3430 EVT VT
= N0
.getValueType();
3433 // If the flag result is dead, turn this into an SUB.
3434 if (!N
->hasAnyUseOfValue(1))
3435 return CombineTo(N
, DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
),
3436 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3438 // fold (subc x, x) -> 0 + no borrow
3440 return CombineTo(N
, DAG
.getConstant(0, DL
, VT
),
3441 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3443 // fold (subc x, 0) -> x + no borrow
3444 if (isNullConstant(N1
))
3445 return CombineTo(N
, N0
, DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3447 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3448 if (isAllOnesConstant(N0
))
3449 return CombineTo(N
, DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
),
3450 DAG
.getNode(ISD::CARRY_FALSE
, DL
, MVT::Glue
));
3455 SDValue
DAGCombiner::visitSUBO(SDNode
*N
) {
3456 SDValue N0
= N
->getOperand(0);
3457 SDValue N1
= N
->getOperand(1);
3458 EVT VT
= N0
.getValueType();
3459 bool IsSigned
= (ISD::SSUBO
== N
->getOpcode());
3461 EVT CarryVT
= N
->getValueType(1);
3464 // If the flag result is dead, turn this into an SUB.
3465 if (!N
->hasAnyUseOfValue(1))
3466 return CombineTo(N
, DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, N1
),
3467 DAG
.getUNDEF(CarryVT
));
3469 // fold (subo x, x) -> 0 + no borrow
3471 return CombineTo(N
, DAG
.getConstant(0, DL
, VT
),
3472 DAG
.getConstant(0, DL
, CarryVT
));
3474 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
3476 // fold (subox, c) -> (addo x, -c)
3477 if (IsSigned
&& N1C
&& !N1C
->getAPIntValue().isMinSignedValue()) {
3478 return DAG
.getNode(ISD::SADDO
, DL
, N
->getVTList(), N0
,
3479 DAG
.getConstant(-N1C
->getAPIntValue(), DL
, VT
));
3482 // fold (subo x, 0) -> x + no borrow
3483 if (isNullOrNullSplat(N1
))
3484 return CombineTo(N
, N0
, DAG
.getConstant(0, DL
, CarryVT
));
3486 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
3487 if (!IsSigned
&& isAllOnesOrAllOnesSplat(N0
))
3488 return CombineTo(N
, DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
),
3489 DAG
.getConstant(0, DL
, CarryVT
));
3494 SDValue
DAGCombiner::visitSUBE(SDNode
*N
) {
3495 SDValue N0
= N
->getOperand(0);
3496 SDValue N1
= N
->getOperand(1);
3497 SDValue CarryIn
= N
->getOperand(2);
3499 // fold (sube x, y, false) -> (subc x, y)
3500 if (CarryIn
.getOpcode() == ISD::CARRY_FALSE
)
3501 return DAG
.getNode(ISD::SUBC
, SDLoc(N
), N
->getVTList(), N0
, N1
);
3506 SDValue
DAGCombiner::visitSUBCARRY(SDNode
*N
) {
3507 SDValue N0
= N
->getOperand(0);
3508 SDValue N1
= N
->getOperand(1);
3509 SDValue CarryIn
= N
->getOperand(2);
3511 // fold (subcarry x, y, false) -> (usubo x, y)
3512 if (isNullConstant(CarryIn
)) {
3513 if (!LegalOperations
||
3514 TLI
.isOperationLegalOrCustom(ISD::USUBO
, N
->getValueType(0)))
3515 return DAG
.getNode(ISD::USUBO
, SDLoc(N
), N
->getVTList(), N0
, N1
);
3521 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT and UMULFIX here.
3522 SDValue
DAGCombiner::visitMULFIX(SDNode
*N
) {
3523 SDValue N0
= N
->getOperand(0);
3524 SDValue N1
= N
->getOperand(1);
3525 SDValue Scale
= N
->getOperand(2);
3526 EVT VT
= N0
.getValueType();
3528 // fold (mulfix x, undef, scale) -> 0
3529 if (N0
.isUndef() || N1
.isUndef())
3530 return DAG
.getConstant(0, SDLoc(N
), VT
);
3532 // Canonicalize constant to RHS (vector doesn't have to splat)
3533 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3534 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
3535 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
, Scale
);
3537 // fold (mulfix x, 0, scale) -> 0
3538 if (isNullConstant(N1
))
3539 return DAG
.getConstant(0, SDLoc(N
), VT
);
3544 SDValue
DAGCombiner::visitMUL(SDNode
*N
) {
3545 SDValue N0
= N
->getOperand(0);
3546 SDValue N1
= N
->getOperand(1);
3547 EVT VT
= N0
.getValueType();
3549 // fold (mul x, undef) -> 0
3550 if (N0
.isUndef() || N1
.isUndef())
3551 return DAG
.getConstant(0, SDLoc(N
), VT
);
3553 bool N0IsConst
= false;
3554 bool N1IsConst
= false;
3555 bool N1IsOpaqueConst
= false;
3556 bool N0IsOpaqueConst
= false;
3557 APInt ConstValue0
, ConstValue1
;
3559 if (VT
.isVector()) {
3560 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3563 N0IsConst
= ISD::isConstantSplatVector(N0
.getNode(), ConstValue0
);
3564 N1IsConst
= ISD::isConstantSplatVector(N1
.getNode(), ConstValue1
);
3565 assert((!N0IsConst
||
3566 ConstValue0
.getBitWidth() == VT
.getScalarSizeInBits()) &&
3567 "Splat APInt should be element width");
3568 assert((!N1IsConst
||
3569 ConstValue1
.getBitWidth() == VT
.getScalarSizeInBits()) &&
3570 "Splat APInt should be element width");
3572 N0IsConst
= isa
<ConstantSDNode
>(N0
);
3574 ConstValue0
= cast
<ConstantSDNode
>(N0
)->getAPIntValue();
3575 N0IsOpaqueConst
= cast
<ConstantSDNode
>(N0
)->isOpaque();
3577 N1IsConst
= isa
<ConstantSDNode
>(N1
);
3579 ConstValue1
= cast
<ConstantSDNode
>(N1
)->getAPIntValue();
3580 N1IsOpaqueConst
= cast
<ConstantSDNode
>(N1
)->isOpaque();
3584 // fold (mul c1, c2) -> c1*c2
3585 if (N0IsConst
&& N1IsConst
&& !N0IsOpaqueConst
&& !N1IsOpaqueConst
)
3586 return DAG
.FoldConstantArithmetic(ISD::MUL
, SDLoc(N
), VT
,
3587 N0
.getNode(), N1
.getNode());
3589 // canonicalize constant to RHS (vector doesn't have to splat)
3590 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
3591 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
3592 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N1
, N0
);
3593 // fold (mul x, 0) -> 0
3594 if (N1IsConst
&& ConstValue1
.isNullValue())
3596 // fold (mul x, 1) -> x
3597 if (N1IsConst
&& ConstValue1
.isOneValue())
3600 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3603 // fold (mul x, -1) -> 0-x
3604 if (N1IsConst
&& ConstValue1
.isAllOnesValue()) {
3606 return DAG
.getNode(ISD::SUB
, DL
, VT
,
3607 DAG
.getConstant(0, DL
, VT
), N0
);
3609 // fold (mul x, (1 << c)) -> x << c
3610 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
3611 DAG
.isKnownToBeAPowerOfTwo(N1
) &&
3612 (!VT
.isVector() || Level
<= AfterLegalizeVectorOps
)) {
3614 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
3615 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
3616 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ShiftVT
);
3617 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
, Trunc
);
3619 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
3620 if (N1IsConst
&& !N1IsOpaqueConst
&& (-ConstValue1
).isPowerOf2()) {
3621 unsigned Log2Val
= (-ConstValue1
).logBase2();
3623 // FIXME: If the input is something that is easily negated (e.g. a
3624 // single-use add), we should put the negate there.
3625 return DAG
.getNode(ISD::SUB
, DL
, VT
,
3626 DAG
.getConstant(0, DL
, VT
),
3627 DAG
.getNode(ISD::SHL
, DL
, VT
, N0
,
3628 DAG
.getConstant(Log2Val
, DL
,
3629 getShiftAmountTy(N0
.getValueType()))));
3632 // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub.
3633 // mul x, (2^N + 1) --> add (shl x, N), x
3634 // mul x, (2^N - 1) --> sub (shl x, N), x
3635 // Examples: x * 33 --> (x << 5) + x
3636 // x * 15 --> (x << 4) - x
3637 // x * -33 --> -((x << 5) + x)
3638 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
3639 if (N1IsConst
&& TLI
.decomposeMulByConstant(*DAG
.getContext(), VT
, N1
)) {
3640 // TODO: We could handle more general decomposition of any constant by
3641 // having the target set a limit on number of ops and making a
3642 // callback to determine that sequence (similar to sqrt expansion).
3643 unsigned MathOp
= ISD::DELETED_NODE
;
3644 APInt MulC
= ConstValue1
.abs();
3645 if ((MulC
- 1).isPowerOf2())
3647 else if ((MulC
+ 1).isPowerOf2())
3650 if (MathOp
!= ISD::DELETED_NODE
) {
3652 MathOp
== ISD::ADD
? (MulC
- 1).logBase2() : (MulC
+ 1).logBase2();
3653 assert(ShAmt
< VT
.getScalarSizeInBits() &&
3654 "multiply-by-constant generated out of bounds shift");
3657 DAG
.getNode(ISD::SHL
, DL
, VT
, N0
, DAG
.getConstant(ShAmt
, DL
, VT
));
3658 SDValue R
= DAG
.getNode(MathOp
, DL
, VT
, Shl
, N0
);
3659 if (ConstValue1
.isNegative())
3660 R
= DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), R
);
3665 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
3666 if (N0
.getOpcode() == ISD::SHL
&&
3667 isConstantOrConstantVector(N1
, /* NoOpaques */ true) &&
3668 isConstantOrConstantVector(N0
.getOperand(1), /* NoOpaques */ true)) {
3669 SDValue C3
= DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N1
, N0
.getOperand(1));
3670 if (isConstantOrConstantVector(C3
))
3671 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N0
.getOperand(0), C3
);
3674 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
3677 SDValue
Sh(nullptr, 0), Y(nullptr, 0);
3679 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
3680 if (N0
.getOpcode() == ISD::SHL
&&
3681 isConstantOrConstantVector(N0
.getOperand(1)) &&
3682 N0
.getNode()->hasOneUse()) {
3684 } else if (N1
.getOpcode() == ISD::SHL
&&
3685 isConstantOrConstantVector(N1
.getOperand(1)) &&
3686 N1
.getNode()->hasOneUse()) {
3691 SDValue Mul
= DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, Sh
.getOperand(0), Y
);
3692 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, Mul
, Sh
.getOperand(1));
3696 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
3697 if (DAG
.isConstantIntBuildVectorOrConstantInt(N1
) &&
3698 N0
.getOpcode() == ISD::ADD
&&
3699 DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1)) &&
3700 isMulAddWithConstProfitable(N
, N0
, N1
))
3701 return DAG
.getNode(ISD::ADD
, SDLoc(N
), VT
,
3702 DAG
.getNode(ISD::MUL
, SDLoc(N0
), VT
,
3703 N0
.getOperand(0), N1
),
3704 DAG
.getNode(ISD::MUL
, SDLoc(N1
), VT
,
3705 N0
.getOperand(1), N1
));
3708 if (SDValue RMUL
= reassociateOps(ISD::MUL
, SDLoc(N
), N0
, N1
, N
->getFlags()))
3714 /// Return true if divmod libcall is available.
3715 static bool isDivRemLibcallAvailable(SDNode
*Node
, bool isSigned
,
3716 const TargetLowering
&TLI
) {
3718 EVT NodeType
= Node
->getValueType(0);
3719 if (!NodeType
.isSimple())
3721 switch (NodeType
.getSimpleVT().SimpleTy
) {
3722 default: return false; // No libcall for vector types.
3723 case MVT::i8
: LC
= isSigned
? RTLIB::SDIVREM_I8
: RTLIB::UDIVREM_I8
; break;
3724 case MVT::i16
: LC
= isSigned
? RTLIB::SDIVREM_I16
: RTLIB::UDIVREM_I16
; break;
3725 case MVT::i32
: LC
= isSigned
? RTLIB::SDIVREM_I32
: RTLIB::UDIVREM_I32
; break;
3726 case MVT::i64
: LC
= isSigned
? RTLIB::SDIVREM_I64
: RTLIB::UDIVREM_I64
; break;
3727 case MVT::i128
: LC
= isSigned
? RTLIB::SDIVREM_I128
:RTLIB::UDIVREM_I128
; break;
3730 return TLI
.getLibcallName(LC
) != nullptr;
3733 /// Issue divrem if both quotient and remainder are needed.
3734 SDValue
DAGCombiner::useDivRem(SDNode
*Node
) {
3735 if (Node
->use_empty())
3736 return SDValue(); // This is a dead node, leave it alone.
3738 unsigned Opcode
= Node
->getOpcode();
3739 bool isSigned
= (Opcode
== ISD::SDIV
) || (Opcode
== ISD::SREM
);
3740 unsigned DivRemOpc
= isSigned
? ISD::SDIVREM
: ISD::UDIVREM
;
3742 // DivMod lib calls can still work on non-legal types if using lib-calls.
3743 EVT VT
= Node
->getValueType(0);
3744 if (VT
.isVector() || !VT
.isInteger())
3747 if (!TLI
.isTypeLegal(VT
) && !TLI
.isOperationCustom(DivRemOpc
, VT
))
3750 // If DIVREM is going to get expanded into a libcall,
3751 // but there is no libcall available, then don't combine.
3752 if (!TLI
.isOperationLegalOrCustom(DivRemOpc
, VT
) &&
3753 !isDivRemLibcallAvailable(Node
, isSigned
, TLI
))
3756 // If div is legal, it's better to do the normal expansion
3757 unsigned OtherOpcode
= 0;
3758 if ((Opcode
== ISD::SDIV
) || (Opcode
== ISD::UDIV
)) {
3759 OtherOpcode
= isSigned
? ISD::SREM
: ISD::UREM
;
3760 if (TLI
.isOperationLegalOrCustom(Opcode
, VT
))
3763 OtherOpcode
= isSigned
? ISD::SDIV
: ISD::UDIV
;
3764 if (TLI
.isOperationLegalOrCustom(OtherOpcode
, VT
))
3768 SDValue Op0
= Node
->getOperand(0);
3769 SDValue Op1
= Node
->getOperand(1);
3771 for (SDNode::use_iterator UI
= Op0
.getNode()->use_begin(),
3772 UE
= Op0
.getNode()->use_end(); UI
!= UE
; ++UI
) {
3774 if (User
== Node
|| User
->getOpcode() == ISD::DELETED_NODE
||
3777 // Convert the other matching node(s), too;
3778 // otherwise, the DIVREM may get target-legalized into something
3779 // target-specific that we won't be able to recognize.
3780 unsigned UserOpc
= User
->getOpcode();
3781 if ((UserOpc
== Opcode
|| UserOpc
== OtherOpcode
|| UserOpc
== DivRemOpc
) &&
3782 User
->getOperand(0) == Op0
&&
3783 User
->getOperand(1) == Op1
) {
3785 if (UserOpc
== OtherOpcode
) {
3786 SDVTList VTs
= DAG
.getVTList(VT
, VT
);
3787 combined
= DAG
.getNode(DivRemOpc
, SDLoc(Node
), VTs
, Op0
, Op1
);
3788 } else if (UserOpc
== DivRemOpc
) {
3789 combined
= SDValue(User
, 0);
3791 assert(UserOpc
== Opcode
);
3795 if (UserOpc
== ISD::SDIV
|| UserOpc
== ISD::UDIV
)
3796 CombineTo(User
, combined
);
3797 else if (UserOpc
== ISD::SREM
|| UserOpc
== ISD::UREM
)
3798 CombineTo(User
, combined
.getValue(1));
3804 static SDValue
simplifyDivRem(SDNode
*N
, SelectionDAG
&DAG
) {
3805 SDValue N0
= N
->getOperand(0);
3806 SDValue N1
= N
->getOperand(1);
3807 EVT VT
= N
->getValueType(0);
3810 unsigned Opc
= N
->getOpcode();
3811 bool IsDiv
= (ISD::SDIV
== Opc
) || (ISD::UDIV
== Opc
);
3812 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
3814 // X / undef -> undef
3815 // X % undef -> undef
3818 // NOTE: This includes vectors where any divisor element is zero/undef.
3819 if (DAG
.isUndef(Opc
, {N0
, N1
}))
3820 return DAG
.getUNDEF(VT
);
3825 return DAG
.getConstant(0, DL
, VT
);
3829 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
3830 if (N0C
&& N0C
->isNullValue())
3836 return DAG
.getConstant(IsDiv
? 1 : 0, DL
, VT
);
3840 // If this is a boolean op (single-bit element type), we can't have
3841 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
3842 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
3844 if ((N1C
&& N1C
->isOne()) || (VT
.getScalarType() == MVT::i1
))
3845 return IsDiv
? N0
: DAG
.getConstant(0, DL
, VT
);
3850 SDValue
DAGCombiner::visitSDIV(SDNode
*N
) {
3851 SDValue N0
= N
->getOperand(0);
3852 SDValue N1
= N
->getOperand(1);
3853 EVT VT
= N
->getValueType(0);
3854 EVT CCVT
= getSetCCResultType(VT
);
3858 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
3863 // fold (sdiv c1, c2) -> c1/c2
3864 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
3865 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
3866 if (N0C
&& N1C
&& !N0C
->isOpaque() && !N1C
->isOpaque())
3867 return DAG
.FoldConstantArithmetic(ISD::SDIV
, DL
, VT
, N0C
, N1C
);
3868 // fold (sdiv X, -1) -> 0-X
3869 if (N1C
&& N1C
->isAllOnesValue())
3870 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), N0
);
3871 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
3872 if (N1C
&& N1C
->getAPIntValue().isMinSignedValue())
3873 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
3874 DAG
.getConstant(1, DL
, VT
),
3875 DAG
.getConstant(0, DL
, VT
));
3877 if (SDValue V
= simplifyDivRem(N
, DAG
))
3880 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
3883 // If we know the sign bits of both operands are zero, strength reduce to a
3884 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
3885 if (DAG
.SignBitIsZero(N1
) && DAG
.SignBitIsZero(N0
))
3886 return DAG
.getNode(ISD::UDIV
, DL
, N1
.getValueType(), N0
, N1
);
3888 if (SDValue V
= visitSDIVLike(N0
, N1
, N
)) {
3889 // If the corresponding remainder node exists, update its users with
3890 // (Dividend - (Quotient * Divisor).
3891 if (SDNode
*RemNode
= DAG
.getNodeIfExists(ISD::SREM
, N
->getVTList(),
3893 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, V
, N1
);
3894 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
3895 AddToWorklist(Mul
.getNode());
3896 AddToWorklist(Sub
.getNode());
3897 CombineTo(RemNode
, Sub
);
3902 // sdiv, srem -> sdivrem
3903 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
3904 // true. Otherwise, we break the simplification logic in visitREM().
3905 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3906 if (!N1C
|| TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
3907 if (SDValue DivRem
= useDivRem(N
))
3913 SDValue
DAGCombiner::visitSDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
3915 EVT VT
= N
->getValueType(0);
3916 EVT CCVT
= getSetCCResultType(VT
);
3917 unsigned BitWidth
= VT
.getScalarSizeInBits();
3919 // Helper for determining whether a value is a power-2 constant scalar or a
3920 // vector of such elements.
3921 auto IsPowerOfTwo
= [](ConstantSDNode
*C
) {
3922 if (C
->isNullValue() || C
->isOpaque())
3924 if (C
->getAPIntValue().isPowerOf2())
3926 if ((-C
->getAPIntValue()).isPowerOf2())
3931 // fold (sdiv X, pow2) -> simple ops after legalize
3932 // FIXME: We check for the exact bit here because the generic lowering gives
3933 // better results in that case. The target-specific lowering should learn how
3934 // to handle exact sdivs efficiently.
3935 if (!N
->getFlags().hasExact() && ISD::matchUnaryPredicate(N1
, IsPowerOfTwo
)) {
3936 // Target-specific implementation of sdiv x, pow2.
3937 if (SDValue Res
= BuildSDIVPow2(N
))
3940 // Create constants that are functions of the shift amount value.
3941 EVT ShiftAmtTy
= getShiftAmountTy(N0
.getValueType());
3942 SDValue Bits
= DAG
.getConstant(BitWidth
, DL
, ShiftAmtTy
);
3943 SDValue C1
= DAG
.getNode(ISD::CTTZ
, DL
, VT
, N1
);
3944 C1
= DAG
.getZExtOrTrunc(C1
, DL
, ShiftAmtTy
);
3945 SDValue Inexact
= DAG
.getNode(ISD::SUB
, DL
, ShiftAmtTy
, Bits
, C1
);
3946 if (!isConstantOrConstantVector(Inexact
))
3949 // Splat the sign bit into the register
3950 SDValue Sign
= DAG
.getNode(ISD::SRA
, DL
, VT
, N0
,
3951 DAG
.getConstant(BitWidth
- 1, DL
, ShiftAmtTy
));
3952 AddToWorklist(Sign
.getNode());
3954 // Add (N0 < 0) ? abs2 - 1 : 0;
3955 SDValue Srl
= DAG
.getNode(ISD::SRL
, DL
, VT
, Sign
, Inexact
);
3956 AddToWorklist(Srl
.getNode());
3957 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Srl
);
3958 AddToWorklist(Add
.getNode());
3959 SDValue Sra
= DAG
.getNode(ISD::SRA
, DL
, VT
, Add
, C1
);
3960 AddToWorklist(Sra
.getNode());
3962 // Special case: (sdiv X, 1) -> X
3963 // Special Case: (sdiv X, -1) -> 0-X
3964 SDValue One
= DAG
.getConstant(1, DL
, VT
);
3965 SDValue AllOnes
= DAG
.getAllOnesConstant(DL
, VT
);
3966 SDValue IsOne
= DAG
.getSetCC(DL
, CCVT
, N1
, One
, ISD::SETEQ
);
3967 SDValue IsAllOnes
= DAG
.getSetCC(DL
, CCVT
, N1
, AllOnes
, ISD::SETEQ
);
3968 SDValue IsOneOrAllOnes
= DAG
.getNode(ISD::OR
, DL
, CCVT
, IsOne
, IsAllOnes
);
3969 Sra
= DAG
.getSelect(DL
, VT
, IsOneOrAllOnes
, N0
, Sra
);
3971 // If dividing by a positive value, we're done. Otherwise, the result must
3973 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
3974 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, Zero
, Sra
);
3976 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
3977 SDValue IsNeg
= DAG
.getSetCC(DL
, CCVT
, N1
, Zero
, ISD::SETLT
);
3978 SDValue Res
= DAG
.getSelect(DL
, VT
, IsNeg
, Sub
, Sra
);
3982 // If integer divide is expensive and we satisfy the requirements, emit an
3983 // alternate sequence. Targets may check function attributes for size/speed
3985 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3986 if (isConstantOrConstantVector(N1
) &&
3987 !TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
3988 if (SDValue Op
= BuildSDIV(N
))
3994 SDValue
DAGCombiner::visitUDIV(SDNode
*N
) {
3995 SDValue N0
= N
->getOperand(0);
3996 SDValue N1
= N
->getOperand(1);
3997 EVT VT
= N
->getValueType(0);
3998 EVT CCVT
= getSetCCResultType(VT
);
4002 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
4007 // fold (udiv c1, c2) -> c1/c2
4008 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
4009 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
4011 if (SDValue Folded
= DAG
.FoldConstantArithmetic(ISD::UDIV
, DL
, VT
,
4014 // fold (udiv X, -1) -> select(X == -1, 1, 0)
4015 if (N1C
&& N1C
->getAPIntValue().isAllOnesValue())
4016 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
4017 DAG
.getConstant(1, DL
, VT
),
4018 DAG
.getConstant(0, DL
, VT
));
4020 if (SDValue V
= simplifyDivRem(N
, DAG
))
4023 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
4026 if (SDValue V
= visitUDIVLike(N0
, N1
, N
)) {
4027 // If the corresponding remainder node exists, update its users with
4028 // (Dividend - (Quotient * Divisor).
4029 if (SDNode
*RemNode
= DAG
.getNodeIfExists(ISD::UREM
, N
->getVTList(),
4031 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, V
, N1
);
4032 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
4033 AddToWorklist(Mul
.getNode());
4034 AddToWorklist(Sub
.getNode());
4035 CombineTo(RemNode
, Sub
);
4040 // sdiv, srem -> sdivrem
4041 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
4042 // true. Otherwise, we break the simplification logic in visitREM().
4043 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4044 if (!N1C
|| TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4045 if (SDValue DivRem
= useDivRem(N
))
4051 SDValue
DAGCombiner::visitUDIVLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
4053 EVT VT
= N
->getValueType(0);
4055 // fold (udiv x, (1 << c)) -> x >>u c
4056 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
4057 DAG
.isKnownToBeAPowerOfTwo(N1
)) {
4058 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
4059 AddToWorklist(LogBase2
.getNode());
4061 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
4062 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ShiftVT
);
4063 AddToWorklist(Trunc
.getNode());
4064 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Trunc
);
4067 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
4068 if (N1
.getOpcode() == ISD::SHL
) {
4069 SDValue N10
= N1
.getOperand(0);
4070 if (isConstantOrConstantVector(N10
, /*NoOpaques*/ true) &&
4071 DAG
.isKnownToBeAPowerOfTwo(N10
)) {
4072 SDValue LogBase2
= BuildLogBase2(N10
, DL
);
4073 AddToWorklist(LogBase2
.getNode());
4075 EVT ADDVT
= N1
.getOperand(1).getValueType();
4076 SDValue Trunc
= DAG
.getZExtOrTrunc(LogBase2
, DL
, ADDVT
);
4077 AddToWorklist(Trunc
.getNode());
4078 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, ADDVT
, N1
.getOperand(1), Trunc
);
4079 AddToWorklist(Add
.getNode());
4080 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Add
);
4084 // fold (udiv x, c) -> alternate
4085 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4086 if (isConstantOrConstantVector(N1
) &&
4087 !TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4088 if (SDValue Op
= BuildUDIV(N
))
4094 // handles ISD::SREM and ISD::UREM
4095 SDValue
DAGCombiner::visitREM(SDNode
*N
) {
4096 unsigned Opcode
= N
->getOpcode();
4097 SDValue N0
= N
->getOperand(0);
4098 SDValue N1
= N
->getOperand(1);
4099 EVT VT
= N
->getValueType(0);
4100 EVT CCVT
= getSetCCResultType(VT
);
4102 bool isSigned
= (Opcode
== ISD::SREM
);
4105 // fold (rem c1, c2) -> c1%c2
4106 ConstantSDNode
*N0C
= isConstOrConstSplat(N0
);
4107 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
4109 if (SDValue Folded
= DAG
.FoldConstantArithmetic(Opcode
, DL
, VT
, N0C
, N1C
))
4111 // fold (urem X, -1) -> select(X == -1, 0, x)
4112 if (!isSigned
&& N1C
&& N1C
->getAPIntValue().isAllOnesValue())
4113 return DAG
.getSelect(DL
, VT
, DAG
.getSetCC(DL
, CCVT
, N0
, N1
, ISD::SETEQ
),
4114 DAG
.getConstant(0, DL
, VT
), N0
);
4116 if (SDValue V
= simplifyDivRem(N
, DAG
))
4119 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
4123 // If we know the sign bits of both operands are zero, strength reduce to a
4124 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
4125 if (DAG
.SignBitIsZero(N1
) && DAG
.SignBitIsZero(N0
))
4126 return DAG
.getNode(ISD::UREM
, DL
, VT
, N0
, N1
);
4128 SDValue NegOne
= DAG
.getAllOnesConstant(DL
, VT
);
4129 if (DAG
.isKnownToBeAPowerOfTwo(N1
)) {
4130 // fold (urem x, pow2) -> (and x, pow2-1)
4131 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, NegOne
);
4132 AddToWorklist(Add
.getNode());
4133 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, Add
);
4135 if (N1
.getOpcode() == ISD::SHL
&&
4136 DAG
.isKnownToBeAPowerOfTwo(N1
.getOperand(0))) {
4137 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
4138 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N1
, NegOne
);
4139 AddToWorklist(Add
.getNode());
4140 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, Add
);
4144 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4146 // If X/C can be simplified by the division-by-constant logic, lower
4147 // X%C to the equivalent of X-X/C*C.
4148 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
4149 // speculative DIV must not cause a DIVREM conversion. We guard against this
4150 // by skipping the simplification if isIntDivCheap(). When div is not cheap,
4151 // combine will not return a DIVREM. Regardless, checking cheapness here
4152 // makes sense since the simplification results in fatter code.
4153 if (DAG
.isKnownNeverZero(N1
) && !TLI
.isIntDivCheap(VT
, Attr
)) {
4154 SDValue OptimizedDiv
=
4155 isSigned
? visitSDIVLike(N0
, N1
, N
) : visitUDIVLike(N0
, N1
, N
);
4156 if (OptimizedDiv
.getNode()) {
4157 // If the equivalent Div node also exists, update its users.
4158 unsigned DivOpcode
= isSigned
? ISD::SDIV
: ISD::UDIV
;
4159 if (SDNode
*DivNode
= DAG
.getNodeIfExists(DivOpcode
, N
->getVTList(),
4161 CombineTo(DivNode
, OptimizedDiv
);
4162 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, VT
, OptimizedDiv
, N1
);
4163 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, VT
, N0
, Mul
);
4164 AddToWorklist(OptimizedDiv
.getNode());
4165 AddToWorklist(Mul
.getNode());
4170 // sdiv, srem -> sdivrem
4171 if (SDValue DivRem
= useDivRem(N
))
4172 return DivRem
.getValue(1);
4177 SDValue
DAGCombiner::visitMULHS(SDNode
*N
) {
4178 SDValue N0
= N
->getOperand(0);
4179 SDValue N1
= N
->getOperand(1);
4180 EVT VT
= N
->getValueType(0);
4183 if (VT
.isVector()) {
4184 // fold (mulhs x, 0) -> 0
4185 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
4187 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
4191 // fold (mulhs x, 0) -> 0
4192 if (isNullConstant(N1
))
4194 // fold (mulhs x, 1) -> (sra x, size(x)-1)
4195 if (isOneConstant(N1
))
4196 return DAG
.getNode(ISD::SRA
, DL
, N0
.getValueType(), N0
,
4197 DAG
.getConstant(N0
.getValueSizeInBits() - 1, DL
,
4198 getShiftAmountTy(N0
.getValueType())));
4200 // fold (mulhs x, undef) -> 0
4201 if (N0
.isUndef() || N1
.isUndef())
4202 return DAG
.getConstant(0, DL
, VT
);
4204 // If the type twice as wide is legal, transform the mulhs to a wider multiply
4206 if (VT
.isSimple() && !VT
.isVector()) {
4207 MVT Simple
= VT
.getSimpleVT();
4208 unsigned SimpleSize
= Simple
.getSizeInBits();
4209 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4210 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4211 N0
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N0
);
4212 N1
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N1
);
4213 N1
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, N0
, N1
);
4214 N1
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, N1
,
4215 DAG
.getConstant(SimpleSize
, DL
,
4216 getShiftAmountTy(N1
.getValueType())));
4217 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N1
);
4224 SDValue
DAGCombiner::visitMULHU(SDNode
*N
) {
4225 SDValue N0
= N
->getOperand(0);
4226 SDValue N1
= N
->getOperand(1);
4227 EVT VT
= N
->getValueType(0);
4230 if (VT
.isVector()) {
4231 // fold (mulhu x, 0) -> 0
4232 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
4234 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
4238 // fold (mulhu x, 0) -> 0
4239 if (isNullConstant(N1
))
4241 // fold (mulhu x, 1) -> 0
4242 if (isOneConstant(N1
))
4243 return DAG
.getConstant(0, DL
, N0
.getValueType());
4244 // fold (mulhu x, undef) -> 0
4245 if (N0
.isUndef() || N1
.isUndef())
4246 return DAG
.getConstant(0, DL
, VT
);
4248 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
4249 if (isConstantOrConstantVector(N1
, /*NoOpaques*/ true) &&
4250 DAG
.isKnownToBeAPowerOfTwo(N1
) && hasOperation(ISD::SRL
, VT
)) {
4251 unsigned NumEltBits
= VT
.getScalarSizeInBits();
4252 SDValue LogBase2
= BuildLogBase2(N1
, DL
);
4253 SDValue SRLAmt
= DAG
.getNode(
4254 ISD::SUB
, DL
, VT
, DAG
.getConstant(NumEltBits
, DL
, VT
), LogBase2
);
4255 EVT ShiftVT
= getShiftAmountTy(N0
.getValueType());
4256 SDValue Trunc
= DAG
.getZExtOrTrunc(SRLAmt
, DL
, ShiftVT
);
4257 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
, Trunc
);
4260 // If the type twice as wide is legal, transform the mulhu to a wider multiply
4262 if (VT
.isSimple() && !VT
.isVector()) {
4263 MVT Simple
= VT
.getSimpleVT();
4264 unsigned SimpleSize
= Simple
.getSizeInBits();
4265 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4266 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4267 N0
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N0
);
4268 N1
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N1
);
4269 N1
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, N0
, N1
);
4270 N1
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, N1
,
4271 DAG
.getConstant(SimpleSize
, DL
,
4272 getShiftAmountTy(N1
.getValueType())));
4273 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N1
);
4280 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
4281 /// give the opcodes for the two computations that are being performed. Return
4282 /// true if a simplification was made.
4283 SDValue
DAGCombiner::SimplifyNodeWithTwoResults(SDNode
*N
, unsigned LoOp
,
4285 // If the high half is not needed, just compute the low half.
4286 bool HiExists
= N
->hasAnyUseOfValue(1);
4287 if (!HiExists
&& (!LegalOperations
||
4288 TLI
.isOperationLegalOrCustom(LoOp
, N
->getValueType(0)))) {
4289 SDValue Res
= DAG
.getNode(LoOp
, SDLoc(N
), N
->getValueType(0), N
->ops());
4290 return CombineTo(N
, Res
, Res
);
4293 // If the low half is not needed, just compute the high half.
4294 bool LoExists
= N
->hasAnyUseOfValue(0);
4295 if (!LoExists
&& (!LegalOperations
||
4296 TLI
.isOperationLegalOrCustom(HiOp
, N
->getValueType(1)))) {
4297 SDValue Res
= DAG
.getNode(HiOp
, SDLoc(N
), N
->getValueType(1), N
->ops());
4298 return CombineTo(N
, Res
, Res
);
4301 // If both halves are used, return as it is.
4302 if (LoExists
&& HiExists
)
4305 // If the two computed results can be simplified separately, separate them.
4307 SDValue Lo
= DAG
.getNode(LoOp
, SDLoc(N
), N
->getValueType(0), N
->ops());
4308 AddToWorklist(Lo
.getNode());
4309 SDValue LoOpt
= combine(Lo
.getNode());
4310 if (LoOpt
.getNode() && LoOpt
.getNode() != Lo
.getNode() &&
4311 (!LegalOperations
||
4312 TLI
.isOperationLegalOrCustom(LoOpt
.getOpcode(), LoOpt
.getValueType())))
4313 return CombineTo(N
, LoOpt
, LoOpt
);
4317 SDValue Hi
= DAG
.getNode(HiOp
, SDLoc(N
), N
->getValueType(1), N
->ops());
4318 AddToWorklist(Hi
.getNode());
4319 SDValue HiOpt
= combine(Hi
.getNode());
4320 if (HiOpt
.getNode() && HiOpt
!= Hi
&&
4321 (!LegalOperations
||
4322 TLI
.isOperationLegalOrCustom(HiOpt
.getOpcode(), HiOpt
.getValueType())))
4323 return CombineTo(N
, HiOpt
, HiOpt
);
4329 SDValue
DAGCombiner::visitSMUL_LOHI(SDNode
*N
) {
4330 if (SDValue Res
= SimplifyNodeWithTwoResults(N
, ISD::MUL
, ISD::MULHS
))
4333 EVT VT
= N
->getValueType(0);
4336 // If the type is twice as wide is legal, transform the mulhu to a wider
4337 // multiply plus a shift.
4338 if (VT
.isSimple() && !VT
.isVector()) {
4339 MVT Simple
= VT
.getSimpleVT();
4340 unsigned SimpleSize
= Simple
.getSizeInBits();
4341 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4342 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4343 SDValue Lo
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N
->getOperand(0));
4344 SDValue Hi
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, NewVT
, N
->getOperand(1));
4345 Lo
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, Lo
, Hi
);
4346 // Compute the high part as N1.
4347 Hi
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, Lo
,
4348 DAG
.getConstant(SimpleSize
, DL
,
4349 getShiftAmountTy(Lo
.getValueType())));
4350 Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Hi
);
4351 // Compute the low part as N0.
4352 Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Lo
);
4353 return CombineTo(N
, Lo
, Hi
);
4360 SDValue
DAGCombiner::visitUMUL_LOHI(SDNode
*N
) {
4361 if (SDValue Res
= SimplifyNodeWithTwoResults(N
, ISD::MUL
, ISD::MULHU
))
4364 EVT VT
= N
->getValueType(0);
4367 // (umul_lohi N0, 0) -> (0, 0)
4368 if (isNullConstant(N
->getOperand(1))) {
4369 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
4370 return CombineTo(N
, Zero
, Zero
);
4373 // (umul_lohi N0, 1) -> (N0, 0)
4374 if (isOneConstant(N
->getOperand(1))) {
4375 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
4376 return CombineTo(N
, N
->getOperand(0), Zero
);
4379 // If the type is twice as wide is legal, transform the mulhu to a wider
4380 // multiply plus a shift.
4381 if (VT
.isSimple() && !VT
.isVector()) {
4382 MVT Simple
= VT
.getSimpleVT();
4383 unsigned SimpleSize
= Simple
.getSizeInBits();
4384 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), SimpleSize
*2);
4385 if (TLI
.isOperationLegal(ISD::MUL
, NewVT
)) {
4386 SDValue Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N
->getOperand(0));
4387 SDValue Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, NewVT
, N
->getOperand(1));
4388 Lo
= DAG
.getNode(ISD::MUL
, DL
, NewVT
, Lo
, Hi
);
4389 // Compute the high part as N1.
4390 Hi
= DAG
.getNode(ISD::SRL
, DL
, NewVT
, Lo
,
4391 DAG
.getConstant(SimpleSize
, DL
,
4392 getShiftAmountTy(Lo
.getValueType())));
4393 Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Hi
);
4394 // Compute the low part as N0.
4395 Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Lo
);
4396 return CombineTo(N
, Lo
, Hi
);
4403 SDValue
DAGCombiner::visitMULO(SDNode
*N
) {
4404 bool IsSigned
= (ISD::SMULO
== N
->getOpcode());
4406 // (mulo x, 2) -> (addo x, x)
4407 if (ConstantSDNode
*C2
= isConstOrConstSplat(N
->getOperand(1)))
4408 if (C2
->getAPIntValue() == 2)
4409 return DAG
.getNode(IsSigned
? ISD::SADDO
: ISD::UADDO
, SDLoc(N
),
4410 N
->getVTList(), N
->getOperand(0), N
->getOperand(0));
4415 SDValue
DAGCombiner::visitIMINMAX(SDNode
*N
) {
4416 SDValue N0
= N
->getOperand(0);
4417 SDValue N1
= N
->getOperand(1);
4418 EVT VT
= N0
.getValueType();
4422 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
4425 // fold operation with constant operands.
4426 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
4427 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
4429 return DAG
.FoldConstantArithmetic(N
->getOpcode(), SDLoc(N
), VT
, N0C
, N1C
);
4431 // canonicalize constant to RHS
4432 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
4433 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
4434 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
);
4436 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
4437 // Only do this if the current op isn't legal and the flipped is.
4438 unsigned Opcode
= N
->getOpcode();
4439 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4440 if (!TLI
.isOperationLegal(Opcode
, VT
) &&
4441 (N0
.isUndef() || DAG
.SignBitIsZero(N0
)) &&
4442 (N1
.isUndef() || DAG
.SignBitIsZero(N1
))) {
4445 case ISD::SMIN
: AltOpcode
= ISD::UMIN
; break;
4446 case ISD::SMAX
: AltOpcode
= ISD::UMAX
; break;
4447 case ISD::UMIN
: AltOpcode
= ISD::SMIN
; break;
4448 case ISD::UMAX
: AltOpcode
= ISD::SMAX
; break;
4449 default: llvm_unreachable("Unknown MINMAX opcode");
4451 if (TLI
.isOperationLegal(AltOpcode
, VT
))
4452 return DAG
.getNode(AltOpcode
, SDLoc(N
), VT
, N0
, N1
);
4458 /// If this is a bitwise logic instruction and both operands have the same
4459 /// opcode, try to sink the other opcode after the logic instruction.
4460 SDValue
DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode
*N
) {
4461 SDValue N0
= N
->getOperand(0), N1
= N
->getOperand(1);
4462 EVT VT
= N0
.getValueType();
4463 unsigned LogicOpcode
= N
->getOpcode();
4464 unsigned HandOpcode
= N0
.getOpcode();
4465 assert((LogicOpcode
== ISD::AND
|| LogicOpcode
== ISD::OR
||
4466 LogicOpcode
== ISD::XOR
) && "Expected logic opcode");
4467 assert(HandOpcode
== N1
.getOpcode() && "Bad input!");
4469 // Bail early if none of these transforms apply.
4470 if (N0
.getNumOperands() == 0)
4473 // FIXME: We should check number of uses of the operands to not increase
4474 // the instruction count for all transforms.
4476 // Handle size-changing casts.
4477 SDValue X
= N0
.getOperand(0);
4478 SDValue Y
= N1
.getOperand(0);
4479 EVT XVT
= X
.getValueType();
4481 if (HandOpcode
== ISD::ANY_EXTEND
|| HandOpcode
== ISD::ZERO_EXTEND
||
4482 HandOpcode
== ISD::SIGN_EXTEND
) {
4483 // If both operands have other uses, this transform would create extra
4484 // instructions without eliminating anything.
4485 if (!N0
.hasOneUse() && !N1
.hasOneUse())
4487 // We need matching integer source types.
4488 if (XVT
!= Y
.getValueType())
4490 // Don't create an illegal op during or after legalization. Don't ever
4491 // create an unsupported vector op.
4492 if ((VT
.isVector() || LegalOperations
) &&
4493 !TLI
.isOperationLegalOrCustom(LogicOpcode
, XVT
))
4495 // Avoid infinite looping with PromoteIntBinOp.
4496 // TODO: Should we apply desirable/legal constraints to all opcodes?
4497 if (HandOpcode
== ISD::ANY_EXTEND
&& LegalTypes
&&
4498 !TLI
.isTypeDesirableForOp(LogicOpcode
, XVT
))
4500 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
4501 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4502 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4505 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
4506 if (HandOpcode
== ISD::TRUNCATE
) {
4507 // If both operands have other uses, this transform would create extra
4508 // instructions without eliminating anything.
4509 if (!N0
.hasOneUse() && !N1
.hasOneUse())
4511 // We need matching source types.
4512 if (XVT
!= Y
.getValueType())
4514 // Don't create an illegal op during or after legalization.
4515 if (LegalOperations
&& !TLI
.isOperationLegal(LogicOpcode
, XVT
))
4517 // Be extra careful sinking truncate. If it's free, there's no benefit in
4518 // widening a binop. Also, don't create a logic op on an illegal type.
4519 if (TLI
.isZExtFree(VT
, XVT
) && TLI
.isTruncateFree(XVT
, VT
))
4521 if (!TLI
.isTypeLegal(XVT
))
4523 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4524 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4527 // For binops SHL/SRL/SRA/AND:
4528 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
4529 if ((HandOpcode
== ISD::SHL
|| HandOpcode
== ISD::SRL
||
4530 HandOpcode
== ISD::SRA
|| HandOpcode
== ISD::AND
) &&
4531 N0
.getOperand(1) == N1
.getOperand(1)) {
4532 // If either operand has other uses, this transform is not an improvement.
4533 if (!N0
.hasOneUse() || !N1
.hasOneUse())
4535 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4536 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
, N0
.getOperand(1));
4539 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
4540 if (HandOpcode
== ISD::BSWAP
) {
4541 // If either operand has other uses, this transform is not an improvement.
4542 if (!N0
.hasOneUse() || !N1
.hasOneUse())
4544 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4545 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4548 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
4549 // Only perform this optimization up until type legalization, before
4550 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
4551 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
4552 // we don't want to undo this promotion.
4553 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
4555 if ((HandOpcode
== ISD::BITCAST
|| HandOpcode
== ISD::SCALAR_TO_VECTOR
) &&
4556 Level
<= AfterLegalizeTypes
) {
4557 // Input types must be integer and the same.
4558 if (XVT
.isInteger() && XVT
== Y
.getValueType()) {
4559 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, XVT
, X
, Y
);
4560 return DAG
.getNode(HandOpcode
, DL
, VT
, Logic
);
4564 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
4565 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
4566 // If both shuffles use the same mask, and both shuffle within a single
4567 // vector, then it is worthwhile to move the swizzle after the operation.
4568 // The type-legalizer generates this pattern when loading illegal
4569 // vector types from memory. In many cases this allows additional shuffle
4571 // There are other cases where moving the shuffle after the xor/and/or
4572 // is profitable even if shuffles don't perform a swizzle.
4573 // If both shuffles use the same mask, and both shuffles have the same first
4574 // or second operand, then it might still be profitable to move the shuffle
4575 // after the xor/and/or operation.
4576 if (HandOpcode
== ISD::VECTOR_SHUFFLE
&& Level
< AfterLegalizeDAG
) {
4577 auto *SVN0
= cast
<ShuffleVectorSDNode
>(N0
);
4578 auto *SVN1
= cast
<ShuffleVectorSDNode
>(N1
);
4579 assert(X
.getValueType() == Y
.getValueType() &&
4580 "Inputs to shuffles are not the same type");
4582 // Check that both shuffles use the same mask. The masks are known to be of
4583 // the same length because the result vector type is the same.
4584 // Check also that shuffles have only one use to avoid introducing extra
4586 if (!SVN0
->hasOneUse() || !SVN1
->hasOneUse() ||
4587 !SVN0
->getMask().equals(SVN1
->getMask()))
4590 // Don't try to fold this node if it requires introducing a
4591 // build vector of all zeros that might be illegal at this stage.
4592 SDValue ShOp
= N0
.getOperand(1);
4593 if (LogicOpcode
== ISD::XOR
&& !ShOp
.isUndef())
4594 ShOp
= tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
4596 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
4597 if (N0
.getOperand(1) == N1
.getOperand(1) && ShOp
.getNode()) {
4598 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, VT
,
4599 N0
.getOperand(0), N1
.getOperand(0));
4600 return DAG
.getVectorShuffle(VT
, DL
, Logic
, ShOp
, SVN0
->getMask());
4603 // Don't try to fold this node if it requires introducing a
4604 // build vector of all zeros that might be illegal at this stage.
4605 ShOp
= N0
.getOperand(0);
4606 if (LogicOpcode
== ISD::XOR
&& !ShOp
.isUndef())
4607 ShOp
= tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
4609 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
4610 if (N0
.getOperand(0) == N1
.getOperand(0) && ShOp
.getNode()) {
4611 SDValue Logic
= DAG
.getNode(LogicOpcode
, DL
, VT
, N0
.getOperand(1),
4613 return DAG
.getVectorShuffle(VT
, DL
, ShOp
, Logic
, SVN0
->getMask());
4620 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
4621 SDValue
DAGCombiner::foldLogicOfSetCCs(bool IsAnd
, SDValue N0
, SDValue N1
,
4623 SDValue LL
, LR
, RL
, RR
, N0CC
, N1CC
;
4624 if (!isSetCCEquivalent(N0
, LL
, LR
, N0CC
) ||
4625 !isSetCCEquivalent(N1
, RL
, RR
, N1CC
))
4628 assert(N0
.getValueType() == N1
.getValueType() &&
4629 "Unexpected operand types for bitwise logic op");
4630 assert(LL
.getValueType() == LR
.getValueType() &&
4631 RL
.getValueType() == RR
.getValueType() &&
4632 "Unexpected operand types for setcc");
4634 // If we're here post-legalization or the logic op type is not i1, the logic
4635 // op type must match a setcc result type. Also, all folds require new
4636 // operations on the left and right operands, so those types must match.
4637 EVT VT
= N0
.getValueType();
4638 EVT OpVT
= LL
.getValueType();
4639 if (LegalOperations
|| VT
.getScalarType() != MVT::i1
)
4640 if (VT
!= getSetCCResultType(OpVT
))
4642 if (OpVT
!= RL
.getValueType())
4645 ISD::CondCode CC0
= cast
<CondCodeSDNode
>(N0CC
)->get();
4646 ISD::CondCode CC1
= cast
<CondCodeSDNode
>(N1CC
)->get();
4647 bool IsInteger
= OpVT
.isInteger();
4648 if (LR
== RR
&& CC0
== CC1
&& IsInteger
) {
4649 bool IsZero
= isNullOrNullSplat(LR
);
4650 bool IsNeg1
= isAllOnesOrAllOnesSplat(LR
);
4653 bool AndEqZero
= IsAnd
&& CC1
== ISD::SETEQ
&& IsZero
;
4654 // All sign bits clear?
4655 bool AndGtNeg1
= IsAnd
&& CC1
== ISD::SETGT
&& IsNeg1
;
4657 bool OrNeZero
= !IsAnd
&& CC1
== ISD::SETNE
&& IsZero
;
4658 // Any sign bits set?
4659 bool OrLtZero
= !IsAnd
&& CC1
== ISD::SETLT
&& IsZero
;
4661 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
4662 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
4663 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
4664 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
4665 if (AndEqZero
|| AndGtNeg1
|| OrNeZero
|| OrLtZero
) {
4666 SDValue Or
= DAG
.getNode(ISD::OR
, SDLoc(N0
), OpVT
, LL
, RL
);
4667 AddToWorklist(Or
.getNode());
4668 return DAG
.getSetCC(DL
, VT
, Or
, LR
, CC1
);
4672 bool AndEqNeg1
= IsAnd
&& CC1
== ISD::SETEQ
&& IsNeg1
;
4673 // All sign bits set?
4674 bool AndLtZero
= IsAnd
&& CC1
== ISD::SETLT
&& IsZero
;
4676 bool OrNeNeg1
= !IsAnd
&& CC1
== ISD::SETNE
&& IsNeg1
;
4677 // Any sign bits clear?
4678 bool OrGtNeg1
= !IsAnd
&& CC1
== ISD::SETGT
&& IsNeg1
;
4680 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
4681 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
4682 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
4683 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
4684 if (AndEqNeg1
|| AndLtZero
|| OrNeNeg1
|| OrGtNeg1
) {
4685 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(N0
), OpVT
, LL
, RL
);
4686 AddToWorklist(And
.getNode());
4687 return DAG
.getSetCC(DL
, VT
, And
, LR
, CC1
);
4691 // TODO: What is the 'or' equivalent of this fold?
4692 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
4693 if (IsAnd
&& LL
== RL
&& CC0
== CC1
&& OpVT
.getScalarSizeInBits() > 1 &&
4694 IsInteger
&& CC0
== ISD::SETNE
&&
4695 ((isNullConstant(LR
) && isAllOnesConstant(RR
)) ||
4696 (isAllOnesConstant(LR
) && isNullConstant(RR
)))) {
4697 SDValue One
= DAG
.getConstant(1, DL
, OpVT
);
4698 SDValue Two
= DAG
.getConstant(2, DL
, OpVT
);
4699 SDValue Add
= DAG
.getNode(ISD::ADD
, SDLoc(N0
), OpVT
, LL
, One
);
4700 AddToWorklist(Add
.getNode());
4701 return DAG
.getSetCC(DL
, VT
, Add
, Two
, ISD::SETUGE
);
4704 // Try more general transforms if the predicates match and the only user of
4705 // the compares is the 'and' or 'or'.
4706 if (IsInteger
&& TLI
.convertSetCCLogicToBitwiseLogic(OpVT
) && CC0
== CC1
&&
4707 N0
.hasOneUse() && N1
.hasOneUse()) {
4708 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
4709 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
4710 if ((IsAnd
&& CC1
== ISD::SETEQ
) || (!IsAnd
&& CC1
== ISD::SETNE
)) {
4711 SDValue XorL
= DAG
.getNode(ISD::XOR
, SDLoc(N0
), OpVT
, LL
, LR
);
4712 SDValue XorR
= DAG
.getNode(ISD::XOR
, SDLoc(N1
), OpVT
, RL
, RR
);
4713 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, OpVT
, XorL
, XorR
);
4714 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
4715 return DAG
.getSetCC(DL
, VT
, Or
, Zero
, CC1
);
4718 // Turn compare of constants whose difference is 1 bit into add+and+setcc.
4719 // TODO - support non-uniform vector amounts.
4720 if ((IsAnd
&& CC1
== ISD::SETNE
) || (!IsAnd
&& CC1
== ISD::SETEQ
)) {
4721 // Match a shared variable operand and 2 non-opaque constant operands.
4722 ConstantSDNode
*C0
= isConstOrConstSplat(LR
);
4723 ConstantSDNode
*C1
= isConstOrConstSplat(RR
);
4724 if (LL
== RL
&& C0
&& C1
&& !C0
->isOpaque() && !C1
->isOpaque()) {
4725 // Canonicalize larger constant as C0.
4726 if (C1
->getAPIntValue().ugt(C0
->getAPIntValue()))
4729 // The difference of the constants must be a single bit.
4730 const APInt
&C0Val
= C0
->getAPIntValue();
4731 const APInt
&C1Val
= C1
->getAPIntValue();
4732 if ((C0Val
- C1Val
).isPowerOf2()) {
4733 // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) -->
4734 // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq
4735 SDValue OffsetC
= DAG
.getConstant(-C1Val
, DL
, OpVT
);
4736 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, OpVT
, LL
, OffsetC
);
4737 SDValue MaskC
= DAG
.getConstant(~(C0Val
- C1Val
), DL
, OpVT
);
4738 SDValue And
= DAG
.getNode(ISD::AND
, DL
, OpVT
, Add
, MaskC
);
4739 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
4740 return DAG
.getSetCC(DL
, VT
, And
, Zero
, CC0
);
4746 // Canonicalize equivalent operands to LL == RL.
4747 if (LL
== RR
&& LR
== RL
) {
4748 CC1
= ISD::getSetCCSwappedOperands(CC1
);
4752 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4753 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
4754 if (LL
== RL
&& LR
== RR
) {
4755 ISD::CondCode NewCC
= IsAnd
? ISD::getSetCCAndOperation(CC0
, CC1
, IsInteger
)
4756 : ISD::getSetCCOrOperation(CC0
, CC1
, IsInteger
);
4757 if (NewCC
!= ISD::SETCC_INVALID
&&
4758 (!LegalOperations
||
4759 (TLI
.isCondCodeLegal(NewCC
, LL
.getSimpleValueType()) &&
4760 TLI
.isOperationLegal(ISD::SETCC
, OpVT
))))
4761 return DAG
.getSetCC(DL
, VT
, LL
, LR
, NewCC
);
4767 /// This contains all DAGCombine rules which reduce two values combined by
4768 /// an And operation to a single value. This makes them reusable in the context
4769 /// of visitSELECT(). Rules involving constants are not included as
4770 /// visitSELECT() already handles those cases.
4771 SDValue
DAGCombiner::visitANDLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
4772 EVT VT
= N1
.getValueType();
4775 // fold (and x, undef) -> 0
4776 if (N0
.isUndef() || N1
.isUndef())
4777 return DAG
.getConstant(0, DL
, VT
);
4779 if (SDValue V
= foldLogicOfSetCCs(true, N0
, N1
, DL
))
4782 if (N0
.getOpcode() == ISD::ADD
&& N1
.getOpcode() == ISD::SRL
&&
4783 VT
.getSizeInBits() <= 64) {
4784 if (ConstantSDNode
*ADDI
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
4785 if (ConstantSDNode
*SRLI
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1))) {
4786 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
4787 // immediate for an add, but it is legal if its top c2 bits are set,
4788 // transform the ADD so the immediate doesn't need to be materialized
4790 APInt ADDC
= ADDI
->getAPIntValue();
4791 APInt SRLC
= SRLI
->getAPIntValue();
4792 if (ADDC
.getMinSignedBits() <= 64 &&
4793 SRLC
.ult(VT
.getSizeInBits()) &&
4794 !TLI
.isLegalAddImmediate(ADDC
.getSExtValue())) {
4795 APInt Mask
= APInt::getHighBitsSet(VT
.getSizeInBits(),
4796 SRLC
.getZExtValue());
4797 if (DAG
.MaskedValueIsZero(N0
.getOperand(1), Mask
)) {
4799 if (TLI
.isLegalAddImmediate(ADDC
.getSExtValue())) {
4802 DAG
.getNode(ISD::ADD
, DL0
, VT
,
4803 N0
.getOperand(0), DAG
.getConstant(ADDC
, DL
, VT
));
4804 CombineTo(N0
.getNode(), NewAdd
);
4805 // Return N so it doesn't get rechecked!
4806 return SDValue(N
, 0);
4814 // Reduce bit extract of low half of an integer to the narrower type.
4815 // (and (srl i64:x, K), KMask) ->
4816 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
4817 if (N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse()) {
4818 if (ConstantSDNode
*CAnd
= dyn_cast
<ConstantSDNode
>(N1
)) {
4819 if (ConstantSDNode
*CShift
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
4820 unsigned Size
= VT
.getSizeInBits();
4821 const APInt
&AndMask
= CAnd
->getAPIntValue();
4822 unsigned ShiftBits
= CShift
->getZExtValue();
4824 // Bail out, this node will probably disappear anyway.
4828 unsigned MaskBits
= AndMask
.countTrailingOnes();
4829 EVT HalfVT
= EVT::getIntegerVT(*DAG
.getContext(), Size
/ 2);
4831 if (AndMask
.isMask() &&
4832 // Required bits must not span the two halves of the integer and
4833 // must fit in the half size type.
4834 (ShiftBits
+ MaskBits
<= Size
/ 2) &&
4835 TLI
.isNarrowingProfitable(VT
, HalfVT
) &&
4836 TLI
.isTypeDesirableForOp(ISD::AND
, HalfVT
) &&
4837 TLI
.isTypeDesirableForOp(ISD::SRL
, HalfVT
) &&
4838 TLI
.isTruncateFree(VT
, HalfVT
) &&
4839 TLI
.isZExtFree(HalfVT
, VT
)) {
4840 // The isNarrowingProfitable is to avoid regressions on PPC and
4841 // AArch64 which match a few 64-bit bit insert / bit extract patterns
4842 // on downstream users of this. Those patterns could probably be
4843 // extended to handle extensions mixed in.
4846 assert(MaskBits
<= Size
);
4848 // Extracting the highest bit of the low half.
4849 EVT ShiftVT
= TLI
.getShiftAmountTy(HalfVT
, DAG
.getDataLayout());
4850 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, HalfVT
,
4853 SDValue NewMask
= DAG
.getConstant(AndMask
.trunc(Size
/ 2), SL
, HalfVT
);
4854 SDValue ShiftK
= DAG
.getConstant(ShiftBits
, SL
, ShiftVT
);
4855 SDValue Shift
= DAG
.getNode(ISD::SRL
, SL
, HalfVT
, Trunc
, ShiftK
);
4856 SDValue And
= DAG
.getNode(ISD::AND
, SL
, HalfVT
, Shift
, NewMask
);
4857 return DAG
.getNode(ISD::ZERO_EXTEND
, SL
, VT
, And
);
4866 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode
*AndC
, LoadSDNode
*LoadN
,
4867 EVT LoadResultTy
, EVT
&ExtVT
) {
4868 if (!AndC
->getAPIntValue().isMask())
4871 unsigned ActiveBits
= AndC
->getAPIntValue().countTrailingOnes();
4873 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
4874 EVT LoadedVT
= LoadN
->getMemoryVT();
4876 if (ExtVT
== LoadedVT
&&
4877 (!LegalOperations
||
4878 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LoadResultTy
, ExtVT
))) {
4879 // ZEXTLOAD will match without needing to change the size of the value being
4884 // Do not change the width of a volatile load.
4885 if (LoadN
->isVolatile())
4888 // Do not generate loads of non-round integer types since these can
4889 // be expensive (and would be wrong if the type is not byte sized).
4890 if (!LoadedVT
.bitsGT(ExtVT
) || !ExtVT
.isRound())
4893 if (LegalOperations
&&
4894 !TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LoadResultTy
, ExtVT
))
4897 if (!TLI
.shouldReduceLoadWidth(LoadN
, ISD::ZEXTLOAD
, ExtVT
))
4903 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode
*LDST
,
4904 ISD::LoadExtType ExtType
, EVT
&MemVT
,
4908 // Only allow byte offsets.
4912 // Do not generate loads of non-round integer types since these can
4913 // be expensive (and would be wrong if the type is not byte sized).
4914 if (!MemVT
.isRound())
4917 // Don't change the width of a volatile load.
4918 if (LDST
->isVolatile())
4921 // Verify that we are actually reducing a load width here.
4922 if (LDST
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits())
4925 // Ensure that this isn't going to produce an unsupported unaligned access.
4927 !TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(), MemVT
,
4928 LDST
->getAddressSpace(), ShAmt
/ 8,
4929 LDST
->getMemOperand()->getFlags()))
4932 // It's not possible to generate a constant of extended or untyped type.
4933 EVT PtrType
= LDST
->getBasePtr().getValueType();
4934 if (PtrType
== MVT::Untyped
|| PtrType
.isExtended())
4937 if (isa
<LoadSDNode
>(LDST
)) {
4938 LoadSDNode
*Load
= cast
<LoadSDNode
>(LDST
);
4939 // Don't transform one with multiple uses, this would require adding a new
4941 if (!SDValue(Load
, 0).hasOneUse())
4944 if (LegalOperations
&&
4945 !TLI
.isLoadExtLegal(ExtType
, Load
->getValueType(0), MemVT
))
4948 // For the transform to be legal, the load must produce only two values
4949 // (the value loaded and the chain). Don't transform a pre-increment
4950 // load, for example, which produces an extra value. Otherwise the
4951 // transformation is not equivalent, and the downstream logic to replace
4952 // uses gets things wrong.
4953 if (Load
->getNumValues() > 2)
4956 // If the load that we're shrinking is an extload and we're not just
4957 // discarding the extension we can't simply shrink the load. Bail.
4958 // TODO: It would be possible to merge the extensions in some cases.
4959 if (Load
->getExtensionType() != ISD::NON_EXTLOAD
&&
4960 Load
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits() + ShAmt
)
4963 if (!TLI
.shouldReduceLoadWidth(Load
, ExtType
, MemVT
))
4966 assert(isa
<StoreSDNode
>(LDST
) && "It is not a Load nor a Store SDNode");
4967 StoreSDNode
*Store
= cast
<StoreSDNode
>(LDST
);
4968 // Can't write outside the original store
4969 if (Store
->getMemoryVT().getSizeInBits() < MemVT
.getSizeInBits() + ShAmt
)
4972 if (LegalOperations
&&
4973 !TLI
.isTruncStoreLegal(Store
->getValue().getValueType(), MemVT
))
4979 bool DAGCombiner::SearchForAndLoads(SDNode
*N
,
4980 SmallVectorImpl
<LoadSDNode
*> &Loads
,
4981 SmallPtrSetImpl
<SDNode
*> &NodesWithConsts
,
4982 ConstantSDNode
*Mask
,
4983 SDNode
*&NodeToMask
) {
4984 // Recursively search for the operands, looking for loads which can be
4986 for (SDValue Op
: N
->op_values()) {
4987 if (Op
.getValueType().isVector())
4990 // Some constants may need fixing up later if they are too large.
4991 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
)) {
4992 if ((N
->getOpcode() == ISD::OR
|| N
->getOpcode() == ISD::XOR
) &&
4993 (Mask
->getAPIntValue() & C
->getAPIntValue()) != C
->getAPIntValue())
4994 NodesWithConsts
.insert(N
);
4998 if (!Op
.hasOneUse())
5001 switch(Op
.getOpcode()) {
5003 auto *Load
= cast
<LoadSDNode
>(Op
);
5005 if (isAndLoadExtLoad(Mask
, Load
, Load
->getValueType(0), ExtVT
) &&
5006 isLegalNarrowLdSt(Load
, ISD::ZEXTLOAD
, ExtVT
)) {
5008 // ZEXTLOAD is already small enough.
5009 if (Load
->getExtensionType() == ISD::ZEXTLOAD
&&
5010 ExtVT
.bitsGE(Load
->getMemoryVT()))
5013 // Use LE to convert equal sized loads to zext.
5014 if (ExtVT
.bitsLE(Load
->getMemoryVT()))
5015 Loads
.push_back(Load
);
5021 case ISD::ZERO_EXTEND
:
5022 case ISD::AssertZext
: {
5023 unsigned ActiveBits
= Mask
->getAPIntValue().countTrailingOnes();
5024 EVT ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
5025 EVT VT
= Op
.getOpcode() == ISD::AssertZext
?
5026 cast
<VTSDNode
>(Op
.getOperand(1))->getVT() :
5027 Op
.getOperand(0).getValueType();
5029 // We can accept extending nodes if the mask is wider or an equal
5030 // width to the original type.
5031 if (ExtVT
.bitsGE(VT
))
5038 if (!SearchForAndLoads(Op
.getNode(), Loads
, NodesWithConsts
, Mask
,
5044 // Allow one node which will masked along with any loads found.
5048 // Also ensure that the node to be masked only produces one data result.
5049 NodeToMask
= Op
.getNode();
5050 if (NodeToMask
->getNumValues() > 1) {
5051 bool HasValue
= false;
5052 for (unsigned i
= 0, e
= NodeToMask
->getNumValues(); i
< e
; ++i
) {
5053 MVT VT
= SDValue(NodeToMask
, i
).getSimpleValueType();
5054 if (VT
!= MVT::Glue
&& VT
!= MVT::Other
) {
5056 NodeToMask
= nullptr;
5062 assert(HasValue
&& "Node to be masked has no data result?");
5068 bool DAGCombiner::BackwardsPropagateMask(SDNode
*N
, SelectionDAG
&DAG
) {
5069 auto *Mask
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
5073 if (!Mask
->getAPIntValue().isMask())
5076 // No need to do anything if the and directly uses a load.
5077 if (isa
<LoadSDNode
>(N
->getOperand(0)))
5080 SmallVector
<LoadSDNode
*, 8> Loads
;
5081 SmallPtrSet
<SDNode
*, 2> NodesWithConsts
;
5082 SDNode
*FixupNode
= nullptr;
5083 if (SearchForAndLoads(N
, Loads
, NodesWithConsts
, Mask
, FixupNode
)) {
5084 if (Loads
.size() == 0)
5087 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N
->dump());
5088 SDValue MaskOp
= N
->getOperand(1);
5090 // If it exists, fixup the single node we allow in the tree that needs
5093 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode
->dump());
5094 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(FixupNode
),
5095 FixupNode
->getValueType(0),
5096 SDValue(FixupNode
, 0), MaskOp
);
5097 DAG
.ReplaceAllUsesOfValueWith(SDValue(FixupNode
, 0), And
);
5098 if (And
.getOpcode() == ISD ::AND
)
5099 DAG
.UpdateNodeOperands(And
.getNode(), SDValue(FixupNode
, 0), MaskOp
);
5102 // Narrow any constants that need it.
5103 for (auto *LogicN
: NodesWithConsts
) {
5104 SDValue Op0
= LogicN
->getOperand(0);
5105 SDValue Op1
= LogicN
->getOperand(1);
5107 if (isa
<ConstantSDNode
>(Op0
))
5108 std::swap(Op0
, Op1
);
5110 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(Op1
), Op1
.getValueType(),
5113 DAG
.UpdateNodeOperands(LogicN
, Op0
, And
);
5116 // Create narrow loads.
5117 for (auto *Load
: Loads
) {
5118 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load
->dump());
5119 SDValue And
= DAG
.getNode(ISD::AND
, SDLoc(Load
), Load
->getValueType(0),
5120 SDValue(Load
, 0), MaskOp
);
5121 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 0), And
);
5122 if (And
.getOpcode() == ISD ::AND
)
5124 DAG
.UpdateNodeOperands(And
.getNode(), SDValue(Load
, 0), MaskOp
), 0);
5125 SDValue NewLoad
= ReduceLoadWidth(And
.getNode());
5127 "Shouldn't be masking the load if it can't be narrowed");
5128 CombineTo(Load
, NewLoad
, NewLoad
.getValue(1));
5130 DAG
.ReplaceAllUsesWith(N
, N
->getOperand(0).getNode());
5137 // x & (-1 'logical shift' y)
5139 // (x 'opposite logical shift' y) 'logical shift' y
5140 // if it is better for performance.
5141 SDValue
DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode
*N
) {
5142 assert(N
->getOpcode() == ISD::AND
);
5144 SDValue N0
= N
->getOperand(0);
5145 SDValue N1
= N
->getOperand(1);
5147 // Do we actually prefer shifts over mask?
5148 if (!TLI
.shouldFoldMaskToVariableShiftPair(N0
))
5151 // Try to match (-1 '[outer] logical shift' y)
5152 unsigned OuterShift
;
5153 unsigned InnerShift
; // The opposite direction to the OuterShift.
5154 SDValue Y
; // Shift amount.
5155 auto matchMask
= [&OuterShift
, &InnerShift
, &Y
](SDValue M
) -> bool {
5158 OuterShift
= M
->getOpcode();
5159 if (OuterShift
== ISD::SHL
)
5160 InnerShift
= ISD::SRL
;
5161 else if (OuterShift
== ISD::SRL
)
5162 InnerShift
= ISD::SHL
;
5165 if (!isAllOnesConstant(M
->getOperand(0)))
5167 Y
= M
->getOperand(1);
5174 else if (matchMask(N0
))
5180 EVT VT
= N
->getValueType(0);
5182 // tmp = x 'opposite logical shift' y
5183 SDValue T0
= DAG
.getNode(InnerShift
, DL
, VT
, X
, Y
);
5184 // ret = tmp 'logical shift' y
5185 SDValue T1
= DAG
.getNode(OuterShift
, DL
, VT
, T0
, Y
);
5190 SDValue
DAGCombiner::visitAND(SDNode
*N
) {
5191 SDValue N0
= N
->getOperand(0);
5192 SDValue N1
= N
->getOperand(1);
5193 EVT VT
= N1
.getValueType();
5200 if (VT
.isVector()) {
5201 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
5204 // fold (and x, 0) -> 0, vector edition
5205 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
5206 // do not return N0, because undef node may exist in N0
5207 return DAG
.getConstant(APInt::getNullValue(N0
.getScalarValueSizeInBits()),
5208 SDLoc(N
), N0
.getValueType());
5209 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
5210 // do not return N1, because undef node may exist in N1
5211 return DAG
.getConstant(APInt::getNullValue(N1
.getScalarValueSizeInBits()),
5212 SDLoc(N
), N1
.getValueType());
5214 // fold (and x, -1) -> x, vector edition
5215 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
5217 if (ISD::isBuildVectorAllOnes(N1
.getNode()))
5221 // fold (and c1, c2) -> c1&c2
5222 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
5223 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
5224 if (N0C
&& N1C
&& !N1C
->isOpaque())
5225 return DAG
.FoldConstantArithmetic(ISD::AND
, SDLoc(N
), VT
, N0C
, N1C
);
5226 // canonicalize constant to RHS
5227 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
5228 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
5229 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, N1
, N0
);
5230 // fold (and x, -1) -> x
5231 if (isAllOnesConstant(N1
))
5233 // if (and x, c) is known to be zero, return 0
5234 unsigned BitWidth
= VT
.getScalarSizeInBits();
5235 if (N1C
&& DAG
.MaskedValueIsZero(SDValue(N
, 0),
5236 APInt::getAllOnesValue(BitWidth
)))
5237 return DAG
.getConstant(0, SDLoc(N
), VT
);
5239 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
5243 if (SDValue RAND
= reassociateOps(ISD::AND
, SDLoc(N
), N0
, N1
, N
->getFlags()))
5246 // Try to convert a constant mask AND into a shuffle clear mask.
5248 if (SDValue Shuffle
= XformToShuffleWithZero(N
))
5251 // fold (and (or x, C), D) -> D if (C & D) == D
5252 auto MatchSubset
= [](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
5253 return RHS
->getAPIntValue().isSubsetOf(LHS
->getAPIntValue());
5255 if (N0
.getOpcode() == ISD::OR
&&
5256 ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchSubset
))
5258 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
5259 if (N1C
&& N0
.getOpcode() == ISD::ANY_EXTEND
) {
5260 SDValue N0Op0
= N0
.getOperand(0);
5261 APInt Mask
= ~N1C
->getAPIntValue();
5262 Mask
= Mask
.trunc(N0Op0
.getScalarValueSizeInBits());
5263 if (DAG
.MaskedValueIsZero(N0Op0
, Mask
)) {
5264 SDValue Zext
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
),
5265 N0
.getValueType(), N0Op0
);
5267 // Replace uses of the AND with uses of the Zero extend node.
5270 // We actually want to replace all uses of the any_extend with the
5271 // zero_extend, to avoid duplicating things. This will later cause this
5272 // AND to be folded.
5273 CombineTo(N0
.getNode(), Zext
);
5274 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5278 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
5279 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
5280 // already be zero by virtue of the width of the base type of the load.
5282 // the 'X' node here can either be nothing or an extract_vector_elt to catch
5284 if ((N0
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
5285 N0
.getValueSizeInBits() == N0
.getOperand(0).getScalarValueSizeInBits() &&
5286 N0
.getOperand(0).getOpcode() == ISD::LOAD
&&
5287 N0
.getOperand(0).getResNo() == 0) ||
5288 (N0
.getOpcode() == ISD::LOAD
&& N0
.getResNo() == 0)) {
5289 LoadSDNode
*Load
= cast
<LoadSDNode
>( (N0
.getOpcode() == ISD::LOAD
) ?
5290 N0
: N0
.getOperand(0) );
5292 // Get the constant (if applicable) the zero'th operand is being ANDed with.
5293 // This can be a pure constant or a vector splat, in which case we treat the
5294 // vector as a scalar and use the splat value.
5295 APInt Constant
= APInt::getNullValue(1);
5296 if (const ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N1
)) {
5297 Constant
= C
->getAPIntValue();
5298 } else if (BuildVectorSDNode
*Vector
= dyn_cast
<BuildVectorSDNode
>(N1
)) {
5299 APInt SplatValue
, SplatUndef
;
5300 unsigned SplatBitSize
;
5302 bool IsSplat
= Vector
->isConstantSplat(SplatValue
, SplatUndef
,
5303 SplatBitSize
, HasAnyUndefs
);
5305 // Undef bits can contribute to a possible optimisation if set, so
5307 SplatValue
|= SplatUndef
;
5309 // The splat value may be something like "0x00FFFFFF", which means 0 for
5310 // the first vector value and FF for the rest, repeating. We need a mask
5311 // that will apply equally to all members of the vector, so AND all the
5312 // lanes of the constant together.
5313 unsigned EltBitWidth
= Vector
->getValueType(0).getScalarSizeInBits();
5315 // If the splat value has been compressed to a bitlength lower
5316 // than the size of the vector lane, we need to re-expand it to
5318 if (EltBitWidth
> SplatBitSize
)
5319 for (SplatValue
= SplatValue
.zextOrTrunc(EltBitWidth
);
5320 SplatBitSize
< EltBitWidth
; SplatBitSize
= SplatBitSize
* 2)
5321 SplatValue
|= SplatValue
.shl(SplatBitSize
);
5323 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
5324 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
5325 if ((SplatBitSize
% EltBitWidth
) == 0) {
5326 Constant
= APInt::getAllOnesValue(EltBitWidth
);
5327 for (unsigned i
= 0, n
= (SplatBitSize
/ EltBitWidth
); i
< n
; ++i
)
5328 Constant
&= SplatValue
.extractBits(EltBitWidth
, i
* EltBitWidth
);
5333 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
5334 // actually legal and isn't going to get expanded, else this is a false
5336 bool CanZextLoadProfitably
= TLI
.isLoadExtLegal(ISD::ZEXTLOAD
,
5337 Load
->getValueType(0),
5338 Load
->getMemoryVT());
5340 // Resize the constant to the same size as the original memory access before
5341 // extension. If it is still the AllOnesValue then this AND is completely
5343 Constant
= Constant
.zextOrTrunc(Load
->getMemoryVT().getScalarSizeInBits());
5346 switch (Load
->getExtensionType()) {
5347 default: B
= false; break;
5348 case ISD::EXTLOAD
: B
= CanZextLoadProfitably
; break;
5350 case ISD::NON_EXTLOAD
: B
= true; break;
5353 if (B
&& Constant
.isAllOnesValue()) {
5354 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
5355 // preserve semantics once we get rid of the AND.
5356 SDValue
NewLoad(Load
, 0);
5358 // Fold the AND away. NewLoad may get replaced immediately.
5359 CombineTo(N
, (N0
.getNode() == Load
) ? NewLoad
: N0
);
5361 if (Load
->getExtensionType() == ISD::EXTLOAD
) {
5362 NewLoad
= DAG
.getLoad(Load
->getAddressingMode(), ISD::ZEXTLOAD
,
5363 Load
->getValueType(0), SDLoc(Load
),
5364 Load
->getChain(), Load
->getBasePtr(),
5365 Load
->getOffset(), Load
->getMemoryVT(),
5366 Load
->getMemOperand());
5367 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
5368 if (Load
->getNumValues() == 3) {
5369 // PRE/POST_INC loads have 3 values.
5370 SDValue To
[] = { NewLoad
.getValue(0), NewLoad
.getValue(1),
5371 NewLoad
.getValue(2) };
5372 CombineTo(Load
, To
, 3, true);
5374 CombineTo(Load
, NewLoad
.getValue(0), NewLoad
.getValue(1));
5378 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5382 // fold (and (load x), 255) -> (zextload x, i8)
5383 // fold (and (extload x, i16), 255) -> (zextload x, i8)
5384 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
5385 if (!VT
.isVector() && N1C
&& (N0
.getOpcode() == ISD::LOAD
||
5386 (N0
.getOpcode() == ISD::ANY_EXTEND
&&
5387 N0
.getOperand(0).getOpcode() == ISD::LOAD
))) {
5388 if (SDValue Res
= ReduceLoadWidth(N
)) {
5389 LoadSDNode
*LN0
= N0
->getOpcode() == ISD::ANY_EXTEND
5390 ? cast
<LoadSDNode
>(N0
.getOperand(0)) : cast
<LoadSDNode
>(N0
);
5392 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 0), Res
);
5393 return SDValue(N
, 0);
5397 if (Level
>= AfterLegalizeTypes
) {
5398 // Attempt to propagate the AND back up to the leaves which, if they're
5399 // loads, can be combined to narrow loads and the AND node can be removed.
5400 // Perform after legalization so that extend nodes will already be
5401 // combined into the loads.
5402 if (BackwardsPropagateMask(N
, DAG
)) {
5403 return SDValue(N
, 0);
5407 if (SDValue Combined
= visitANDLike(N0
, N1
, N
))
5410 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
5411 if (N0
.getOpcode() == N1
.getOpcode())
5412 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
5415 // Masking the negated extension of a boolean is just the zero-extended
5417 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
5418 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
5420 // Note: the SimplifyDemandedBits fold below can make an information-losing
5421 // transform, and then we have no way to find this better fold.
5422 if (N1C
&& N1C
->isOne() && N0
.getOpcode() == ISD::SUB
) {
5423 if (isNullOrNullSplat(N0
.getOperand(0))) {
5424 SDValue SubRHS
= N0
.getOperand(1);
5425 if (SubRHS
.getOpcode() == ISD::ZERO_EXTEND
&&
5426 SubRHS
.getOperand(0).getScalarValueSizeInBits() == 1)
5428 if (SubRHS
.getOpcode() == ISD::SIGN_EXTEND
&&
5429 SubRHS
.getOperand(0).getScalarValueSizeInBits() == 1)
5430 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), VT
, SubRHS
.getOperand(0));
5434 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
5435 // fold (and (sra)) -> (and (srl)) when possible.
5436 if (SimplifyDemandedBits(SDValue(N
, 0)))
5437 return SDValue(N
, 0);
5439 // fold (zext_inreg (extload x)) -> (zextload x)
5440 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
5441 if (ISD::isUNINDEXEDLoad(N0
.getNode()) &&
5442 (ISD::isEXTLoad(N0
.getNode()) ||
5443 (ISD::isSEXTLoad(N0
.getNode()) && N0
.hasOneUse()))) {
5444 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
5445 EVT MemVT
= LN0
->getMemoryVT();
5446 // If we zero all the possible extended bits, then we can turn this into
5447 // a zextload if we are running before legalize or the operation is legal.
5448 unsigned ExtBitSize
= N1
.getScalarValueSizeInBits();
5449 unsigned MemBitSize
= MemVT
.getScalarSizeInBits();
5450 APInt ExtBits
= APInt::getHighBitsSet(ExtBitSize
, ExtBitSize
- MemBitSize
);
5451 if (DAG
.MaskedValueIsZero(N1
, ExtBits
) &&
5452 ((!LegalOperations
&& !LN0
->isVolatile()) ||
5453 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
))) {
5455 DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(N0
), VT
, LN0
->getChain(),
5456 LN0
->getBasePtr(), MemVT
, LN0
->getMemOperand());
5458 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
5459 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
5463 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
5464 if (N1C
&& N1C
->getAPIntValue() == 0xffff && N0
.getOpcode() == ISD::OR
) {
5465 if (SDValue BSwap
= MatchBSwapHWordLow(N0
.getNode(), N0
.getOperand(0),
5466 N0
.getOperand(1), false))
5470 if (SDValue Shifts
= unfoldExtremeBitClearingToShifts(N
))
5476 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
5477 SDValue
DAGCombiner::MatchBSwapHWordLow(SDNode
*N
, SDValue N0
, SDValue N1
,
5478 bool DemandHighBits
) {
5479 if (!LegalOperations
)
5482 EVT VT
= N
->getValueType(0);
5483 if (VT
!= MVT::i64
&& VT
!= MVT::i32
&& VT
!= MVT::i16
)
5485 if (!TLI
.isOperationLegalOrCustom(ISD::BSWAP
, VT
))
5488 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
5489 bool LookPassAnd0
= false;
5490 bool LookPassAnd1
= false;
5491 if (N0
.getOpcode() == ISD::AND
&& N0
.getOperand(0).getOpcode() == ISD::SRL
)
5493 if (N1
.getOpcode() == ISD::AND
&& N1
.getOperand(0).getOpcode() == ISD::SHL
)
5495 if (N0
.getOpcode() == ISD::AND
) {
5496 if (!N0
.getNode()->hasOneUse())
5498 ConstantSDNode
*N01C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5499 // Also handle 0xffff since the LHS is guaranteed to have zeros there.
5500 // This is needed for X86.
5501 if (!N01C
|| (N01C
->getZExtValue() != 0xFF00 &&
5502 N01C
->getZExtValue() != 0xFFFF))
5504 N0
= N0
.getOperand(0);
5505 LookPassAnd0
= true;
5508 if (N1
.getOpcode() == ISD::AND
) {
5509 if (!N1
.getNode()->hasOneUse())
5511 ConstantSDNode
*N11C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1));
5512 if (!N11C
|| N11C
->getZExtValue() != 0xFF)
5514 N1
= N1
.getOperand(0);
5515 LookPassAnd1
= true;
5518 if (N0
.getOpcode() == ISD::SRL
&& N1
.getOpcode() == ISD::SHL
)
5520 if (N0
.getOpcode() != ISD::SHL
|| N1
.getOpcode() != ISD::SRL
)
5522 if (!N0
.getNode()->hasOneUse() || !N1
.getNode()->hasOneUse())
5525 ConstantSDNode
*N01C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5526 ConstantSDNode
*N11C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1));
5529 if (N01C
->getZExtValue() != 8 || N11C
->getZExtValue() != 8)
5532 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
5533 SDValue N00
= N0
->getOperand(0);
5534 if (!LookPassAnd0
&& N00
.getOpcode() == ISD::AND
) {
5535 if (!N00
.getNode()->hasOneUse())
5537 ConstantSDNode
*N001C
= dyn_cast
<ConstantSDNode
>(N00
.getOperand(1));
5538 if (!N001C
|| N001C
->getZExtValue() != 0xFF)
5540 N00
= N00
.getOperand(0);
5541 LookPassAnd0
= true;
5544 SDValue N10
= N1
->getOperand(0);
5545 if (!LookPassAnd1
&& N10
.getOpcode() == ISD::AND
) {
5546 if (!N10
.getNode()->hasOneUse())
5548 ConstantSDNode
*N101C
= dyn_cast
<ConstantSDNode
>(N10
.getOperand(1));
5549 // Also allow 0xFFFF since the bits will be shifted out. This is needed
5551 if (!N101C
|| (N101C
->getZExtValue() != 0xFF00 &&
5552 N101C
->getZExtValue() != 0xFFFF))
5554 N10
= N10
.getOperand(0);
5555 LookPassAnd1
= true;
5561 // Make sure everything beyond the low halfword gets set to zero since the SRL
5562 // 16 will clear the top bits.
5563 unsigned OpSizeInBits
= VT
.getSizeInBits();
5564 if (DemandHighBits
&& OpSizeInBits
> 16) {
5565 // If the left-shift isn't masked out then the only way this is a bswap is
5566 // if all bits beyond the low 8 are 0. In that case the entire pattern
5567 // reduces to a left shift anyway: leave it for other parts of the combiner.
5571 // However, if the right shift isn't masked out then it might be because
5572 // it's not needed. See if we can spot that too.
5573 if (!LookPassAnd1
&&
5574 !DAG
.MaskedValueIsZero(
5575 N10
, APInt::getHighBitsSet(OpSizeInBits
, OpSizeInBits
- 16)))
5579 SDValue Res
= DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, N00
);
5580 if (OpSizeInBits
> 16) {
5582 Res
= DAG
.getNode(ISD::SRL
, DL
, VT
, Res
,
5583 DAG
.getConstant(OpSizeInBits
- 16, DL
,
5584 getShiftAmountTy(VT
)));
5589 /// Return true if the specified node is an element that makes up a 32-bit
5590 /// packed halfword byteswap.
5591 /// ((x & 0x000000ff) << 8) |
5592 /// ((x & 0x0000ff00) >> 8) |
5593 /// ((x & 0x00ff0000) << 8) |
5594 /// ((x & 0xff000000) >> 8)
5595 static bool isBSwapHWordElement(SDValue N
, MutableArrayRef
<SDNode
*> Parts
) {
5596 if (!N
.getNode()->hasOneUse())
5599 unsigned Opc
= N
.getOpcode();
5600 if (Opc
!= ISD::AND
&& Opc
!= ISD::SHL
&& Opc
!= ISD::SRL
)
5603 SDValue N0
= N
.getOperand(0);
5604 unsigned Opc0
= N0
.getOpcode();
5605 if (Opc0
!= ISD::AND
&& Opc0
!= ISD::SHL
&& Opc0
!= ISD::SRL
)
5608 ConstantSDNode
*N1C
= nullptr;
5609 // SHL or SRL: look upstream for AND mask operand
5610 if (Opc
== ISD::AND
)
5611 N1C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5612 else if (Opc0
== ISD::AND
)
5613 N1C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5617 unsigned MaskByteOffset
;
5618 switch (N1C
->getZExtValue()) {
5621 case 0xFF: MaskByteOffset
= 0; break;
5622 case 0xFF00: MaskByteOffset
= 1; break;
5624 // In case demanded bits didn't clear the bits that will be shifted out.
5625 // This is needed for X86.
5626 if (Opc
== ISD::SRL
|| (Opc
== ISD::AND
&& Opc0
== ISD::SHL
)) {
5631 case 0xFF0000: MaskByteOffset
= 2; break;
5632 case 0xFF000000: MaskByteOffset
= 3; break;
5635 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
5636 if (Opc
== ISD::AND
) {
5637 if (MaskByteOffset
== 0 || MaskByteOffset
== 2) {
5639 // (x >> 8) & 0xff0000
5640 if (Opc0
!= ISD::SRL
)
5642 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5643 if (!C
|| C
->getZExtValue() != 8)
5646 // (x << 8) & 0xff00
5647 // (x << 8) & 0xff000000
5648 if (Opc0
!= ISD::SHL
)
5650 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
5651 if (!C
|| C
->getZExtValue() != 8)
5654 } else if (Opc
== ISD::SHL
) {
5656 // (x & 0xff0000) << 8
5657 if (MaskByteOffset
!= 0 && MaskByteOffset
!= 2)
5659 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5660 if (!C
|| C
->getZExtValue() != 8)
5662 } else { // Opc == ISD::SRL
5663 // (x & 0xff00) >> 8
5664 // (x & 0xff000000) >> 8
5665 if (MaskByteOffset
!= 1 && MaskByteOffset
!= 3)
5667 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N
.getOperand(1));
5668 if (!C
|| C
->getZExtValue() != 8)
5672 if (Parts
[MaskByteOffset
])
5675 Parts
[MaskByteOffset
] = N0
.getOperand(0).getNode();
5679 /// Match a 32-bit packed halfword bswap. That is
5680 /// ((x & 0x000000ff) << 8) |
5681 /// ((x & 0x0000ff00) >> 8) |
5682 /// ((x & 0x00ff0000) << 8) |
5683 /// ((x & 0xff000000) >> 8)
5684 /// => (rotl (bswap x), 16)
5685 SDValue
DAGCombiner::MatchBSwapHWord(SDNode
*N
, SDValue N0
, SDValue N1
) {
5686 if (!LegalOperations
)
5689 EVT VT
= N
->getValueType(0);
5692 if (!TLI
.isOperationLegalOrCustom(ISD::BSWAP
, VT
))
5696 // (or (or (and), (and)), (or (and), (and)))
5697 // (or (or (or (and), (and)), (and)), (and))
5698 if (N0
.getOpcode() != ISD::OR
)
5700 SDValue N00
= N0
.getOperand(0);
5701 SDValue N01
= N0
.getOperand(1);
5702 SDNode
*Parts
[4] = {};
5704 if (N1
.getOpcode() == ISD::OR
&&
5705 N00
.getNumOperands() == 2 && N01
.getNumOperands() == 2) {
5706 // (or (or (and), (and)), (or (and), (and)))
5707 if (!isBSwapHWordElement(N00
, Parts
))
5710 if (!isBSwapHWordElement(N01
, Parts
))
5712 SDValue N10
= N1
.getOperand(0);
5713 if (!isBSwapHWordElement(N10
, Parts
))
5715 SDValue N11
= N1
.getOperand(1);
5716 if (!isBSwapHWordElement(N11
, Parts
))
5719 // (or (or (or (and), (and)), (and)), (and))
5720 if (!isBSwapHWordElement(N1
, Parts
))
5722 if (!isBSwapHWordElement(N01
, Parts
))
5724 if (N00
.getOpcode() != ISD::OR
)
5726 SDValue N000
= N00
.getOperand(0);
5727 if (!isBSwapHWordElement(N000
, Parts
))
5729 SDValue N001
= N00
.getOperand(1);
5730 if (!isBSwapHWordElement(N001
, Parts
))
5734 // Make sure the parts are all coming from the same node.
5735 if (Parts
[0] != Parts
[1] || Parts
[0] != Parts
[2] || Parts
[0] != Parts
[3])
5739 SDValue BSwap
= DAG
.getNode(ISD::BSWAP
, DL
, VT
,
5740 SDValue(Parts
[0], 0));
5742 // Result of the bswap should be rotated by 16. If it's not legal, then
5743 // do (x << 16) | (x >> 16).
5744 SDValue ShAmt
= DAG
.getConstant(16, DL
, getShiftAmountTy(VT
));
5745 if (TLI
.isOperationLegalOrCustom(ISD::ROTL
, VT
))
5746 return DAG
.getNode(ISD::ROTL
, DL
, VT
, BSwap
, ShAmt
);
5747 if (TLI
.isOperationLegalOrCustom(ISD::ROTR
, VT
))
5748 return DAG
.getNode(ISD::ROTR
, DL
, VT
, BSwap
, ShAmt
);
5749 return DAG
.getNode(ISD::OR
, DL
, VT
,
5750 DAG
.getNode(ISD::SHL
, DL
, VT
, BSwap
, ShAmt
),
5751 DAG
.getNode(ISD::SRL
, DL
, VT
, BSwap
, ShAmt
));
5754 /// This contains all DAGCombine rules which reduce two values combined by
5755 /// an Or operation to a single value \see visitANDLike().
5756 SDValue
DAGCombiner::visitORLike(SDValue N0
, SDValue N1
, SDNode
*N
) {
5757 EVT VT
= N1
.getValueType();
5760 // fold (or x, undef) -> -1
5761 if (!LegalOperations
&& (N0
.isUndef() || N1
.isUndef()))
5762 return DAG
.getAllOnesConstant(DL
, VT
);
5764 if (SDValue V
= foldLogicOfSetCCs(false, N0
, N1
, DL
))
5767 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
5768 if (N0
.getOpcode() == ISD::AND
&& N1
.getOpcode() == ISD::AND
&&
5769 // Don't increase # computations.
5770 (N0
.getNode()->hasOneUse() || N1
.getNode()->hasOneUse())) {
5771 // We can only do this xform if we know that bits from X that are set in C2
5772 // but not in C1 are already zero. Likewise for Y.
5773 if (const ConstantSDNode
*N0O1C
=
5774 getAsNonOpaqueConstant(N0
.getOperand(1))) {
5775 if (const ConstantSDNode
*N1O1C
=
5776 getAsNonOpaqueConstant(N1
.getOperand(1))) {
5777 // We can only do this xform if we know that bits from X that are set in
5778 // C2 but not in C1 are already zero. Likewise for Y.
5779 const APInt
&LHSMask
= N0O1C
->getAPIntValue();
5780 const APInt
&RHSMask
= N1O1C
->getAPIntValue();
5782 if (DAG
.MaskedValueIsZero(N0
.getOperand(0), RHSMask
&~LHSMask
) &&
5783 DAG
.MaskedValueIsZero(N1
.getOperand(0), LHSMask
&~RHSMask
)) {
5784 SDValue X
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
,
5785 N0
.getOperand(0), N1
.getOperand(0));
5786 return DAG
.getNode(ISD::AND
, DL
, VT
, X
,
5787 DAG
.getConstant(LHSMask
| RHSMask
, DL
, VT
));
5793 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
5794 if (N0
.getOpcode() == ISD::AND
&&
5795 N1
.getOpcode() == ISD::AND
&&
5796 N0
.getOperand(0) == N1
.getOperand(0) &&
5797 // Don't increase # computations.
5798 (N0
.getNode()->hasOneUse() || N1
.getNode()->hasOneUse())) {
5799 SDValue X
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
,
5800 N0
.getOperand(1), N1
.getOperand(1));
5801 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), X
);
5807 /// OR combines for which the commuted variant will be tried as well.
5808 static SDValue
visitORCommutative(
5809 SelectionDAG
&DAG
, SDValue N0
, SDValue N1
, SDNode
*N
) {
5810 EVT VT
= N0
.getValueType();
5811 if (N0
.getOpcode() == ISD::AND
) {
5812 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
5813 if (isBitwiseNot(N0
.getOperand(1)) && N0
.getOperand(1).getOperand(0) == N1
)
5814 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
5816 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
5817 if (isBitwiseNot(N0
.getOperand(0)) && N0
.getOperand(0).getOperand(0) == N1
)
5818 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N0
.getOperand(1), N1
);
5824 SDValue
DAGCombiner::visitOR(SDNode
*N
) {
5825 SDValue N0
= N
->getOperand(0);
5826 SDValue N1
= N
->getOperand(1);
5827 EVT VT
= N1
.getValueType();
5834 if (VT
.isVector()) {
5835 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
5838 // fold (or x, 0) -> x, vector edition
5839 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
5841 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
5844 // fold (or x, -1) -> -1, vector edition
5845 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
5846 // do not return N0, because undef node may exist in N0
5847 return DAG
.getAllOnesConstant(SDLoc(N
), N0
.getValueType());
5848 if (ISD::isBuildVectorAllOnes(N1
.getNode()))
5849 // do not return N1, because undef node may exist in N1
5850 return DAG
.getAllOnesConstant(SDLoc(N
), N1
.getValueType());
5852 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
5853 // Do this only if the resulting shuffle is legal.
5854 if (isa
<ShuffleVectorSDNode
>(N0
) &&
5855 isa
<ShuffleVectorSDNode
>(N1
) &&
5856 // Avoid folding a node with illegal type.
5857 TLI
.isTypeLegal(VT
)) {
5858 bool ZeroN00
= ISD::isBuildVectorAllZeros(N0
.getOperand(0).getNode());
5859 bool ZeroN01
= ISD::isBuildVectorAllZeros(N0
.getOperand(1).getNode());
5860 bool ZeroN10
= ISD::isBuildVectorAllZeros(N1
.getOperand(0).getNode());
5861 bool ZeroN11
= ISD::isBuildVectorAllZeros(N1
.getOperand(1).getNode());
5862 // Ensure both shuffles have a zero input.
5863 if ((ZeroN00
!= ZeroN01
) && (ZeroN10
!= ZeroN11
)) {
5864 assert((!ZeroN00
|| !ZeroN01
) && "Both inputs zero!");
5865 assert((!ZeroN10
|| !ZeroN11
) && "Both inputs zero!");
5866 const ShuffleVectorSDNode
*SV0
= cast
<ShuffleVectorSDNode
>(N0
);
5867 const ShuffleVectorSDNode
*SV1
= cast
<ShuffleVectorSDNode
>(N1
);
5868 bool CanFold
= true;
5869 int NumElts
= VT
.getVectorNumElements();
5870 SmallVector
<int, 4> Mask(NumElts
);
5872 for (int i
= 0; i
!= NumElts
; ++i
) {
5873 int M0
= SV0
->getMaskElt(i
);
5874 int M1
= SV1
->getMaskElt(i
);
5876 // Determine if either index is pointing to a zero vector.
5877 bool M0Zero
= M0
< 0 || (ZeroN00
== (M0
< NumElts
));
5878 bool M1Zero
= M1
< 0 || (ZeroN10
== (M1
< NumElts
));
5880 // If one element is zero and the otherside is undef, keep undef.
5881 // This also handles the case that both are undef.
5882 if ((M0Zero
&& M1
< 0) || (M1Zero
&& M0
< 0)) {
5887 // Make sure only one of the elements is zero.
5888 if (M0Zero
== M1Zero
) {
5893 assert((M0
>= 0 || M1
>= 0) && "Undef index!");
5895 // We have a zero and non-zero element. If the non-zero came from
5896 // SV0 make the index a LHS index. If it came from SV1, make it
5897 // a RHS index. We need to mod by NumElts because we don't care
5898 // which operand it came from in the original shuffles.
5899 Mask
[i
] = M1Zero
? M0
% NumElts
: (M1
% NumElts
) + NumElts
;
5903 SDValue NewLHS
= ZeroN00
? N0
.getOperand(1) : N0
.getOperand(0);
5904 SDValue NewRHS
= ZeroN10
? N1
.getOperand(1) : N1
.getOperand(0);
5906 bool LegalMask
= TLI
.isShuffleMaskLegal(Mask
, VT
);
5908 std::swap(NewLHS
, NewRHS
);
5909 ShuffleVectorSDNode::commuteMask(Mask
);
5910 LegalMask
= TLI
.isShuffleMaskLegal(Mask
, VT
);
5914 return DAG
.getVectorShuffle(VT
, SDLoc(N
), NewLHS
, NewRHS
, Mask
);
5920 // fold (or c1, c2) -> c1|c2
5921 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
5922 ConstantSDNode
*N1C
= dyn_cast
<ConstantSDNode
>(N1
);
5923 if (N0C
&& N1C
&& !N1C
->isOpaque())
5924 return DAG
.FoldConstantArithmetic(ISD::OR
, SDLoc(N
), VT
, N0C
, N1C
);
5925 // canonicalize constant to RHS
5926 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
5927 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
5928 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, N1
, N0
);
5929 // fold (or x, 0) -> x
5930 if (isNullConstant(N1
))
5932 // fold (or x, -1) -> -1
5933 if (isAllOnesConstant(N1
))
5936 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
5939 // fold (or x, c) -> c iff (x & ~c) == 0
5940 if (N1C
&& DAG
.MaskedValueIsZero(N0
, ~N1C
->getAPIntValue()))
5943 if (SDValue Combined
= visitORLike(N0
, N1
, N
))
5946 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
5947 if (SDValue BSwap
= MatchBSwapHWord(N
, N0
, N1
))
5949 if (SDValue BSwap
= MatchBSwapHWordLow(N
, N0
, N1
))
5953 if (SDValue ROR
= reassociateOps(ISD::OR
, SDLoc(N
), N0
, N1
, N
->getFlags()))
5956 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
5957 // iff (c1 & c2) != 0 or c1/c2 are undef.
5958 auto MatchIntersect
= [](ConstantSDNode
*C1
, ConstantSDNode
*C2
) {
5959 return !C1
|| !C2
|| C1
->getAPIntValue().intersects(C2
->getAPIntValue());
5961 if (N0
.getOpcode() == ISD::AND
&& N0
.getNode()->hasOneUse() &&
5962 ISD::matchBinaryPredicate(N0
.getOperand(1), N1
, MatchIntersect
, true)) {
5963 if (SDValue COR
= DAG
.FoldConstantArithmetic(
5964 ISD::OR
, SDLoc(N1
), VT
, N1
.getNode(), N0
.getOperand(1).getNode())) {
5965 SDValue IOR
= DAG
.getNode(ISD::OR
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
5966 AddToWorklist(IOR
.getNode());
5967 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, COR
, IOR
);
5971 if (SDValue Combined
= visitORCommutative(DAG
, N0
, N1
, N
))
5973 if (SDValue Combined
= visitORCommutative(DAG
, N1
, N0
, N
))
5976 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
5977 if (N0
.getOpcode() == N1
.getOpcode())
5978 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
5981 // See if this is some rotate idiom.
5982 if (SDNode
*Rot
= MatchRotate(N0
, N1
, SDLoc(N
)))
5983 return SDValue(Rot
, 0);
5985 if (SDValue Load
= MatchLoadCombine(N
))
5988 // Simplify the operands using demanded-bits information.
5989 if (SimplifyDemandedBits(SDValue(N
, 0)))
5990 return SDValue(N
, 0);
5992 // If OR can be rewritten into ADD, try combines based on ADD.
5993 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::ADD
, VT
)) &&
5994 DAG
.haveNoCommonBitsSet(N0
, N1
))
5995 if (SDValue Combined
= visitADDLike(N
))
6001 static SDValue
stripConstantMask(SelectionDAG
&DAG
, SDValue Op
, SDValue
&Mask
) {
6002 if (Op
.getOpcode() == ISD::AND
&&
6003 DAG
.isConstantIntBuildVectorOrConstantInt(Op
.getOperand(1))) {
6004 Mask
= Op
.getOperand(1);
6005 return Op
.getOperand(0);
6010 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
6011 static bool matchRotateHalf(SelectionDAG
&DAG
, SDValue Op
, SDValue
&Shift
,
6013 Op
= stripConstantMask(DAG
, Op
, Mask
);
6014 if (Op
.getOpcode() == ISD::SRL
|| Op
.getOpcode() == ISD::SHL
) {
6021 /// Helper function for visitOR to extract the needed side of a rotate idiom
6022 /// from a shl/srl/mul/udiv. This is meant to handle cases where
6023 /// InstCombine merged some outside op with one of the shifts from
6024 /// the rotate pattern.
6025 /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
6026 /// Otherwise, returns an expansion of \p ExtractFrom based on the following
6029 /// (or (mul v c0) (shrl (mul v c1) c2)):
6030 /// expands (mul v c0) -> (shl (mul v c1) c3)
6032 /// (or (udiv v c0) (shl (udiv v c1) c2)):
6033 /// expands (udiv v c0) -> (shrl (udiv v c1) c3)
6035 /// (or (shl v c0) (shrl (shl v c1) c2)):
6036 /// expands (shl v c0) -> (shl (shl v c1) c3)
6038 /// (or (shrl v c0) (shl (shrl v c1) c2)):
6039 /// expands (shrl v c0) -> (shrl (shrl v c1) c3)
6041 /// Such that in all cases, c3+c2==bitwidth(op v c1).
6042 static SDValue
extractShiftForRotate(SelectionDAG
&DAG
, SDValue OppShift
,
6043 SDValue ExtractFrom
, SDValue
&Mask
,
6045 assert(OppShift
&& ExtractFrom
&& "Empty SDValue");
6047 (OppShift
.getOpcode() == ISD::SHL
|| OppShift
.getOpcode() == ISD::SRL
) &&
6048 "Existing shift must be valid as a rotate half");
6050 ExtractFrom
= stripConstantMask(DAG
, ExtractFrom
, Mask
);
6052 // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
6054 // Find opcode of the needed shift to be extracted from (op0 v c0).
6055 unsigned Opcode
= ISD::DELETED_NODE
;
6056 bool IsMulOrDiv
= false;
6057 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
6058 // opcode or its arithmetic (mul or udiv) variant.
6059 auto SelectOpcode
= [&](unsigned NeededShift
, unsigned MulOrDivVariant
) {
6060 IsMulOrDiv
= ExtractFrom
.getOpcode() == MulOrDivVariant
;
6061 if (!IsMulOrDiv
&& ExtractFrom
.getOpcode() != NeededShift
)
6063 Opcode
= NeededShift
;
6066 // op0 must be either the needed shift opcode or the mul/udiv equivalent
6067 // that the needed shift can be extracted from.
6068 if ((OppShift
.getOpcode() != ISD::SRL
|| !SelectOpcode(ISD::SHL
, ISD::MUL
)) &&
6069 (OppShift
.getOpcode() != ISD::SHL
|| !SelectOpcode(ISD::SRL
, ISD::UDIV
)))
6072 // op0 must be the same opcode on both sides, have the same LHS argument,
6073 // and produce the same value type.
6074 SDValue OppShiftLHS
= OppShift
.getOperand(0);
6075 EVT ShiftedVT
= OppShiftLHS
.getValueType();
6076 if (OppShiftLHS
.getOpcode() != ExtractFrom
.getOpcode() ||
6077 OppShiftLHS
.getOperand(0) != ExtractFrom
.getOperand(0) ||
6078 ShiftedVT
!= ExtractFrom
.getValueType())
6081 // Amount of the existing shift.
6082 ConstantSDNode
*OppShiftCst
= isConstOrConstSplat(OppShift
.getOperand(1));
6083 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
6084 ConstantSDNode
*OppLHSCst
= isConstOrConstSplat(OppShiftLHS
.getOperand(1));
6085 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
6086 ConstantSDNode
*ExtractFromCst
=
6087 isConstOrConstSplat(ExtractFrom
.getOperand(1));
6088 // TODO: We should be able to handle non-uniform constant vectors for these values
6089 // Check that we have constant values.
6090 if (!OppShiftCst
|| !OppShiftCst
->getAPIntValue() ||
6091 !OppLHSCst
|| !OppLHSCst
->getAPIntValue() ||
6092 !ExtractFromCst
|| !ExtractFromCst
->getAPIntValue())
6095 // Compute the shift amount we need to extract to complete the rotate.
6096 const unsigned VTWidth
= ShiftedVT
.getScalarSizeInBits();
6097 if (OppShiftCst
->getAPIntValue().ugt(VTWidth
))
6099 APInt NeededShiftAmt
= VTWidth
- OppShiftCst
->getAPIntValue();
6100 // Normalize the bitwidth of the two mul/udiv/shift constant operands.
6101 APInt ExtractFromAmt
= ExtractFromCst
->getAPIntValue();
6102 APInt OppLHSAmt
= OppLHSCst
->getAPIntValue();
6103 zeroExtendToMatch(ExtractFromAmt
, OppLHSAmt
);
6105 // Now try extract the needed shift from the ExtractFrom op and see if the
6106 // result matches up with the existing shift's LHS op.
6108 // Op to extract from is a mul or udiv by a constant.
6110 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
6111 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
6112 const APInt ExtractDiv
= APInt::getOneBitSet(ExtractFromAmt
.getBitWidth(),
6113 NeededShiftAmt
.getZExtValue());
6116 APInt::udivrem(ExtractFromAmt
, ExtractDiv
, ResultAmt
, Rem
);
6117 if (Rem
!= 0 || ResultAmt
!= OppLHSAmt
)
6120 // Op to extract from is a shift by a constant.
6122 // c2 - (bitwidth(op0 v c0) - c1) == c0
6123 if (OppLHSAmt
!= ExtractFromAmt
- NeededShiftAmt
.zextOrTrunc(
6124 ExtractFromAmt
.getBitWidth()))
6128 // Return the expanded shift op that should allow a rotate to be formed.
6129 EVT ShiftVT
= OppShift
.getOperand(1).getValueType();
6130 EVT ResVT
= ExtractFrom
.getValueType();
6131 SDValue NewShiftNode
= DAG
.getConstant(NeededShiftAmt
, DL
, ShiftVT
);
6132 return DAG
.getNode(Opcode
, DL
, ResVT
, OppShiftLHS
, NewShiftNode
);
6135 // Return true if we can prove that, whenever Neg and Pos are both in the
6136 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
6137 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
6139 // (or (shift1 X, Neg), (shift2 X, Pos))
6141 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
6142 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
6143 // to consider shift amounts with defined behavior.
6144 static bool matchRotateSub(SDValue Pos
, SDValue Neg
, unsigned EltSize
,
6145 SelectionDAG
&DAG
) {
6146 // If EltSize is a power of 2 then:
6148 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
6149 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
6151 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
6152 // for the stronger condition:
6154 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
6156 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
6157 // we can just replace Neg with Neg' for the rest of the function.
6159 // In other cases we check for the even stronger condition:
6161 // Neg == EltSize - Pos [B]
6163 // for all Neg and Pos. Note that the (or ...) then invokes undefined
6164 // behavior if Pos == 0 (and consequently Neg == EltSize).
6166 // We could actually use [A] whenever EltSize is a power of 2, but the
6167 // only extra cases that it would match are those uninteresting ones
6168 // where Neg and Pos are never in range at the same time. E.g. for
6169 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
6170 // as well as (sub 32, Pos), but:
6172 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
6174 // always invokes undefined behavior for 32-bit X.
6176 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
6177 unsigned MaskLoBits
= 0;
6178 if (Neg
.getOpcode() == ISD::AND
&& isPowerOf2_64(EltSize
)) {
6179 if (ConstantSDNode
*NegC
= isConstOrConstSplat(Neg
.getOperand(1))) {
6180 KnownBits Known
= DAG
.computeKnownBits(Neg
.getOperand(0));
6181 unsigned Bits
= Log2_64(EltSize
);
6182 if (NegC
->getAPIntValue().getActiveBits() <= Bits
&&
6183 ((NegC
->getAPIntValue() | Known
.Zero
).countTrailingOnes() >= Bits
)) {
6184 Neg
= Neg
.getOperand(0);
6190 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
6191 if (Neg
.getOpcode() != ISD::SUB
)
6193 ConstantSDNode
*NegC
= isConstOrConstSplat(Neg
.getOperand(0));
6196 SDValue NegOp1
= Neg
.getOperand(1);
6198 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
6199 // Pos'. The truncation is redundant for the purpose of the equality.
6200 if (MaskLoBits
&& Pos
.getOpcode() == ISD::AND
) {
6201 if (ConstantSDNode
*PosC
= isConstOrConstSplat(Pos
.getOperand(1))) {
6202 KnownBits Known
= DAG
.computeKnownBits(Pos
.getOperand(0));
6203 if (PosC
->getAPIntValue().getActiveBits() <= MaskLoBits
&&
6204 ((PosC
->getAPIntValue() | Known
.Zero
).countTrailingOnes() >=
6206 Pos
= Pos
.getOperand(0);
6210 // The condition we need is now:
6212 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
6214 // If NegOp1 == Pos then we need:
6216 // EltSize & Mask == NegC & Mask
6218 // (because "x & Mask" is a truncation and distributes through subtraction).
6221 Width
= NegC
->getAPIntValue();
6223 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
6224 // Then the condition we want to prove becomes:
6226 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
6228 // which, again because "x & Mask" is a truncation, becomes:
6230 // NegC & Mask == (EltSize - PosC) & Mask
6231 // EltSize & Mask == (NegC + PosC) & Mask
6232 else if (Pos
.getOpcode() == ISD::ADD
&& Pos
.getOperand(0) == NegOp1
) {
6233 if (ConstantSDNode
*PosC
= isConstOrConstSplat(Pos
.getOperand(1)))
6234 Width
= PosC
->getAPIntValue() + NegC
->getAPIntValue();
6240 // Now we just need to check that EltSize & Mask == Width & Mask.
6242 // EltSize & Mask is 0 since Mask is EltSize - 1.
6243 return Width
.getLoBits(MaskLoBits
) == 0;
6244 return Width
== EltSize
;
6247 // A subroutine of MatchRotate used once we have found an OR of two opposite
6248 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
6249 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
6250 // former being preferred if supported. InnerPos and InnerNeg are Pos and
6251 // Neg with outer conversions stripped away.
6252 SDNode
*DAGCombiner::MatchRotatePosNeg(SDValue Shifted
, SDValue Pos
,
6253 SDValue Neg
, SDValue InnerPos
,
6254 SDValue InnerNeg
, unsigned PosOpcode
,
6255 unsigned NegOpcode
, const SDLoc
&DL
) {
6256 // fold (or (shl x, (*ext y)),
6257 // (srl x, (*ext (sub 32, y)))) ->
6258 // (rotl x, y) or (rotr x, (sub 32, y))
6260 // fold (or (shl x, (*ext (sub 32, y))),
6261 // (srl x, (*ext y))) ->
6262 // (rotr x, y) or (rotl x, (sub 32, y))
6263 EVT VT
= Shifted
.getValueType();
6264 if (matchRotateSub(InnerPos
, InnerNeg
, VT
.getScalarSizeInBits(), DAG
)) {
6265 bool HasPos
= TLI
.isOperationLegalOrCustom(PosOpcode
, VT
);
6266 return DAG
.getNode(HasPos
? PosOpcode
: NegOpcode
, DL
, VT
, Shifted
,
6267 HasPos
? Pos
: Neg
).getNode();
6273 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
6274 // idioms for rotate, and if the target supports rotation instructions, generate
6276 SDNode
*DAGCombiner::MatchRotate(SDValue LHS
, SDValue RHS
, const SDLoc
&DL
) {
6277 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
6278 EVT VT
= LHS
.getValueType();
6279 if (!TLI
.isTypeLegal(VT
)) return nullptr;
6281 // The target must have at least one rotate flavor.
6282 bool HasROTL
= hasOperation(ISD::ROTL
, VT
);
6283 bool HasROTR
= hasOperation(ISD::ROTR
, VT
);
6284 if (!HasROTL
&& !HasROTR
) return nullptr;
6286 // Check for truncated rotate.
6287 if (LHS
.getOpcode() == ISD::TRUNCATE
&& RHS
.getOpcode() == ISD::TRUNCATE
&&
6288 LHS
.getOperand(0).getValueType() == RHS
.getOperand(0).getValueType()) {
6289 assert(LHS
.getValueType() == RHS
.getValueType());
6290 if (SDNode
*Rot
= MatchRotate(LHS
.getOperand(0), RHS
.getOperand(0), DL
)) {
6291 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(LHS
), LHS
.getValueType(),
6292 SDValue(Rot
, 0)).getNode();
6296 // Match "(X shl/srl V1) & V2" where V2 may not be present.
6297 SDValue LHSShift
; // The shift.
6298 SDValue LHSMask
; // AND value if any.
6299 matchRotateHalf(DAG
, LHS
, LHSShift
, LHSMask
);
6301 SDValue RHSShift
; // The shift.
6302 SDValue RHSMask
; // AND value if any.
6303 matchRotateHalf(DAG
, RHS
, RHSShift
, RHSMask
);
6305 // If neither side matched a rotate half, bail
6306 if (!LHSShift
&& !RHSShift
)
6309 // InstCombine may have combined a constant shl, srl, mul, or udiv with one
6310 // side of the rotate, so try to handle that here. In all cases we need to
6311 // pass the matched shift from the opposite side to compute the opcode and
6312 // needed shift amount to extract. We still want to do this if both sides
6313 // matched a rotate half because one half may be a potential overshift that
6314 // can be broken down (ie if InstCombine merged two shl or srl ops into a
6317 // Have LHS side of the rotate, try to extract the needed shift from the RHS.
6319 if (SDValue NewRHSShift
=
6320 extractShiftForRotate(DAG
, LHSShift
, RHS
, RHSMask
, DL
))
6321 RHSShift
= NewRHSShift
;
6322 // Have RHS side of the rotate, try to extract the needed shift from the LHS.
6324 if (SDValue NewLHSShift
=
6325 extractShiftForRotate(DAG
, RHSShift
, LHS
, LHSMask
, DL
))
6326 LHSShift
= NewLHSShift
;
6328 // If a side is still missing, nothing else we can do.
6329 if (!RHSShift
|| !LHSShift
)
6332 // At this point we've matched or extracted a shift op on each side.
6334 if (LHSShift
.getOperand(0) != RHSShift
.getOperand(0))
6335 return nullptr; // Not shifting the same value.
6337 if (LHSShift
.getOpcode() == RHSShift
.getOpcode())
6338 return nullptr; // Shifts must disagree.
6340 // Canonicalize shl to left side in a shl/srl pair.
6341 if (RHSShift
.getOpcode() == ISD::SHL
) {
6342 std::swap(LHS
, RHS
);
6343 std::swap(LHSShift
, RHSShift
);
6344 std::swap(LHSMask
, RHSMask
);
6347 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
6348 SDValue LHSShiftArg
= LHSShift
.getOperand(0);
6349 SDValue LHSShiftAmt
= LHSShift
.getOperand(1);
6350 SDValue RHSShiftArg
= RHSShift
.getOperand(0);
6351 SDValue RHSShiftAmt
= RHSShift
.getOperand(1);
6353 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
6354 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
6355 auto MatchRotateSum
= [EltSizeInBits
](ConstantSDNode
*LHS
,
6356 ConstantSDNode
*RHS
) {
6357 return (LHS
->getAPIntValue() + RHS
->getAPIntValue()) == EltSizeInBits
;
6359 if (ISD::matchBinaryPredicate(LHSShiftAmt
, RHSShiftAmt
, MatchRotateSum
)) {
6360 SDValue Rot
= DAG
.getNode(HasROTL
? ISD::ROTL
: ISD::ROTR
, DL
, VT
,
6361 LHSShiftArg
, HasROTL
? LHSShiftAmt
: RHSShiftAmt
);
6363 // If there is an AND of either shifted operand, apply it to the result.
6364 if (LHSMask
.getNode() || RHSMask
.getNode()) {
6365 SDValue AllOnes
= DAG
.getAllOnesConstant(DL
, VT
);
6366 SDValue Mask
= AllOnes
;
6368 if (LHSMask
.getNode()) {
6369 SDValue RHSBits
= DAG
.getNode(ISD::SRL
, DL
, VT
, AllOnes
, RHSShiftAmt
);
6370 Mask
= DAG
.getNode(ISD::AND
, DL
, VT
, Mask
,
6371 DAG
.getNode(ISD::OR
, DL
, VT
, LHSMask
, RHSBits
));
6373 if (RHSMask
.getNode()) {
6374 SDValue LHSBits
= DAG
.getNode(ISD::SHL
, DL
, VT
, AllOnes
, LHSShiftAmt
);
6375 Mask
= DAG
.getNode(ISD::AND
, DL
, VT
, Mask
,
6376 DAG
.getNode(ISD::OR
, DL
, VT
, RHSMask
, LHSBits
));
6379 Rot
= DAG
.getNode(ISD::AND
, DL
, VT
, Rot
, Mask
);
6382 return Rot
.getNode();
6385 // If there is a mask here, and we have a variable shift, we can't be sure
6386 // that we're masking out the right stuff.
6387 if (LHSMask
.getNode() || RHSMask
.getNode())
6390 // If the shift amount is sign/zext/any-extended just peel it off.
6391 SDValue LExtOp0
= LHSShiftAmt
;
6392 SDValue RExtOp0
= RHSShiftAmt
;
6393 if ((LHSShiftAmt
.getOpcode() == ISD::SIGN_EXTEND
||
6394 LHSShiftAmt
.getOpcode() == ISD::ZERO_EXTEND
||
6395 LHSShiftAmt
.getOpcode() == ISD::ANY_EXTEND
||
6396 LHSShiftAmt
.getOpcode() == ISD::TRUNCATE
) &&
6397 (RHSShiftAmt
.getOpcode() == ISD::SIGN_EXTEND
||
6398 RHSShiftAmt
.getOpcode() == ISD::ZERO_EXTEND
||
6399 RHSShiftAmt
.getOpcode() == ISD::ANY_EXTEND
||
6400 RHSShiftAmt
.getOpcode() == ISD::TRUNCATE
)) {
6401 LExtOp0
= LHSShiftAmt
.getOperand(0);
6402 RExtOp0
= RHSShiftAmt
.getOperand(0);
6405 SDNode
*TryL
= MatchRotatePosNeg(LHSShiftArg
, LHSShiftAmt
, RHSShiftAmt
,
6406 LExtOp0
, RExtOp0
, ISD::ROTL
, ISD::ROTR
, DL
);
6410 SDNode
*TryR
= MatchRotatePosNeg(RHSShiftArg
, RHSShiftAmt
, LHSShiftAmt
,
6411 RExtOp0
, LExtOp0
, ISD::ROTR
, ISD::ROTL
, DL
);
6420 /// Represents known origin of an individual byte in load combine pattern. The
6421 /// value of the byte is either constant zero or comes from memory.
6422 struct ByteProvider
{
6423 // For constant zero providers Load is set to nullptr. For memory providers
6424 // Load represents the node which loads the byte from memory.
6425 // ByteOffset is the offset of the byte in the value produced by the load.
6426 LoadSDNode
*Load
= nullptr;
6427 unsigned ByteOffset
= 0;
6429 ByteProvider() = default;
6431 static ByteProvider
getMemory(LoadSDNode
*Load
, unsigned ByteOffset
) {
6432 return ByteProvider(Load
, ByteOffset
);
6435 static ByteProvider
getConstantZero() { return ByteProvider(nullptr, 0); }
6437 bool isConstantZero() const { return !Load
; }
6438 bool isMemory() const { return Load
; }
6440 bool operator==(const ByteProvider
&Other
) const {
6441 return Other
.Load
== Load
&& Other
.ByteOffset
== ByteOffset
;
6445 ByteProvider(LoadSDNode
*Load
, unsigned ByteOffset
)
6446 : Load(Load
), ByteOffset(ByteOffset
) {}
6449 } // end anonymous namespace
6451 /// Recursively traverses the expression calculating the origin of the requested
6452 /// byte of the given value. Returns None if the provider can't be calculated.
6454 /// For all the values except the root of the expression verifies that the value
6455 /// has exactly one use and if it's not true return None. This way if the origin
6456 /// of the byte is returned it's guaranteed that the values which contribute to
6457 /// the byte are not used outside of this expression.
6459 /// Because the parts of the expression are not allowed to have more than one
6460 /// use this function iterates over trees, not DAGs. So it never visits the same
6461 /// node more than once.
6462 static const Optional
<ByteProvider
>
6463 calculateByteProvider(SDValue Op
, unsigned Index
, unsigned Depth
,
6464 bool Root
= false) {
6465 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
6469 if (!Root
&& !Op
.hasOneUse())
6472 assert(Op
.getValueType().isScalarInteger() && "can't handle other types");
6473 unsigned BitWidth
= Op
.getValueSizeInBits();
6474 if (BitWidth
% 8 != 0)
6476 unsigned ByteWidth
= BitWidth
/ 8;
6477 assert(Index
< ByteWidth
&& "invalid index requested");
6480 switch (Op
.getOpcode()) {
6482 auto LHS
= calculateByteProvider(Op
->getOperand(0), Index
, Depth
+ 1);
6485 auto RHS
= calculateByteProvider(Op
->getOperand(1), Index
, Depth
+ 1);
6489 if (LHS
->isConstantZero())
6491 if (RHS
->isConstantZero())
6496 auto ShiftOp
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1));
6500 uint64_t BitShift
= ShiftOp
->getZExtValue();
6501 if (BitShift
% 8 != 0)
6503 uint64_t ByteShift
= BitShift
/ 8;
6505 return Index
< ByteShift
6506 ? ByteProvider::getConstantZero()
6507 : calculateByteProvider(Op
->getOperand(0), Index
- ByteShift
,
6510 case ISD::ANY_EXTEND
:
6511 case ISD::SIGN_EXTEND
:
6512 case ISD::ZERO_EXTEND
: {
6513 SDValue NarrowOp
= Op
->getOperand(0);
6514 unsigned NarrowBitWidth
= NarrowOp
.getScalarValueSizeInBits();
6515 if (NarrowBitWidth
% 8 != 0)
6517 uint64_t NarrowByteWidth
= NarrowBitWidth
/ 8;
6519 if (Index
>= NarrowByteWidth
)
6520 return Op
.getOpcode() == ISD::ZERO_EXTEND
6521 ? Optional
<ByteProvider
>(ByteProvider::getConstantZero())
6523 return calculateByteProvider(NarrowOp
, Index
, Depth
+ 1);
6526 return calculateByteProvider(Op
->getOperand(0), ByteWidth
- Index
- 1,
6529 auto L
= cast
<LoadSDNode
>(Op
.getNode());
6530 if (L
->isVolatile() || L
->isIndexed())
6533 unsigned NarrowBitWidth
= L
->getMemoryVT().getSizeInBits();
6534 if (NarrowBitWidth
% 8 != 0)
6536 uint64_t NarrowByteWidth
= NarrowBitWidth
/ 8;
6538 if (Index
>= NarrowByteWidth
)
6539 return L
->getExtensionType() == ISD::ZEXTLOAD
6540 ? Optional
<ByteProvider
>(ByteProvider::getConstantZero())
6542 return ByteProvider::getMemory(L
, Index
);
6549 static unsigned LittleEndianByteAt(unsigned BW
, unsigned i
) {
6553 static unsigned BigEndianByteAt(unsigned BW
, unsigned i
) {
6557 // Check if the bytes offsets we are looking at match with either big or
6558 // little endian value loaded. Return true for big endian, false for little
6559 // endian, and None if match failed.
6560 static Optional
<bool> isBigEndian(const SmallVector
<int64_t, 4> &ByteOffsets
,
6561 int64_t FirstOffset
) {
6562 // The endian can be decided only when it is 2 bytes at least.
6563 unsigned Width
= ByteOffsets
.size();
6567 bool BigEndian
= true, LittleEndian
= true;
6568 for (unsigned i
= 0; i
< Width
; i
++) {
6569 int64_t CurrentByteOffset
= ByteOffsets
[i
] - FirstOffset
;
6570 LittleEndian
&= CurrentByteOffset
== LittleEndianByteAt(Width
, i
);
6571 BigEndian
&= CurrentByteOffset
== BigEndianByteAt(Width
, i
);
6572 if (!BigEndian
&& !LittleEndian
)
6576 assert((BigEndian
!= LittleEndian
) && "It should be either big endian or"
6581 static SDValue
stripTruncAndExt(SDValue Value
) {
6582 switch (Value
.getOpcode()) {
6584 case ISD::ZERO_EXTEND
:
6585 case ISD::SIGN_EXTEND
:
6586 case ISD::ANY_EXTEND
:
6587 return stripTruncAndExt(Value
.getOperand(0));
6592 /// Match a pattern where a wide type scalar value is stored by several narrow
6593 /// stores. Fold it into a single store or a BSWAP and a store if the targets
6596 /// Assuming little endian target:
6599 /// p[0] = (val >> 0) & 0xFF;
6600 /// p[1] = (val >> 8) & 0xFF;
6601 /// p[2] = (val >> 16) & 0xFF;
6602 /// p[3] = (val >> 24) & 0xFF;
6604 /// *((i32)p) = val;
6608 /// p[0] = (val >> 24) & 0xFF;
6609 /// p[1] = (val >> 16) & 0xFF;
6610 /// p[2] = (val >> 8) & 0xFF;
6611 /// p[3] = (val >> 0) & 0xFF;
6613 /// *((i32)p) = BSWAP(val);
6614 SDValue
DAGCombiner::MatchStoreCombine(StoreSDNode
*N
) {
6615 // Collect all the stores in the chain.
6617 SmallVector
<StoreSDNode
*, 8> Stores
;
6618 for (StoreSDNode
*Store
= N
; Store
; Store
= dyn_cast
<StoreSDNode
>(Chain
)) {
6619 if (Store
->getMemoryVT() != MVT::i8
||
6620 Store
->isVolatile() || Store
->isIndexed())
6622 Stores
.push_back(Store
);
6623 Chain
= Store
->getChain();
6625 // Handle the simple type only.
6626 unsigned Width
= Stores
.size();
6627 EVT VT
= EVT::getIntegerVT(
6628 *DAG
.getContext(), Width
* N
->getMemoryVT().getSizeInBits());
6629 if (VT
!= MVT::i16
&& VT
!= MVT::i32
&& VT
!= MVT::i64
)
6632 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6633 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::STORE
, VT
))
6636 // Check if all the bytes of the combined value we are looking at are stored
6637 // to the same base address. Collect bytes offsets from Base address into
6639 SDValue CombinedValue
;
6640 SmallVector
<int64_t, 4> ByteOffsets(Width
, INT64_MAX
);
6641 int64_t FirstOffset
= INT64_MAX
;
6642 StoreSDNode
*FirstStore
= nullptr;
6643 Optional
<BaseIndexOffset
> Base
;
6644 for (auto Store
: Stores
) {
6645 // All the stores store different byte of the CombinedValue. A truncate is
6646 // required to get that byte value.
6647 SDValue Trunc
= Store
->getValue();
6648 if (Trunc
.getOpcode() != ISD::TRUNCATE
)
6650 // A shift operation is required to get the right byte offset, except the
6653 SDValue Value
= Trunc
.getOperand(0);
6654 if (Value
.getOpcode() == ISD::SRL
||
6655 Value
.getOpcode() == ISD::SRA
) {
6656 ConstantSDNode
*ShiftOffset
=
6657 dyn_cast
<ConstantSDNode
>(Value
.getOperand(1));
6658 // Trying to match the following pattern. The shift offset must be
6659 // a constant and a multiple of 8. It is the byte offset in "y".
6661 // x = srl y, offset
6664 if (!ShiftOffset
|| (ShiftOffset
->getSExtValue() % 8))
6667 Offset
= ShiftOffset
->getSExtValue()/8;
6668 Value
= Value
.getOperand(0);
6671 // Stores must share the same combined value with different offsets.
6673 CombinedValue
= Value
;
6674 else if (stripTruncAndExt(CombinedValue
) != stripTruncAndExt(Value
))
6677 // The trunc and all the extend operation should be stripped to get the
6678 // real value we are stored.
6679 else if (CombinedValue
.getValueType() != VT
) {
6680 if (Value
.getValueType() == VT
||
6681 Value
.getValueSizeInBits() > CombinedValue
.getValueSizeInBits())
6682 CombinedValue
= Value
;
6683 // Give up if the combined value type is smaller than the store size.
6684 if (CombinedValue
.getValueSizeInBits() < VT
.getSizeInBits())
6688 // Stores must share the same base address
6689 BaseIndexOffset Ptr
= BaseIndexOffset::match(Store
, DAG
);
6690 int64_t ByteOffsetFromBase
= 0;
6693 else if (!Base
->equalBaseIndex(Ptr
, DAG
, ByteOffsetFromBase
))
6696 // Remember the first byte store
6697 if (ByteOffsetFromBase
< FirstOffset
) {
6699 FirstOffset
= ByteOffsetFromBase
;
6701 // Map the offset in the store and the offset in the combined value, and
6702 // early return if it has been set before.
6703 if (Offset
< 0 || Offset
>= Width
|| ByteOffsets
[Offset
] != INT64_MAX
)
6705 ByteOffsets
[Offset
] = ByteOffsetFromBase
;
6708 assert(FirstOffset
!= INT64_MAX
&& "First byte offset must be set");
6709 assert(FirstStore
&& "First store must be set");
6711 // Check if the bytes of the combined value we are looking at match with
6712 // either big or little endian value store.
6713 Optional
<bool> IsBigEndian
= isBigEndian(ByteOffsets
, FirstOffset
);
6714 if (!IsBigEndian
.hasValue())
6717 // The node we are looking at matches with the pattern, check if we can
6718 // replace it with a single bswap if needed and store.
6720 // If the store needs byte swap check if the target supports it
6721 bool NeedsBswap
= DAG
.getDataLayout().isBigEndian() != *IsBigEndian
;
6723 // Before legalize we can introduce illegal bswaps which will be later
6724 // converted to an explicit bswap sequence. This way we end up with a single
6725 // store and byte shuffling instead of several stores and byte shuffling.
6726 if (NeedsBswap
&& LegalOperations
&& !TLI
.isOperationLegal(ISD::BSWAP
, VT
))
6729 // Check that a store of the wide type is both allowed and fast on the target
6732 TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(), VT
,
6733 *FirstStore
->getMemOperand(), &Fast
);
6734 if (!Allowed
|| !Fast
)
6737 if (VT
!= CombinedValue
.getValueType()) {
6738 assert(CombinedValue
.getValueType().getSizeInBits() > VT
.getSizeInBits() &&
6739 "Get unexpected store value to combine");
6740 CombinedValue
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
,
6745 CombinedValue
= DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, CombinedValue
);
6748 DAG
.getStore(Chain
, SDLoc(N
), CombinedValue
, FirstStore
->getBasePtr(),
6749 FirstStore
->getPointerInfo(), FirstStore
->getAlignment());
6751 // Rely on other DAG combine rules to remove the other individual stores.
6752 DAG
.ReplaceAllUsesWith(N
, NewStore
.getNode());
6756 /// Match a pattern where a wide type scalar value is loaded by several narrow
6757 /// loads and combined by shifts and ors. Fold it into a single load or a load
6758 /// and a BSWAP if the targets supports it.
6760 /// Assuming little endian target:
6762 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
6764 /// i32 val = *((i32)a)
6767 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
6769 /// i32 val = BSWAP(*((i32)a))
6771 /// TODO: This rule matches complex patterns with OR node roots and doesn't
6772 /// interact well with the worklist mechanism. When a part of the pattern is
6773 /// updated (e.g. one of the loads) its direct users are put into the worklist,
6774 /// but the root node of the pattern which triggers the load combine is not
6775 /// necessarily a direct user of the changed node. For example, once the address
6776 /// of t28 load is reassociated load combine won't be triggered:
6777 /// t25: i32 = add t4, Constant:i32<2>
6778 /// t26: i64 = sign_extend t25
6779 /// t27: i64 = add t2, t26
6780 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
6781 /// t29: i32 = zero_extend t28
6782 /// t32: i32 = shl t29, Constant:i8<8>
6783 /// t33: i32 = or t23, t32
6784 /// As a possible fix visitLoad can check if the load can be a part of a load
6785 /// combine pattern and add corresponding OR roots to the worklist.
6786 SDValue
DAGCombiner::MatchLoadCombine(SDNode
*N
) {
6787 assert(N
->getOpcode() == ISD::OR
&&
6788 "Can only match load combining against OR nodes");
6790 // Handles simple types only
6791 EVT VT
= N
->getValueType(0);
6792 if (VT
!= MVT::i16
&& VT
!= MVT::i32
&& VT
!= MVT::i64
)
6794 unsigned ByteWidth
= VT
.getSizeInBits() / 8;
6796 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
6797 // Before legalize we can introduce too wide illegal loads which will be later
6798 // split into legal sized loads. This enables us to combine i64 load by i8
6799 // patterns to a couple of i32 loads on 32 bit targets.
6800 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::LOAD
, VT
))
6803 bool IsBigEndianTarget
= DAG
.getDataLayout().isBigEndian();
6804 auto MemoryByteOffset
= [&] (ByteProvider P
) {
6805 assert(P
.isMemory() && "Must be a memory byte provider");
6806 unsigned LoadBitWidth
= P
.Load
->getMemoryVT().getSizeInBits();
6807 assert(LoadBitWidth
% 8 == 0 &&
6808 "can only analyze providers for individual bytes not bit");
6809 unsigned LoadByteWidth
= LoadBitWidth
/ 8;
6810 return IsBigEndianTarget
6811 ? BigEndianByteAt(LoadByteWidth
, P
.ByteOffset
)
6812 : LittleEndianByteAt(LoadByteWidth
, P
.ByteOffset
);
6815 Optional
<BaseIndexOffset
> Base
;
6818 SmallPtrSet
<LoadSDNode
*, 8> Loads
;
6819 Optional
<ByteProvider
> FirstByteProvider
;
6820 int64_t FirstOffset
= INT64_MAX
;
6822 // Check if all the bytes of the OR we are looking at are loaded from the same
6823 // base address. Collect bytes offsets from Base address in ByteOffsets.
6824 SmallVector
<int64_t, 4> ByteOffsets(ByteWidth
);
6825 for (unsigned i
= 0; i
< ByteWidth
; i
++) {
6826 auto P
= calculateByteProvider(SDValue(N
, 0), i
, 0, /*Root=*/true);
6827 if (!P
|| !P
->isMemory()) // All the bytes must be loaded from memory
6830 LoadSDNode
*L
= P
->Load
;
6831 assert(L
->hasNUsesOfValue(1, 0) && !L
->isVolatile() && !L
->isIndexed() &&
6832 "Must be enforced by calculateByteProvider");
6833 assert(L
->getOffset().isUndef() && "Unindexed load must have undef offset");
6835 // All loads must share the same chain
6836 SDValue LChain
= L
->getChain();
6839 else if (Chain
!= LChain
)
6842 // Loads must share the same base address
6843 BaseIndexOffset Ptr
= BaseIndexOffset::match(L
, DAG
);
6844 int64_t ByteOffsetFromBase
= 0;
6847 else if (!Base
->equalBaseIndex(Ptr
, DAG
, ByteOffsetFromBase
))
6850 // Calculate the offset of the current byte from the base address
6851 ByteOffsetFromBase
+= MemoryByteOffset(*P
);
6852 ByteOffsets
[i
] = ByteOffsetFromBase
;
6854 // Remember the first byte load
6855 if (ByteOffsetFromBase
< FirstOffset
) {
6856 FirstByteProvider
= P
;
6857 FirstOffset
= ByteOffsetFromBase
;
6862 assert(!Loads
.empty() && "All the bytes of the value must be loaded from "
6863 "memory, so there must be at least one load which produces the value");
6864 assert(Base
&& "Base address of the accessed memory location must be set");
6865 assert(FirstOffset
!= INT64_MAX
&& "First byte offset must be set");
6867 // Check if the bytes of the OR we are looking at match with either big or
6868 // little endian value load
6869 Optional
<bool> IsBigEndian
= isBigEndian(ByteOffsets
, FirstOffset
);
6870 if (!IsBigEndian
.hasValue())
6873 assert(FirstByteProvider
&& "must be set");
6875 // Ensure that the first byte is loaded from zero offset of the first load.
6876 // So the combined value can be loaded from the first load address.
6877 if (MemoryByteOffset(*FirstByteProvider
) != 0)
6879 LoadSDNode
*FirstLoad
= FirstByteProvider
->Load
;
6881 // The node we are looking at matches with the pattern, check if we can
6882 // replace it with a single load and bswap if needed.
6884 // If the load needs byte swap check if the target supports it
6885 bool NeedsBswap
= IsBigEndianTarget
!= *IsBigEndian
;
6887 // Before legalize we can introduce illegal bswaps which will be later
6888 // converted to an explicit bswap sequence. This way we end up with a single
6889 // load and byte shuffling instead of several loads and byte shuffling.
6890 if (NeedsBswap
&& LegalOperations
&& !TLI
.isOperationLegal(ISD::BSWAP
, VT
))
6893 // Check that a load of the wide type is both allowed and fast on the target
6895 bool Allowed
= TLI
.allowsMemoryAccess(*DAG
.getContext(), DAG
.getDataLayout(),
6896 VT
, *FirstLoad
->getMemOperand(), &Fast
);
6897 if (!Allowed
|| !Fast
)
6901 DAG
.getLoad(VT
, SDLoc(N
), Chain
, FirstLoad
->getBasePtr(),
6902 FirstLoad
->getPointerInfo(), FirstLoad
->getAlignment());
6904 // Transfer chain users from old loads to the new load.
6905 for (LoadSDNode
*L
: Loads
)
6906 DAG
.ReplaceAllUsesOfValueWith(SDValue(L
, 1), SDValue(NewLoad
.getNode(), 1));
6908 return NeedsBswap
? DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, NewLoad
) : NewLoad
;
6911 // If the target has andn, bsl, or a similar bit-select instruction,
6912 // we want to unfold masked merge, with canonical pattern of:
6914 // ((x ^ y) & m) ^ y
6917 // (x & m) | (y & ~m)
6918 // If y is a constant, and the 'andn' does not work with immediates,
6919 // we unfold into a different pattern:
6920 // ~(~x & m) & (m | y)
6921 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
6922 // the very least that breaks andnpd / andnps patterns, and because those
6923 // patterns are simplified in IR and shouldn't be created in the DAG
6924 SDValue
DAGCombiner::unfoldMaskedMerge(SDNode
*N
) {
6925 assert(N
->getOpcode() == ISD::XOR
);
6927 // Don't touch 'not' (i.e. where y = -1).
6928 if (isAllOnesOrAllOnesSplat(N
->getOperand(1)))
6931 EVT VT
= N
->getValueType(0);
6933 // There are 3 commutable operators in the pattern,
6934 // so we have to deal with 8 possible variants of the basic pattern.
6936 auto matchAndXor
= [&X
, &Y
, &M
](SDValue And
, unsigned XorIdx
, SDValue Other
) {
6937 if (And
.getOpcode() != ISD::AND
|| !And
.hasOneUse())
6939 SDValue Xor
= And
.getOperand(XorIdx
);
6940 if (Xor
.getOpcode() != ISD::XOR
|| !Xor
.hasOneUse())
6942 SDValue Xor0
= Xor
.getOperand(0);
6943 SDValue Xor1
= Xor
.getOperand(1);
6944 // Don't touch 'not' (i.e. where y = -1).
6945 if (isAllOnesOrAllOnesSplat(Xor1
))
6948 std::swap(Xor0
, Xor1
);
6953 M
= And
.getOperand(XorIdx
? 0 : 1);
6957 SDValue N0
= N
->getOperand(0);
6958 SDValue N1
= N
->getOperand(1);
6959 if (!matchAndXor(N0
, 0, N1
) && !matchAndXor(N0
, 1, N1
) &&
6960 !matchAndXor(N1
, 0, N0
) && !matchAndXor(N1
, 1, N0
))
6963 // Don't do anything if the mask is constant. This should not be reachable.
6964 // InstCombine should have already unfolded this pattern, and DAGCombiner
6965 // probably shouldn't produce it, too.
6966 if (isa
<ConstantSDNode
>(M
.getNode()))
6969 // We can transform if the target has AndNot
6970 if (!TLI
.hasAndNot(M
))
6975 // If Y is a constant, check that 'andn' works with immediates.
6976 if (!TLI
.hasAndNot(Y
)) {
6977 assert(TLI
.hasAndNot(X
) && "Only mask is a variable? Unreachable.");
6978 // If not, we need to do a bit more work to make sure andn is still used.
6979 SDValue NotX
= DAG
.getNOT(DL
, X
, VT
);
6980 SDValue LHS
= DAG
.getNode(ISD::AND
, DL
, VT
, NotX
, M
);
6981 SDValue NotLHS
= DAG
.getNOT(DL
, LHS
, VT
);
6982 SDValue RHS
= DAG
.getNode(ISD::OR
, DL
, VT
, M
, Y
);
6983 return DAG
.getNode(ISD::AND
, DL
, VT
, NotLHS
, RHS
);
6986 SDValue LHS
= DAG
.getNode(ISD::AND
, DL
, VT
, X
, M
);
6987 SDValue NotM
= DAG
.getNOT(DL
, M
, VT
);
6988 SDValue RHS
= DAG
.getNode(ISD::AND
, DL
, VT
, Y
, NotM
);
6990 return DAG
.getNode(ISD::OR
, DL
, VT
, LHS
, RHS
);
6993 SDValue
DAGCombiner::visitXOR(SDNode
*N
) {
6994 SDValue N0
= N
->getOperand(0);
6995 SDValue N1
= N
->getOperand(1);
6996 EVT VT
= N0
.getValueType();
6999 if (VT
.isVector()) {
7000 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7003 // fold (xor x, 0) -> x, vector edition
7004 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
7006 if (ISD::isBuildVectorAllZeros(N1
.getNode()))
7010 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
7012 if (N0
.isUndef() && N1
.isUndef())
7013 return DAG
.getConstant(0, DL
, VT
);
7014 // fold (xor x, undef) -> undef
7019 // fold (xor c1, c2) -> c1^c2
7020 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7021 ConstantSDNode
*N1C
= getAsNonOpaqueConstant(N1
);
7023 return DAG
.FoldConstantArithmetic(ISD::XOR
, DL
, VT
, N0C
, N1C
);
7024 // canonicalize constant to RHS
7025 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
7026 !DAG
.isConstantIntBuildVectorOrConstantInt(N1
))
7027 return DAG
.getNode(ISD::XOR
, DL
, VT
, N1
, N0
);
7028 // fold (xor x, 0) -> x
7029 if (isNullConstant(N1
))
7032 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7036 if (SDValue RXOR
= reassociateOps(ISD::XOR
, DL
, N0
, N1
, N
->getFlags()))
7039 // fold !(x cc y) -> (x !cc y)
7040 unsigned N0Opcode
= N0
.getOpcode();
7041 SDValue LHS
, RHS
, CC
;
7042 if (TLI
.isConstTrueVal(N1
.getNode()) && isSetCCEquivalent(N0
, LHS
, RHS
, CC
)) {
7043 ISD::CondCode NotCC
= ISD::getSetCCInverse(cast
<CondCodeSDNode
>(CC
)->get(),
7044 LHS
.getValueType().isInteger());
7045 if (!LegalOperations
||
7046 TLI
.isCondCodeLegal(NotCC
, LHS
.getSimpleValueType())) {
7049 llvm_unreachable("Unhandled SetCC Equivalent!");
7051 return DAG
.getSetCC(SDLoc(N0
), VT
, LHS
, RHS
, NotCC
);
7052 case ISD::SELECT_CC
:
7053 return DAG
.getSelectCC(SDLoc(N0
), LHS
, RHS
, N0
.getOperand(2),
7054 N0
.getOperand(3), NotCC
);
7059 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
7060 if (isOneConstant(N1
) && N0Opcode
== ISD::ZERO_EXTEND
&& N0
.hasOneUse() &&
7061 isSetCCEquivalent(N0
.getOperand(0), LHS
, RHS
, CC
)){
7062 SDValue V
= N0
.getOperand(0);
7064 V
= DAG
.getNode(ISD::XOR
, DL0
, V
.getValueType(), V
,
7065 DAG
.getConstant(1, DL0
, V
.getValueType()));
7066 AddToWorklist(V
.getNode());
7067 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, V
);
7070 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
7071 if (isOneConstant(N1
) && VT
== MVT::i1
&& N0
.hasOneUse() &&
7072 (N0Opcode
== ISD::OR
|| N0Opcode
== ISD::AND
)) {
7073 SDValue LHS
= N0
.getOperand(0), RHS
= N0
.getOperand(1);
7074 if (isOneUseSetCC(RHS
) || isOneUseSetCC(LHS
)) {
7075 unsigned NewOpcode
= N0Opcode
== ISD::AND
? ISD::OR
: ISD::AND
;
7076 LHS
= DAG
.getNode(ISD::XOR
, SDLoc(LHS
), VT
, LHS
, N1
); // LHS = ~LHS
7077 RHS
= DAG
.getNode(ISD::XOR
, SDLoc(RHS
), VT
, RHS
, N1
); // RHS = ~RHS
7078 AddToWorklist(LHS
.getNode()); AddToWorklist(RHS
.getNode());
7079 return DAG
.getNode(NewOpcode
, DL
, VT
, LHS
, RHS
);
7082 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
7083 if (isAllOnesConstant(N1
) && N0
.hasOneUse() &&
7084 (N0Opcode
== ISD::OR
|| N0Opcode
== ISD::AND
)) {
7085 SDValue LHS
= N0
.getOperand(0), RHS
= N0
.getOperand(1);
7086 if (isa
<ConstantSDNode
>(RHS
) || isa
<ConstantSDNode
>(LHS
)) {
7087 unsigned NewOpcode
= N0Opcode
== ISD::AND
? ISD::OR
: ISD::AND
;
7088 LHS
= DAG
.getNode(ISD::XOR
, SDLoc(LHS
), VT
, LHS
, N1
); // LHS = ~LHS
7089 RHS
= DAG
.getNode(ISD::XOR
, SDLoc(RHS
), VT
, RHS
, N1
); // RHS = ~RHS
7090 AddToWorklist(LHS
.getNode()); AddToWorklist(RHS
.getNode());
7091 return DAG
.getNode(NewOpcode
, DL
, VT
, LHS
, RHS
);
7095 // fold (not (neg x)) -> (add X, -1)
7096 // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
7097 // Y is a constant or the subtract has a single use.
7098 if (isAllOnesConstant(N1
) && N0
.getOpcode() == ISD::SUB
&&
7099 isNullConstant(N0
.getOperand(0))) {
7100 return DAG
.getNode(ISD::ADD
, DL
, VT
, N0
.getOperand(1),
7101 DAG
.getAllOnesConstant(DL
, VT
));
7104 // fold (xor (and x, y), y) -> (and (not x), y)
7105 if (N0Opcode
== ISD::AND
&& N0
.hasOneUse() && N0
->getOperand(1) == N1
) {
7106 SDValue X
= N0
.getOperand(0);
7107 SDValue NotX
= DAG
.getNOT(SDLoc(X
), X
, VT
);
7108 AddToWorklist(NotX
.getNode());
7109 return DAG
.getNode(ISD::AND
, DL
, VT
, NotX
, N1
);
7112 if ((N0Opcode
== ISD::SRL
|| N0Opcode
== ISD::SHL
) && N0
.hasOneUse()) {
7113 ConstantSDNode
*XorC
= isConstOrConstSplat(N1
);
7114 ConstantSDNode
*ShiftC
= isConstOrConstSplat(N0
.getOperand(1));
7115 unsigned BitWidth
= VT
.getScalarSizeInBits();
7116 if (XorC
&& ShiftC
) {
7117 // Don't crash on an oversized shift. We can not guarantee that a bogus
7118 // shift has been simplified to undef.
7119 uint64_t ShiftAmt
= ShiftC
->getLimitedValue();
7120 if (ShiftAmt
< BitWidth
) {
7121 APInt Ones
= APInt::getAllOnesValue(BitWidth
);
7122 Ones
= N0Opcode
== ISD::SHL
? Ones
.shl(ShiftAmt
) : Ones
.lshr(ShiftAmt
);
7123 if (XorC
->getAPIntValue() == Ones
) {
7124 // If the xor constant is a shifted -1, do a 'not' before the shift:
7125 // xor (X << ShiftC), XorC --> (not X) << ShiftC
7126 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
7127 SDValue Not
= DAG
.getNOT(DL
, N0
.getOperand(0), VT
);
7128 return DAG
.getNode(N0Opcode
, DL
, VT
, Not
, N0
.getOperand(1));
7134 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
7135 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
)) {
7136 SDValue A
= N0Opcode
== ISD::ADD
? N0
: N1
;
7137 SDValue S
= N0Opcode
== ISD::SRA
? N0
: N1
;
7138 if (A
.getOpcode() == ISD::ADD
&& S
.getOpcode() == ISD::SRA
) {
7139 SDValue A0
= A
.getOperand(0), A1
= A
.getOperand(1);
7140 SDValue S0
= S
.getOperand(0);
7141 if ((A0
== S
&& A1
== S0
) || (A1
== S
&& A0
== S0
)) {
7142 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7143 if (ConstantSDNode
*C
= isConstOrConstSplat(S
.getOperand(1)))
7144 if (C
->getAPIntValue() == (OpSizeInBits
- 1))
7145 return DAG
.getNode(ISD::ABS
, DL
, VT
, S0
);
7150 // fold (xor x, x) -> 0
7152 return tryFoldToZero(DL
, TLI
, VT
, DAG
, LegalOperations
);
7154 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
7155 // Here is a concrete example of this equivalence:
7157 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
7158 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
7162 // i16 ~1 == 0b1111111111111110
7163 // i16 rol(~1, 14) == 0b1011111111111111
7165 // Some additional tips to help conceptualize this transform:
7166 // - Try to see the operation as placing a single zero in a value of all ones.
7167 // - There exists no value for x which would allow the result to contain zero.
7168 // - Values of x larger than the bitwidth are undefined and do not require a
7169 // consistent result.
7170 // - Pushing the zero left requires shifting one bits in from the right.
7171 // A rotate left of ~1 is a nice way of achieving the desired result.
7172 if (TLI
.isOperationLegalOrCustom(ISD::ROTL
, VT
) && N0Opcode
== ISD::SHL
&&
7173 isAllOnesConstant(N1
) && isOneConstant(N0
.getOperand(0))) {
7174 return DAG
.getNode(ISD::ROTL
, DL
, VT
, DAG
.getConstant(~1, DL
, VT
),
7178 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
7179 if (N0Opcode
== N1
.getOpcode())
7180 if (SDValue V
= hoistLogicOpWithSameOpcodeHands(N
))
7183 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
7184 if (SDValue MM
= unfoldMaskedMerge(N
))
7187 // Simplify the expression using non-local knowledge.
7188 if (SimplifyDemandedBits(SDValue(N
, 0)))
7189 return SDValue(N
, 0);
7194 /// Handle transforms common to the three shifts, when the shift amount is a
7196 /// We are looking for: (shift being one of shl/sra/srl)
7197 /// shift (binop X, C0), C1
7198 /// And want to transform into:
7199 /// binop (shift X, C1), (shift C0, C1)
7200 SDValue
DAGCombiner::visitShiftByConstant(SDNode
*N
, ConstantSDNode
*Amt
) {
7201 // Do not turn a 'not' into a regular xor.
7202 if (isBitwiseNot(N
->getOperand(0)))
7205 // The inner binop must be one-use, since we want to replace it.
7206 SDNode
*LHS
= N
->getOperand(0).getNode();
7207 if (!LHS
->hasOneUse()) return SDValue();
7209 // We want to pull some binops through shifts, so that we have (and (shift))
7210 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
7211 // thing happens with address calculations, so it's important to canonicalize
7213 switch (LHS
->getOpcode()) {
7221 if (N
->getOpcode() != ISD::SHL
)
7222 return SDValue(); // only shl(add) not sr[al](add).
7226 // We require the RHS of the binop to be a constant and not opaque as well.
7227 ConstantSDNode
*BinOpCst
= getAsNonOpaqueConstant(LHS
->getOperand(1));
7231 // FIXME: disable this unless the input to the binop is a shift by a constant
7232 // or is copy/select. Enable this in other cases when figure out it's exactly
7234 SDValue BinOpLHSVal
= LHS
->getOperand(0);
7235 bool IsShiftByConstant
= (BinOpLHSVal
.getOpcode() == ISD::SHL
||
7236 BinOpLHSVal
.getOpcode() == ISD::SRA
||
7237 BinOpLHSVal
.getOpcode() == ISD::SRL
) &&
7238 isa
<ConstantSDNode
>(BinOpLHSVal
.getOperand(1));
7239 bool IsCopyOrSelect
= BinOpLHSVal
.getOpcode() == ISD::CopyFromReg
||
7240 BinOpLHSVal
.getOpcode() == ISD::SELECT
;
7242 if (!IsShiftByConstant
&& !IsCopyOrSelect
)
7245 if (IsCopyOrSelect
&& N
->hasOneUse())
7248 EVT VT
= N
->getValueType(0);
7250 if (!TLI
.isDesirableToCommuteWithShift(N
, Level
))
7253 // Fold the constants, shifting the binop RHS by the shift amount.
7254 SDValue NewRHS
= DAG
.getNode(N
->getOpcode(), SDLoc(LHS
->getOperand(1)),
7256 LHS
->getOperand(1), N
->getOperand(1));
7257 assert(isa
<ConstantSDNode
>(NewRHS
) && "Folding was not successful!");
7259 // Create the new shift.
7260 SDValue NewShift
= DAG
.getNode(N
->getOpcode(),
7261 SDLoc(LHS
->getOperand(0)),
7262 VT
, LHS
->getOperand(0), N
->getOperand(1));
7264 // Create the new binop.
7265 return DAG
.getNode(LHS
->getOpcode(), SDLoc(N
), VT
, NewShift
, NewRHS
);
7268 SDValue
DAGCombiner::distributeTruncateThroughAnd(SDNode
*N
) {
7269 assert(N
->getOpcode() == ISD::TRUNCATE
);
7270 assert(N
->getOperand(0).getOpcode() == ISD::AND
);
7272 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
7273 EVT TruncVT
= N
->getValueType(0);
7274 if (N
->hasOneUse() && N
->getOperand(0).hasOneUse() &&
7275 TLI
.isTypeDesirableForOp(ISD::AND
, TruncVT
)) {
7276 SDValue N01
= N
->getOperand(0).getOperand(1);
7277 if (isConstantOrConstantVector(N01
, /* NoOpaques */ true)) {
7279 SDValue N00
= N
->getOperand(0).getOperand(0);
7280 SDValue Trunc00
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
, N00
);
7281 SDValue Trunc01
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
, N01
);
7282 AddToWorklist(Trunc00
.getNode());
7283 AddToWorklist(Trunc01
.getNode());
7284 return DAG
.getNode(ISD::AND
, DL
, TruncVT
, Trunc00
, Trunc01
);
7291 SDValue
DAGCombiner::visitRotate(SDNode
*N
) {
7293 SDValue N0
= N
->getOperand(0);
7294 SDValue N1
= N
->getOperand(1);
7295 EVT VT
= N
->getValueType(0);
7296 unsigned Bitsize
= VT
.getScalarSizeInBits();
7298 // fold (rot x, 0) -> x
7299 if (isNullOrNullSplat(N1
))
7302 // fold (rot x, c) -> x iff (c % BitSize) == 0
7303 if (isPowerOf2_32(Bitsize
) && Bitsize
> 1) {
7304 APInt
ModuloMask(N1
.getScalarValueSizeInBits(), Bitsize
- 1);
7305 if (DAG
.MaskedValueIsZero(N1
, ModuloMask
))
7309 // fold (rot x, c) -> (rot x, c % BitSize)
7310 // TODO - support non-uniform vector amounts.
7311 if (ConstantSDNode
*Cst
= isConstOrConstSplat(N1
)) {
7312 if (Cst
->getAPIntValue().uge(Bitsize
)) {
7313 uint64_t RotAmt
= Cst
->getAPIntValue().urem(Bitsize
);
7314 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
,
7315 DAG
.getConstant(RotAmt
, dl
, N1
.getValueType()));
7319 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
7320 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7321 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7322 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7323 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
, NewOp1
);
7326 unsigned NextOp
= N0
.getOpcode();
7327 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
7328 if (NextOp
== ISD::ROTL
|| NextOp
== ISD::ROTR
) {
7329 SDNode
*C1
= DAG
.isConstantIntBuildVectorOrConstantInt(N1
);
7330 SDNode
*C2
= DAG
.isConstantIntBuildVectorOrConstantInt(N0
.getOperand(1));
7331 if (C1
&& C2
&& C1
->getValueType(0) == C2
->getValueType(0)) {
7332 EVT ShiftVT
= C1
->getValueType(0);
7333 bool SameSide
= (N
->getOpcode() == NextOp
);
7334 unsigned CombineOp
= SameSide
? ISD::ADD
: ISD::SUB
;
7335 if (SDValue CombinedShift
=
7336 DAG
.FoldConstantArithmetic(CombineOp
, dl
, ShiftVT
, C1
, C2
)) {
7337 SDValue BitsizeC
= DAG
.getConstant(Bitsize
, dl
, ShiftVT
);
7338 SDValue CombinedShiftNorm
= DAG
.FoldConstantArithmetic(
7339 ISD::SREM
, dl
, ShiftVT
, CombinedShift
.getNode(),
7340 BitsizeC
.getNode());
7341 return DAG
.getNode(N
->getOpcode(), dl
, VT
, N0
->getOperand(0),
7349 SDValue
DAGCombiner::visitSHL(SDNode
*N
) {
7350 SDValue N0
= N
->getOperand(0);
7351 SDValue N1
= N
->getOperand(1);
7352 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7355 EVT VT
= N0
.getValueType();
7356 EVT ShiftVT
= N1
.getValueType();
7357 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7360 if (VT
.isVector()) {
7361 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7364 BuildVectorSDNode
*N1CV
= dyn_cast
<BuildVectorSDNode
>(N1
);
7365 // If setcc produces all-one true value then:
7366 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
7367 if (N1CV
&& N1CV
->isConstant()) {
7368 if (N0
.getOpcode() == ISD::AND
) {
7369 SDValue N00
= N0
->getOperand(0);
7370 SDValue N01
= N0
->getOperand(1);
7371 BuildVectorSDNode
*N01CV
= dyn_cast
<BuildVectorSDNode
>(N01
);
7373 if (N01CV
&& N01CV
->isConstant() && N00
.getOpcode() == ISD::SETCC
&&
7374 TLI
.getBooleanContents(N00
.getOperand(0).getValueType()) ==
7375 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
7376 if (SDValue C
= DAG
.FoldConstantArithmetic(ISD::SHL
, SDLoc(N
), VT
,
7378 return DAG
.getNode(ISD::AND
, SDLoc(N
), VT
, N00
, C
);
7384 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7386 // fold (shl c1, c2) -> c1<<c2
7387 // TODO - support non-uniform vector shift amounts.
7388 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7389 if (N0C
&& N1C
&& !N1C
->isOpaque())
7390 return DAG
.FoldConstantArithmetic(ISD::SHL
, SDLoc(N
), VT
, N0C
, N1C
);
7392 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7395 // if (shl x, c) is known to be zero, return 0
7396 if (DAG
.MaskedValueIsZero(SDValue(N
, 0),
7397 APInt::getAllOnesValue(OpSizeInBits
)))
7398 return DAG
.getConstant(0, SDLoc(N
), VT
);
7400 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
7401 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7402 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7403 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7404 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
, NewOp1
);
7407 // TODO - support non-uniform vector shift amounts.
7408 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
7409 return SDValue(N
, 0);
7411 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
7412 if (N0
.getOpcode() == ISD::SHL
) {
7413 auto MatchOutOfRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7414 ConstantSDNode
*RHS
) {
7415 APInt c1
= LHS
->getAPIntValue();
7416 APInt c2
= RHS
->getAPIntValue();
7417 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7418 return (c1
+ c2
).uge(OpSizeInBits
);
7420 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchOutOfRange
))
7421 return DAG
.getConstant(0, SDLoc(N
), VT
);
7423 auto MatchInRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7424 ConstantSDNode
*RHS
) {
7425 APInt c1
= LHS
->getAPIntValue();
7426 APInt c2
= RHS
->getAPIntValue();
7427 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7428 return (c1
+ c2
).ult(OpSizeInBits
);
7430 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchInRange
)) {
7432 SDValue Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, N1
, N0
.getOperand(1));
7433 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0), Sum
);
7437 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
7438 // For this to be valid, the second form must not preserve any of the bits
7439 // that are shifted out by the inner shift in the first form. This means
7440 // the outer shift size must be >= the number of bits added by the ext.
7441 // As a corollary, we don't care what kind of ext it is.
7442 if ((N0
.getOpcode() == ISD::ZERO_EXTEND
||
7443 N0
.getOpcode() == ISD::ANY_EXTEND
||
7444 N0
.getOpcode() == ISD::SIGN_EXTEND
) &&
7445 N0
.getOperand(0).getOpcode() == ISD::SHL
) {
7446 SDValue N0Op0
= N0
.getOperand(0);
7447 SDValue InnerShiftAmt
= N0Op0
.getOperand(1);
7448 EVT InnerVT
= N0Op0
.getValueType();
7449 uint64_t InnerBitwidth
= InnerVT
.getScalarSizeInBits();
7451 auto MatchOutOfRange
= [OpSizeInBits
, InnerBitwidth
](ConstantSDNode
*LHS
,
7452 ConstantSDNode
*RHS
) {
7453 APInt c1
= LHS
->getAPIntValue();
7454 APInt c2
= RHS
->getAPIntValue();
7455 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7456 return c2
.uge(OpSizeInBits
- InnerBitwidth
) &&
7457 (c1
+ c2
).uge(OpSizeInBits
);
7459 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchOutOfRange
,
7460 /*AllowUndefs*/ false,
7461 /*AllowTypeMismatch*/ true))
7462 return DAG
.getConstant(0, SDLoc(N
), VT
);
7464 auto MatchInRange
= [OpSizeInBits
, InnerBitwidth
](ConstantSDNode
*LHS
,
7465 ConstantSDNode
*RHS
) {
7466 APInt c1
= LHS
->getAPIntValue();
7467 APInt c2
= RHS
->getAPIntValue();
7468 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7469 return c2
.uge(OpSizeInBits
- InnerBitwidth
) &&
7470 (c1
+ c2
).ult(OpSizeInBits
);
7472 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchInRange
,
7473 /*AllowUndefs*/ false,
7474 /*AllowTypeMismatch*/ true)) {
7476 SDValue Ext
= DAG
.getNode(N0
.getOpcode(), DL
, VT
, N0Op0
.getOperand(0));
7477 SDValue Sum
= DAG
.getZExtOrTrunc(InnerShiftAmt
, DL
, ShiftVT
);
7478 Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, Sum
, N1
);
7479 return DAG
.getNode(ISD::SHL
, DL
, VT
, Ext
, Sum
);
7483 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
7484 // Only fold this if the inner zext has no other uses to avoid increasing
7485 // the total number of instructions.
7486 if (N0
.getOpcode() == ISD::ZERO_EXTEND
&& N0
.hasOneUse() &&
7487 N0
.getOperand(0).getOpcode() == ISD::SRL
) {
7488 SDValue N0Op0
= N0
.getOperand(0);
7489 SDValue InnerShiftAmt
= N0Op0
.getOperand(1);
7491 auto MatchEqual
= [VT
](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
7492 APInt c1
= LHS
->getAPIntValue();
7493 APInt c2
= RHS
->getAPIntValue();
7494 zeroExtendToMatch(c1
, c2
);
7495 return c1
.ult(VT
.getScalarSizeInBits()) && (c1
== c2
);
7497 if (ISD::matchBinaryPredicate(InnerShiftAmt
, N1
, MatchEqual
,
7498 /*AllowUndefs*/ false,
7499 /*AllowTypeMismatch*/ true)) {
7501 EVT InnerShiftAmtVT
= N0Op0
.getOperand(1).getValueType();
7502 SDValue NewSHL
= DAG
.getZExtOrTrunc(N1
, DL
, InnerShiftAmtVT
);
7503 NewSHL
= DAG
.getNode(ISD::SHL
, DL
, N0Op0
.getValueType(), N0Op0
, NewSHL
);
7504 AddToWorklist(NewSHL
.getNode());
7505 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N0
), VT
, NewSHL
);
7509 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
7510 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
7511 // TODO - support non-uniform vector shift amounts.
7512 if (N1C
&& (N0
.getOpcode() == ISD::SRL
|| N0
.getOpcode() == ISD::SRA
) &&
7513 N0
->getFlags().hasExact()) {
7514 if (ConstantSDNode
*N0C1
= isConstOrConstSplat(N0
.getOperand(1))) {
7515 uint64_t C1
= N0C1
->getZExtValue();
7516 uint64_t C2
= N1C
->getZExtValue();
7519 return DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0),
7520 DAG
.getConstant(C2
- C1
, DL
, ShiftVT
));
7521 return DAG
.getNode(N0
.getOpcode(), DL
, VT
, N0
.getOperand(0),
7522 DAG
.getConstant(C1
- C2
, DL
, ShiftVT
));
7526 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
7527 // (and (srl x, (sub c1, c2), MASK)
7528 // Only fold this if the inner shift has no other uses -- if it does, folding
7529 // this will increase the total number of instructions.
7530 // TODO - drop hasOneUse requirement if c1 == c2?
7531 // TODO - support non-uniform vector shift amounts.
7532 if (N1C
&& N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse() &&
7533 TLI
.shouldFoldConstantShiftPairToMask(N
, Level
)) {
7534 if (ConstantSDNode
*N0C1
= isConstOrConstSplat(N0
.getOperand(1))) {
7535 if (N0C1
->getAPIntValue().ult(OpSizeInBits
)) {
7536 uint64_t c1
= N0C1
->getZExtValue();
7537 uint64_t c2
= N1C
->getZExtValue();
7538 APInt Mask
= APInt::getHighBitsSet(OpSizeInBits
, OpSizeInBits
- c1
);
7543 Shift
= DAG
.getNode(ISD::SHL
, DL
, VT
, N0
.getOperand(0),
7544 DAG
.getConstant(c2
- c1
, DL
, ShiftVT
));
7546 Mask
.lshrInPlace(c1
- c2
);
7548 Shift
= DAG
.getNode(ISD::SRL
, DL
, VT
, N0
.getOperand(0),
7549 DAG
.getConstant(c1
- c2
, DL
, ShiftVT
));
7552 return DAG
.getNode(ISD::AND
, DL
, VT
, Shift
,
7553 DAG
.getConstant(Mask
, DL
, VT
));
7558 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
7559 if (N0
.getOpcode() == ISD::SRA
&& N1
== N0
.getOperand(1) &&
7560 isConstantOrConstantVector(N1
, /* No Opaques */ true)) {
7562 SDValue AllBits
= DAG
.getAllOnesConstant(DL
, VT
);
7563 SDValue HiBitsMask
= DAG
.getNode(ISD::SHL
, DL
, VT
, AllBits
, N1
);
7564 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), HiBitsMask
);
7567 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
7568 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
7569 // Variant of version done on multiply, except mul by a power of 2 is turned
7571 if ((N0
.getOpcode() == ISD::ADD
|| N0
.getOpcode() == ISD::OR
) &&
7572 N0
.getNode()->hasOneUse() &&
7573 isConstantOrConstantVector(N1
, /* No Opaques */ true) &&
7574 isConstantOrConstantVector(N0
.getOperand(1), /* No Opaques */ true) &&
7575 TLI
.isDesirableToCommuteWithShift(N
, Level
)) {
7576 SDValue Shl0
= DAG
.getNode(ISD::SHL
, SDLoc(N0
), VT
, N0
.getOperand(0), N1
);
7577 SDValue Shl1
= DAG
.getNode(ISD::SHL
, SDLoc(N1
), VT
, N0
.getOperand(1), N1
);
7578 AddToWorklist(Shl0
.getNode());
7579 AddToWorklist(Shl1
.getNode());
7580 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, Shl0
, Shl1
);
7583 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
7584 if (N0
.getOpcode() == ISD::MUL
&& N0
.getNode()->hasOneUse() &&
7585 isConstantOrConstantVector(N1
, /* No Opaques */ true) &&
7586 isConstantOrConstantVector(N0
.getOperand(1), /* No Opaques */ true)) {
7587 SDValue Shl
= DAG
.getNode(ISD::SHL
, SDLoc(N1
), VT
, N0
.getOperand(1), N1
);
7588 if (isConstantOrConstantVector(Shl
))
7589 return DAG
.getNode(ISD::MUL
, SDLoc(N
), VT
, N0
.getOperand(0), Shl
);
7592 if (N1C
&& !N1C
->isOpaque())
7593 if (SDValue NewSHL
= visitShiftByConstant(N
, N1C
))
7599 SDValue
DAGCombiner::visitSRA(SDNode
*N
) {
7600 SDValue N0
= N
->getOperand(0);
7601 SDValue N1
= N
->getOperand(1);
7602 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7605 EVT VT
= N0
.getValueType();
7606 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7608 // Arithmetic shifting an all-sign-bit value is a no-op.
7609 // fold (sra 0, x) -> 0
7610 // fold (sra -1, x) -> -1
7611 if (DAG
.ComputeNumSignBits(N0
) == OpSizeInBits
)
7616 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7619 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7621 // fold (sra c1, c2) -> (sra c1, c2)
7622 // TODO - support non-uniform vector shift amounts.
7623 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7624 if (N0C
&& N1C
&& !N1C
->isOpaque())
7625 return DAG
.FoldConstantArithmetic(ISD::SRA
, SDLoc(N
), VT
, N0C
, N1C
);
7627 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7630 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
7632 if (N1C
&& N0
.getOpcode() == ISD::SHL
&& N1
== N0
.getOperand(1)) {
7633 unsigned LowBits
= OpSizeInBits
- (unsigned)N1C
->getZExtValue();
7634 EVT ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), LowBits
);
7636 ExtVT
= EVT::getVectorVT(*DAG
.getContext(),
7637 ExtVT
, VT
.getVectorNumElements());
7638 if ((!LegalOperations
||
7639 TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
, ExtVT
)))
7640 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
7641 N0
.getOperand(0), DAG
.getValueType(ExtVT
));
7644 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
7645 // clamp (add c1, c2) to max shift.
7646 if (N0
.getOpcode() == ISD::SRA
) {
7648 EVT ShiftVT
= N1
.getValueType();
7649 EVT ShiftSVT
= ShiftVT
.getScalarType();
7650 SmallVector
<SDValue
, 16> ShiftValues
;
7652 auto SumOfShifts
= [&](ConstantSDNode
*LHS
, ConstantSDNode
*RHS
) {
7653 APInt c1
= LHS
->getAPIntValue();
7654 APInt c2
= RHS
->getAPIntValue();
7655 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7656 APInt Sum
= c1
+ c2
;
7658 Sum
.uge(OpSizeInBits
) ? (OpSizeInBits
- 1) : Sum
.getZExtValue();
7659 ShiftValues
.push_back(DAG
.getConstant(ShiftSum
, DL
, ShiftSVT
));
7662 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), SumOfShifts
)) {
7665 ShiftValue
= DAG
.getBuildVector(ShiftVT
, DL
, ShiftValues
);
7667 ShiftValue
= ShiftValues
[0];
7668 return DAG
.getNode(ISD::SRA
, DL
, VT
, N0
.getOperand(0), ShiftValue
);
7672 // fold (sra (shl X, m), (sub result_size, n))
7673 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
7674 // result_size - n != m.
7675 // If truncate is free for the target sext(shl) is likely to result in better
7677 if (N0
.getOpcode() == ISD::SHL
&& N1C
) {
7678 // Get the two constanst of the shifts, CN0 = m, CN = n.
7679 const ConstantSDNode
*N01C
= isConstOrConstSplat(N0
.getOperand(1));
7681 LLVMContext
&Ctx
= *DAG
.getContext();
7682 // Determine what the truncate's result bitsize and type would be.
7683 EVT TruncVT
= EVT::getIntegerVT(Ctx
, OpSizeInBits
- N1C
->getZExtValue());
7686 TruncVT
= EVT::getVectorVT(Ctx
, TruncVT
, VT
.getVectorNumElements());
7688 // Determine the residual right-shift amount.
7689 int ShiftAmt
= N1C
->getZExtValue() - N01C
->getZExtValue();
7691 // If the shift is not a no-op (in which case this should be just a sign
7692 // extend already), the truncated to type is legal, sign_extend is legal
7693 // on that type, and the truncate to that type is both legal and free,
7694 // perform the transform.
7695 if ((ShiftAmt
> 0) &&
7696 TLI
.isOperationLegalOrCustom(ISD::SIGN_EXTEND
, TruncVT
) &&
7697 TLI
.isOperationLegalOrCustom(ISD::TRUNCATE
, VT
) &&
7698 TLI
.isTruncateFree(VT
, TruncVT
)) {
7700 SDValue Amt
= DAG
.getConstant(ShiftAmt
, DL
,
7701 getShiftAmountTy(N0
.getOperand(0).getValueType()));
7702 SDValue Shift
= DAG
.getNode(ISD::SRL
, DL
, VT
,
7703 N0
.getOperand(0), Amt
);
7704 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, TruncVT
,
7706 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
,
7707 N
->getValueType(0), Trunc
);
7712 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
7713 // sra (add (shl X, N1C), AddC), N1C -->
7714 // sext (add (trunc X to (width - N1C)), AddC')
7715 if (!LegalTypes
&& N0
.getOpcode() == ISD::ADD
&& N0
.hasOneUse() && N1C
&&
7716 N0
.getOperand(0).getOpcode() == ISD::SHL
&&
7717 N0
.getOperand(0).getOperand(1) == N1
&& N0
.getOperand(0).hasOneUse()) {
7718 if (ConstantSDNode
*AddC
= isConstOrConstSplat(N0
.getOperand(1))) {
7719 SDValue Shl
= N0
.getOperand(0);
7720 // Determine what the truncate's type would be and ask the target if that
7721 // is a free operation.
7722 LLVMContext
&Ctx
= *DAG
.getContext();
7723 unsigned ShiftAmt
= N1C
->getZExtValue();
7724 EVT TruncVT
= EVT::getIntegerVT(Ctx
, OpSizeInBits
- ShiftAmt
);
7726 TruncVT
= EVT::getVectorVT(Ctx
, TruncVT
, VT
.getVectorNumElements());
7728 // TODO: The simple type check probably belongs in the default hook
7729 // implementation and/or target-specific overrides (because
7730 // non-simple types likely require masking when legalized), but that
7731 // restriction may conflict with other transforms.
7732 if (TruncVT
.isSimple() && TLI
.isTruncateFree(VT
, TruncVT
)) {
7734 SDValue Trunc
= DAG
.getZExtOrTrunc(Shl
.getOperand(0), DL
, TruncVT
);
7735 SDValue ShiftC
= DAG
.getConstant(AddC
->getAPIntValue().lshr(ShiftAmt
).
7736 trunc(TruncVT
.getScalarSizeInBits()), DL
, TruncVT
);
7737 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, TruncVT
, Trunc
, ShiftC
);
7738 return DAG
.getSExtOrTrunc(Add
, DL
, VT
);
7743 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
7744 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7745 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7746 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7747 return DAG
.getNode(ISD::SRA
, SDLoc(N
), VT
, N0
, NewOp1
);
7750 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
7751 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
7752 // if c1 is equal to the number of bits the trunc removes
7753 // TODO - support non-uniform vector shift amounts.
7754 if (N0
.getOpcode() == ISD::TRUNCATE
&&
7755 (N0
.getOperand(0).getOpcode() == ISD::SRL
||
7756 N0
.getOperand(0).getOpcode() == ISD::SRA
) &&
7757 N0
.getOperand(0).hasOneUse() &&
7758 N0
.getOperand(0).getOperand(1).hasOneUse() && N1C
) {
7759 SDValue N0Op0
= N0
.getOperand(0);
7760 if (ConstantSDNode
*LargeShift
= isConstOrConstSplat(N0Op0
.getOperand(1))) {
7761 EVT LargeVT
= N0Op0
.getValueType();
7762 unsigned TruncBits
= LargeVT
.getScalarSizeInBits() - OpSizeInBits
;
7763 if (LargeShift
->getAPIntValue() == TruncBits
) {
7765 SDValue Amt
= DAG
.getConstant(N1C
->getZExtValue() + TruncBits
, DL
,
7766 getShiftAmountTy(LargeVT
));
7768 DAG
.getNode(ISD::SRA
, DL
, LargeVT
, N0Op0
.getOperand(0), Amt
);
7769 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, SRA
);
7774 // Simplify, based on bits shifted out of the LHS.
7775 // TODO - support non-uniform vector shift amounts.
7776 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
7777 return SDValue(N
, 0);
7779 // If the sign bit is known to be zero, switch this to a SRL.
7780 if (DAG
.SignBitIsZero(N0
))
7781 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
, N1
);
7783 if (N1C
&& !N1C
->isOpaque())
7784 if (SDValue NewSRA
= visitShiftByConstant(N
, N1C
))
7790 SDValue
DAGCombiner::visitSRL(SDNode
*N
) {
7791 SDValue N0
= N
->getOperand(0);
7792 SDValue N1
= N
->getOperand(1);
7793 if (SDValue V
= DAG
.simplifyShift(N0
, N1
))
7796 EVT VT
= N0
.getValueType();
7797 unsigned OpSizeInBits
= VT
.getScalarSizeInBits();
7801 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
7804 ConstantSDNode
*N1C
= isConstOrConstSplat(N1
);
7806 // fold (srl c1, c2) -> c1 >>u c2
7807 // TODO - support non-uniform vector shift amounts.
7808 ConstantSDNode
*N0C
= getAsNonOpaqueConstant(N0
);
7809 if (N0C
&& N1C
&& !N1C
->isOpaque())
7810 return DAG
.FoldConstantArithmetic(ISD::SRL
, SDLoc(N
), VT
, N0C
, N1C
);
7812 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
7815 // if (srl x, c) is known to be zero, return 0
7816 if (N1C
&& DAG
.MaskedValueIsZero(SDValue(N
, 0),
7817 APInt::getAllOnesValue(OpSizeInBits
)))
7818 return DAG
.getConstant(0, SDLoc(N
), VT
);
7820 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
7821 if (N0
.getOpcode() == ISD::SRL
) {
7822 auto MatchOutOfRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7823 ConstantSDNode
*RHS
) {
7824 APInt c1
= LHS
->getAPIntValue();
7825 APInt c2
= RHS
->getAPIntValue();
7826 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7827 return (c1
+ c2
).uge(OpSizeInBits
);
7829 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchOutOfRange
))
7830 return DAG
.getConstant(0, SDLoc(N
), VT
);
7832 auto MatchInRange
= [OpSizeInBits
](ConstantSDNode
*LHS
,
7833 ConstantSDNode
*RHS
) {
7834 APInt c1
= LHS
->getAPIntValue();
7835 APInt c2
= RHS
->getAPIntValue();
7836 zeroExtendToMatch(c1
, c2
, 1 /* Overflow Bit */);
7837 return (c1
+ c2
).ult(OpSizeInBits
);
7839 if (ISD::matchBinaryPredicate(N1
, N0
.getOperand(1), MatchInRange
)) {
7841 EVT ShiftVT
= N1
.getValueType();
7842 SDValue Sum
= DAG
.getNode(ISD::ADD
, DL
, ShiftVT
, N1
, N0
.getOperand(1));
7843 return DAG
.getNode(ISD::SRL
, DL
, VT
, N0
.getOperand(0), Sum
);
7847 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
7848 // TODO - support non-uniform vector shift amounts.
7849 if (N1C
&& N0
.getOpcode() == ISD::TRUNCATE
&&
7850 N0
.getOperand(0).getOpcode() == ISD::SRL
) {
7851 if (auto N001C
= isConstOrConstSplat(N0
.getOperand(0).getOperand(1))) {
7852 uint64_t c1
= N001C
->getZExtValue();
7853 uint64_t c2
= N1C
->getZExtValue();
7854 EVT InnerShiftVT
= N0
.getOperand(0).getValueType();
7855 EVT ShiftCountVT
= N0
.getOperand(0).getOperand(1).getValueType();
7856 uint64_t InnerShiftSize
= InnerShiftVT
.getScalarSizeInBits();
7857 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
7858 if (c1
+ OpSizeInBits
== InnerShiftSize
) {
7860 if (c1
+ c2
>= InnerShiftSize
)
7861 return DAG
.getConstant(0, DL
, VT
);
7862 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
,
7863 DAG
.getNode(ISD::SRL
, DL
, InnerShiftVT
,
7864 N0
.getOperand(0).getOperand(0),
7865 DAG
.getConstant(c1
+ c2
, DL
,
7871 // fold (srl (shl x, c), c) -> (and x, cst2)
7872 // TODO - (srl (shl x, c1), c2).
7873 if (N0
.getOpcode() == ISD::SHL
&& N0
.getOperand(1) == N1
&&
7874 isConstantOrConstantVector(N1
, /* NoOpaques */ true)) {
7877 DAG
.getNode(ISD::SRL
, DL
, VT
, DAG
.getAllOnesConstant(DL
, VT
), N1
);
7878 AddToWorklist(Mask
.getNode());
7879 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
.getOperand(0), Mask
);
7882 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
7883 // TODO - support non-uniform vector shift amounts.
7884 if (N1C
&& N0
.getOpcode() == ISD::ANY_EXTEND
) {
7885 // Shifting in all undef bits?
7886 EVT SmallVT
= N0
.getOperand(0).getValueType();
7887 unsigned BitSize
= SmallVT
.getScalarSizeInBits();
7888 if (N1C
->getAPIntValue().uge(BitSize
))
7889 return DAG
.getUNDEF(VT
);
7891 if (!LegalTypes
|| TLI
.isTypeDesirableForOp(ISD::SRL
, SmallVT
)) {
7892 uint64_t ShiftAmt
= N1C
->getZExtValue();
7894 SDValue SmallShift
= DAG
.getNode(ISD::SRL
, DL0
, SmallVT
,
7896 DAG
.getConstant(ShiftAmt
, DL0
,
7897 getShiftAmountTy(SmallVT
)));
7898 AddToWorklist(SmallShift
.getNode());
7899 APInt Mask
= APInt::getLowBitsSet(OpSizeInBits
, OpSizeInBits
- ShiftAmt
);
7901 return DAG
.getNode(ISD::AND
, DL
, VT
,
7902 DAG
.getNode(ISD::ANY_EXTEND
, DL
, VT
, SmallShift
),
7903 DAG
.getConstant(Mask
, DL
, VT
));
7907 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
7908 // bit, which is unmodified by sra.
7909 if (N1C
&& N1C
->getAPIntValue() == (OpSizeInBits
- 1)) {
7910 if (N0
.getOpcode() == ISD::SRA
)
7911 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
7914 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
7915 if (N1C
&& N0
.getOpcode() == ISD::CTLZ
&&
7916 N1C
->getAPIntValue() == Log2_32(OpSizeInBits
)) {
7917 KnownBits Known
= DAG
.computeKnownBits(N0
.getOperand(0));
7919 // If any of the input bits are KnownOne, then the input couldn't be all
7920 // zeros, thus the result of the srl will always be zero.
7921 if (Known
.One
.getBoolValue()) return DAG
.getConstant(0, SDLoc(N0
), VT
);
7923 // If all of the bits input the to ctlz node are known to be zero, then
7924 // the result of the ctlz is "32" and the result of the shift is one.
7925 APInt UnknownBits
= ~Known
.Zero
;
7926 if (UnknownBits
== 0) return DAG
.getConstant(1, SDLoc(N0
), VT
);
7928 // Otherwise, check to see if there is exactly one bit input to the ctlz.
7929 if (UnknownBits
.isPowerOf2()) {
7930 // Okay, we know that only that the single bit specified by UnknownBits
7931 // could be set on input to the CTLZ node. If this bit is set, the SRL
7932 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
7933 // to an SRL/XOR pair, which is likely to simplify more.
7934 unsigned ShAmt
= UnknownBits
.countTrailingZeros();
7935 SDValue Op
= N0
.getOperand(0);
7939 Op
= DAG
.getNode(ISD::SRL
, DL
, VT
, Op
,
7940 DAG
.getConstant(ShAmt
, DL
,
7941 getShiftAmountTy(Op
.getValueType())));
7942 AddToWorklist(Op
.getNode());
7946 return DAG
.getNode(ISD::XOR
, DL
, VT
,
7947 Op
, DAG
.getConstant(1, DL
, VT
));
7951 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
7952 if (N1
.getOpcode() == ISD::TRUNCATE
&&
7953 N1
.getOperand(0).getOpcode() == ISD::AND
) {
7954 if (SDValue NewOp1
= distributeTruncateThroughAnd(N1
.getNode()))
7955 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N0
, NewOp1
);
7958 // fold operands of srl based on knowledge that the low bits are not
7960 // TODO - support non-uniform vector shift amounts.
7961 if (N1C
&& SimplifyDemandedBits(SDValue(N
, 0)))
7962 return SDValue(N
, 0);
7964 if (N1C
&& !N1C
->isOpaque())
7965 if (SDValue NewSRL
= visitShiftByConstant(N
, N1C
))
7968 // Attempt to convert a srl of a load into a narrower zero-extending load.
7969 if (SDValue NarrowLoad
= ReduceLoadWidth(N
))
7972 // Here is a common situation. We want to optimize:
7975 // %b = and i32 %a, 2
7976 // %c = srl i32 %b, 1
7977 // brcond i32 %c ...
7983 // %c = setcc eq %b, 0
7986 // However when after the source operand of SRL is optimized into AND, the SRL
7987 // itself may not be optimized further. Look for it and add the BRCOND into
7989 if (N
->hasOneUse()) {
7990 SDNode
*Use
= *N
->use_begin();
7991 if (Use
->getOpcode() == ISD::BRCOND
)
7993 else if (Use
->getOpcode() == ISD::TRUNCATE
&& Use
->hasOneUse()) {
7994 // Also look pass the truncate.
7995 Use
= *Use
->use_begin();
7996 if (Use
->getOpcode() == ISD::BRCOND
)
8004 SDValue
DAGCombiner::visitFunnelShift(SDNode
*N
) {
8005 EVT VT
= N
->getValueType(0);
8006 SDValue N0
= N
->getOperand(0);
8007 SDValue N1
= N
->getOperand(1);
8008 SDValue N2
= N
->getOperand(2);
8009 bool IsFSHL
= N
->getOpcode() == ISD::FSHL
;
8010 unsigned BitWidth
= VT
.getScalarSizeInBits();
8012 // fold (fshl N0, N1, 0) -> N0
8013 // fold (fshr N0, N1, 0) -> N1
8014 if (isPowerOf2_32(BitWidth
))
8015 if (DAG
.MaskedValueIsZero(
8016 N2
, APInt(N2
.getScalarValueSizeInBits(), BitWidth
- 1)))
8017 return IsFSHL
? N0
: N1
;
8019 auto IsUndefOrZero
= [](SDValue V
) {
8020 return V
.isUndef() || isNullOrNullSplat(V
, /*AllowUndefs*/ true);
8023 // TODO - support non-uniform vector shift amounts.
8024 if (ConstantSDNode
*Cst
= isConstOrConstSplat(N2
)) {
8025 EVT ShAmtTy
= N2
.getValueType();
8027 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
8028 if (Cst
->getAPIntValue().uge(BitWidth
)) {
8029 uint64_t RotAmt
= Cst
->getAPIntValue().urem(BitWidth
);
8030 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N0
, N1
,
8031 DAG
.getConstant(RotAmt
, SDLoc(N
), ShAmtTy
));
8034 unsigned ShAmt
= Cst
->getZExtValue();
8036 return IsFSHL
? N0
: N1
;
8038 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
8039 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
8040 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
8041 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
8042 if (IsUndefOrZero(N0
))
8043 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N1
,
8044 DAG
.getConstant(IsFSHL
? BitWidth
- ShAmt
: ShAmt
,
8045 SDLoc(N
), ShAmtTy
));
8046 if (IsUndefOrZero(N1
))
8047 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
,
8048 DAG
.getConstant(IsFSHL
? ShAmt
: BitWidth
- ShAmt
,
8049 SDLoc(N
), ShAmtTy
));
8052 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
8053 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
8054 // iff We know the shift amount is in range.
8055 // TODO: when is it worth doing SUB(BW, N2) as well?
8056 if (isPowerOf2_32(BitWidth
)) {
8057 APInt
ModuloBits(N2
.getScalarValueSizeInBits(), BitWidth
- 1);
8058 if (IsUndefOrZero(N0
) && !IsFSHL
&& DAG
.MaskedValueIsZero(N2
, ~ModuloBits
))
8059 return DAG
.getNode(ISD::SRL
, SDLoc(N
), VT
, N1
, N2
);
8060 if (IsUndefOrZero(N1
) && IsFSHL
&& DAG
.MaskedValueIsZero(N2
, ~ModuloBits
))
8061 return DAG
.getNode(ISD::SHL
, SDLoc(N
), VT
, N0
, N2
);
8064 // fold (fshl N0, N0, N2) -> (rotl N0, N2)
8065 // fold (fshr N0, N0, N2) -> (rotr N0, N2)
8066 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
8067 // is legal as well we might be better off avoiding non-constant (BW - N2).
8068 unsigned RotOpc
= IsFSHL
? ISD::ROTL
: ISD::ROTR
;
8069 if (N0
== N1
&& hasOperation(RotOpc
, VT
))
8070 return DAG
.getNode(RotOpc
, SDLoc(N
), VT
, N0
, N2
);
8072 // Simplify, based on bits shifted out of N0/N1.
8073 if (SimplifyDemandedBits(SDValue(N
, 0)))
8074 return SDValue(N
, 0);
8079 SDValue
DAGCombiner::visitABS(SDNode
*N
) {
8080 SDValue N0
= N
->getOperand(0);
8081 EVT VT
= N
->getValueType(0);
8083 // fold (abs c1) -> c2
8084 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8085 return DAG
.getNode(ISD::ABS
, SDLoc(N
), VT
, N0
);
8086 // fold (abs (abs x)) -> (abs x)
8087 if (N0
.getOpcode() == ISD::ABS
)
8089 // fold (abs x) -> x iff not-negative
8090 if (DAG
.SignBitIsZero(N0
))
8095 SDValue
DAGCombiner::visitBSWAP(SDNode
*N
) {
8096 SDValue N0
= N
->getOperand(0);
8097 EVT VT
= N
->getValueType(0);
8099 // fold (bswap c1) -> c2
8100 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8101 return DAG
.getNode(ISD::BSWAP
, SDLoc(N
), VT
, N0
);
8102 // fold (bswap (bswap x)) -> x
8103 if (N0
.getOpcode() == ISD::BSWAP
)
8104 return N0
->getOperand(0);
8108 SDValue
DAGCombiner::visitBITREVERSE(SDNode
*N
) {
8109 SDValue N0
= N
->getOperand(0);
8110 EVT VT
= N
->getValueType(0);
8112 // fold (bitreverse c1) -> c2
8113 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8114 return DAG
.getNode(ISD::BITREVERSE
, SDLoc(N
), VT
, N0
);
8115 // fold (bitreverse (bitreverse x)) -> x
8116 if (N0
.getOpcode() == ISD::BITREVERSE
)
8117 return N0
.getOperand(0);
8121 SDValue
DAGCombiner::visitCTLZ(SDNode
*N
) {
8122 SDValue N0
= N
->getOperand(0);
8123 EVT VT
= N
->getValueType(0);
8125 // fold (ctlz c1) -> c2
8126 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8127 return DAG
.getNode(ISD::CTLZ
, SDLoc(N
), VT
, N0
);
8129 // If the value is known never to be zero, switch to the undef version.
8130 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTLZ_ZERO_UNDEF
, VT
)) {
8131 if (DAG
.isKnownNeverZero(N0
))
8132 return DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8138 SDValue
DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode
*N
) {
8139 SDValue N0
= N
->getOperand(0);
8140 EVT VT
= N
->getValueType(0);
8142 // fold (ctlz_zero_undef c1) -> c2
8143 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8144 return DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8148 SDValue
DAGCombiner::visitCTTZ(SDNode
*N
) {
8149 SDValue N0
= N
->getOperand(0);
8150 EVT VT
= N
->getValueType(0);
8152 // fold (cttz c1) -> c2
8153 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8154 return DAG
.getNode(ISD::CTTZ
, SDLoc(N
), VT
, N0
);
8156 // If the value is known never to be zero, switch to the undef version.
8157 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTTZ_ZERO_UNDEF
, VT
)) {
8158 if (DAG
.isKnownNeverZero(N0
))
8159 return DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8165 SDValue
DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode
*N
) {
8166 SDValue N0
= N
->getOperand(0);
8167 EVT VT
= N
->getValueType(0);
8169 // fold (cttz_zero_undef c1) -> c2
8170 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8171 return DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, SDLoc(N
), VT
, N0
);
8175 SDValue
DAGCombiner::visitCTPOP(SDNode
*N
) {
8176 SDValue N0
= N
->getOperand(0);
8177 EVT VT
= N
->getValueType(0);
8179 // fold (ctpop c1) -> c2
8180 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
8181 return DAG
.getNode(ISD::CTPOP
, SDLoc(N
), VT
, N0
);
8185 // FIXME: This should be checking for no signed zeros on individual operands, as
8187 static bool isLegalToCombineMinNumMaxNum(SelectionDAG
&DAG
, SDValue LHS
,
8189 const TargetLowering
&TLI
) {
8190 const TargetOptions
&Options
= DAG
.getTarget().Options
;
8191 EVT VT
= LHS
.getValueType();
8193 return Options
.NoSignedZerosFPMath
&& VT
.isFloatingPoint() &&
8194 TLI
.isProfitableToCombineMinNumMaxNum(VT
) &&
8195 DAG
.isKnownNeverNaN(LHS
) && DAG
.isKnownNeverNaN(RHS
);
8198 /// Generate Min/Max node
8199 static SDValue
combineMinNumMaxNum(const SDLoc
&DL
, EVT VT
, SDValue LHS
,
8200 SDValue RHS
, SDValue True
, SDValue False
,
8201 ISD::CondCode CC
, const TargetLowering
&TLI
,
8202 SelectionDAG
&DAG
) {
8203 if (!(LHS
== True
&& RHS
== False
) && !(LHS
== False
&& RHS
== True
))
8206 EVT TransformVT
= TLI
.getTypeToTransformTo(*DAG
.getContext(), VT
);
8214 // Since it's known never nan to get here already, either fminnum or
8215 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
8216 // expanded in terms of it.
8217 unsigned IEEEOpcode
= (LHS
== True
) ? ISD::FMINNUM_IEEE
: ISD::FMAXNUM_IEEE
;
8218 if (TLI
.isOperationLegalOrCustom(IEEEOpcode
, VT
))
8219 return DAG
.getNode(IEEEOpcode
, DL
, VT
, LHS
, RHS
);
8221 unsigned Opcode
= (LHS
== True
) ? ISD::FMINNUM
: ISD::FMAXNUM
;
8222 if (TLI
.isOperationLegalOrCustom(Opcode
, TransformVT
))
8223 return DAG
.getNode(Opcode
, DL
, VT
, LHS
, RHS
);
8232 unsigned IEEEOpcode
= (LHS
== True
) ? ISD::FMAXNUM_IEEE
: ISD::FMINNUM_IEEE
;
8233 if (TLI
.isOperationLegalOrCustom(IEEEOpcode
, VT
))
8234 return DAG
.getNode(IEEEOpcode
, DL
, VT
, LHS
, RHS
);
8236 unsigned Opcode
= (LHS
== True
) ? ISD::FMAXNUM
: ISD::FMINNUM
;
8237 if (TLI
.isOperationLegalOrCustom(Opcode
, TransformVT
))
8238 return DAG
.getNode(Opcode
, DL
, VT
, LHS
, RHS
);
8246 SDValue
DAGCombiner::foldSelectOfConstants(SDNode
*N
) {
8247 SDValue Cond
= N
->getOperand(0);
8248 SDValue N1
= N
->getOperand(1);
8249 SDValue N2
= N
->getOperand(2);
8250 EVT VT
= N
->getValueType(0);
8251 EVT CondVT
= Cond
.getValueType();
8254 if (!VT
.isInteger())
8257 auto *C1
= dyn_cast
<ConstantSDNode
>(N1
);
8258 auto *C2
= dyn_cast
<ConstantSDNode
>(N2
);
8262 // Only do this before legalization to avoid conflicting with target-specific
8263 // transforms in the other direction (create a select from a zext/sext). There
8264 // is also a target-independent combine here in DAGCombiner in the other
8265 // direction for (select Cond, -1, 0) when the condition is not i1.
8266 if (CondVT
== MVT::i1
&& !LegalOperations
) {
8267 if (C1
->isNullValue() && C2
->isOne()) {
8268 // select Cond, 0, 1 --> zext (!Cond)
8269 SDValue NotCond
= DAG
.getNOT(DL
, Cond
, MVT::i1
);
8271 NotCond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, NotCond
);
8274 if (C1
->isNullValue() && C2
->isAllOnesValue()) {
8275 // select Cond, 0, -1 --> sext (!Cond)
8276 SDValue NotCond
= DAG
.getNOT(DL
, Cond
, MVT::i1
);
8278 NotCond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, NotCond
);
8281 if (C1
->isOne() && C2
->isNullValue()) {
8282 // select Cond, 1, 0 --> zext (Cond)
8284 Cond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Cond
);
8287 if (C1
->isAllOnesValue() && C2
->isNullValue()) {
8288 // select Cond, -1, 0 --> sext (Cond)
8290 Cond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Cond
);
8294 // For any constants that differ by 1, we can transform the select into an
8295 // extend and add. Use a target hook because some targets may prefer to
8296 // transform in the other direction.
8297 if (TLI
.convertSelectOfConstantsToMath(VT
)) {
8298 if (C1
->getAPIntValue() - 1 == C2
->getAPIntValue()) {
8299 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
8301 Cond
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Cond
);
8302 return DAG
.getNode(ISD::ADD
, DL
, VT
, Cond
, N2
);
8304 if (C1
->getAPIntValue() + 1 == C2
->getAPIntValue()) {
8305 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
8307 Cond
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Cond
);
8308 return DAG
.getNode(ISD::ADD
, DL
, VT
, Cond
, N2
);
8315 // fold (select Cond, 0, 1) -> (xor Cond, 1)
8316 // We can't do this reliably if integer based booleans have different contents
8317 // to floating point based booleans. This is because we can't tell whether we
8318 // have an integer-based boolean or a floating-point-based boolean unless we
8319 // can find the SETCC that produced it and inspect its operands. This is
8320 // fairly easy if C is the SETCC node, but it can potentially be
8321 // undiscoverable (or not reasonably discoverable). For example, it could be
8322 // in another basic block or it could require searching a complicated
8324 if (CondVT
.isInteger() &&
8325 TLI
.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
8326 TargetLowering::ZeroOrOneBooleanContent
&&
8327 TLI
.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
8328 TargetLowering::ZeroOrOneBooleanContent
&&
8329 C1
->isNullValue() && C2
->isOne()) {
8331 DAG
.getNode(ISD::XOR
, DL
, CondVT
, Cond
, DAG
.getConstant(1, DL
, CondVT
));
8332 if (VT
.bitsEq(CondVT
))
8334 return DAG
.getZExtOrTrunc(NotCond
, DL
, VT
);
8340 SDValue
DAGCombiner::visitSELECT(SDNode
*N
) {
8341 SDValue N0
= N
->getOperand(0);
8342 SDValue N1
= N
->getOperand(1);
8343 SDValue N2
= N
->getOperand(2);
8344 EVT VT
= N
->getValueType(0);
8345 EVT VT0
= N0
.getValueType();
8347 SDNodeFlags Flags
= N
->getFlags();
8349 if (SDValue V
= DAG
.simplifySelect(N0
, N1
, N2
))
8352 // fold (select X, X, Y) -> (or X, Y)
8353 // fold (select X, 1, Y) -> (or C, Y)
8354 if (VT
== VT0
&& VT
== MVT::i1
&& (N0
== N1
|| isOneConstant(N1
)))
8355 return DAG
.getNode(ISD::OR
, DL
, VT
, N0
, N2
);
8357 if (SDValue V
= foldSelectOfConstants(N
))
8360 // fold (select C, 0, X) -> (and (not C), X)
8361 if (VT
== VT0
&& VT
== MVT::i1
&& isNullConstant(N1
)) {
8362 SDValue NOTNode
= DAG
.getNOT(SDLoc(N0
), N0
, VT
);
8363 AddToWorklist(NOTNode
.getNode());
8364 return DAG
.getNode(ISD::AND
, DL
, VT
, NOTNode
, N2
);
8366 // fold (select C, X, 1) -> (or (not C), X)
8367 if (VT
== VT0
&& VT
== MVT::i1
&& isOneConstant(N2
)) {
8368 SDValue NOTNode
= DAG
.getNOT(SDLoc(N0
), N0
, VT
);
8369 AddToWorklist(NOTNode
.getNode());
8370 return DAG
.getNode(ISD::OR
, DL
, VT
, NOTNode
, N1
);
8372 // fold (select X, Y, X) -> (and X, Y)
8373 // fold (select X, Y, 0) -> (and X, Y)
8374 if (VT
== VT0
&& VT
== MVT::i1
&& (N0
== N2
|| isNullConstant(N2
)))
8375 return DAG
.getNode(ISD::AND
, DL
, VT
, N0
, N1
);
8377 // If we can fold this based on the true/false value, do so.
8378 if (SimplifySelectOps(N
, N1
, N2
))
8379 return SDValue(N
, 0); // Don't revisit N.
8381 if (VT0
== MVT::i1
) {
8382 // The code in this block deals with the following 2 equivalences:
8383 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
8384 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
8385 // The target can specify its preferred form with the
8386 // shouldNormalizeToSelectSequence() callback. However we always transform
8387 // to the right anyway if we find the inner select exists in the DAG anyway
8388 // and we always transform to the left side if we know that we can further
8389 // optimize the combination of the conditions.
8390 bool normalizeToSequence
=
8391 TLI
.shouldNormalizeToSelectSequence(*DAG
.getContext(), VT
);
8392 // select (and Cond0, Cond1), X, Y
8393 // -> select Cond0, (select Cond1, X, Y), Y
8394 if (N0
->getOpcode() == ISD::AND
&& N0
->hasOneUse()) {
8395 SDValue Cond0
= N0
->getOperand(0);
8396 SDValue Cond1
= N0
->getOperand(1);
8397 SDValue InnerSelect
=
8398 DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond1
, N1
, N2
, Flags
);
8399 if (normalizeToSequence
|| !InnerSelect
.use_empty())
8400 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond0
,
8401 InnerSelect
, N2
, Flags
);
8402 // Cleanup on failure.
8403 if (InnerSelect
.use_empty())
8404 recursivelyDeleteUnusedNodes(InnerSelect
.getNode());
8406 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
8407 if (N0
->getOpcode() == ISD::OR
&& N0
->hasOneUse()) {
8408 SDValue Cond0
= N0
->getOperand(0);
8409 SDValue Cond1
= N0
->getOperand(1);
8410 SDValue InnerSelect
= DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(),
8411 Cond1
, N1
, N2
, Flags
);
8412 if (normalizeToSequence
|| !InnerSelect
.use_empty())
8413 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Cond0
, N1
,
8414 InnerSelect
, Flags
);
8415 // Cleanup on failure.
8416 if (InnerSelect
.use_empty())
8417 recursivelyDeleteUnusedNodes(InnerSelect
.getNode());
8420 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
8421 if (N1
->getOpcode() == ISD::SELECT
&& N1
->hasOneUse()) {
8422 SDValue N1_0
= N1
->getOperand(0);
8423 SDValue N1_1
= N1
->getOperand(1);
8424 SDValue N1_2
= N1
->getOperand(2);
8425 if (N1_2
== N2
&& N0
.getValueType() == N1_0
.getValueType()) {
8426 // Create the actual and node if we can generate good code for it.
8427 if (!normalizeToSequence
) {
8428 SDValue And
= DAG
.getNode(ISD::AND
, DL
, N0
.getValueType(), N0
, N1_0
);
8429 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), And
, N1_1
,
8432 // Otherwise see if we can optimize the "and" to a better pattern.
8433 if (SDValue Combined
= visitANDLike(N0
, N1_0
, N
)) {
8434 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Combined
, N1_1
,
8439 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
8440 if (N2
->getOpcode() == ISD::SELECT
&& N2
->hasOneUse()) {
8441 SDValue N2_0
= N2
->getOperand(0);
8442 SDValue N2_1
= N2
->getOperand(1);
8443 SDValue N2_2
= N2
->getOperand(2);
8444 if (N2_1
== N1
&& N0
.getValueType() == N2_0
.getValueType()) {
8445 // Create the actual or node if we can generate good code for it.
8446 if (!normalizeToSequence
) {
8447 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, N0
.getValueType(), N0
, N2_0
);
8448 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Or
, N1
,
8451 // Otherwise see if we can optimize to a better pattern.
8452 if (SDValue Combined
= visitORLike(N0
, N2_0
, N
))
8453 return DAG
.getNode(ISD::SELECT
, DL
, N1
.getValueType(), Combined
, N1
,
8459 // select (not Cond), N1, N2 -> select Cond, N2, N1
8460 if (SDValue F
= extractBooleanFlip(N0
, DAG
, TLI
, false)) {
8461 SDValue SelectOp
= DAG
.getSelect(DL
, VT
, F
, N2
, N1
);
8462 SelectOp
->setFlags(Flags
);
8466 // Fold selects based on a setcc into other things, such as min/max/abs.
8467 if (N0
.getOpcode() == ISD::SETCC
) {
8468 SDValue Cond0
= N0
.getOperand(0), Cond1
= N0
.getOperand(1);
8469 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
8471 // select (fcmp lt x, y), x, y -> fminnum x, y
8472 // select (fcmp gt x, y), x, y -> fmaxnum x, y
8474 // This is OK if we don't care what happens if either operand is a NaN.
8475 if (N0
.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG
, N1
, N2
, TLI
))
8476 if (SDValue FMinMax
= combineMinNumMaxNum(DL
, VT
, Cond0
, Cond1
, N1
, N2
,
8480 // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
8481 // This is conservatively limited to pre-legal-operations to give targets
8482 // a chance to reverse the transform if they want to do that. Also, it is
8483 // unlikely that the pattern would be formed late, so it's probably not
8484 // worth going through the other checks.
8485 if (!LegalOperations
&& TLI
.isOperationLegalOrCustom(ISD::UADDO
, VT
) &&
8486 CC
== ISD::SETUGT
&& N0
.hasOneUse() && isAllOnesConstant(N1
) &&
8487 N2
.getOpcode() == ISD::ADD
&& Cond0
== N2
.getOperand(0)) {
8488 auto *C
= dyn_cast
<ConstantSDNode
>(N2
.getOperand(1));
8489 auto *NotC
= dyn_cast
<ConstantSDNode
>(Cond1
);
8490 if (C
&& NotC
&& C
->getAPIntValue() == ~NotC
->getAPIntValue()) {
8491 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
8492 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
8494 // The IR equivalent of this transform would have this form:
8496 // %c = icmp ugt %x, ~C
8497 // %r = select %c, -1, %a
8499 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
8500 // %u0 = extractvalue %u, 0
8501 // %u1 = extractvalue %u, 1
8502 // %r = select %u1, -1, %u0
8503 SDVTList VTs
= DAG
.getVTList(VT
, VT0
);
8504 SDValue UAO
= DAG
.getNode(ISD::UADDO
, DL
, VTs
, Cond0
, N2
.getOperand(1));
8505 return DAG
.getSelect(DL
, VT
, UAO
.getValue(1), N1
, UAO
.getValue(0));
8509 if (TLI
.isOperationLegal(ISD::SELECT_CC
, VT
) ||
8510 (!LegalOperations
&&
8511 TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
))) {
8512 // Any flags available in a select/setcc fold will be on the setcc as they
8513 // migrated from fcmp
8514 Flags
= N0
.getNode()->getFlags();
8515 SDValue SelectNode
= DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Cond0
, Cond1
, N1
,
8516 N2
, N0
.getOperand(2));
8517 SelectNode
->setFlags(Flags
);
8521 return SimplifySelect(DL
, N0
, N1
, N2
);
8527 // This function assumes all the vselect's arguments are CONCAT_VECTOR
8528 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
8529 static SDValue
ConvertSelectToConcatVector(SDNode
*N
, SelectionDAG
&DAG
) {
8531 SDValue Cond
= N
->getOperand(0);
8532 SDValue LHS
= N
->getOperand(1);
8533 SDValue RHS
= N
->getOperand(2);
8534 EVT VT
= N
->getValueType(0);
8535 int NumElems
= VT
.getVectorNumElements();
8536 assert(LHS
.getOpcode() == ISD::CONCAT_VECTORS
&&
8537 RHS
.getOpcode() == ISD::CONCAT_VECTORS
&&
8538 Cond
.getOpcode() == ISD::BUILD_VECTOR
);
8540 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
8541 // binary ones here.
8542 if (LHS
->getNumOperands() != 2 || RHS
->getNumOperands() != 2)
8545 // We're sure we have an even number of elements due to the
8546 // concat_vectors we have as arguments to vselect.
8547 // Skip BV elements until we find one that's not an UNDEF
8548 // After we find an UNDEF element, keep looping until we get to half the
8549 // length of the BV and see if all the non-undef nodes are the same.
8550 ConstantSDNode
*BottomHalf
= nullptr;
8551 for (int i
= 0; i
< NumElems
/ 2; ++i
) {
8552 if (Cond
->getOperand(i
)->isUndef())
8555 if (BottomHalf
== nullptr)
8556 BottomHalf
= cast
<ConstantSDNode
>(Cond
.getOperand(i
));
8557 else if (Cond
->getOperand(i
).getNode() != BottomHalf
)
8561 // Do the same for the second half of the BuildVector
8562 ConstantSDNode
*TopHalf
= nullptr;
8563 for (int i
= NumElems
/ 2; i
< NumElems
; ++i
) {
8564 if (Cond
->getOperand(i
)->isUndef())
8567 if (TopHalf
== nullptr)
8568 TopHalf
= cast
<ConstantSDNode
>(Cond
.getOperand(i
));
8569 else if (Cond
->getOperand(i
).getNode() != TopHalf
)
8573 assert(TopHalf
&& BottomHalf
&&
8574 "One half of the selector was all UNDEFs and the other was all the "
8575 "same value. This should have been addressed before this function.");
8577 ISD::CONCAT_VECTORS
, DL
, VT
,
8578 BottomHalf
->isNullValue() ? RHS
->getOperand(0) : LHS
->getOperand(0),
8579 TopHalf
->isNullValue() ? RHS
->getOperand(1) : LHS
->getOperand(1));
8582 SDValue
DAGCombiner::visitMSCATTER(SDNode
*N
) {
8583 MaskedScatterSDNode
*MSC
= cast
<MaskedScatterSDNode
>(N
);
8584 SDValue Mask
= MSC
->getMask();
8585 SDValue Chain
= MSC
->getChain();
8588 // Zap scatters with a zero mask.
8589 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8595 SDValue
DAGCombiner::visitMSTORE(SDNode
*N
) {
8596 MaskedStoreSDNode
*MST
= cast
<MaskedStoreSDNode
>(N
);
8597 SDValue Mask
= MST
->getMask();
8598 SDValue Chain
= MST
->getChain();
8601 // Zap masked stores with a zero mask.
8602 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8608 SDValue
DAGCombiner::visitMGATHER(SDNode
*N
) {
8609 MaskedGatherSDNode
*MGT
= cast
<MaskedGatherSDNode
>(N
);
8610 SDValue Mask
= MGT
->getMask();
8613 // Zap gathers with a zero mask.
8614 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8615 return CombineTo(N
, MGT
->getPassThru(), MGT
->getChain());
8620 SDValue
DAGCombiner::visitMLOAD(SDNode
*N
) {
8621 MaskedLoadSDNode
*MLD
= cast
<MaskedLoadSDNode
>(N
);
8622 SDValue Mask
= MLD
->getMask();
8625 // Zap masked loads with a zero mask.
8626 if (ISD::isBuildVectorAllZeros(Mask
.getNode()))
8627 return CombineTo(N
, MLD
->getPassThru(), MLD
->getChain());
8632 /// A vector select of 2 constant vectors can be simplified to math/logic to
8633 /// avoid a variable select instruction and possibly avoid constant loads.
8634 SDValue
DAGCombiner::foldVSelectOfConstants(SDNode
*N
) {
8635 SDValue Cond
= N
->getOperand(0);
8636 SDValue N1
= N
->getOperand(1);
8637 SDValue N2
= N
->getOperand(2);
8638 EVT VT
= N
->getValueType(0);
8639 if (!Cond
.hasOneUse() || Cond
.getScalarValueSizeInBits() != 1 ||
8640 !TLI
.convertSelectOfConstantsToMath(VT
) ||
8641 !ISD::isBuildVectorOfConstantSDNodes(N1
.getNode()) ||
8642 !ISD::isBuildVectorOfConstantSDNodes(N2
.getNode()))
8645 // Check if we can use the condition value to increment/decrement a single
8646 // constant value. This simplifies a select to an add and removes a constant
8647 // load/materialization from the general case.
8648 bool AllAddOne
= true;
8649 bool AllSubOne
= true;
8650 unsigned Elts
= VT
.getVectorNumElements();
8651 for (unsigned i
= 0; i
!= Elts
; ++i
) {
8652 SDValue N1Elt
= N1
.getOperand(i
);
8653 SDValue N2Elt
= N2
.getOperand(i
);
8654 if (N1Elt
.isUndef() || N2Elt
.isUndef())
8657 const APInt
&C1
= cast
<ConstantSDNode
>(N1Elt
)->getAPIntValue();
8658 const APInt
&C2
= cast
<ConstantSDNode
>(N2Elt
)->getAPIntValue();
8665 // Further simplifications for the extra-special cases where the constants are
8666 // all 0 or all -1 should be implemented as folds of these patterns.
8668 if (AllAddOne
|| AllSubOne
) {
8669 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
8670 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
8671 auto ExtendOpcode
= AllAddOne
? ISD::ZERO_EXTEND
: ISD::SIGN_EXTEND
;
8672 SDValue ExtendedCond
= DAG
.getNode(ExtendOpcode
, DL
, VT
, Cond
);
8673 return DAG
.getNode(ISD::ADD
, DL
, VT
, ExtendedCond
, N2
);
8676 // The general case for select-of-constants:
8677 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
8678 // ...but that only makes sense if a vselect is slower than 2 logic ops, so
8679 // leave that to a machine-specific pass.
8683 SDValue
DAGCombiner::visitVSELECT(SDNode
*N
) {
8684 SDValue N0
= N
->getOperand(0);
8685 SDValue N1
= N
->getOperand(1);
8686 SDValue N2
= N
->getOperand(2);
8687 EVT VT
= N
->getValueType(0);
8690 if (SDValue V
= DAG
.simplifySelect(N0
, N1
, N2
))
8693 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
8694 if (SDValue F
= extractBooleanFlip(N0
, DAG
, TLI
, false))
8695 return DAG
.getSelect(DL
, VT
, F
, N2
, N1
);
8697 // Canonicalize integer abs.
8698 // vselect (setg[te] X, 0), X, -X ->
8699 // vselect (setgt X, -1), X, -X ->
8700 // vselect (setl[te] X, 0), -X, X ->
8701 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8702 if (N0
.getOpcode() == ISD::SETCC
) {
8703 SDValue LHS
= N0
.getOperand(0), RHS
= N0
.getOperand(1);
8704 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
8706 bool RHSIsAllZeros
= ISD::isBuildVectorAllZeros(RHS
.getNode());
8708 if (((RHSIsAllZeros
&& (CC
== ISD::SETGT
|| CC
== ISD::SETGE
)) ||
8709 (ISD::isBuildVectorAllOnes(RHS
.getNode()) && CC
== ISD::SETGT
)) &&
8710 N1
== LHS
&& N2
.getOpcode() == ISD::SUB
&& N1
== N2
.getOperand(1))
8711 isAbs
= ISD::isBuildVectorAllZeros(N2
.getOperand(0).getNode());
8712 else if ((RHSIsAllZeros
&& (CC
== ISD::SETLT
|| CC
== ISD::SETLE
)) &&
8713 N2
== LHS
&& N1
.getOpcode() == ISD::SUB
&& N2
== N1
.getOperand(1))
8714 isAbs
= ISD::isBuildVectorAllZeros(N1
.getOperand(0).getNode());
8717 EVT VT
= LHS
.getValueType();
8718 if (TLI
.isOperationLegalOrCustom(ISD::ABS
, VT
))
8719 return DAG
.getNode(ISD::ABS
, DL
, VT
, LHS
);
8721 SDValue Shift
= DAG
.getNode(
8722 ISD::SRA
, DL
, VT
, LHS
,
8723 DAG
.getConstant(VT
.getScalarSizeInBits() - 1, DL
, VT
));
8724 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, LHS
, Shift
);
8725 AddToWorklist(Shift
.getNode());
8726 AddToWorklist(Add
.getNode());
8727 return DAG
.getNode(ISD::XOR
, DL
, VT
, Add
, Shift
);
8730 // vselect x, y (fcmp lt x, y) -> fminnum x, y
8731 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
8733 // This is OK if we don't care about what happens if either operand is a
8736 if (N0
.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG
, N0
.getOperand(0),
8737 N0
.getOperand(1), TLI
)) {
8738 if (SDValue FMinMax
= combineMinNumMaxNum(
8739 DL
, VT
, N0
.getOperand(0), N0
.getOperand(1), N1
, N2
, CC
, TLI
, DAG
))
8743 // If this select has a condition (setcc) with narrower operands than the
8744 // select, try to widen the compare to match the select width.
8745 // TODO: This should be extended to handle any constant.
8746 // TODO: This could be extended to handle non-loading patterns, but that
8747 // requires thorough testing to avoid regressions.
8748 if (isNullOrNullSplat(RHS
)) {
8749 EVT NarrowVT
= LHS
.getValueType();
8750 EVT WideVT
= N1
.getValueType().changeVectorElementTypeToInteger();
8751 EVT SetCCVT
= getSetCCResultType(LHS
.getValueType());
8752 unsigned SetCCWidth
= SetCCVT
.getScalarSizeInBits();
8753 unsigned WideWidth
= WideVT
.getScalarSizeInBits();
8754 bool IsSigned
= isSignedIntSetCC(CC
);
8755 auto LoadExtOpcode
= IsSigned
? ISD::SEXTLOAD
: ISD::ZEXTLOAD
;
8756 if (LHS
.getOpcode() == ISD::LOAD
&& LHS
.hasOneUse() &&
8757 SetCCWidth
!= 1 && SetCCWidth
< WideWidth
&&
8758 TLI
.isLoadExtLegalOrCustom(LoadExtOpcode
, WideVT
, NarrowVT
) &&
8759 TLI
.isOperationLegalOrCustom(ISD::SETCC
, WideVT
)) {
8760 // Both compare operands can be widened for free. The LHS can use an
8761 // extended load, and the RHS is a constant:
8762 // vselect (ext (setcc load(X), C)), N1, N2 -->
8763 // vselect (setcc extload(X), C'), N1, N2
8764 auto ExtOpcode
= IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
8765 SDValue WideLHS
= DAG
.getNode(ExtOpcode
, DL
, WideVT
, LHS
);
8766 SDValue WideRHS
= DAG
.getNode(ExtOpcode
, DL
, WideVT
, RHS
);
8767 EVT WideSetCCVT
= getSetCCResultType(WideVT
);
8768 SDValue WideSetCC
= DAG
.getSetCC(DL
, WideSetCCVT
, WideLHS
, WideRHS
, CC
);
8769 return DAG
.getSelect(DL
, N1
.getValueType(), WideSetCC
, N1
, N2
);
8774 if (SimplifySelectOps(N
, N1
, N2
))
8775 return SDValue(N
, 0); // Don't revisit N.
8777 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
8778 if (ISD::isBuildVectorAllOnes(N0
.getNode()))
8780 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
8781 if (ISD::isBuildVectorAllZeros(N0
.getNode()))
8784 // The ConvertSelectToConcatVector function is assuming both the above
8785 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
8787 if (N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
8788 N2
.getOpcode() == ISD::CONCAT_VECTORS
&&
8789 ISD::isBuildVectorOfConstantSDNodes(N0
.getNode())) {
8790 if (SDValue CV
= ConvertSelectToConcatVector(N
, DAG
))
8794 if (SDValue V
= foldVSelectOfConstants(N
))
8800 SDValue
DAGCombiner::visitSELECT_CC(SDNode
*N
) {
8801 SDValue N0
= N
->getOperand(0);
8802 SDValue N1
= N
->getOperand(1);
8803 SDValue N2
= N
->getOperand(2);
8804 SDValue N3
= N
->getOperand(3);
8805 SDValue N4
= N
->getOperand(4);
8806 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N4
)->get();
8808 // fold select_cc lhs, rhs, x, x, cc -> x
8812 // Determine if the condition we're dealing with is constant
8813 if (SDValue SCC
= SimplifySetCC(getSetCCResultType(N0
.getValueType()), N0
, N1
,
8814 CC
, SDLoc(N
), false)) {
8815 AddToWorklist(SCC
.getNode());
8817 if (ConstantSDNode
*SCCC
= dyn_cast
<ConstantSDNode
>(SCC
.getNode())) {
8818 if (!SCCC
->isNullValue())
8819 return N2
; // cond always true -> true val
8821 return N3
; // cond always false -> false val
8822 } else if (SCC
->isUndef()) {
8823 // When the condition is UNDEF, just return the first operand. This is
8824 // coherent the DAG creation, no setcc node is created in this case
8826 } else if (SCC
.getOpcode() == ISD::SETCC
) {
8827 // Fold to a simpler select_cc
8828 SDValue SelectOp
= DAG
.getNode(
8829 ISD::SELECT_CC
, SDLoc(N
), N2
.getValueType(), SCC
.getOperand(0),
8830 SCC
.getOperand(1), N2
, N3
, SCC
.getOperand(2));
8831 SelectOp
->setFlags(SCC
->getFlags());
8836 // If we can fold this based on the true/false value, do so.
8837 if (SimplifySelectOps(N
, N2
, N3
))
8838 return SDValue(N
, 0); // Don't revisit N.
8840 // fold select_cc into other things, such as min/max/abs
8841 return SimplifySelectCC(SDLoc(N
), N0
, N1
, N2
, N3
, CC
);
8844 SDValue
DAGCombiner::visitSETCC(SDNode
*N
) {
8845 // setcc is very commonly used as an argument to brcond. This pattern
8846 // also lend itself to numerous combines and, as a result, it is desired
8847 // we keep the argument to a brcond as a setcc as much as possible.
8849 N
->hasOneUse() && N
->use_begin()->getOpcode() == ISD::BRCOND
;
8851 SDValue Combined
= SimplifySetCC(
8852 N
->getValueType(0), N
->getOperand(0), N
->getOperand(1),
8853 cast
<CondCodeSDNode
>(N
->getOperand(2))->get(), SDLoc(N
), !PreferSetCC
);
8858 // If we prefer to have a setcc, and we don't, we'll try our best to
8859 // recreate one using rebuildSetCC.
8860 if (PreferSetCC
&& Combined
.getOpcode() != ISD::SETCC
) {
8861 SDValue NewSetCC
= rebuildSetCC(Combined
);
8863 // We don't have anything interesting to combine to.
8864 if (NewSetCC
.getNode() == N
)
8874 SDValue
DAGCombiner::visitSETCCCARRY(SDNode
*N
) {
8875 SDValue LHS
= N
->getOperand(0);
8876 SDValue RHS
= N
->getOperand(1);
8877 SDValue Carry
= N
->getOperand(2);
8878 SDValue Cond
= N
->getOperand(3);
8880 // If Carry is false, fold to a regular SETCC.
8881 if (isNullConstant(Carry
))
8882 return DAG
.getNode(ISD::SETCC
, SDLoc(N
), N
->getVTList(), LHS
, RHS
, Cond
);
8887 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
8888 /// a build_vector of constants.
8889 /// This function is called by the DAGCombiner when visiting sext/zext/aext
8890 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
8891 /// Vector extends are not folded if operations are legal; this is to
8892 /// avoid introducing illegal build_vector dag nodes.
8893 static SDValue
tryToFoldExtendOfConstant(SDNode
*N
, const TargetLowering
&TLI
,
8894 SelectionDAG
&DAG
, bool LegalTypes
) {
8895 unsigned Opcode
= N
->getOpcode();
8896 SDValue N0
= N
->getOperand(0);
8897 EVT VT
= N
->getValueType(0);
8900 assert((Opcode
== ISD::SIGN_EXTEND
|| Opcode
== ISD::ZERO_EXTEND
||
8901 Opcode
== ISD::ANY_EXTEND
|| Opcode
== ISD::SIGN_EXTEND_VECTOR_INREG
||
8902 Opcode
== ISD::ZERO_EXTEND_VECTOR_INREG
)
8903 && "Expected EXTEND dag node in input!");
8905 // fold (sext c1) -> c1
8906 // fold (zext c1) -> c1
8907 // fold (aext c1) -> c1
8908 if (isa
<ConstantSDNode
>(N0
))
8909 return DAG
.getNode(Opcode
, DL
, VT
, N0
);
8911 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
8912 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
8913 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
8914 if (N0
->getOpcode() == ISD::SELECT
) {
8915 SDValue Op1
= N0
->getOperand(1);
8916 SDValue Op2
= N0
->getOperand(2);
8917 if (isa
<ConstantSDNode
>(Op1
) && isa
<ConstantSDNode
>(Op2
) &&
8918 (Opcode
!= ISD::ZERO_EXTEND
|| !TLI
.isZExtFree(N0
.getValueType(), VT
))) {
8919 // For any_extend, choose sign extension of the constants to allow a
8920 // possible further transform to sign_extend_inreg.i.e.
8922 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
8923 // t2: i64 = any_extend t1
8925 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
8927 // t4: i64 = sign_extend_inreg t3
8928 unsigned FoldOpc
= Opcode
;
8929 if (FoldOpc
== ISD::ANY_EXTEND
)
8930 FoldOpc
= ISD::SIGN_EXTEND
;
8931 return DAG
.getSelect(DL
, VT
, N0
->getOperand(0),
8932 DAG
.getNode(FoldOpc
, DL
, VT
, Op1
),
8933 DAG
.getNode(FoldOpc
, DL
, VT
, Op2
));
8937 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
8938 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
8939 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
8940 EVT SVT
= VT
.getScalarType();
8941 if (!(VT
.isVector() && (!LegalTypes
|| TLI
.isTypeLegal(SVT
)) &&
8942 ISD::isBuildVectorOfConstantSDNodes(N0
.getNode())))
8945 // We can fold this node into a build_vector.
8946 unsigned VTBits
= SVT
.getSizeInBits();
8947 unsigned EVTBits
= N0
->getValueType(0).getScalarSizeInBits();
8948 SmallVector
<SDValue
, 8> Elts
;
8949 unsigned NumElts
= VT
.getVectorNumElements();
8951 // For zero-extensions, UNDEF elements still guarantee to have the upper
8952 // bits set to zero.
8954 Opcode
== ISD::ZERO_EXTEND
|| Opcode
== ISD::ZERO_EXTEND_VECTOR_INREG
;
8956 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
8957 SDValue Op
= N0
.getOperand(i
);
8959 Elts
.push_back(IsZext
? DAG
.getConstant(0, DL
, SVT
) : DAG
.getUNDEF(SVT
));
8964 // Get the constant value and if needed trunc it to the size of the type.
8965 // Nodes like build_vector might have constants wider than the scalar type.
8966 APInt C
= cast
<ConstantSDNode
>(Op
)->getAPIntValue().zextOrTrunc(EVTBits
);
8967 if (Opcode
== ISD::SIGN_EXTEND
|| Opcode
== ISD::SIGN_EXTEND_VECTOR_INREG
)
8968 Elts
.push_back(DAG
.getConstant(C
.sext(VTBits
), DL
, SVT
));
8970 Elts
.push_back(DAG
.getConstant(C
.zext(VTBits
), DL
, SVT
));
8973 return DAG
.getBuildVector(VT
, DL
, Elts
);
8976 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
8977 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
8978 // transformation. Returns true if extension are possible and the above
8979 // mentioned transformation is profitable.
8980 static bool ExtendUsesToFormExtLoad(EVT VT
, SDNode
*N
, SDValue N0
,
8982 SmallVectorImpl
<SDNode
*> &ExtendNodes
,
8983 const TargetLowering
&TLI
) {
8984 bool HasCopyToRegUses
= false;
8985 bool isTruncFree
= TLI
.isTruncateFree(VT
, N0
.getValueType());
8986 for (SDNode::use_iterator UI
= N0
.getNode()->use_begin(),
8987 UE
= N0
.getNode()->use_end();
8992 if (UI
.getUse().getResNo() != N0
.getResNo())
8994 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
8995 if (ExtOpc
!= ISD::ANY_EXTEND
&& User
->getOpcode() == ISD::SETCC
) {
8996 ISD::CondCode CC
= cast
<CondCodeSDNode
>(User
->getOperand(2))->get();
8997 if (ExtOpc
== ISD::ZERO_EXTEND
&& ISD::isSignedIntSetCC(CC
))
8998 // Sign bits will be lost after a zext.
9001 for (unsigned i
= 0; i
!= 2; ++i
) {
9002 SDValue UseOp
= User
->getOperand(i
);
9005 if (!isa
<ConstantSDNode
>(UseOp
))
9010 ExtendNodes
.push_back(User
);
9013 // If truncates aren't free and there are users we can't
9014 // extend, it isn't worthwhile.
9017 // Remember if this value is live-out.
9018 if (User
->getOpcode() == ISD::CopyToReg
)
9019 HasCopyToRegUses
= true;
9022 if (HasCopyToRegUses
) {
9023 bool BothLiveOut
= false;
9024 for (SDNode::use_iterator UI
= N
->use_begin(), UE
= N
->use_end();
9026 SDUse
&Use
= UI
.getUse();
9027 if (Use
.getResNo() == 0 && Use
.getUser()->getOpcode() == ISD::CopyToReg
) {
9033 // Both unextended and extended values are live out. There had better be
9034 // a good reason for the transformation.
9035 return ExtendNodes
.size();
9040 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl
<SDNode
*> &SetCCs
,
9041 SDValue OrigLoad
, SDValue ExtLoad
,
9042 ISD::NodeType ExtType
) {
9043 // Extend SetCC uses if necessary.
9045 for (SDNode
*SetCC
: SetCCs
) {
9046 SmallVector
<SDValue
, 4> Ops
;
9048 for (unsigned j
= 0; j
!= 2; ++j
) {
9049 SDValue SOp
= SetCC
->getOperand(j
);
9050 if (SOp
== OrigLoad
)
9051 Ops
.push_back(ExtLoad
);
9053 Ops
.push_back(DAG
.getNode(ExtType
, DL
, ExtLoad
->getValueType(0), SOp
));
9056 Ops
.push_back(SetCC
->getOperand(2));
9057 CombineTo(SetCC
, DAG
.getNode(ISD::SETCC
, DL
, SetCC
->getValueType(0), Ops
));
9061 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
9062 SDValue
DAGCombiner::CombineExtLoad(SDNode
*N
) {
9063 SDValue N0
= N
->getOperand(0);
9064 EVT DstVT
= N
->getValueType(0);
9065 EVT SrcVT
= N0
.getValueType();
9067 assert((N
->getOpcode() == ISD::SIGN_EXTEND
||
9068 N
->getOpcode() == ISD::ZERO_EXTEND
) &&
9069 "Unexpected node type (not an extend)!");
9071 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
9072 // For example, on a target with legal v4i32, but illegal v8i32, turn:
9073 // (v8i32 (sext (v8i16 (load x))))
9075 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9076 // (v4i32 (sextload (x + 16)))))
9077 // Where uses of the original load, i.e.:
9079 // are replaced with:
9081 // (v8i32 (concat_vectors (v4i32 (sextload x)),
9082 // (v4i32 (sextload (x + 16)))))))
9084 // This combine is only applicable to illegal, but splittable, vectors.
9085 // All legal types, and illegal non-vector types, are handled elsewhere.
9086 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
9088 if (N0
->getOpcode() != ISD::LOAD
)
9091 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9093 if (!ISD::isNON_EXTLoad(LN0
) || !ISD::isUNINDEXEDLoad(LN0
) ||
9094 !N0
.hasOneUse() || LN0
->isVolatile() || !DstVT
.isVector() ||
9095 !DstVT
.isPow2VectorType() || !TLI
.isVectorLoadExtDesirable(SDValue(N
, 0)))
9098 SmallVector
<SDNode
*, 4> SetCCs
;
9099 if (!ExtendUsesToFormExtLoad(DstVT
, N
, N0
, N
->getOpcode(), SetCCs
, TLI
))
9102 ISD::LoadExtType ExtType
=
9103 N
->getOpcode() == ISD::SIGN_EXTEND
? ISD::SEXTLOAD
: ISD::ZEXTLOAD
;
9105 // Try to split the vector types to get down to legal types.
9106 EVT SplitSrcVT
= SrcVT
;
9107 EVT SplitDstVT
= DstVT
;
9108 while (!TLI
.isLoadExtLegalOrCustom(ExtType
, SplitDstVT
, SplitSrcVT
) &&
9109 SplitSrcVT
.getVectorNumElements() > 1) {
9110 SplitDstVT
= DAG
.GetSplitDestVTs(SplitDstVT
).first
;
9111 SplitSrcVT
= DAG
.GetSplitDestVTs(SplitSrcVT
).first
;
9114 if (!TLI
.isLoadExtLegalOrCustom(ExtType
, SplitDstVT
, SplitSrcVT
))
9118 const unsigned NumSplits
=
9119 DstVT
.getVectorNumElements() / SplitDstVT
.getVectorNumElements();
9120 const unsigned Stride
= SplitSrcVT
.getStoreSize();
9121 SmallVector
<SDValue
, 4> Loads
;
9122 SmallVector
<SDValue
, 4> Chains
;
9124 SDValue BasePtr
= LN0
->getBasePtr();
9125 for (unsigned Idx
= 0; Idx
< NumSplits
; Idx
++) {
9126 const unsigned Offset
= Idx
* Stride
;
9127 const unsigned Align
= MinAlign(LN0
->getAlignment(), Offset
);
9129 SDValue SplitLoad
= DAG
.getExtLoad(
9130 ExtType
, SDLoc(LN0
), SplitDstVT
, LN0
->getChain(), BasePtr
,
9131 LN0
->getPointerInfo().getWithOffset(Offset
), SplitSrcVT
, Align
,
9132 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
9134 BasePtr
= DAG
.getNode(ISD::ADD
, DL
, BasePtr
.getValueType(), BasePtr
,
9135 DAG
.getConstant(Stride
, DL
, BasePtr
.getValueType()));
9137 Loads
.push_back(SplitLoad
.getValue(0));
9138 Chains
.push_back(SplitLoad
.getValue(1));
9141 SDValue NewChain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, Chains
);
9142 SDValue NewValue
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, DstVT
, Loads
);
9145 AddToWorklist(NewChain
.getNode());
9147 CombineTo(N
, NewValue
);
9149 // Replace uses of the original load (before extension)
9150 // with a truncate of the concatenated sextloaded vectors.
9152 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), N0
.getValueType(), NewValue
);
9153 ExtendSetCCUses(SetCCs
, N0
, NewValue
, (ISD::NodeType
)N
->getOpcode());
9154 CombineTo(N0
.getNode(), Trunc
, NewChain
);
9155 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9158 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9159 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9160 SDValue
DAGCombiner::CombineZExtLogicopShiftLoad(SDNode
*N
) {
9161 assert(N
->getOpcode() == ISD::ZERO_EXTEND
);
9162 EVT VT
= N
->getValueType(0);
9163 EVT OrigVT
= N
->getOperand(0).getValueType();
9164 if (TLI
.isZExtFree(OrigVT
, VT
))
9168 SDValue N0
= N
->getOperand(0);
9169 if (!(N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9170 N0
.getOpcode() == ISD::XOR
) ||
9171 N0
.getOperand(1).getOpcode() != ISD::Constant
||
9172 (LegalOperations
&& !TLI
.isOperationLegal(N0
.getOpcode(), VT
)))
9176 SDValue N1
= N0
->getOperand(0);
9177 if (!(N1
.getOpcode() == ISD::SHL
|| N1
.getOpcode() == ISD::SRL
) ||
9178 N1
.getOperand(1).getOpcode() != ISD::Constant
||
9179 (LegalOperations
&& !TLI
.isOperationLegal(N1
.getOpcode(), VT
)))
9183 if (!isa
<LoadSDNode
>(N1
.getOperand(0)))
9185 LoadSDNode
*Load
= cast
<LoadSDNode
>(N1
.getOperand(0));
9186 EVT MemVT
= Load
->getMemoryVT();
9187 if (!TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
) ||
9188 Load
->getExtensionType() == ISD::SEXTLOAD
|| Load
->isIndexed())
9192 // If the shift op is SHL, the logic op must be AND, otherwise the result
9194 if (N1
.getOpcode() == ISD::SHL
&& N0
.getOpcode() != ISD::AND
)
9197 if (!N0
.hasOneUse() || !N1
.hasOneUse())
9200 SmallVector
<SDNode
*, 4> SetCCs
;
9201 if (!ExtendUsesToFormExtLoad(VT
, N1
.getNode(), N1
.getOperand(0),
9202 ISD::ZERO_EXTEND
, SetCCs
, TLI
))
9205 // Actually do the transformation.
9206 SDValue ExtLoad
= DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(Load
), VT
,
9207 Load
->getChain(), Load
->getBasePtr(),
9208 Load
->getMemoryVT(), Load
->getMemOperand());
9211 SDValue Shift
= DAG
.getNode(N1
.getOpcode(), DL1
, VT
, ExtLoad
,
9214 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9215 Mask
= Mask
.zext(VT
.getSizeInBits());
9217 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL0
, VT
, Shift
,
9218 DAG
.getConstant(Mask
, DL0
, VT
));
9220 ExtendSetCCUses(SetCCs
, N1
.getOperand(0), ExtLoad
, ISD::ZERO_EXTEND
);
9222 if (SDValue(Load
, 0).hasOneUse()) {
9223 DAG
.ReplaceAllUsesOfValueWith(SDValue(Load
, 1), ExtLoad
.getValue(1));
9225 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(Load
),
9226 Load
->getValueType(0), ExtLoad
);
9227 CombineTo(Load
, Trunc
, ExtLoad
.getValue(1));
9230 // N0 is dead at this point.
9231 recursivelyDeleteUnusedNodes(N0
.getNode());
9233 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9236 /// If we're narrowing or widening the result of a vector select and the final
9237 /// size is the same size as a setcc (compare) feeding the select, then try to
9238 /// apply the cast operation to the select's operands because matching vector
9239 /// sizes for a select condition and other operands should be more efficient.
9240 SDValue
DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode
*Cast
) {
9241 unsigned CastOpcode
= Cast
->getOpcode();
9242 assert((CastOpcode
== ISD::SIGN_EXTEND
|| CastOpcode
== ISD::ZERO_EXTEND
||
9243 CastOpcode
== ISD::TRUNCATE
|| CastOpcode
== ISD::FP_EXTEND
||
9244 CastOpcode
== ISD::FP_ROUND
) &&
9245 "Unexpected opcode for vector select narrowing/widening");
9247 // We only do this transform before legal ops because the pattern may be
9248 // obfuscated by target-specific operations after legalization. Do not create
9249 // an illegal select op, however, because that may be difficult to lower.
9250 EVT VT
= Cast
->getValueType(0);
9251 if (LegalOperations
|| !TLI
.isOperationLegalOrCustom(ISD::VSELECT
, VT
))
9254 SDValue VSel
= Cast
->getOperand(0);
9255 if (VSel
.getOpcode() != ISD::VSELECT
|| !VSel
.hasOneUse() ||
9256 VSel
.getOperand(0).getOpcode() != ISD::SETCC
)
9259 // Does the setcc have the same vector size as the casted select?
9260 SDValue SetCC
= VSel
.getOperand(0);
9261 EVT SetCCVT
= getSetCCResultType(SetCC
.getOperand(0).getValueType());
9262 if (SetCCVT
.getSizeInBits() != VT
.getSizeInBits())
9265 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
9266 SDValue A
= VSel
.getOperand(1);
9267 SDValue B
= VSel
.getOperand(2);
9268 SDValue CastA
, CastB
;
9270 if (CastOpcode
== ISD::FP_ROUND
) {
9271 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
9272 CastA
= DAG
.getNode(CastOpcode
, DL
, VT
, A
, Cast
->getOperand(1));
9273 CastB
= DAG
.getNode(CastOpcode
, DL
, VT
, B
, Cast
->getOperand(1));
9275 CastA
= DAG
.getNode(CastOpcode
, DL
, VT
, A
);
9276 CastB
= DAG
.getNode(CastOpcode
, DL
, VT
, B
);
9278 return DAG
.getNode(ISD::VSELECT
, DL
, VT
, SetCC
, CastA
, CastB
);
9281 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9282 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9283 static SDValue
tryToFoldExtOfExtload(SelectionDAG
&DAG
, DAGCombiner
&Combiner
,
9284 const TargetLowering
&TLI
, EVT VT
,
9285 bool LegalOperations
, SDNode
*N
,
9286 SDValue N0
, ISD::LoadExtType ExtLoadType
) {
9287 SDNode
*N0Node
= N0
.getNode();
9288 bool isAExtLoad
= (ExtLoadType
== ISD::SEXTLOAD
) ? ISD::isSEXTLoad(N0Node
)
9289 : ISD::isZEXTLoad(N0Node
);
9290 if ((!isAExtLoad
&& !ISD::isEXTLoad(N0Node
)) ||
9291 !ISD::isUNINDEXEDLoad(N0Node
) || !N0
.hasOneUse())
9294 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9295 EVT MemVT
= LN0
->getMemoryVT();
9296 if ((LegalOperations
|| LN0
->isVolatile() || VT
.isVector()) &&
9297 !TLI
.isLoadExtLegal(ExtLoadType
, VT
, MemVT
))
9301 DAG
.getExtLoad(ExtLoadType
, SDLoc(LN0
), VT
, LN0
->getChain(),
9302 LN0
->getBasePtr(), MemVT
, LN0
->getMemOperand());
9303 Combiner
.CombineTo(N
, ExtLoad
);
9304 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9305 if (LN0
->use_empty())
9306 Combiner
.recursivelyDeleteUnusedNodes(LN0
);
9307 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9310 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
9311 // Only generate vector extloads when 1) they're legal, and 2) they are
9312 // deemed desirable by the target.
9313 static SDValue
tryToFoldExtOfLoad(SelectionDAG
&DAG
, DAGCombiner
&Combiner
,
9314 const TargetLowering
&TLI
, EVT VT
,
9315 bool LegalOperations
, SDNode
*N
, SDValue N0
,
9316 ISD::LoadExtType ExtLoadType
,
9317 ISD::NodeType ExtOpc
) {
9318 if (!ISD::isNON_EXTLoad(N0
.getNode()) ||
9319 !ISD::isUNINDEXEDLoad(N0
.getNode()) ||
9320 ((LegalOperations
|| VT
.isVector() ||
9321 cast
<LoadSDNode
>(N0
)->isVolatile()) &&
9322 !TLI
.isLoadExtLegal(ExtLoadType
, VT
, N0
.getValueType())))
9325 bool DoXform
= true;
9326 SmallVector
<SDNode
*, 4> SetCCs
;
9327 if (!N0
.hasOneUse())
9328 DoXform
= ExtendUsesToFormExtLoad(VT
, N
, N0
, ExtOpc
, SetCCs
, TLI
);
9330 DoXform
&= TLI
.isVectorLoadExtDesirable(SDValue(N
, 0));
9334 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9335 SDValue ExtLoad
= DAG
.getExtLoad(ExtLoadType
, SDLoc(LN0
), VT
, LN0
->getChain(),
9336 LN0
->getBasePtr(), N0
.getValueType(),
9337 LN0
->getMemOperand());
9338 Combiner
.ExtendSetCCUses(SetCCs
, N0
, ExtLoad
, ExtOpc
);
9339 // If the load value is used only by N, replace it via CombineTo N.
9340 bool NoReplaceTrunc
= SDValue(LN0
, 0).hasOneUse();
9341 Combiner
.CombineTo(N
, ExtLoad
);
9342 if (NoReplaceTrunc
) {
9343 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9344 Combiner
.recursivelyDeleteUnusedNodes(LN0
);
9347 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), N0
.getValueType(), ExtLoad
);
9348 Combiner
.CombineTo(LN0
, Trunc
, ExtLoad
.getValue(1));
9350 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9353 static SDValue
foldExtendedSignBitTest(SDNode
*N
, SelectionDAG
&DAG
,
9354 bool LegalOperations
) {
9355 assert((N
->getOpcode() == ISD::SIGN_EXTEND
||
9356 N
->getOpcode() == ISD::ZERO_EXTEND
) && "Expected sext or zext");
9358 SDValue SetCC
= N
->getOperand(0);
9359 if (LegalOperations
|| SetCC
.getOpcode() != ISD::SETCC
||
9360 !SetCC
.hasOneUse() || SetCC
.getValueType() != MVT::i1
)
9363 SDValue X
= SetCC
.getOperand(0);
9364 SDValue Ones
= SetCC
.getOperand(1);
9365 ISD::CondCode CC
= cast
<CondCodeSDNode
>(SetCC
.getOperand(2))->get();
9366 EVT VT
= N
->getValueType(0);
9367 EVT XVT
= X
.getValueType();
9368 // setge X, C is canonicalized to setgt, so we do not need to match that
9369 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
9370 // not require the 'not' op.
9371 if (CC
== ISD::SETGT
&& isAllOnesConstant(Ones
) && VT
== XVT
) {
9372 // Invert and smear/shift the sign bit:
9373 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
9374 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
9376 SDValue NotX
= DAG
.getNOT(DL
, X
, VT
);
9377 SDValue ShiftAmount
= DAG
.getConstant(VT
.getSizeInBits() - 1, DL
, VT
);
9378 auto ShiftOpcode
= N
->getOpcode() == ISD::SIGN_EXTEND
? ISD::SRA
: ISD::SRL
;
9379 return DAG
.getNode(ShiftOpcode
, DL
, VT
, NotX
, ShiftAmount
);
9384 SDValue
DAGCombiner::visitSIGN_EXTEND(SDNode
*N
) {
9385 SDValue N0
= N
->getOperand(0);
9386 EVT VT
= N
->getValueType(0);
9389 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
9392 // fold (sext (sext x)) -> (sext x)
9393 // fold (sext (aext x)) -> (sext x)
9394 if (N0
.getOpcode() == ISD::SIGN_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
)
9395 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, N0
.getOperand(0));
9397 if (N0
.getOpcode() == ISD::TRUNCATE
) {
9398 // fold (sext (truncate (load x))) -> (sext (smaller load x))
9399 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
9400 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
9401 SDNode
*oye
= N0
.getOperand(0).getNode();
9402 if (NarrowLoad
.getNode() != N0
.getNode()) {
9403 CombineTo(N0
.getNode(), NarrowLoad
);
9404 // CombineTo deleted the truncate, if needed, but not what's under it.
9407 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9410 // See if the value being truncated is already sign extended. If so, just
9411 // eliminate the trunc/sext pair.
9412 SDValue Op
= N0
.getOperand(0);
9413 unsigned OpBits
= Op
.getScalarValueSizeInBits();
9414 unsigned MidBits
= N0
.getScalarValueSizeInBits();
9415 unsigned DestBits
= VT
.getScalarSizeInBits();
9416 unsigned NumSignBits
= DAG
.ComputeNumSignBits(Op
);
9418 if (OpBits
== DestBits
) {
9419 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9420 // bits, it is already ready.
9421 if (NumSignBits
> DestBits
-MidBits
)
9423 } else if (OpBits
< DestBits
) {
9424 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9425 // bits, just sext from i32.
9426 if (NumSignBits
> OpBits
-MidBits
)
9427 return DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VT
, Op
);
9429 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9430 // bits, just truncate to i32.
9431 if (NumSignBits
> OpBits
-MidBits
)
9432 return DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, Op
);
9435 // fold (sext (truncate x)) -> (sextinreg x).
9436 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND_INREG
,
9437 N0
.getValueType())) {
9438 if (OpBits
< DestBits
)
9439 Op
= DAG
.getNode(ISD::ANY_EXTEND
, SDLoc(N0
), VT
, Op
);
9440 else if (OpBits
> DestBits
)
9441 Op
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
), VT
, Op
);
9442 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, DL
, VT
, Op
,
9443 DAG
.getValueType(N0
.getValueType()));
9447 // Try to simplify (sext (load x)).
9448 if (SDValue foldedExt
=
9449 tryToFoldExtOfLoad(DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
,
9450 ISD::SEXTLOAD
, ISD::SIGN_EXTEND
))
9453 // fold (sext (load x)) to multiple smaller sextloads.
9454 // Only on illegal but splittable vectors.
9455 if (SDValue ExtLoad
= CombineExtLoad(N
))
9458 // Try to simplify (sext (sextload x)).
9459 if (SDValue foldedExt
= tryToFoldExtOfExtload(
9460 DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
, ISD::SEXTLOAD
))
9463 // fold (sext (and/or/xor (load x), cst)) ->
9464 // (and/or/xor (sextload x), (sext cst))
9465 if ((N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9466 N0
.getOpcode() == ISD::XOR
) &&
9467 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
9468 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9469 (!LegalOperations
&& TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
9470 LoadSDNode
*LN00
= cast
<LoadSDNode
>(N0
.getOperand(0));
9471 EVT MemVT
= LN00
->getMemoryVT();
9472 if (TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, MemVT
) &&
9473 LN00
->getExtensionType() != ISD::ZEXTLOAD
&& LN00
->isUnindexed()) {
9474 SmallVector
<SDNode
*, 4> SetCCs
;
9475 bool DoXform
= ExtendUsesToFormExtLoad(VT
, N0
.getNode(), N0
.getOperand(0),
9476 ISD::SIGN_EXTEND
, SetCCs
, TLI
);
9478 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(LN00
), VT
,
9479 LN00
->getChain(), LN00
->getBasePtr(),
9480 LN00
->getMemoryVT(),
9481 LN00
->getMemOperand());
9482 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9483 Mask
= Mask
.sext(VT
.getSizeInBits());
9484 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL
, VT
,
9485 ExtLoad
, DAG
.getConstant(Mask
, DL
, VT
));
9486 ExtendSetCCUses(SetCCs
, N0
.getOperand(0), ExtLoad
, ISD::SIGN_EXTEND
);
9487 bool NoReplaceTruncAnd
= !N0
.hasOneUse();
9488 bool NoReplaceTrunc
= SDValue(LN00
, 0).hasOneUse();
9490 // If N0 has multiple uses, change other uses as well.
9491 if (NoReplaceTruncAnd
) {
9493 DAG
.getNode(ISD::TRUNCATE
, DL
, N0
.getValueType(), And
);
9494 CombineTo(N0
.getNode(), TruncAnd
);
9496 if (NoReplaceTrunc
) {
9497 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN00
, 1), ExtLoad
.getValue(1));
9499 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LN00
),
9500 LN00
->getValueType(0), ExtLoad
);
9501 CombineTo(LN00
, Trunc
, ExtLoad
.getValue(1));
9503 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9508 if (SDValue V
= foldExtendedSignBitTest(N
, DAG
, LegalOperations
))
9511 if (N0
.getOpcode() == ISD::SETCC
) {
9512 SDValue N00
= N0
.getOperand(0);
9513 SDValue N01
= N0
.getOperand(1);
9514 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
9515 EVT N00VT
= N0
.getOperand(0).getValueType();
9517 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
9518 // Only do this before legalize for now.
9519 if (VT
.isVector() && !LegalOperations
&&
9520 TLI
.getBooleanContents(N00VT
) ==
9521 TargetLowering::ZeroOrNegativeOneBooleanContent
) {
9522 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
9523 // of the same size as the compared operands. Only optimize sext(setcc())
9524 // if this is the case.
9525 EVT SVT
= getSetCCResultType(N00VT
);
9527 // If we already have the desired type, don't change it.
9528 if (SVT
!= N0
.getValueType()) {
9529 // We know that the # elements of the results is the same as the
9530 // # elements of the compare (and the # elements of the compare result
9531 // for that matter). Check to see that they are the same size. If so,
9532 // we know that the element size of the sext'd result matches the
9533 // element size of the compare operands.
9534 if (VT
.getSizeInBits() == SVT
.getSizeInBits())
9535 return DAG
.getSetCC(DL
, VT
, N00
, N01
, CC
);
9537 // If the desired elements are smaller or larger than the source
9538 // elements, we can use a matching integer vector type and then
9539 // truncate/sign extend.
9540 EVT MatchingVecType
= N00VT
.changeVectorElementTypeToInteger();
9541 if (SVT
== MatchingVecType
) {
9542 SDValue VsetCC
= DAG
.getSetCC(DL
, MatchingVecType
, N00
, N01
, CC
);
9543 return DAG
.getSExtOrTrunc(VsetCC
, DL
, VT
);
9548 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
9549 // Here, T can be 1 or -1, depending on the type of the setcc and
9550 // getBooleanContents().
9551 unsigned SetCCWidth
= N0
.getScalarValueSizeInBits();
9553 // To determine the "true" side of the select, we need to know the high bit
9554 // of the value returned by the setcc if it evaluates to true.
9555 // If the type of the setcc is i1, then the true case of the select is just
9556 // sext(i1 1), that is, -1.
9557 // If the type of the setcc is larger (say, i8) then the value of the high
9558 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
9559 // of the appropriate width.
9560 SDValue ExtTrueVal
= (SetCCWidth
== 1)
9561 ? DAG
.getAllOnesConstant(DL
, VT
)
9562 : DAG
.getBoolConstant(true, DL
, VT
, N00VT
);
9563 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
9565 SimplifySelectCC(DL
, N00
, N01
, ExtTrueVal
, Zero
, CC
, true))
9568 if (!VT
.isVector() && !TLI
.convertSelectOfConstantsToMath(VT
)) {
9569 EVT SetCCVT
= getSetCCResultType(N00VT
);
9570 // Don't do this transform for i1 because there's a select transform
9571 // that would reverse it.
9572 // TODO: We should not do this transform at all without a target hook
9573 // because a sext is likely cheaper than a select?
9574 if (SetCCVT
.getScalarSizeInBits() != 1 &&
9575 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SETCC
, N00VT
))) {
9576 SDValue SetCC
= DAG
.getSetCC(DL
, SetCCVT
, N00
, N01
, CC
);
9577 return DAG
.getSelect(DL
, VT
, SetCC
, ExtTrueVal
, Zero
);
9582 // fold (sext x) -> (zext x) if the sign bit is known zero.
9583 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
)) &&
9584 DAG
.SignBitIsZero(N0
))
9585 return DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
);
9587 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
9590 // Eliminate this sign extend by doing a negation in the destination type:
9591 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
9592 if (N0
.getOpcode() == ISD::SUB
&& N0
.hasOneUse() &&
9593 isNullOrNullSplat(N0
.getOperand(0)) &&
9594 N0
.getOperand(1).getOpcode() == ISD::ZERO_EXTEND
&&
9595 TLI
.isOperationLegalOrCustom(ISD::SUB
, VT
)) {
9596 SDValue Zext
= DAG
.getZExtOrTrunc(N0
.getOperand(1).getOperand(0), DL
, VT
);
9597 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), Zext
);
9599 // Eliminate this sign extend by doing a decrement in the destination type:
9600 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
9601 if (N0
.getOpcode() == ISD::ADD
&& N0
.hasOneUse() &&
9602 isAllOnesOrAllOnesSplat(N0
.getOperand(1)) &&
9603 N0
.getOperand(0).getOpcode() == ISD::ZERO_EXTEND
&&
9604 TLI
.isOperationLegalOrCustom(ISD::ADD
, VT
)) {
9605 SDValue Zext
= DAG
.getZExtOrTrunc(N0
.getOperand(0).getOperand(0), DL
, VT
);
9606 return DAG
.getNode(ISD::ADD
, DL
, VT
, Zext
, DAG
.getAllOnesConstant(DL
, VT
));
9612 // isTruncateOf - If N is a truncate of some other value, return true, record
9613 // the value being truncated in Op and which of Op's bits are zero/one in Known.
9614 // This function computes KnownBits to avoid a duplicated call to
9615 // computeKnownBits in the caller.
9616 static bool isTruncateOf(SelectionDAG
&DAG
, SDValue N
, SDValue
&Op
,
9618 if (N
->getOpcode() == ISD::TRUNCATE
) {
9619 Op
= N
->getOperand(0);
9620 Known
= DAG
.computeKnownBits(Op
);
9624 if (N
.getOpcode() != ISD::SETCC
||
9625 N
.getValueType().getScalarType() != MVT::i1
||
9626 cast
<CondCodeSDNode
>(N
.getOperand(2))->get() != ISD::SETNE
)
9629 SDValue Op0
= N
->getOperand(0);
9630 SDValue Op1
= N
->getOperand(1);
9631 assert(Op0
.getValueType() == Op1
.getValueType());
9633 if (isNullOrNullSplat(Op0
))
9635 else if (isNullOrNullSplat(Op1
))
9640 Known
= DAG
.computeKnownBits(Op
);
9642 return (Known
.Zero
| 1).isAllOnesValue();
9645 SDValue
DAGCombiner::visitZERO_EXTEND(SDNode
*N
) {
9646 SDValue N0
= N
->getOperand(0);
9647 EVT VT
= N
->getValueType(0);
9649 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
9652 // fold (zext (zext x)) -> (zext x)
9653 // fold (zext (aext x)) -> (zext x)
9654 if (N0
.getOpcode() == ISD::ZERO_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
)
9655 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), VT
,
9658 // fold (zext (truncate x)) -> (zext x) or
9659 // (zext (truncate x)) -> (truncate x)
9660 // This is valid when the truncated bits of x are already zero.
9663 if (isTruncateOf(DAG
, N0
, Op
, Known
)) {
9664 APInt TruncatedBits
=
9665 (Op
.getScalarValueSizeInBits() == N0
.getScalarValueSizeInBits()) ?
9666 APInt(Op
.getScalarValueSizeInBits(), 0) :
9667 APInt::getBitsSet(Op
.getScalarValueSizeInBits(),
9668 N0
.getScalarValueSizeInBits(),
9669 std::min(Op
.getScalarValueSizeInBits(),
9670 VT
.getScalarSizeInBits()));
9671 if (TruncatedBits
.isSubsetOf(Known
.Zero
))
9672 return DAG
.getZExtOrTrunc(Op
, SDLoc(N
), VT
);
9675 // fold (zext (truncate x)) -> (and x, mask)
9676 if (N0
.getOpcode() == ISD::TRUNCATE
) {
9677 // fold (zext (truncate (load x))) -> (zext (smaller load x))
9678 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
9679 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
9680 SDNode
*oye
= N0
.getOperand(0).getNode();
9681 if (NarrowLoad
.getNode() != N0
.getNode()) {
9682 CombineTo(N0
.getNode(), NarrowLoad
);
9683 // CombineTo deleted the truncate, if needed, but not what's under it.
9686 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9689 EVT SrcVT
= N0
.getOperand(0).getValueType();
9690 EVT MinVT
= N0
.getValueType();
9692 // Try to mask before the extension to avoid having to generate a larger mask,
9693 // possibly over several sub-vectors.
9694 if (SrcVT
.bitsLT(VT
) && VT
.isVector()) {
9695 if (!LegalOperations
|| (TLI
.isOperationLegal(ISD::AND
, SrcVT
) &&
9696 TLI
.isOperationLegal(ISD::ZERO_EXTEND
, VT
))) {
9697 SDValue Op
= N0
.getOperand(0);
9698 Op
= DAG
.getZeroExtendInReg(Op
, SDLoc(N
), MinVT
.getScalarType());
9699 AddToWorklist(Op
.getNode());
9700 SDValue ZExtOrTrunc
= DAG
.getZExtOrTrunc(Op
, SDLoc(N
), VT
);
9701 // Transfer the debug info; the new node is equivalent to N0.
9702 DAG
.transferDbgValues(N0
, ZExtOrTrunc
);
9707 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::AND
, VT
)) {
9708 SDValue Op
= DAG
.getAnyExtOrTrunc(N0
.getOperand(0), SDLoc(N
), VT
);
9709 AddToWorklist(Op
.getNode());
9710 SDValue And
= DAG
.getZeroExtendInReg(Op
, SDLoc(N
), MinVT
.getScalarType());
9711 // We may safely transfer the debug info describing the truncate node over
9712 // to the equivalent and operation.
9713 DAG
.transferDbgValues(N0
, And
);
9718 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
9719 // if either of the casts is not free.
9720 if (N0
.getOpcode() == ISD::AND
&&
9721 N0
.getOperand(0).getOpcode() == ISD::TRUNCATE
&&
9722 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9723 (!TLI
.isTruncateFree(N0
.getOperand(0).getOperand(0).getValueType(),
9724 N0
.getValueType()) ||
9725 !TLI
.isZExtFree(N0
.getValueType(), VT
))) {
9726 SDValue X
= N0
.getOperand(0).getOperand(0);
9727 X
= DAG
.getAnyExtOrTrunc(X
, SDLoc(X
), VT
);
9728 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9729 Mask
= Mask
.zext(VT
.getSizeInBits());
9731 return DAG
.getNode(ISD::AND
, DL
, VT
,
9732 X
, DAG
.getConstant(Mask
, DL
, VT
));
9735 // Try to simplify (zext (load x)).
9736 if (SDValue foldedExt
=
9737 tryToFoldExtOfLoad(DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
,
9738 ISD::ZEXTLOAD
, ISD::ZERO_EXTEND
))
9741 // fold (zext (load x)) to multiple smaller zextloads.
9742 // Only on illegal but splittable vectors.
9743 if (SDValue ExtLoad
= CombineExtLoad(N
))
9746 // fold (zext (and/or/xor (load x), cst)) ->
9747 // (and/or/xor (zextload x), (zext cst))
9748 // Unless (and (load x) cst) will match as a zextload already and has
9749 // additional users.
9750 if ((N0
.getOpcode() == ISD::AND
|| N0
.getOpcode() == ISD::OR
||
9751 N0
.getOpcode() == ISD::XOR
) &&
9752 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
9753 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9754 (!LegalOperations
&& TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
9755 LoadSDNode
*LN00
= cast
<LoadSDNode
>(N0
.getOperand(0));
9756 EVT MemVT
= LN00
->getMemoryVT();
9757 if (TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, VT
, MemVT
) &&
9758 LN00
->getExtensionType() != ISD::SEXTLOAD
&& LN00
->isUnindexed()) {
9759 bool DoXform
= true;
9760 SmallVector
<SDNode
*, 4> SetCCs
;
9761 if (!N0
.hasOneUse()) {
9762 if (N0
.getOpcode() == ISD::AND
) {
9763 auto *AndC
= cast
<ConstantSDNode
>(N0
.getOperand(1));
9764 EVT LoadResultTy
= AndC
->getValueType(0);
9766 if (isAndLoadExtLoad(AndC
, LN00
, LoadResultTy
, ExtVT
))
9771 DoXform
= ExtendUsesToFormExtLoad(VT
, N0
.getNode(), N0
.getOperand(0),
9772 ISD::ZERO_EXTEND
, SetCCs
, TLI
);
9774 SDValue ExtLoad
= DAG
.getExtLoad(ISD::ZEXTLOAD
, SDLoc(LN00
), VT
,
9775 LN00
->getChain(), LN00
->getBasePtr(),
9776 LN00
->getMemoryVT(),
9777 LN00
->getMemOperand());
9778 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9779 Mask
= Mask
.zext(VT
.getSizeInBits());
9781 SDValue And
= DAG
.getNode(N0
.getOpcode(), DL
, VT
,
9782 ExtLoad
, DAG
.getConstant(Mask
, DL
, VT
));
9783 ExtendSetCCUses(SetCCs
, N0
.getOperand(0), ExtLoad
, ISD::ZERO_EXTEND
);
9784 bool NoReplaceTruncAnd
= !N0
.hasOneUse();
9785 bool NoReplaceTrunc
= SDValue(LN00
, 0).hasOneUse();
9787 // If N0 has multiple uses, change other uses as well.
9788 if (NoReplaceTruncAnd
) {
9790 DAG
.getNode(ISD::TRUNCATE
, DL
, N0
.getValueType(), And
);
9791 CombineTo(N0
.getNode(), TruncAnd
);
9793 if (NoReplaceTrunc
) {
9794 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN00
, 1), ExtLoad
.getValue(1));
9796 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LN00
),
9797 LN00
->getValueType(0), ExtLoad
);
9798 CombineTo(LN00
, Trunc
, ExtLoad
.getValue(1));
9800 return SDValue(N
,0); // Return N so it doesn't get rechecked!
9805 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
9806 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
9807 if (SDValue ZExtLoad
= CombineZExtLogicopShiftLoad(N
))
9810 // Try to simplify (zext (zextload x)).
9811 if (SDValue foldedExt
= tryToFoldExtOfExtload(
9812 DAG
, *this, TLI
, VT
, LegalOperations
, N
, N0
, ISD::ZEXTLOAD
))
9815 if (SDValue V
= foldExtendedSignBitTest(N
, DAG
, LegalOperations
))
9818 if (N0
.getOpcode() == ISD::SETCC
) {
9819 // Only do this before legalize for now.
9820 if (!LegalOperations
&& VT
.isVector() &&
9821 N0
.getValueType().getVectorElementType() == MVT::i1
) {
9822 EVT N00VT
= N0
.getOperand(0).getValueType();
9823 if (getSetCCResultType(N00VT
) == N0
.getValueType())
9826 // We know that the # elements of the results is the same as the #
9827 // elements of the compare (and the # elements of the compare result for
9828 // that matter). Check to see that they are the same size. If so, we know
9829 // that the element size of the sext'd result matches the element size of
9830 // the compare operands.
9832 SDValue VecOnes
= DAG
.getConstant(1, DL
, VT
);
9833 if (VT
.getSizeInBits() == N00VT
.getSizeInBits()) {
9834 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
9835 SDValue VSetCC
= DAG
.getNode(ISD::SETCC
, DL
, VT
, N0
.getOperand(0),
9836 N0
.getOperand(1), N0
.getOperand(2));
9837 return DAG
.getNode(ISD::AND
, DL
, VT
, VSetCC
, VecOnes
);
9840 // If the desired elements are smaller or larger than the source
9841 // elements we can use a matching integer vector type and then
9842 // truncate/sign extend.
9843 EVT MatchingVectorType
= N00VT
.changeVectorElementTypeToInteger();
9845 DAG
.getNode(ISD::SETCC
, DL
, MatchingVectorType
, N0
.getOperand(0),
9846 N0
.getOperand(1), N0
.getOperand(2));
9847 return DAG
.getNode(ISD::AND
, DL
, VT
, DAG
.getSExtOrTrunc(VsetCC
, DL
, VT
),
9851 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
9853 if (SDValue SCC
= SimplifySelectCC(
9854 DL
, N0
.getOperand(0), N0
.getOperand(1), DAG
.getConstant(1, DL
, VT
),
9855 DAG
.getConstant(0, DL
, VT
),
9856 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get(), true))
9860 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
9861 if ((N0
.getOpcode() == ISD::SHL
|| N0
.getOpcode() == ISD::SRL
) &&
9862 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
9863 N0
.getOperand(0).getOpcode() == ISD::ZERO_EXTEND
&&
9865 SDValue ShAmt
= N0
.getOperand(1);
9866 if (N0
.getOpcode() == ISD::SHL
) {
9867 SDValue InnerZExt
= N0
.getOperand(0);
9868 // If the original shl may be shifting out bits, do not perform this
9870 unsigned KnownZeroBits
= InnerZExt
.getValueSizeInBits() -
9871 InnerZExt
.getOperand(0).getValueSizeInBits();
9872 if (cast
<ConstantSDNode
>(ShAmt
)->getAPIntValue().ugt(KnownZeroBits
))
9878 // Ensure that the shift amount is wide enough for the shifted value.
9879 if (VT
.getSizeInBits() >= 256)
9880 ShAmt
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i32
, ShAmt
);
9882 return DAG
.getNode(N0
.getOpcode(), DL
, VT
,
9883 DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, N0
.getOperand(0)),
9887 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
9893 SDValue
DAGCombiner::visitANY_EXTEND(SDNode
*N
) {
9894 SDValue N0
= N
->getOperand(0);
9895 EVT VT
= N
->getValueType(0);
9897 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
9900 // fold (aext (aext x)) -> (aext x)
9901 // fold (aext (zext x)) -> (zext x)
9902 // fold (aext (sext x)) -> (sext x)
9903 if (N0
.getOpcode() == ISD::ANY_EXTEND
||
9904 N0
.getOpcode() == ISD::ZERO_EXTEND
||
9905 N0
.getOpcode() == ISD::SIGN_EXTEND
)
9906 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, N0
.getOperand(0));
9908 // fold (aext (truncate (load x))) -> (aext (smaller load x))
9909 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
9910 if (N0
.getOpcode() == ISD::TRUNCATE
) {
9911 if (SDValue NarrowLoad
= ReduceLoadWidth(N0
.getNode())) {
9912 SDNode
*oye
= N0
.getOperand(0).getNode();
9913 if (NarrowLoad
.getNode() != N0
.getNode()) {
9914 CombineTo(N0
.getNode(), NarrowLoad
);
9915 // CombineTo deleted the truncate, if needed, but not what's under it.
9918 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9922 // fold (aext (truncate x))
9923 if (N0
.getOpcode() == ISD::TRUNCATE
)
9924 return DAG
.getAnyExtOrTrunc(N0
.getOperand(0), SDLoc(N
), VT
);
9926 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
9927 // if the trunc is not free.
9928 if (N0
.getOpcode() == ISD::AND
&&
9929 N0
.getOperand(0).getOpcode() == ISD::TRUNCATE
&&
9930 N0
.getOperand(1).getOpcode() == ISD::Constant
&&
9931 !TLI
.isTruncateFree(N0
.getOperand(0).getOperand(0).getValueType(),
9932 N0
.getValueType())) {
9934 SDValue X
= N0
.getOperand(0).getOperand(0);
9935 X
= DAG
.getAnyExtOrTrunc(X
, DL
, VT
);
9936 APInt Mask
= cast
<ConstantSDNode
>(N0
.getOperand(1))->getAPIntValue();
9937 Mask
= Mask
.zext(VT
.getSizeInBits());
9938 return DAG
.getNode(ISD::AND
, DL
, VT
,
9939 X
, DAG
.getConstant(Mask
, DL
, VT
));
9942 // fold (aext (load x)) -> (aext (truncate (extload x)))
9943 // None of the supported targets knows how to perform load and any_ext
9944 // on vectors in one instruction. We only perform this transformation on
9946 if (ISD::isNON_EXTLoad(N0
.getNode()) && !VT
.isVector() &&
9947 ISD::isUNINDEXEDLoad(N0
.getNode()) &&
9948 TLI
.isLoadExtLegal(ISD::EXTLOAD
, VT
, N0
.getValueType())) {
9949 bool DoXform
= true;
9950 SmallVector
<SDNode
*, 4> SetCCs
;
9951 if (!N0
.hasOneUse())
9952 DoXform
= ExtendUsesToFormExtLoad(VT
, N
, N0
, ISD::ANY_EXTEND
, SetCCs
,
9955 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9956 SDValue ExtLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, SDLoc(N
), VT
,
9958 LN0
->getBasePtr(), N0
.getValueType(),
9959 LN0
->getMemOperand());
9960 ExtendSetCCUses(SetCCs
, N0
, ExtLoad
, ISD::ANY_EXTEND
);
9961 // If the load value is used only by N, replace it via CombineTo N.
9962 bool NoReplaceTrunc
= N0
.hasOneUse();
9963 CombineTo(N
, ExtLoad
);
9964 if (NoReplaceTrunc
) {
9965 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9966 recursivelyDeleteUnusedNodes(LN0
);
9968 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N0
),
9969 N0
.getValueType(), ExtLoad
);
9970 CombineTo(LN0
, Trunc
, ExtLoad
.getValue(1));
9972 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9976 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
9977 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
9978 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
9979 if (N0
.getOpcode() == ISD::LOAD
&& !ISD::isNON_EXTLoad(N0
.getNode()) &&
9980 ISD::isUNINDEXEDLoad(N0
.getNode()) && N0
.hasOneUse()) {
9981 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9982 ISD::LoadExtType ExtType
= LN0
->getExtensionType();
9983 EVT MemVT
= LN0
->getMemoryVT();
9984 if (!LegalOperations
|| TLI
.isLoadExtLegal(ExtType
, VT
, MemVT
)) {
9985 SDValue ExtLoad
= DAG
.getExtLoad(ExtType
, SDLoc(N
),
9986 VT
, LN0
->getChain(), LN0
->getBasePtr(),
9987 MemVT
, LN0
->getMemOperand());
9988 CombineTo(N
, ExtLoad
);
9989 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), ExtLoad
.getValue(1));
9990 recursivelyDeleteUnusedNodes(LN0
);
9991 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
9995 if (N0
.getOpcode() == ISD::SETCC
) {
9997 // aext(setcc) -> vsetcc
9998 // aext(setcc) -> truncate(vsetcc)
9999 // aext(setcc) -> aext(vsetcc)
10000 // Only do this before legalize for now.
10001 if (VT
.isVector() && !LegalOperations
) {
10002 EVT N00VT
= N0
.getOperand(0).getValueType();
10003 if (getSetCCResultType(N00VT
) == N0
.getValueType())
10006 // We know that the # elements of the results is the same as the
10007 // # elements of the compare (and the # elements of the compare result
10008 // for that matter). Check to see that they are the same size. If so,
10009 // we know that the element size of the sext'd result matches the
10010 // element size of the compare operands.
10011 if (VT
.getSizeInBits() == N00VT
.getSizeInBits())
10012 return DAG
.getSetCC(SDLoc(N
), VT
, N0
.getOperand(0),
10014 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
10016 // If the desired elements are smaller or larger than the source
10017 // elements we can use a matching integer vector type and then
10018 // truncate/any extend
10019 EVT MatchingVectorType
= N00VT
.changeVectorElementTypeToInteger();
10021 DAG
.getSetCC(SDLoc(N
), MatchingVectorType
, N0
.getOperand(0),
10023 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
10024 return DAG
.getAnyExtOrTrunc(VsetCC
, SDLoc(N
), VT
);
10027 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
10029 if (SDValue SCC
= SimplifySelectCC(
10030 DL
, N0
.getOperand(0), N0
.getOperand(1), DAG
.getConstant(1, DL
, VT
),
10031 DAG
.getConstant(0, DL
, VT
),
10032 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get(), true))
10039 SDValue
DAGCombiner::visitAssertExt(SDNode
*N
) {
10040 unsigned Opcode
= N
->getOpcode();
10041 SDValue N0
= N
->getOperand(0);
10042 SDValue N1
= N
->getOperand(1);
10043 EVT AssertVT
= cast
<VTSDNode
>(N1
)->getVT();
10045 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
10046 if (N0
.getOpcode() == Opcode
&&
10047 AssertVT
== cast
<VTSDNode
>(N0
.getOperand(1))->getVT())
10050 if (N0
.getOpcode() == ISD::TRUNCATE
&& N0
.hasOneUse() &&
10051 N0
.getOperand(0).getOpcode() == Opcode
) {
10052 // We have an assert, truncate, assert sandwich. Make one stronger assert
10053 // by asserting on the smallest asserted type to the larger source type.
10054 // This eliminates the later assert:
10055 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
10056 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
10057 SDValue BigA
= N0
.getOperand(0);
10058 EVT BigA_AssertVT
= cast
<VTSDNode
>(BigA
.getOperand(1))->getVT();
10059 assert(BigA_AssertVT
.bitsLE(N0
.getValueType()) &&
10060 "Asserting zero/sign-extended bits to a type larger than the "
10061 "truncated destination does not provide information");
10064 EVT MinAssertVT
= AssertVT
.bitsLT(BigA_AssertVT
) ? AssertVT
: BigA_AssertVT
;
10065 SDValue MinAssertVTVal
= DAG
.getValueType(MinAssertVT
);
10066 SDValue NewAssert
= DAG
.getNode(Opcode
, DL
, BigA
.getValueType(),
10067 BigA
.getOperand(0), MinAssertVTVal
);
10068 return DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), NewAssert
);
10071 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
10072 // than X. Just move the AssertZext in front of the truncate and drop the
10074 if (N0
.getOpcode() == ISD::TRUNCATE
&& N0
.hasOneUse() &&
10075 N0
.getOperand(0).getOpcode() == ISD::AssertSext
&&
10076 Opcode
== ISD::AssertZext
) {
10077 SDValue BigA
= N0
.getOperand(0);
10078 EVT BigA_AssertVT
= cast
<VTSDNode
>(BigA
.getOperand(1))->getVT();
10079 assert(BigA_AssertVT
.bitsLE(N0
.getValueType()) &&
10080 "Asserting zero/sign-extended bits to a type larger than the "
10081 "truncated destination does not provide information");
10083 if (AssertVT
.bitsLT(BigA_AssertVT
)) {
10085 SDValue NewAssert
= DAG
.getNode(Opcode
, DL
, BigA
.getValueType(),
10086 BigA
.getOperand(0), N1
);
10087 return DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), NewAssert
);
10094 /// If the result of a wider load is shifted to right of N bits and then
10095 /// truncated to a narrower type and where N is a multiple of number of bits of
10096 /// the narrower type, transform it to a narrower load from address + N / num of
10097 /// bits of new type. Also narrow the load if the result is masked with an AND
10098 /// to effectively produce a smaller type. If the result is to be extended, also
10099 /// fold the extension to form a extending load.
10100 SDValue
DAGCombiner::ReduceLoadWidth(SDNode
*N
) {
10101 unsigned Opc
= N
->getOpcode();
10103 ISD::LoadExtType ExtType
= ISD::NON_EXTLOAD
;
10104 SDValue N0
= N
->getOperand(0);
10105 EVT VT
= N
->getValueType(0);
10108 // This transformation isn't valid for vector loads.
10112 unsigned ShAmt
= 0;
10113 bool HasShiftedOffset
= false;
10114 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
10116 if (Opc
== ISD::SIGN_EXTEND_INREG
) {
10117 ExtType
= ISD::SEXTLOAD
;
10118 ExtVT
= cast
<VTSDNode
>(N
->getOperand(1))->getVT();
10119 } else if (Opc
== ISD::SRL
) {
10120 // Another special-case: SRL is basically zero-extending a narrower value,
10121 // or it maybe shifting a higher subword, half or byte into the lowest
10123 ExtType
= ISD::ZEXTLOAD
;
10124 N0
= SDValue(N
, 0);
10126 auto *LN0
= dyn_cast
<LoadSDNode
>(N0
.getOperand(0));
10127 auto *N01
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1));
10131 uint64_t ShiftAmt
= N01
->getZExtValue();
10132 uint64_t MemoryWidth
= LN0
->getMemoryVT().getSizeInBits();
10133 if (LN0
->getExtensionType() != ISD::SEXTLOAD
&& MemoryWidth
> ShiftAmt
)
10134 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), MemoryWidth
- ShiftAmt
);
10136 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(),
10137 VT
.getSizeInBits() - ShiftAmt
);
10138 } else if (Opc
== ISD::AND
) {
10139 // An AND with a constant mask is the same as a truncate + zero-extend.
10140 auto AndC
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
10144 const APInt
&Mask
= AndC
->getAPIntValue();
10145 unsigned ActiveBits
= 0;
10146 if (Mask
.isMask()) {
10147 ActiveBits
= Mask
.countTrailingOnes();
10148 } else if (Mask
.isShiftedMask()) {
10149 ShAmt
= Mask
.countTrailingZeros();
10150 APInt ShiftedMask
= Mask
.lshr(ShAmt
);
10151 ActiveBits
= ShiftedMask
.countTrailingOnes();
10152 HasShiftedOffset
= true;
10156 ExtType
= ISD::ZEXTLOAD
;
10157 ExtVT
= EVT::getIntegerVT(*DAG
.getContext(), ActiveBits
);
10160 if (N0
.getOpcode() == ISD::SRL
&& N0
.hasOneUse()) {
10162 if (auto *ConstShift
= dyn_cast
<ConstantSDNode
>(SRL
.getOperand(1))) {
10163 ShAmt
= ConstShift
->getZExtValue();
10164 unsigned EVTBits
= ExtVT
.getSizeInBits();
10165 // Is the shift amount a multiple of size of VT?
10166 if ((ShAmt
& (EVTBits
-1)) == 0) {
10167 N0
= N0
.getOperand(0);
10168 // Is the load width a multiple of size of VT?
10169 if ((N0
.getValueSizeInBits() & (EVTBits
-1)) != 0)
10173 // At this point, we must have a load or else we can't do the transform.
10174 if (!isa
<LoadSDNode
>(N0
)) return SDValue();
10176 auto *LN0
= cast
<LoadSDNode
>(N0
);
10178 // Because a SRL must be assumed to *need* to zero-extend the high bits
10179 // (as opposed to anyext the high bits), we can't combine the zextload
10180 // lowering of SRL and an sextload.
10181 if (LN0
->getExtensionType() == ISD::SEXTLOAD
)
10184 // If the shift amount is larger than the input type then we're not
10185 // accessing any of the loaded bytes. If the load was a zextload/extload
10186 // then the result of the shift+trunc is zero/undef (handled elsewhere).
10187 if (ShAmt
>= LN0
->getMemoryVT().getSizeInBits())
10190 // If the SRL is only used by a masking AND, we may be able to adjust
10191 // the ExtVT to make the AND redundant.
10192 SDNode
*Mask
= *(SRL
->use_begin());
10193 if (Mask
->getOpcode() == ISD::AND
&&
10194 isa
<ConstantSDNode
>(Mask
->getOperand(1))) {
10195 const APInt
&ShiftMask
=
10196 cast
<ConstantSDNode
>(Mask
->getOperand(1))->getAPIntValue();
10197 if (ShiftMask
.isMask()) {
10198 EVT MaskedVT
= EVT::getIntegerVT(*DAG
.getContext(),
10199 ShiftMask
.countTrailingOnes());
10200 // If the mask is smaller, recompute the type.
10201 if ((ExtVT
.getSizeInBits() > MaskedVT
.getSizeInBits()) &&
10202 TLI
.isLoadExtLegal(ExtType
, N0
.getValueType(), MaskedVT
))
10209 // If the load is shifted left (and the result isn't shifted back right),
10210 // we can fold the truncate through the shift.
10211 unsigned ShLeftAmt
= 0;
10212 if (ShAmt
== 0 && N0
.getOpcode() == ISD::SHL
&& N0
.hasOneUse() &&
10213 ExtVT
== VT
&& TLI
.isNarrowingProfitable(N0
.getValueType(), VT
)) {
10214 if (ConstantSDNode
*N01
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
10215 ShLeftAmt
= N01
->getZExtValue();
10216 N0
= N0
.getOperand(0);
10220 // If we haven't found a load, we can't narrow it.
10221 if (!isa
<LoadSDNode
>(N0
))
10224 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10225 if (!isLegalNarrowLdSt(LN0
, ExtType
, ExtVT
, ShAmt
))
10228 auto AdjustBigEndianShift
= [&](unsigned ShAmt
) {
10229 unsigned LVTStoreBits
= LN0
->getMemoryVT().getStoreSizeInBits();
10230 unsigned EVTStoreBits
= ExtVT
.getStoreSizeInBits();
10231 return LVTStoreBits
- EVTStoreBits
- ShAmt
;
10234 // For big endian targets, we need to adjust the offset to the pointer to
10235 // load the correct bytes.
10236 if (DAG
.getDataLayout().isBigEndian())
10237 ShAmt
= AdjustBigEndianShift(ShAmt
);
10239 EVT PtrType
= N0
.getOperand(1).getValueType();
10240 uint64_t PtrOff
= ShAmt
/ 8;
10241 unsigned NewAlign
= MinAlign(LN0
->getAlignment(), PtrOff
);
10243 // The original load itself didn't wrap, so an offset within it doesn't.
10245 Flags
.setNoUnsignedWrap(true);
10246 SDValue NewPtr
= DAG
.getNode(ISD::ADD
, DL
,
10247 PtrType
, LN0
->getBasePtr(),
10248 DAG
.getConstant(PtrOff
, DL
, PtrType
),
10250 AddToWorklist(NewPtr
.getNode());
10253 if (ExtType
== ISD::NON_EXTLOAD
)
10254 Load
= DAG
.getLoad(VT
, SDLoc(N0
), LN0
->getChain(), NewPtr
,
10255 LN0
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
,
10256 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
10258 Load
= DAG
.getExtLoad(ExtType
, SDLoc(N0
), VT
, LN0
->getChain(), NewPtr
,
10259 LN0
->getPointerInfo().getWithOffset(PtrOff
), ExtVT
,
10260 NewAlign
, LN0
->getMemOperand()->getFlags(),
10263 // Replace the old load's chain with the new load's chain.
10264 WorklistRemover
DeadNodes(*this);
10265 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), Load
.getValue(1));
10267 // Shift the result left, if we've swallowed a left shift.
10268 SDValue Result
= Load
;
10269 if (ShLeftAmt
!= 0) {
10270 EVT ShImmTy
= getShiftAmountTy(Result
.getValueType());
10271 if (!isUIntN(ShImmTy
.getSizeInBits(), ShLeftAmt
))
10273 // If the shift amount is as large as the result size (but, presumably,
10274 // no larger than the source) then the useful bits of the result are
10275 // zero; we can't simply return the shortened shift, because the result
10276 // of that operation is undefined.
10278 if (ShLeftAmt
>= VT
.getSizeInBits())
10279 Result
= DAG
.getConstant(0, DL
, VT
);
10281 Result
= DAG
.getNode(ISD::SHL
, DL
, VT
,
10282 Result
, DAG
.getConstant(ShLeftAmt
, DL
, ShImmTy
));
10285 if (HasShiftedOffset
) {
10286 // Recalculate the shift amount after it has been altered to calculate
10288 if (DAG
.getDataLayout().isBigEndian())
10289 ShAmt
= AdjustBigEndianShift(ShAmt
);
10291 // We're using a shifted mask, so the load now has an offset. This means
10292 // that data has been loaded into the lower bytes than it would have been
10293 // before, so we need to shl the loaded data into the correct position in the
10295 SDValue ShiftC
= DAG
.getConstant(ShAmt
, DL
, VT
);
10296 Result
= DAG
.getNode(ISD::SHL
, DL
, VT
, Result
, ShiftC
);
10297 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
);
10300 // Return the new loaded value.
10304 SDValue
DAGCombiner::visitSIGN_EXTEND_INREG(SDNode
*N
) {
10305 SDValue N0
= N
->getOperand(0);
10306 SDValue N1
= N
->getOperand(1);
10307 EVT VT
= N
->getValueType(0);
10308 EVT EVT
= cast
<VTSDNode
>(N1
)->getVT();
10309 unsigned VTBits
= VT
.getScalarSizeInBits();
10310 unsigned EVTBits
= EVT
.getScalarSizeInBits();
10313 return DAG
.getUNDEF(VT
);
10315 // fold (sext_in_reg c1) -> c1
10316 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
))
10317 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
, N0
, N1
);
10319 // If the input is already sign extended, just drop the extension.
10320 if (DAG
.ComputeNumSignBits(N0
) >= VTBits
-EVTBits
+1)
10323 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
10324 if (N0
.getOpcode() == ISD::SIGN_EXTEND_INREG
&&
10325 EVT
.bitsLT(cast
<VTSDNode
>(N0
.getOperand(1))->getVT()))
10326 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
10327 N0
.getOperand(0), N1
);
10329 // fold (sext_in_reg (sext x)) -> (sext x)
10330 // fold (sext_in_reg (aext x)) -> (sext x)
10331 // if x is small enough or if we know that x has more than 1 sign bit and the
10332 // sign_extend_inreg is extending from one of them.
10333 if (N0
.getOpcode() == ISD::SIGN_EXTEND
|| N0
.getOpcode() == ISD::ANY_EXTEND
) {
10334 SDValue N00
= N0
.getOperand(0);
10335 unsigned N00Bits
= N00
.getScalarValueSizeInBits();
10336 if ((N00Bits
<= EVTBits
||
10337 (N00Bits
- DAG
.ComputeNumSignBits(N00
)) < EVTBits
) &&
10338 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND
, VT
)))
10339 return DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, N00
);
10342 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
10343 if ((N0
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
||
10344 N0
.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG
||
10345 N0
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
) &&
10346 N0
.getOperand(0).getScalarValueSizeInBits() == EVTBits
) {
10347 if (!LegalOperations
||
10348 TLI
.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG
, VT
))
10349 return DAG
.getNode(ISD::SIGN_EXTEND_VECTOR_INREG
, SDLoc(N
), VT
,
10353 // fold (sext_in_reg (zext x)) -> (sext x)
10354 // iff we are extending the source sign bit.
10355 if (N0
.getOpcode() == ISD::ZERO_EXTEND
) {
10356 SDValue N00
= N0
.getOperand(0);
10357 if (N00
.getScalarValueSizeInBits() == EVTBits
&&
10358 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SIGN_EXTEND
, VT
)))
10359 return DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, N00
, N1
);
10362 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
10363 if (DAG
.MaskedValueIsZero(N0
, APInt::getOneBitSet(VTBits
, EVTBits
- 1)))
10364 return DAG
.getZeroExtendInReg(N0
, SDLoc(N
), EVT
.getScalarType());
10366 // fold operands of sext_in_reg based on knowledge that the top bits are not
10368 if (SimplifyDemandedBits(SDValue(N
, 0)))
10369 return SDValue(N
, 0);
10371 // fold (sext_in_reg (load x)) -> (smaller sextload x)
10372 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
10373 if (SDValue NarrowLoad
= ReduceLoadWidth(N
))
10376 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
10377 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
10378 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
10379 if (N0
.getOpcode() == ISD::SRL
) {
10380 if (auto *ShAmt
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1)))
10381 if (ShAmt
->getAPIntValue().ule(VTBits
- EVTBits
)) {
10382 // We can turn this into an SRA iff the input to the SRL is already sign
10383 // extended enough.
10384 unsigned InSignBits
= DAG
.ComputeNumSignBits(N0
.getOperand(0));
10385 if (((VTBits
- EVTBits
) - ShAmt
->getZExtValue()) < InSignBits
)
10386 return DAG
.getNode(ISD::SRA
, SDLoc(N
), VT
, N0
.getOperand(0),
10391 // fold (sext_inreg (extload x)) -> (sextload x)
10392 // If sextload is not supported by target, we can only do the combine when
10393 // load has one use. Doing otherwise can block folding the extload with other
10394 // extends that the target does support.
10395 if (ISD::isEXTLoad(N0
.getNode()) &&
10396 ISD::isUNINDEXEDLoad(N0
.getNode()) &&
10397 EVT
== cast
<LoadSDNode
>(N0
)->getMemoryVT() &&
10398 ((!LegalOperations
&& !cast
<LoadSDNode
>(N0
)->isVolatile() &&
10400 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, EVT
))) {
10401 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10402 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(N
), VT
,
10404 LN0
->getBasePtr(), EVT
,
10405 LN0
->getMemOperand());
10406 CombineTo(N
, ExtLoad
);
10407 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
10408 AddToWorklist(ExtLoad
.getNode());
10409 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10411 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
10412 if (ISD::isZEXTLoad(N0
.getNode()) && ISD::isUNINDEXEDLoad(N0
.getNode()) &&
10414 EVT
== cast
<LoadSDNode
>(N0
)->getMemoryVT() &&
10415 ((!LegalOperations
&& !cast
<LoadSDNode
>(N0
)->isVolatile()) ||
10416 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, VT
, EVT
))) {
10417 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10418 SDValue ExtLoad
= DAG
.getExtLoad(ISD::SEXTLOAD
, SDLoc(N
), VT
,
10420 LN0
->getBasePtr(), EVT
,
10421 LN0
->getMemOperand());
10422 CombineTo(N
, ExtLoad
);
10423 CombineTo(N0
.getNode(), ExtLoad
, ExtLoad
.getValue(1));
10424 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
10427 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
10428 if (EVTBits
<= 16 && N0
.getOpcode() == ISD::OR
) {
10429 if (SDValue BSwap
= MatchBSwapHWordLow(N0
.getNode(), N0
.getOperand(0),
10430 N0
.getOperand(1), false))
10431 return DAG
.getNode(ISD::SIGN_EXTEND_INREG
, SDLoc(N
), VT
,
10438 SDValue
DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode
*N
) {
10439 SDValue N0
= N
->getOperand(0);
10440 EVT VT
= N
->getValueType(0);
10443 return DAG
.getUNDEF(VT
);
10445 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
10448 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
10449 return SDValue(N
, 0);
10454 SDValue
DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode
*N
) {
10455 SDValue N0
= N
->getOperand(0);
10456 EVT VT
= N
->getValueType(0);
10459 return DAG
.getUNDEF(VT
);
10461 if (SDValue Res
= tryToFoldExtendOfConstant(N
, TLI
, DAG
, LegalTypes
))
10464 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
10465 return SDValue(N
, 0);
10470 SDValue
DAGCombiner::visitTRUNCATE(SDNode
*N
) {
10471 SDValue N0
= N
->getOperand(0);
10472 EVT VT
= N
->getValueType(0);
10473 EVT SrcVT
= N0
.getValueType();
10474 bool isLE
= DAG
.getDataLayout().isLittleEndian();
10480 // fold (truncate (truncate x)) -> (truncate x)
10481 if (N0
.getOpcode() == ISD::TRUNCATE
)
10482 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
.getOperand(0));
10484 // fold (truncate c1) -> c1
10485 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
)) {
10486 SDValue C
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
);
10487 if (C
.getNode() != N
)
10491 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
10492 if (N0
.getOpcode() == ISD::ZERO_EXTEND
||
10493 N0
.getOpcode() == ISD::SIGN_EXTEND
||
10494 N0
.getOpcode() == ISD::ANY_EXTEND
) {
10495 // if the source is smaller than the dest, we still need an extend.
10496 if (N0
.getOperand(0).getValueType().bitsLT(VT
))
10497 return DAG
.getNode(N0
.getOpcode(), SDLoc(N
), VT
, N0
.getOperand(0));
10498 // if the source is larger than the dest, than we just need the truncate.
10499 if (N0
.getOperand(0).getValueType().bitsGT(VT
))
10500 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, N0
.getOperand(0));
10501 // if the source and dest are the same type, we can drop both the extend
10502 // and the truncate.
10503 return N0
.getOperand(0);
10506 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
10507 if (N
->hasOneUse() && (N
->use_begin()->getOpcode() == ISD::ANY_EXTEND
))
10510 // Fold extract-and-trunc into a narrow extract. For example:
10511 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
10512 // i32 y = TRUNCATE(i64 x)
10514 // v16i8 b = BITCAST (v2i64 val)
10515 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
10517 // Note: We only run this optimization after type legalization (which often
10518 // creates this pattern) and before operation legalization after which
10519 // we need to be more careful about the vector instructions that we generate.
10520 if (N0
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
10521 LegalTypes
&& !LegalOperations
&& N0
->hasOneUse() && VT
!= MVT::i1
) {
10522 EVT VecTy
= N0
.getOperand(0).getValueType();
10523 EVT ExTy
= N0
.getValueType();
10524 EVT TrTy
= N
->getValueType(0);
10526 unsigned NumElem
= VecTy
.getVectorNumElements();
10527 unsigned SizeRatio
= ExTy
.getSizeInBits()/TrTy
.getSizeInBits();
10529 EVT NVT
= EVT::getVectorVT(*DAG
.getContext(), TrTy
, SizeRatio
* NumElem
);
10530 assert(NVT
.getSizeInBits() == VecTy
.getSizeInBits() && "Invalid Size");
10532 SDValue EltNo
= N0
->getOperand(1);
10533 if (isa
<ConstantSDNode
>(EltNo
) && isTypeLegal(NVT
)) {
10534 int Elt
= cast
<ConstantSDNode
>(EltNo
)->getZExtValue();
10535 EVT IndexTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
10536 int Index
= isLE
? (Elt
*SizeRatio
) : (Elt
*SizeRatio
+ (SizeRatio
-1));
10539 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, TrTy
,
10540 DAG
.getBitcast(NVT
, N0
.getOperand(0)),
10541 DAG
.getConstant(Index
, DL
, IndexTy
));
10545 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
10546 if (N0
.getOpcode() == ISD::SELECT
&& N0
.hasOneUse()) {
10547 if ((!LegalOperations
|| TLI
.isOperationLegal(ISD::SELECT
, SrcVT
)) &&
10548 TLI
.isTruncateFree(SrcVT
, VT
)) {
10550 SDValue Cond
= N0
.getOperand(0);
10551 SDValue TruncOp0
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(1));
10552 SDValue TruncOp1
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(2));
10553 return DAG
.getNode(ISD::SELECT
, SDLoc(N
), VT
, Cond
, TruncOp0
, TruncOp1
);
10557 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
10558 if (N0
.getOpcode() == ISD::SHL
&& N0
.hasOneUse() &&
10559 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SHL
, VT
)) &&
10560 TLI
.isTypeDesirableForOp(ISD::SHL
, VT
)) {
10561 SDValue Amt
= N0
.getOperand(1);
10562 KnownBits Known
= DAG
.computeKnownBits(Amt
);
10563 unsigned Size
= VT
.getScalarSizeInBits();
10564 if (Known
.getBitWidth() - Known
.countMinLeadingZeros() <= Log2_32(Size
)) {
10566 EVT AmtVT
= TLI
.getShiftAmountTy(VT
, DAG
.getDataLayout());
10568 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(0));
10569 if (AmtVT
!= Amt
.getValueType()) {
10570 Amt
= DAG
.getZExtOrTrunc(Amt
, SL
, AmtVT
);
10571 AddToWorklist(Amt
.getNode());
10573 return DAG
.getNode(ISD::SHL
, SL
, VT
, Trunc
, Amt
);
10577 // Attempt to pre-truncate BUILD_VECTOR sources.
10578 if (N0
.getOpcode() == ISD::BUILD_VECTOR
&& !LegalOperations
&&
10579 TLI
.isTruncateFree(SrcVT
.getScalarType(), VT
.getScalarType())) {
10581 EVT SVT
= VT
.getScalarType();
10582 SmallVector
<SDValue
, 8> TruncOps
;
10583 for (const SDValue
&Op
: N0
->op_values()) {
10584 SDValue TruncOp
= DAG
.getNode(ISD::TRUNCATE
, DL
, SVT
, Op
);
10585 TruncOps
.push_back(TruncOp
);
10587 return DAG
.getBuildVector(VT
, DL
, TruncOps
);
10590 // Fold a series of buildvector, bitcast, and truncate if possible.
10591 // For example fold
10592 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
10593 // (2xi32 (buildvector x, y)).
10594 if (Level
== AfterLegalizeVectorOps
&& VT
.isVector() &&
10595 N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse() &&
10596 N0
.getOperand(0).getOpcode() == ISD::BUILD_VECTOR
&&
10597 N0
.getOperand(0).hasOneUse()) {
10598 SDValue BuildVect
= N0
.getOperand(0);
10599 EVT BuildVectEltTy
= BuildVect
.getValueType().getVectorElementType();
10600 EVT TruncVecEltTy
= VT
.getVectorElementType();
10602 // Check that the element types match.
10603 if (BuildVectEltTy
== TruncVecEltTy
) {
10604 // Now we only need to compute the offset of the truncated elements.
10605 unsigned BuildVecNumElts
= BuildVect
.getNumOperands();
10606 unsigned TruncVecNumElts
= VT
.getVectorNumElements();
10607 unsigned TruncEltOffset
= BuildVecNumElts
/ TruncVecNumElts
;
10609 assert((BuildVecNumElts
% TruncVecNumElts
) == 0 &&
10610 "Invalid number of elements");
10612 SmallVector
<SDValue
, 8> Opnds
;
10613 for (unsigned i
= 0, e
= BuildVecNumElts
; i
!= e
; i
+= TruncEltOffset
)
10614 Opnds
.push_back(BuildVect
.getOperand(i
));
10616 return DAG
.getBuildVector(VT
, SDLoc(N
), Opnds
);
10620 // See if we can simplify the input to this truncate through knowledge that
10621 // only the low bits are being used.
10622 // For example "trunc (or (shl x, 8), y)" // -> trunc y
10623 // Currently we only perform this optimization on scalars because vectors
10624 // may have different active low bits.
10625 if (!VT
.isVector()) {
10627 APInt::getLowBitsSet(N0
.getValueSizeInBits(), VT
.getSizeInBits());
10628 if (SDValue Shorter
= DAG
.GetDemandedBits(N0
, Mask
))
10629 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, Shorter
);
10632 // fold (truncate (load x)) -> (smaller load x)
10633 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
10634 if (!LegalTypes
|| TLI
.isTypeDesirableForOp(N0
.getOpcode(), VT
)) {
10635 if (SDValue Reduced
= ReduceLoadWidth(N
))
10638 // Handle the case where the load remains an extending load even
10639 // after truncation.
10640 if (N0
.hasOneUse() && ISD::isUNINDEXEDLoad(N0
.getNode())) {
10641 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10642 if (!LN0
->isVolatile() &&
10643 LN0
->getMemoryVT().getStoreSizeInBits() < VT
.getSizeInBits()) {
10644 SDValue NewLoad
= DAG
.getExtLoad(LN0
->getExtensionType(), SDLoc(LN0
),
10645 VT
, LN0
->getChain(), LN0
->getBasePtr(),
10646 LN0
->getMemoryVT(),
10647 LN0
->getMemOperand());
10648 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), NewLoad
.getValue(1));
10654 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
10655 // where ... are all 'undef'.
10656 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&& !LegalTypes
) {
10657 SmallVector
<EVT
, 8> VTs
;
10660 unsigned NumDefs
= 0;
10662 for (unsigned i
= 0, e
= N0
.getNumOperands(); i
!= e
; ++i
) {
10663 SDValue X
= N0
.getOperand(i
);
10664 if (!X
.isUndef()) {
10669 // Stop if more than one members are non-undef.
10672 VTs
.push_back(EVT::getVectorVT(*DAG
.getContext(),
10673 VT
.getVectorElementType(),
10674 X
.getValueType().getVectorNumElements()));
10678 return DAG
.getUNDEF(VT
);
10680 if (NumDefs
== 1) {
10681 assert(V
.getNode() && "The single defined operand is empty!");
10682 SmallVector
<SDValue
, 8> Opnds
;
10683 for (unsigned i
= 0, e
= VTs
.size(); i
!= e
; ++i
) {
10685 Opnds
.push_back(DAG
.getUNDEF(VTs
[i
]));
10688 SDValue NV
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(V
), VTs
[i
], V
);
10689 AddToWorklist(NV
.getNode());
10690 Opnds
.push_back(NV
);
10692 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Opnds
);
10696 // Fold truncate of a bitcast of a vector to an extract of the low vector
10699 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
10700 if (N0
.getOpcode() == ISD::BITCAST
&& !VT
.isVector()) {
10701 SDValue VecSrc
= N0
.getOperand(0);
10702 EVT SrcVT
= VecSrc
.getValueType();
10703 if (SrcVT
.isVector() && SrcVT
.getScalarType() == VT
&&
10704 (!LegalOperations
||
10705 TLI
.isOperationLegal(ISD::EXTRACT_VECTOR_ELT
, SrcVT
))) {
10708 EVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
10709 unsigned Idx
= isLE
? 0 : SrcVT
.getVectorNumElements() - 1;
10710 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, VT
,
10711 VecSrc
, DAG
.getConstant(Idx
, SL
, IdxVT
));
10715 // Simplify the operands using demanded-bits information.
10716 if (!VT
.isVector() &&
10717 SimplifyDemandedBits(SDValue(N
, 0)))
10718 return SDValue(N
, 0);
10720 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
10721 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
10722 // When the adde's carry is not used.
10723 if ((N0
.getOpcode() == ISD::ADDE
|| N0
.getOpcode() == ISD::ADDCARRY
) &&
10724 N0
.hasOneUse() && !N0
.getNode()->hasAnyUseOfValue(1) &&
10725 // We only do for addcarry before legalize operation
10726 ((!LegalOperations
&& N0
.getOpcode() == ISD::ADDCARRY
) ||
10727 TLI
.isOperationLegal(N0
.getOpcode(), VT
))) {
10729 auto X
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(0));
10730 auto Y
= DAG
.getNode(ISD::TRUNCATE
, SL
, VT
, N0
.getOperand(1));
10731 auto VTs
= DAG
.getVTList(VT
, N0
->getValueType(1));
10732 return DAG
.getNode(N0
.getOpcode(), SL
, VTs
, X
, Y
, N0
.getOperand(2));
10735 // fold (truncate (extract_subvector(ext x))) ->
10736 // (extract_subvector x)
10737 // TODO: This can be generalized to cover cases where the truncate and extract
10738 // do not fully cancel each other out.
10739 if (!LegalTypes
&& N0
.getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
10740 SDValue N00
= N0
.getOperand(0);
10741 if (N00
.getOpcode() == ISD::SIGN_EXTEND
||
10742 N00
.getOpcode() == ISD::ZERO_EXTEND
||
10743 N00
.getOpcode() == ISD::ANY_EXTEND
) {
10744 if (N00
.getOperand(0)->getValueType(0).getVectorElementType() ==
10745 VT
.getVectorElementType())
10746 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N0
->getOperand(0)), VT
,
10747 N00
.getOperand(0), N0
.getOperand(1));
10751 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
10754 // Narrow a suitable binary operation with a non-opaque constant operand by
10755 // moving it ahead of the truncate. This is limited to pre-legalization
10756 // because targets may prefer a wider type during later combines and invert
10758 switch (N0
.getOpcode()) {
10765 if (!LegalOperations
&& N0
.hasOneUse() &&
10766 (isConstantOrConstantVector(N0
.getOperand(0), true) ||
10767 isConstantOrConstantVector(N0
.getOperand(1), true))) {
10768 // TODO: We already restricted this to pre-legalization, but for vectors
10769 // we are extra cautious to not create an unsupported operation.
10770 // Target-specific changes are likely needed to avoid regressions here.
10771 if (VT
.isScalarInteger() || TLI
.isOperationLegal(N0
.getOpcode(), VT
)) {
10773 SDValue NarrowL
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N0
.getOperand(0));
10774 SDValue NarrowR
= DAG
.getNode(ISD::TRUNCATE
, DL
, VT
, N0
.getOperand(1));
10775 return DAG
.getNode(N0
.getOpcode(), DL
, VT
, NarrowL
, NarrowR
);
10783 static SDNode
*getBuildPairElt(SDNode
*N
, unsigned i
) {
10784 SDValue Elt
= N
->getOperand(i
);
10785 if (Elt
.getOpcode() != ISD::MERGE_VALUES
)
10786 return Elt
.getNode();
10787 return Elt
.getOperand(Elt
.getResNo()).getNode();
10790 /// build_pair (load, load) -> load
10791 /// if load locations are consecutive.
10792 SDValue
DAGCombiner::CombineConsecutiveLoads(SDNode
*N
, EVT VT
) {
10793 assert(N
->getOpcode() == ISD::BUILD_PAIR
);
10795 LoadSDNode
*LD1
= dyn_cast
<LoadSDNode
>(getBuildPairElt(N
, 0));
10796 LoadSDNode
*LD2
= dyn_cast
<LoadSDNode
>(getBuildPairElt(N
, 1));
10798 // A BUILD_PAIR is always having the least significant part in elt 0 and the
10799 // most significant part in elt 1. So when combining into one large load, we
10800 // need to consider the endianness.
10801 if (DAG
.getDataLayout().isBigEndian())
10802 std::swap(LD1
, LD2
);
10804 if (!LD1
|| !LD2
|| !ISD::isNON_EXTLoad(LD1
) || !LD1
->hasOneUse() ||
10805 LD1
->getAddressSpace() != LD2
->getAddressSpace())
10807 EVT LD1VT
= LD1
->getValueType(0);
10808 unsigned LD1Bytes
= LD1VT
.getStoreSize();
10809 if (ISD::isNON_EXTLoad(LD2
) && LD2
->hasOneUse() &&
10810 DAG
.areNonVolatileConsecutiveLoads(LD2
, LD1
, LD1Bytes
, 1)) {
10811 unsigned Align
= LD1
->getAlignment();
10812 unsigned NewAlign
= DAG
.getDataLayout().getABITypeAlignment(
10813 VT
.getTypeForEVT(*DAG
.getContext()));
10815 if (NewAlign
<= Align
&&
10816 (!LegalOperations
|| TLI
.isOperationLegal(ISD::LOAD
, VT
)))
10817 return DAG
.getLoad(VT
, SDLoc(N
), LD1
->getChain(), LD1
->getBasePtr(),
10818 LD1
->getPointerInfo(), Align
);
10824 static unsigned getPPCf128HiElementSelector(const SelectionDAG
&DAG
) {
10825 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
10826 // and Lo parts; on big-endian machines it doesn't.
10827 return DAG
.getDataLayout().isBigEndian() ? 1 : 0;
10830 static SDValue
foldBitcastedFPLogic(SDNode
*N
, SelectionDAG
&DAG
,
10831 const TargetLowering
&TLI
) {
10832 // If this is not a bitcast to an FP type or if the target doesn't have
10833 // IEEE754-compliant FP logic, we're done.
10834 EVT VT
= N
->getValueType(0);
10835 if (!VT
.isFloatingPoint() || !TLI
.hasBitPreservingFPLogic(VT
))
10838 // TODO: Handle cases where the integer constant is a different scalar
10839 // bitwidth to the FP.
10840 SDValue N0
= N
->getOperand(0);
10841 EVT SourceVT
= N0
.getValueType();
10842 if (VT
.getScalarSizeInBits() != SourceVT
.getScalarSizeInBits())
10847 switch (N0
.getOpcode()) {
10849 FPOpcode
= ISD::FABS
;
10850 SignMask
= ~APInt::getSignMask(SourceVT
.getScalarSizeInBits());
10853 FPOpcode
= ISD::FNEG
;
10854 SignMask
= APInt::getSignMask(SourceVT
.getScalarSizeInBits());
10857 FPOpcode
= ISD::FABS
;
10858 SignMask
= APInt::getSignMask(SourceVT
.getScalarSizeInBits());
10864 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
10865 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
10866 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
10868 SDValue LogicOp0
= N0
.getOperand(0);
10869 ConstantSDNode
*LogicOp1
= isConstOrConstSplat(N0
.getOperand(1), true);
10870 if (LogicOp1
&& LogicOp1
->getAPIntValue() == SignMask
&&
10871 LogicOp0
.getOpcode() == ISD::BITCAST
&&
10872 LogicOp0
.getOperand(0).getValueType() == VT
) {
10873 SDValue FPOp
= DAG
.getNode(FPOpcode
, SDLoc(N
), VT
, LogicOp0
.getOperand(0));
10874 NumFPLogicOpsConv
++;
10875 if (N0
.getOpcode() == ISD::OR
)
10876 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, FPOp
);
10883 SDValue
DAGCombiner::visitBITCAST(SDNode
*N
) {
10884 SDValue N0
= N
->getOperand(0);
10885 EVT VT
= N
->getValueType(0);
10888 return DAG
.getUNDEF(VT
);
10890 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
10891 // Only do this before legalize types, unless both types are integer and the
10892 // scalar type is legal. Only do this before legalize ops, since the target
10893 // maybe depending on the bitcast.
10894 // First check to see if this is all constant.
10895 // TODO: Support FP bitcasts after legalize types.
10896 if (VT
.isVector() &&
10898 (!LegalOperations
&& VT
.isInteger() && N0
.getValueType().isInteger() &&
10899 TLI
.isTypeLegal(VT
.getVectorElementType()))) &&
10900 N0
.getOpcode() == ISD::BUILD_VECTOR
&& N0
.getNode()->hasOneUse() &&
10901 cast
<BuildVectorSDNode
>(N0
)->isConstant())
10902 return ConstantFoldBITCASTofBUILD_VECTOR(N0
.getNode(),
10903 VT
.getVectorElementType());
10905 // If the input is a constant, let getNode fold it.
10906 if (isa
<ConstantSDNode
>(N0
) || isa
<ConstantFPSDNode
>(N0
)) {
10907 // If we can't allow illegal operations, we need to check that this is just
10908 // a fp -> int or int -> conversion and that the resulting operation will
10910 if (!LegalOperations
||
10911 (isa
<ConstantSDNode
>(N0
) && VT
.isFloatingPoint() && !VT
.isVector() &&
10912 TLI
.isOperationLegal(ISD::ConstantFP
, VT
)) ||
10913 (isa
<ConstantFPSDNode
>(N0
) && VT
.isInteger() && !VT
.isVector() &&
10914 TLI
.isOperationLegal(ISD::Constant
, VT
))) {
10915 SDValue C
= DAG
.getBitcast(VT
, N0
);
10916 if (C
.getNode() != N
)
10921 // (conv (conv x, t1), t2) -> (conv x, t2)
10922 if (N0
.getOpcode() == ISD::BITCAST
)
10923 return DAG
.getBitcast(VT
, N0
.getOperand(0));
10925 // fold (conv (load x)) -> (load (conv*)x)
10926 // If the resultant load doesn't need a higher alignment than the original!
10927 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
10928 // Do not remove the cast if the types differ in endian layout.
10929 TLI
.hasBigEndianPartOrdering(N0
.getValueType(), DAG
.getDataLayout()) ==
10930 TLI
.hasBigEndianPartOrdering(VT
, DAG
.getDataLayout()) &&
10931 // If the load is volatile, we only want to change the load type if the
10932 // resulting load is legal. Otherwise we might increase the number of
10933 // memory accesses. We don't care if the original type was legal or not
10934 // as we assume software couldn't rely on the number of accesses of an
10936 ((!LegalOperations
&& !cast
<LoadSDNode
>(N0
)->isVolatile()) ||
10937 TLI
.isOperationLegal(ISD::LOAD
, VT
))) {
10938 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
10940 if (TLI
.isLoadBitCastBeneficial(N0
.getValueType(), VT
, DAG
,
10941 *LN0
->getMemOperand())) {
10943 DAG
.getLoad(VT
, SDLoc(N
), LN0
->getChain(), LN0
->getBasePtr(),
10944 LN0
->getPointerInfo(), LN0
->getAlignment(),
10945 LN0
->getMemOperand()->getFlags(), LN0
->getAAInfo());
10946 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), Load
.getValue(1));
10951 if (SDValue V
= foldBitcastedFPLogic(N
, DAG
, TLI
))
10954 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
10955 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
10958 // fold (bitcast (fneg x)) ->
10959 // flipbit = signbit
10960 // (xor (bitcast x) (build_pair flipbit, flipbit))
10962 // fold (bitcast (fabs x)) ->
10963 // flipbit = (and (extract_element (bitcast x), 0), signbit)
10964 // (xor (bitcast x) (build_pair flipbit, flipbit))
10965 // This often reduces constant pool loads.
10966 if (((N0
.getOpcode() == ISD::FNEG
&& !TLI
.isFNegFree(N0
.getValueType())) ||
10967 (N0
.getOpcode() == ISD::FABS
&& !TLI
.isFAbsFree(N0
.getValueType()))) &&
10968 N0
.getNode()->hasOneUse() && VT
.isInteger() &&
10969 !VT
.isVector() && !N0
.getValueType().isVector()) {
10970 SDValue NewConv
= DAG
.getBitcast(VT
, N0
.getOperand(0));
10971 AddToWorklist(NewConv
.getNode());
10974 if (N0
.getValueType() == MVT::ppcf128
&& !LegalTypes
) {
10975 assert(VT
.getSizeInBits() == 128);
10976 SDValue SignBit
= DAG
.getConstant(
10977 APInt::getSignMask(VT
.getSizeInBits() / 2), SDLoc(N0
), MVT::i64
);
10979 if (N0
.getOpcode() == ISD::FNEG
) {
10981 AddToWorklist(FlipBit
.getNode());
10983 assert(N0
.getOpcode() == ISD::FABS
);
10985 DAG
.getNode(ISD::EXTRACT_ELEMENT
, SDLoc(NewConv
), MVT::i64
, NewConv
,
10986 DAG
.getIntPtrConstant(getPPCf128HiElementSelector(DAG
),
10988 AddToWorklist(Hi
.getNode());
10989 FlipBit
= DAG
.getNode(ISD::AND
, SDLoc(N0
), MVT::i64
, Hi
, SignBit
);
10990 AddToWorklist(FlipBit
.getNode());
10993 DAG
.getNode(ISD::BUILD_PAIR
, SDLoc(N0
), VT
, FlipBit
, FlipBit
);
10994 AddToWorklist(FlipBits
.getNode());
10995 return DAG
.getNode(ISD::XOR
, DL
, VT
, NewConv
, FlipBits
);
10997 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits());
10998 if (N0
.getOpcode() == ISD::FNEG
)
10999 return DAG
.getNode(ISD::XOR
, DL
, VT
,
11000 NewConv
, DAG
.getConstant(SignBit
, DL
, VT
));
11001 assert(N0
.getOpcode() == ISD::FABS
);
11002 return DAG
.getNode(ISD::AND
, DL
, VT
,
11003 NewConv
, DAG
.getConstant(~SignBit
, DL
, VT
));
11006 // fold (bitconvert (fcopysign cst, x)) ->
11007 // (or (and (bitconvert x), sign), (and cst, (not sign)))
11008 // Note that we don't handle (copysign x, cst) because this can always be
11009 // folded to an fneg or fabs.
11012 // fold (bitcast (fcopysign cst, x)) ->
11013 // flipbit = (and (extract_element
11014 // (xor (bitcast cst), (bitcast x)), 0),
11016 // (xor (bitcast cst) (build_pair flipbit, flipbit))
11017 if (N0
.getOpcode() == ISD::FCOPYSIGN
&& N0
.getNode()->hasOneUse() &&
11018 isa
<ConstantFPSDNode
>(N0
.getOperand(0)) &&
11019 VT
.isInteger() && !VT
.isVector()) {
11020 unsigned OrigXWidth
= N0
.getOperand(1).getValueSizeInBits();
11021 EVT IntXVT
= EVT::getIntegerVT(*DAG
.getContext(), OrigXWidth
);
11022 if (isTypeLegal(IntXVT
)) {
11023 SDValue X
= DAG
.getBitcast(IntXVT
, N0
.getOperand(1));
11024 AddToWorklist(X
.getNode());
11026 // If X has a different width than the result/lhs, sext it or truncate it.
11027 unsigned VTWidth
= VT
.getSizeInBits();
11028 if (OrigXWidth
< VTWidth
) {
11029 X
= DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(N
), VT
, X
);
11030 AddToWorklist(X
.getNode());
11031 } else if (OrigXWidth
> VTWidth
) {
11032 // To get the sign bit in the right place, we have to shift it right
11033 // before truncating.
11035 X
= DAG
.getNode(ISD::SRL
, DL
,
11036 X
.getValueType(), X
,
11037 DAG
.getConstant(OrigXWidth
-VTWidth
, DL
,
11038 X
.getValueType()));
11039 AddToWorklist(X
.getNode());
11040 X
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(X
), VT
, X
);
11041 AddToWorklist(X
.getNode());
11044 if (N0
.getValueType() == MVT::ppcf128
&& !LegalTypes
) {
11045 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits() / 2);
11046 SDValue Cst
= DAG
.getBitcast(VT
, N0
.getOperand(0));
11047 AddToWorklist(Cst
.getNode());
11048 SDValue X
= DAG
.getBitcast(VT
, N0
.getOperand(1));
11049 AddToWorklist(X
.getNode());
11050 SDValue XorResult
= DAG
.getNode(ISD::XOR
, SDLoc(N0
), VT
, Cst
, X
);
11051 AddToWorklist(XorResult
.getNode());
11052 SDValue XorResult64
= DAG
.getNode(
11053 ISD::EXTRACT_ELEMENT
, SDLoc(XorResult
), MVT::i64
, XorResult
,
11054 DAG
.getIntPtrConstant(getPPCf128HiElementSelector(DAG
),
11055 SDLoc(XorResult
)));
11056 AddToWorklist(XorResult64
.getNode());
11058 DAG
.getNode(ISD::AND
, SDLoc(XorResult64
), MVT::i64
, XorResult64
,
11059 DAG
.getConstant(SignBit
, SDLoc(XorResult64
), MVT::i64
));
11060 AddToWorklist(FlipBit
.getNode());
11062 DAG
.getNode(ISD::BUILD_PAIR
, SDLoc(N0
), VT
, FlipBit
, FlipBit
);
11063 AddToWorklist(FlipBits
.getNode());
11064 return DAG
.getNode(ISD::XOR
, SDLoc(N
), VT
, Cst
, FlipBits
);
11066 APInt SignBit
= APInt::getSignMask(VT
.getSizeInBits());
11067 X
= DAG
.getNode(ISD::AND
, SDLoc(X
), VT
,
11068 X
, DAG
.getConstant(SignBit
, SDLoc(X
), VT
));
11069 AddToWorklist(X
.getNode());
11071 SDValue Cst
= DAG
.getBitcast(VT
, N0
.getOperand(0));
11072 Cst
= DAG
.getNode(ISD::AND
, SDLoc(Cst
), VT
,
11073 Cst
, DAG
.getConstant(~SignBit
, SDLoc(Cst
), VT
));
11074 AddToWorklist(Cst
.getNode());
11076 return DAG
.getNode(ISD::OR
, SDLoc(N
), VT
, X
, Cst
);
11080 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
11081 if (N0
.getOpcode() == ISD::BUILD_PAIR
)
11082 if (SDValue CombineLD
= CombineConsecutiveLoads(N0
.getNode(), VT
))
11085 // Remove double bitcasts from shuffles - this is often a legacy of
11086 // XformToShuffleWithZero being used to combine bitmaskings (of
11087 // float vectors bitcast to integer vectors) into shuffles.
11088 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
11089 if (Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
) && VT
.isVector() &&
11090 N0
->getOpcode() == ISD::VECTOR_SHUFFLE
&& N0
.hasOneUse() &&
11091 VT
.getVectorNumElements() >= N0
.getValueType().getVectorNumElements() &&
11092 !(VT
.getVectorNumElements() % N0
.getValueType().getVectorNumElements())) {
11093 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N0
);
11095 // If operands are a bitcast, peek through if it casts the original VT.
11096 // If operands are a constant, just bitcast back to original VT.
11097 auto PeekThroughBitcast
= [&](SDValue Op
) {
11098 if (Op
.getOpcode() == ISD::BITCAST
&&
11099 Op
.getOperand(0).getValueType() == VT
)
11100 return SDValue(Op
.getOperand(0));
11101 if (Op
.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op
.getNode()) ||
11102 ISD::isBuildVectorOfConstantFPSDNodes(Op
.getNode()))
11103 return DAG
.getBitcast(VT
, Op
);
11107 // FIXME: If either input vector is bitcast, try to convert the shuffle to
11108 // the result type of this bitcast. This would eliminate at least one
11109 // bitcast. See the transform in InstCombine.
11110 SDValue SV0
= PeekThroughBitcast(N0
->getOperand(0));
11111 SDValue SV1
= PeekThroughBitcast(N0
->getOperand(1));
11116 VT
.getVectorNumElements() / N0
.getValueType().getVectorNumElements();
11117 SmallVector
<int, 8> NewMask
;
11118 for (int M
: SVN
->getMask())
11119 for (int i
= 0; i
!= MaskScale
; ++i
)
11120 NewMask
.push_back(M
< 0 ? -1 : M
* MaskScale
+ i
);
11122 bool LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, VT
);
11124 std::swap(SV0
, SV1
);
11125 ShuffleVectorSDNode::commuteMask(NewMask
);
11126 LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, VT
);
11130 return DAG
.getVectorShuffle(VT
, SDLoc(N
), SV0
, SV1
, NewMask
);
11136 SDValue
DAGCombiner::visitBUILD_PAIR(SDNode
*N
) {
11137 EVT VT
= N
->getValueType(0);
11138 return CombineConsecutiveLoads(N
, VT
);
11141 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
11142 /// operands. DstEltVT indicates the destination element value type.
11143 SDValue
DAGCombiner::
11144 ConstantFoldBITCASTofBUILD_VECTOR(SDNode
*BV
, EVT DstEltVT
) {
11145 EVT SrcEltVT
= BV
->getValueType(0).getVectorElementType();
11147 // If this is already the right type, we're done.
11148 if (SrcEltVT
== DstEltVT
) return SDValue(BV
, 0);
11150 unsigned SrcBitSize
= SrcEltVT
.getSizeInBits();
11151 unsigned DstBitSize
= DstEltVT
.getSizeInBits();
11153 // If this is a conversion of N elements of one type to N elements of another
11154 // type, convert each element. This handles FP<->INT cases.
11155 if (SrcBitSize
== DstBitSize
) {
11156 SmallVector
<SDValue
, 8> Ops
;
11157 for (SDValue Op
: BV
->op_values()) {
11158 // If the vector element type is not legal, the BUILD_VECTOR operands
11159 // are promoted and implicitly truncated. Make that explicit here.
11160 if (Op
.getValueType() != SrcEltVT
)
11161 Op
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(BV
), SrcEltVT
, Op
);
11162 Ops
.push_back(DAG
.getBitcast(DstEltVT
, Op
));
11163 AddToWorklist(Ops
.back().getNode());
11165 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
,
11166 BV
->getValueType(0).getVectorNumElements());
11167 return DAG
.getBuildVector(VT
, SDLoc(BV
), Ops
);
11170 // Otherwise, we're growing or shrinking the elements. To avoid having to
11171 // handle annoying details of growing/shrinking FP values, we convert them to
11173 if (SrcEltVT
.isFloatingPoint()) {
11174 // Convert the input float vector to a int vector where the elements are the
11176 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), SrcEltVT
.getSizeInBits());
11177 BV
= ConstantFoldBITCASTofBUILD_VECTOR(BV
, IntVT
).getNode();
11181 // Now we know the input is an integer vector. If the output is a FP type,
11182 // convert to integer first, then to FP of the right size.
11183 if (DstEltVT
.isFloatingPoint()) {
11184 EVT TmpVT
= EVT::getIntegerVT(*DAG
.getContext(), DstEltVT
.getSizeInBits());
11185 SDNode
*Tmp
= ConstantFoldBITCASTofBUILD_VECTOR(BV
, TmpVT
).getNode();
11187 // Next, convert to FP elements of the same size.
11188 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp
, DstEltVT
);
11193 // Okay, we know the src/dst types are both integers of differing types.
11194 // Handling growing first.
11195 assert(SrcEltVT
.isInteger() && DstEltVT
.isInteger());
11196 if (SrcBitSize
< DstBitSize
) {
11197 unsigned NumInputsPerOutput
= DstBitSize
/SrcBitSize
;
11199 SmallVector
<SDValue
, 8> Ops
;
11200 for (unsigned i
= 0, e
= BV
->getNumOperands(); i
!= e
;
11201 i
+= NumInputsPerOutput
) {
11202 bool isLE
= DAG
.getDataLayout().isLittleEndian();
11203 APInt NewBits
= APInt(DstBitSize
, 0);
11204 bool EltIsUndef
= true;
11205 for (unsigned j
= 0; j
!= NumInputsPerOutput
; ++j
) {
11206 // Shift the previously computed bits over.
11207 NewBits
<<= SrcBitSize
;
11208 SDValue Op
= BV
->getOperand(i
+ (isLE
? (NumInputsPerOutput
-j
-1) : j
));
11209 if (Op
.isUndef()) continue;
11210 EltIsUndef
= false;
11212 NewBits
|= cast
<ConstantSDNode
>(Op
)->getAPIntValue().
11213 zextOrTrunc(SrcBitSize
).zext(DstBitSize
);
11217 Ops
.push_back(DAG
.getUNDEF(DstEltVT
));
11219 Ops
.push_back(DAG
.getConstant(NewBits
, DL
, DstEltVT
));
11222 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
, Ops
.size());
11223 return DAG
.getBuildVector(VT
, DL
, Ops
);
11226 // Finally, this must be the case where we are shrinking elements: each input
11227 // turns into multiple outputs.
11228 unsigned NumOutputsPerInput
= SrcBitSize
/DstBitSize
;
11229 EVT VT
= EVT::getVectorVT(*DAG
.getContext(), DstEltVT
,
11230 NumOutputsPerInput
*BV
->getNumOperands());
11231 SmallVector
<SDValue
, 8> Ops
;
11233 for (const SDValue
&Op
: BV
->op_values()) {
11234 if (Op
.isUndef()) {
11235 Ops
.append(NumOutputsPerInput
, DAG
.getUNDEF(DstEltVT
));
11239 APInt OpVal
= cast
<ConstantSDNode
>(Op
)->
11240 getAPIntValue().zextOrTrunc(SrcBitSize
);
11242 for (unsigned j
= 0; j
!= NumOutputsPerInput
; ++j
) {
11243 APInt ThisVal
= OpVal
.trunc(DstBitSize
);
11244 Ops
.push_back(DAG
.getConstant(ThisVal
, DL
, DstEltVT
));
11245 OpVal
.lshrInPlace(DstBitSize
);
11248 // For big endian targets, swap the order of the pieces of each element.
11249 if (DAG
.getDataLayout().isBigEndian())
11250 std::reverse(Ops
.end()-NumOutputsPerInput
, Ops
.end());
11253 return DAG
.getBuildVector(VT
, DL
, Ops
);
11256 static bool isContractable(SDNode
*N
) {
11257 SDNodeFlags F
= N
->getFlags();
11258 return F
.hasAllowContract() || F
.hasAllowReassociation();
11261 /// Try to perform FMA combining on a given FADD node.
11262 SDValue
DAGCombiner::visitFADDForFMACombine(SDNode
*N
) {
11263 SDValue N0
= N
->getOperand(0);
11264 SDValue N1
= N
->getOperand(1);
11265 EVT VT
= N
->getValueType(0);
11268 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11270 // Floating-point multiply-add with intermediate rounding.
11271 bool HasFMAD
= (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11273 // Floating-point multiply-add without intermediate rounding.
11275 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11276 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11278 // No valid opcode, do not combine.
11279 if (!HasFMAD
&& !HasFMA
)
11282 SDNodeFlags Flags
= N
->getFlags();
11283 bool CanFuse
= Options
.UnsafeFPMath
|| isContractable(N
);
11284 bool AllowFusionGlobally
= (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
11285 CanFuse
|| HasFMAD
);
11286 // If the addition is not contractable, do not combine.
11287 if (!AllowFusionGlobally
&& !isContractable(N
))
11290 const SelectionDAGTargetInfo
*STI
= DAG
.getSubtarget().getSelectionDAGInfo();
11291 if (STI
&& STI
->generateFMAsInMachineCombiner(OptLevel
))
11294 // Always prefer FMAD to FMA for precision.
11295 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11296 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11298 // Is the node an FMUL and contractable either due to global flags or
11300 auto isContractableFMUL
= [AllowFusionGlobally
](SDValue N
) {
11301 if (N
.getOpcode() != ISD::FMUL
)
11303 return AllowFusionGlobally
|| isContractable(N
.getNode());
11305 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
11306 // prefer to fold the multiply with fewer uses.
11307 if (Aggressive
&& isContractableFMUL(N0
) && isContractableFMUL(N1
)) {
11308 if (N0
.getNode()->use_size() > N1
.getNode()->use_size())
11312 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
11313 if (isContractableFMUL(N0
) && (Aggressive
|| N0
->hasOneUse())) {
11314 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11315 N0
.getOperand(0), N0
.getOperand(1), N1
, Flags
);
11318 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
11319 // Note: Commutes FADD operands.
11320 if (isContractableFMUL(N1
) && (Aggressive
|| N1
->hasOneUse())) {
11321 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11322 N1
.getOperand(0), N1
.getOperand(1), N0
, Flags
);
11325 // Look through FP_EXTEND nodes to do more combining.
11327 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
11328 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11329 SDValue N00
= N0
.getOperand(0);
11330 if (isContractableFMUL(N00
) &&
11331 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11332 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11333 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11334 N00
.getOperand(0)),
11335 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11336 N00
.getOperand(1)), N1
, Flags
);
11340 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
11341 // Note: Commutes FADD operands.
11342 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11343 SDValue N10
= N1
.getOperand(0);
11344 if (isContractableFMUL(N10
) &&
11345 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11346 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11347 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11348 N10
.getOperand(0)),
11349 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11350 N10
.getOperand(1)), N0
, Flags
);
11354 // More folding opportunities when target permits.
11356 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
11358 N0
.getOpcode() == PreferredFusedOpcode
&&
11359 N0
.getOperand(2).getOpcode() == ISD::FMUL
&&
11360 N0
->hasOneUse() && N0
.getOperand(2)->hasOneUse()) {
11361 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11362 N0
.getOperand(0), N0
.getOperand(1),
11363 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11364 N0
.getOperand(2).getOperand(0),
11365 N0
.getOperand(2).getOperand(1),
11366 N1
, Flags
), Flags
);
11369 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
11371 N1
->getOpcode() == PreferredFusedOpcode
&&
11372 N1
.getOperand(2).getOpcode() == ISD::FMUL
&&
11373 N1
->hasOneUse() && N1
.getOperand(2)->hasOneUse()) {
11374 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11375 N1
.getOperand(0), N1
.getOperand(1),
11376 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11377 N1
.getOperand(2).getOperand(0),
11378 N1
.getOperand(2).getOperand(1),
11379 N0
, Flags
), Flags
);
11383 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
11384 // -> (fma x, y, (fma (fpext u), (fpext v), z))
11385 auto FoldFAddFMAFPExtFMul
= [&] (
11386 SDValue X
, SDValue Y
, SDValue U
, SDValue V
, SDValue Z
,
11387 SDNodeFlags Flags
) {
11388 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
, Y
,
11389 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11390 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, U
),
11391 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, V
),
11394 if (N0
.getOpcode() == PreferredFusedOpcode
) {
11395 SDValue N02
= N0
.getOperand(2);
11396 if (N02
.getOpcode() == ISD::FP_EXTEND
) {
11397 SDValue N020
= N02
.getOperand(0);
11398 if (isContractableFMUL(N020
) &&
11399 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N020
.getValueType())) {
11400 return FoldFAddFMAFPExtFMul(N0
.getOperand(0), N0
.getOperand(1),
11401 N020
.getOperand(0), N020
.getOperand(1),
11407 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
11408 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
11409 // FIXME: This turns two single-precision and one double-precision
11410 // operation into two double-precision operations, which might not be
11411 // interesting for all targets, especially GPUs.
11412 auto FoldFAddFPExtFMAFMul
= [&] (
11413 SDValue X
, SDValue Y
, SDValue U
, SDValue V
, SDValue Z
,
11414 SDNodeFlags Flags
) {
11415 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11416 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, X
),
11417 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, Y
),
11418 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11419 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, U
),
11420 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, V
),
11423 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11424 SDValue N00
= N0
.getOperand(0);
11425 if (N00
.getOpcode() == PreferredFusedOpcode
) {
11426 SDValue N002
= N00
.getOperand(2);
11427 if (isContractableFMUL(N002
) &&
11428 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11429 return FoldFAddFPExtFMAFMul(N00
.getOperand(0), N00
.getOperand(1),
11430 N002
.getOperand(0), N002
.getOperand(1),
11436 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
11437 // -> (fma y, z, (fma (fpext u), (fpext v), x))
11438 if (N1
.getOpcode() == PreferredFusedOpcode
) {
11439 SDValue N12
= N1
.getOperand(2);
11440 if (N12
.getOpcode() == ISD::FP_EXTEND
) {
11441 SDValue N120
= N12
.getOperand(0);
11442 if (isContractableFMUL(N120
) &&
11443 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N120
.getValueType())) {
11444 return FoldFAddFMAFPExtFMul(N1
.getOperand(0), N1
.getOperand(1),
11445 N120
.getOperand(0), N120
.getOperand(1),
11451 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
11452 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
11453 // FIXME: This turns two single-precision and one double-precision
11454 // operation into two double-precision operations, which might not be
11455 // interesting for all targets, especially GPUs.
11456 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11457 SDValue N10
= N1
.getOperand(0);
11458 if (N10
.getOpcode() == PreferredFusedOpcode
) {
11459 SDValue N102
= N10
.getOperand(2);
11460 if (isContractableFMUL(N102
) &&
11461 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11462 return FoldFAddFPExtFMAFMul(N10
.getOperand(0), N10
.getOperand(1),
11463 N102
.getOperand(0), N102
.getOperand(1),
11473 /// Try to perform FMA combining on a given FSUB node.
11474 SDValue
DAGCombiner::visitFSUBForFMACombine(SDNode
*N
) {
11475 SDValue N0
= N
->getOperand(0);
11476 SDValue N1
= N
->getOperand(1);
11477 EVT VT
= N
->getValueType(0);
11480 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11481 // Floating-point multiply-add with intermediate rounding.
11482 bool HasFMAD
= (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11484 // Floating-point multiply-add without intermediate rounding.
11486 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11487 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11489 // No valid opcode, do not combine.
11490 if (!HasFMAD
&& !HasFMA
)
11493 const SDNodeFlags Flags
= N
->getFlags();
11494 bool CanFuse
= Options
.UnsafeFPMath
|| isContractable(N
);
11495 bool AllowFusionGlobally
= (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
11496 CanFuse
|| HasFMAD
);
11498 // If the subtraction is not contractable, do not combine.
11499 if (!AllowFusionGlobally
&& !isContractable(N
))
11502 const SelectionDAGTargetInfo
*STI
= DAG
.getSubtarget().getSelectionDAGInfo();
11503 if (STI
&& STI
->generateFMAsInMachineCombiner(OptLevel
))
11506 // Always prefer FMAD to FMA for precision.
11507 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11508 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11510 // Is the node an FMUL and contractable either due to global flags or
11512 auto isContractableFMUL
= [AllowFusionGlobally
](SDValue N
) {
11513 if (N
.getOpcode() != ISD::FMUL
)
11515 return AllowFusionGlobally
|| isContractable(N
.getNode());
11518 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
11519 if (isContractableFMUL(N0
) && (Aggressive
|| N0
->hasOneUse())) {
11520 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11521 N0
.getOperand(0), N0
.getOperand(1),
11522 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11525 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
11526 // Note: Commutes FSUB operands.
11527 if (isContractableFMUL(N1
) && (Aggressive
|| N1
->hasOneUse())) {
11528 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11529 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11531 N1
.getOperand(1), N0
, Flags
);
11534 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
11535 if (N0
.getOpcode() == ISD::FNEG
&& isContractableFMUL(N0
.getOperand(0)) &&
11536 (Aggressive
|| (N0
->hasOneUse() && N0
.getOperand(0).hasOneUse()))) {
11537 SDValue N00
= N0
.getOperand(0).getOperand(0);
11538 SDValue N01
= N0
.getOperand(0).getOperand(1);
11539 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11540 DAG
.getNode(ISD::FNEG
, SL
, VT
, N00
), N01
,
11541 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11544 // Look through FP_EXTEND nodes to do more combining.
11546 // fold (fsub (fpext (fmul x, y)), z)
11547 // -> (fma (fpext x), (fpext y), (fneg z))
11548 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11549 SDValue N00
= N0
.getOperand(0);
11550 if (isContractableFMUL(N00
) &&
11551 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11552 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11553 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11554 N00
.getOperand(0)),
11555 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11556 N00
.getOperand(1)),
11557 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
), Flags
);
11561 // fold (fsub x, (fpext (fmul y, z)))
11562 // -> (fma (fneg (fpext y)), (fpext z), x)
11563 // Note: Commutes FSUB operands.
11564 if (N1
.getOpcode() == ISD::FP_EXTEND
) {
11565 SDValue N10
= N1
.getOperand(0);
11566 if (isContractableFMUL(N10
) &&
11567 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N10
.getValueType())) {
11568 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11569 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11570 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11571 N10
.getOperand(0))),
11572 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11573 N10
.getOperand(1)),
11578 // fold (fsub (fpext (fneg (fmul, x, y))), z)
11579 // -> (fneg (fma (fpext x), (fpext y), z))
11580 // Note: This could be removed with appropriate canonicalization of the
11581 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11582 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11583 // from implementing the canonicalization in visitFSUB.
11584 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11585 SDValue N00
= N0
.getOperand(0);
11586 if (N00
.getOpcode() == ISD::FNEG
) {
11587 SDValue N000
= N00
.getOperand(0);
11588 if (isContractableFMUL(N000
) &&
11589 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11590 return DAG
.getNode(ISD::FNEG
, SL
, VT
,
11591 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11592 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11593 N000
.getOperand(0)),
11594 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11595 N000
.getOperand(1)),
11601 // fold (fsub (fneg (fpext (fmul, x, y))), z)
11602 // -> (fneg (fma (fpext x)), (fpext y), z)
11603 // Note: This could be removed with appropriate canonicalization of the
11604 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
11605 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
11606 // from implementing the canonicalization in visitFSUB.
11607 if (N0
.getOpcode() == ISD::FNEG
) {
11608 SDValue N00
= N0
.getOperand(0);
11609 if (N00
.getOpcode() == ISD::FP_EXTEND
) {
11610 SDValue N000
= N00
.getOperand(0);
11611 if (isContractableFMUL(N000
) &&
11612 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N000
.getValueType())) {
11613 return DAG
.getNode(ISD::FNEG
, SL
, VT
,
11614 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11615 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11616 N000
.getOperand(0)),
11617 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11618 N000
.getOperand(1)),
11624 // More folding opportunities when target permits.
11626 // fold (fsub (fma x, y, (fmul u, v)), z)
11627 // -> (fma x, y (fma u, v, (fneg z)))
11628 if (CanFuse
&& N0
.getOpcode() == PreferredFusedOpcode
&&
11629 isContractableFMUL(N0
.getOperand(2)) && N0
->hasOneUse() &&
11630 N0
.getOperand(2)->hasOneUse()) {
11631 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11632 N0
.getOperand(0), N0
.getOperand(1),
11633 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11634 N0
.getOperand(2).getOperand(0),
11635 N0
.getOperand(2).getOperand(1),
11636 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11637 N1
), Flags
), Flags
);
11640 // fold (fsub x, (fma y, z, (fmul u, v)))
11641 // -> (fma (fneg y), z, (fma (fneg u), v, x))
11642 if (CanFuse
&& N1
.getOpcode() == PreferredFusedOpcode
&&
11643 isContractableFMUL(N1
.getOperand(2))) {
11644 SDValue N20
= N1
.getOperand(2).getOperand(0);
11645 SDValue N21
= N1
.getOperand(2).getOperand(1);
11646 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11647 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11650 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11651 DAG
.getNode(ISD::FNEG
, SL
, VT
, N20
),
11652 N21
, N0
, Flags
), Flags
);
11656 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
11657 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
11658 if (N0
.getOpcode() == PreferredFusedOpcode
) {
11659 SDValue N02
= N0
.getOperand(2);
11660 if (N02
.getOpcode() == ISD::FP_EXTEND
) {
11661 SDValue N020
= N02
.getOperand(0);
11662 if (isContractableFMUL(N020
) &&
11663 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N020
.getValueType())) {
11664 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11665 N0
.getOperand(0), N0
.getOperand(1),
11666 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11667 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11668 N020
.getOperand(0)),
11669 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11670 N020
.getOperand(1)),
11671 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11672 N1
), Flags
), Flags
);
11677 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
11678 // -> (fma (fpext x), (fpext y),
11679 // (fma (fpext u), (fpext v), (fneg z)))
11680 // FIXME: This turns two single-precision and one double-precision
11681 // operation into two double-precision operations, which might not be
11682 // interesting for all targets, especially GPUs.
11683 if (N0
.getOpcode() == ISD::FP_EXTEND
) {
11684 SDValue N00
= N0
.getOperand(0);
11685 if (N00
.getOpcode() == PreferredFusedOpcode
) {
11686 SDValue N002
= N00
.getOperand(2);
11687 if (isContractableFMUL(N002
) &&
11688 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N00
.getValueType())) {
11689 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11690 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11691 N00
.getOperand(0)),
11692 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11693 N00
.getOperand(1)),
11694 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11695 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11696 N002
.getOperand(0)),
11697 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11698 N002
.getOperand(1)),
11699 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11700 N1
), Flags
), Flags
);
11705 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
11706 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
11707 if (N1
.getOpcode() == PreferredFusedOpcode
&&
11708 N1
.getOperand(2).getOpcode() == ISD::FP_EXTEND
) {
11709 SDValue N120
= N1
.getOperand(2).getOperand(0);
11710 if (isContractableFMUL(N120
) &&
11711 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, N120
.getValueType())) {
11712 SDValue N1200
= N120
.getOperand(0);
11713 SDValue N1201
= N120
.getOperand(1);
11714 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11715 DAG
.getNode(ISD::FNEG
, SL
, VT
, N1
.getOperand(0)),
11717 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11718 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11719 DAG
.getNode(ISD::FP_EXTEND
, SL
,
11721 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11723 N0
, Flags
), Flags
);
11727 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
11728 // -> (fma (fneg (fpext y)), (fpext z),
11729 // (fma (fneg (fpext u)), (fpext v), x))
11730 // FIXME: This turns two single-precision and one double-precision
11731 // operation into two double-precision operations, which might not be
11732 // interesting for all targets, especially GPUs.
11733 if (N1
.getOpcode() == ISD::FP_EXTEND
&&
11734 N1
.getOperand(0).getOpcode() == PreferredFusedOpcode
) {
11735 SDValue CvtSrc
= N1
.getOperand(0);
11736 SDValue N100
= CvtSrc
.getOperand(0);
11737 SDValue N101
= CvtSrc
.getOperand(1);
11738 SDValue N102
= CvtSrc
.getOperand(2);
11739 if (isContractableFMUL(N102
) &&
11740 TLI
.isFPExtFoldable(PreferredFusedOpcode
, VT
, CvtSrc
.getValueType())) {
11741 SDValue N1020
= N102
.getOperand(0);
11742 SDValue N1021
= N102
.getOperand(1);
11743 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11744 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11745 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11747 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
, N101
),
11748 DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11749 DAG
.getNode(ISD::FNEG
, SL
, VT
,
11750 DAG
.getNode(ISD::FP_EXTEND
, SL
,
11752 DAG
.getNode(ISD::FP_EXTEND
, SL
, VT
,
11754 N0
, Flags
), Flags
);
11762 /// Try to perform FMA combining on a given FMUL node based on the distributive
11763 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
11764 /// subtraction instead of addition).
11765 SDValue
DAGCombiner::visitFMULForFMADistributiveCombine(SDNode
*N
) {
11766 SDValue N0
= N
->getOperand(0);
11767 SDValue N1
= N
->getOperand(1);
11768 EVT VT
= N
->getValueType(0);
11770 const SDNodeFlags Flags
= N
->getFlags();
11772 assert(N
->getOpcode() == ISD::FMUL
&& "Expected FMUL Operation");
11774 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11776 // The transforms below are incorrect when x == 0 and y == inf, because the
11777 // intermediate multiplication produces a nan.
11778 if (!Options
.NoInfsFPMath
)
11781 // Floating-point multiply-add without intermediate rounding.
11783 (Options
.AllowFPOpFusion
== FPOpFusion::Fast
|| Options
.UnsafeFPMath
) &&
11784 TLI
.isFMAFasterThanFMulAndFAdd(VT
) &&
11785 (!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FMA
, VT
));
11787 // Floating-point multiply-add with intermediate rounding. This can result
11788 // in a less precise result due to the changed rounding order.
11789 bool HasFMAD
= Options
.UnsafeFPMath
&&
11790 (LegalOperations
&& TLI
.isOperationLegal(ISD::FMAD
, VT
));
11792 // No valid opcode, do not combine.
11793 if (!HasFMAD
&& !HasFMA
)
11796 // Always prefer FMAD to FMA for precision.
11797 unsigned PreferredFusedOpcode
= HasFMAD
? ISD::FMAD
: ISD::FMA
;
11798 bool Aggressive
= TLI
.enableAggressiveFMAFusion(VT
);
11800 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
11801 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
11802 auto FuseFADD
= [&](SDValue X
, SDValue Y
, const SDNodeFlags Flags
) {
11803 if (X
.getOpcode() == ISD::FADD
&& (Aggressive
|| X
->hasOneUse())) {
11804 if (auto *C
= isConstOrConstSplatFP(X
.getOperand(1), true)) {
11805 if (C
->isExactlyValue(+1.0))
11806 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11808 if (C
->isExactlyValue(-1.0))
11809 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11810 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11816 if (SDValue FMA
= FuseFADD(N0
, N1
, Flags
))
11818 if (SDValue FMA
= FuseFADD(N1
, N0
, Flags
))
11821 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
11822 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
11823 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
11824 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
11825 auto FuseFSUB
= [&](SDValue X
, SDValue Y
, const SDNodeFlags Flags
) {
11826 if (X
.getOpcode() == ISD::FSUB
&& (Aggressive
|| X
->hasOneUse())) {
11827 if (auto *C0
= isConstOrConstSplatFP(X
.getOperand(0), true)) {
11828 if (C0
->isExactlyValue(+1.0))
11829 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11830 DAG
.getNode(ISD::FNEG
, SL
, VT
, X
.getOperand(1)), Y
,
11832 if (C0
->isExactlyValue(-1.0))
11833 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
,
11834 DAG
.getNode(ISD::FNEG
, SL
, VT
, X
.getOperand(1)), Y
,
11835 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11837 if (auto *C1
= isConstOrConstSplatFP(X
.getOperand(1), true)) {
11838 if (C1
->isExactlyValue(+1.0))
11839 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11840 DAG
.getNode(ISD::FNEG
, SL
, VT
, Y
), Flags
);
11841 if (C1
->isExactlyValue(-1.0))
11842 return DAG
.getNode(PreferredFusedOpcode
, SL
, VT
, X
.getOperand(0), Y
,
11849 if (SDValue FMA
= FuseFSUB(N0
, N1
, Flags
))
11851 if (SDValue FMA
= FuseFSUB(N1
, N0
, Flags
))
11857 SDValue
DAGCombiner::visitFADD(SDNode
*N
) {
11858 SDValue N0
= N
->getOperand(0);
11859 SDValue N1
= N
->getOperand(1);
11860 bool N0CFP
= isConstantFPBuildVectorOrConstantFP(N0
);
11861 bool N1CFP
= isConstantFPBuildVectorOrConstantFP(N1
);
11862 EVT VT
= N
->getValueType(0);
11864 const TargetOptions
&Options
= DAG
.getTarget().Options
;
11865 const SDNodeFlags Flags
= N
->getFlags();
11869 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
11872 // fold (fadd c1, c2) -> c1 + c2
11873 if (N0CFP
&& N1CFP
)
11874 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N1
, Flags
);
11876 // canonicalize constant to RHS
11877 if (N0CFP
&& !N1CFP
)
11878 return DAG
.getNode(ISD::FADD
, DL
, VT
, N1
, N0
, Flags
);
11880 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
11881 ConstantFPSDNode
*N1C
= isConstOrConstSplatFP(N1
, true);
11882 if (N1C
&& N1C
->isZero())
11883 if (N1C
->isNegative() || Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros())
11886 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
11889 // fold (fadd A, (fneg B)) -> (fsub A, B)
11890 if ((!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
)) &&
11891 isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
) == 2)
11892 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
,
11893 GetNegatedExpression(N1
, DAG
, LegalOperations
,
11894 ForCodeSize
), Flags
);
11896 // fold (fadd (fneg A), B) -> (fsub B, A)
11897 if ((!LegalOperations
|| TLI
.isOperationLegalOrCustom(ISD::FSUB
, VT
)) &&
11898 isNegatibleForFree(N0
, LegalOperations
, TLI
, &Options
, ForCodeSize
) == 2)
11899 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N1
,
11900 GetNegatedExpression(N0
, DAG
, LegalOperations
,
11901 ForCodeSize
), Flags
);
11903 auto isFMulNegTwo
= [](SDValue FMul
) {
11904 if (!FMul
.hasOneUse() || FMul
.getOpcode() != ISD::FMUL
)
11906 auto *C
= isConstOrConstSplatFP(FMul
.getOperand(1), true);
11907 return C
&& C
->isExactlyValue(-2.0);
11910 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
11911 if (isFMulNegTwo(N0
)) {
11912 SDValue B
= N0
.getOperand(0);
11913 SDValue Add
= DAG
.getNode(ISD::FADD
, DL
, VT
, B
, B
, Flags
);
11914 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N1
, Add
, Flags
);
11916 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
11917 if (isFMulNegTwo(N1
)) {
11918 SDValue B
= N1
.getOperand(0);
11919 SDValue Add
= DAG
.getNode(ISD::FADD
, DL
, VT
, B
, B
, Flags
);
11920 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
, Add
, Flags
);
11923 // No FP constant should be created after legalization as Instruction
11924 // Selection pass has a hard time dealing with FP constants.
11925 bool AllowNewConst
= (Level
< AfterLegalizeDAG
);
11927 // If nnan is enabled, fold lots of things.
11928 if ((Options
.NoNaNsFPMath
|| Flags
.hasNoNaNs()) && AllowNewConst
) {
11929 // If allowed, fold (fadd (fneg x), x) -> 0.0
11930 if (N0
.getOpcode() == ISD::FNEG
&& N0
.getOperand(0) == N1
)
11931 return DAG
.getConstantFP(0.0, DL
, VT
);
11933 // If allowed, fold (fadd x, (fneg x)) -> 0.0
11934 if (N1
.getOpcode() == ISD::FNEG
&& N1
.getOperand(0) == N0
)
11935 return DAG
.getConstantFP(0.0, DL
, VT
);
11938 // If 'unsafe math' or reassoc and nsz, fold lots of things.
11939 // TODO: break out portions of the transformations below for which Unsafe is
11940 // considered and which do not require both nsz and reassoc
11941 if (((Options
.UnsafeFPMath
&& Options
.NoSignedZerosFPMath
) ||
11942 (Flags
.hasAllowReassociation() && Flags
.hasNoSignedZeros())) &&
11944 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
11945 if (N1CFP
&& N0
.getOpcode() == ISD::FADD
&&
11946 isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1))) {
11947 SDValue NewC
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1), N1
, Flags
);
11948 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(0), NewC
, Flags
);
11951 // We can fold chains of FADD's of the same value into multiplications.
11952 // This transform is not safe in general because we are reducing the number
11953 // of rounding steps.
11954 if (TLI
.isOperationLegalOrCustom(ISD::FMUL
, VT
) && !N0CFP
&& !N1CFP
) {
11955 if (N0
.getOpcode() == ISD::FMUL
) {
11956 bool CFP00
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(0));
11957 bool CFP01
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1));
11959 // (fadd (fmul x, c), x) -> (fmul x, c+1)
11960 if (CFP01
&& !CFP00
&& N0
.getOperand(0) == N1
) {
11961 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1),
11962 DAG
.getConstantFP(1.0, DL
, VT
), Flags
);
11963 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, NewCFP
, Flags
);
11966 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
11967 if (CFP01
&& !CFP00
&& N1
.getOpcode() == ISD::FADD
&&
11968 N1
.getOperand(0) == N1
.getOperand(1) &&
11969 N0
.getOperand(0) == N1
.getOperand(0)) {
11970 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N0
.getOperand(1),
11971 DAG
.getConstantFP(2.0, DL
, VT
), Flags
);
11972 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0), NewCFP
, Flags
);
11976 if (N1
.getOpcode() == ISD::FMUL
) {
11977 bool CFP10
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(0));
11978 bool CFP11
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(1));
11980 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
11981 if (CFP11
&& !CFP10
&& N1
.getOperand(0) == N0
) {
11982 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N1
.getOperand(1),
11983 DAG
.getConstantFP(1.0, DL
, VT
), Flags
);
11984 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, NewCFP
, Flags
);
11987 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
11988 if (CFP11
&& !CFP10
&& N0
.getOpcode() == ISD::FADD
&&
11989 N0
.getOperand(0) == N0
.getOperand(1) &&
11990 N1
.getOperand(0) == N0
.getOperand(0)) {
11991 SDValue NewCFP
= DAG
.getNode(ISD::FADD
, DL
, VT
, N1
.getOperand(1),
11992 DAG
.getConstantFP(2.0, DL
, VT
), Flags
);
11993 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
.getOperand(0), NewCFP
, Flags
);
11997 if (N0
.getOpcode() == ISD::FADD
) {
11998 bool CFP00
= isConstantFPBuildVectorOrConstantFP(N0
.getOperand(0));
11999 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
12000 if (!CFP00
&& N0
.getOperand(0) == N0
.getOperand(1) &&
12001 (N0
.getOperand(0) == N1
)) {
12002 return DAG
.getNode(ISD::FMUL
, DL
, VT
,
12003 N1
, DAG
.getConstantFP(3.0, DL
, VT
), Flags
);
12007 if (N1
.getOpcode() == ISD::FADD
) {
12008 bool CFP10
= isConstantFPBuildVectorOrConstantFP(N1
.getOperand(0));
12009 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
12010 if (!CFP10
&& N1
.getOperand(0) == N1
.getOperand(1) &&
12011 N1
.getOperand(0) == N0
) {
12012 return DAG
.getNode(ISD::FMUL
, DL
, VT
,
12013 N0
, DAG
.getConstantFP(3.0, DL
, VT
), Flags
);
12017 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
12018 if (N0
.getOpcode() == ISD::FADD
&& N1
.getOpcode() == ISD::FADD
&&
12019 N0
.getOperand(0) == N0
.getOperand(1) &&
12020 N1
.getOperand(0) == N1
.getOperand(1) &&
12021 N0
.getOperand(0) == N1
.getOperand(0)) {
12022 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0),
12023 DAG
.getConstantFP(4.0, DL
, VT
), Flags
);
12026 } // enable-unsafe-fp-math
12028 // FADD -> FMA combines:
12029 if (SDValue Fused
= visitFADDForFMACombine(N
)) {
12030 AddToWorklist(Fused
.getNode());
12036 SDValue
DAGCombiner::visitFSUB(SDNode
*N
) {
12037 SDValue N0
= N
->getOperand(0);
12038 SDValue N1
= N
->getOperand(1);
12039 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, true);
12040 ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
, true);
12041 EVT VT
= N
->getValueType(0);
12043 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12044 const SDNodeFlags Flags
= N
->getFlags();
12048 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12051 // fold (fsub c1, c2) -> c1-c2
12052 if (N0CFP
&& N1CFP
)
12053 return DAG
.getNode(ISD::FSUB
, DL
, VT
, N0
, N1
, Flags
);
12055 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12058 // (fsub A, 0) -> A
12059 if (N1CFP
&& N1CFP
->isZero()) {
12060 if (!N1CFP
->isNegative() || Options
.NoSignedZerosFPMath
||
12061 Flags
.hasNoSignedZeros()) {
12067 // (fsub x, x) -> 0.0
12068 if (Options
.NoNaNsFPMath
|| Flags
.hasNoNaNs())
12069 return DAG
.getConstantFP(0.0f
, DL
, VT
);
12072 // (fsub -0.0, N1) -> -N1
12073 // NOTE: It is safe to transform an FSUB(-0.0,X) into an FNEG(X), since the
12074 // FSUB does not specify the sign bit of a NaN. Also note that for
12075 // the same reason, the inverse transform is not safe, unless fast math
12076 // flags are in play.
12077 if (N0CFP
&& N0CFP
->isZero()) {
12078 if (N0CFP
->isNegative() ||
12079 (Options
.NoSignedZerosFPMath
|| Flags
.hasNoSignedZeros())) {
12080 if (isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
))
12081 return GetNegatedExpression(N1
, DAG
, LegalOperations
, ForCodeSize
);
12082 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12083 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
, Flags
);
12087 if (((Options
.UnsafeFPMath
&& Options
.NoSignedZerosFPMath
) ||
12088 (Flags
.hasAllowReassociation() && Flags
.hasNoSignedZeros()))
12089 && N1
.getOpcode() == ISD::FADD
) {
12090 // X - (X + Y) -> -Y
12091 if (N0
== N1
->getOperand(0))
12092 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
->getOperand(1), Flags
);
12093 // X - (Y + X) -> -Y
12094 if (N0
== N1
->getOperand(1))
12095 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
->getOperand(0), Flags
);
12098 // fold (fsub A, (fneg B)) -> (fadd A, B)
12099 if (isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
, ForCodeSize
))
12100 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
,
12101 GetNegatedExpression(N1
, DAG
, LegalOperations
,
12102 ForCodeSize
), Flags
);
12104 // FSUB -> FMA combines:
12105 if (SDValue Fused
= visitFSUBForFMACombine(N
)) {
12106 AddToWorklist(Fused
.getNode());
12113 SDValue
DAGCombiner::visitFMUL(SDNode
*N
) {
12114 SDValue N0
= N
->getOperand(0);
12115 SDValue N1
= N
->getOperand(1);
12116 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, true);
12117 ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
, true);
12118 EVT VT
= N
->getValueType(0);
12120 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12121 const SDNodeFlags Flags
= N
->getFlags();
12124 if (VT
.isVector()) {
12125 // This just handles C1 * C2 for vectors. Other vector folds are below.
12126 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12130 // fold (fmul c1, c2) -> c1*c2
12131 if (N0CFP
&& N1CFP
)
12132 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, N1
, Flags
);
12134 // canonicalize constant to RHS
12135 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
12136 !isConstantFPBuildVectorOrConstantFP(N1
))
12137 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, N0
, Flags
);
12139 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12142 if ((Options
.NoNaNsFPMath
&& Options
.NoSignedZerosFPMath
) ||
12143 (Flags
.hasNoNaNs() && Flags
.hasNoSignedZeros())) {
12144 // fold (fmul A, 0) -> 0
12145 if (N1CFP
&& N1CFP
->isZero())
12149 if (Options
.UnsafeFPMath
|| Flags
.hasAllowReassociation()) {
12150 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
12151 if (isConstantFPBuildVectorOrConstantFP(N1
) &&
12152 N0
.getOpcode() == ISD::FMUL
) {
12153 SDValue N00
= N0
.getOperand(0);
12154 SDValue N01
= N0
.getOperand(1);
12155 // Avoid an infinite loop by making sure that N00 is not a constant
12156 // (the inner multiply has not been constant folded yet).
12157 if (isConstantFPBuildVectorOrConstantFP(N01
) &&
12158 !isConstantFPBuildVectorOrConstantFP(N00
)) {
12159 SDValue MulConsts
= DAG
.getNode(ISD::FMUL
, DL
, VT
, N01
, N1
, Flags
);
12160 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N00
, MulConsts
, Flags
);
12164 // Match a special-case: we convert X * 2.0 into fadd.
12165 // fmul (fadd X, X), C -> fmul X, 2.0 * C
12166 if (N0
.getOpcode() == ISD::FADD
&& N0
.hasOneUse() &&
12167 N0
.getOperand(0) == N0
.getOperand(1)) {
12168 const SDValue Two
= DAG
.getConstantFP(2.0, DL
, VT
);
12169 SDValue MulConsts
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Two
, N1
, Flags
);
12170 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
.getOperand(0), MulConsts
, Flags
);
12174 // fold (fmul X, 2.0) -> (fadd X, X)
12175 if (N1CFP
&& N1CFP
->isExactlyValue(+2.0))
12176 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N0
, Flags
);
12178 // fold (fmul X, -1.0) -> (fneg X)
12179 if (N1CFP
&& N1CFP
->isExactlyValue(-1.0))
12180 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12181 return DAG
.getNode(ISD::FNEG
, DL
, VT
, N0
);
12183 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
12184 if (char LHSNeg
= isNegatibleForFree(N0
, LegalOperations
, TLI
, &Options
,
12186 if (char RHSNeg
= isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
,
12188 // Both can be negated for free, check to see if at least one is cheaper
12190 if (LHSNeg
== 2 || RHSNeg
== 2)
12191 return DAG
.getNode(ISD::FMUL
, DL
, VT
,
12192 GetNegatedExpression(N0
, DAG
, LegalOperations
,
12194 GetNegatedExpression(N1
, DAG
, LegalOperations
,
12200 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
12201 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
12202 if (Flags
.hasNoNaNs() && Flags
.hasNoSignedZeros() &&
12203 (N0
.getOpcode() == ISD::SELECT
|| N1
.getOpcode() == ISD::SELECT
) &&
12204 TLI
.isOperationLegal(ISD::FABS
, VT
)) {
12205 SDValue Select
= N0
, X
= N1
;
12206 if (Select
.getOpcode() != ISD::SELECT
)
12207 std::swap(Select
, X
);
12209 SDValue Cond
= Select
.getOperand(0);
12210 auto TrueOpnd
= dyn_cast
<ConstantFPSDNode
>(Select
.getOperand(1));
12211 auto FalseOpnd
= dyn_cast
<ConstantFPSDNode
>(Select
.getOperand(2));
12213 if (TrueOpnd
&& FalseOpnd
&&
12214 Cond
.getOpcode() == ISD::SETCC
&& Cond
.getOperand(0) == X
&&
12215 isa
<ConstantFPSDNode
>(Cond
.getOperand(1)) &&
12216 cast
<ConstantFPSDNode
>(Cond
.getOperand(1))->isExactlyValue(0.0)) {
12217 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Cond
.getOperand(2))->get();
12226 std::swap(TrueOpnd
, FalseOpnd
);
12234 if (TrueOpnd
->isExactlyValue(-1.0) && FalseOpnd
->isExactlyValue(1.0) &&
12235 TLI
.isOperationLegal(ISD::FNEG
, VT
))
12236 return DAG
.getNode(ISD::FNEG
, DL
, VT
,
12237 DAG
.getNode(ISD::FABS
, DL
, VT
, X
));
12238 if (TrueOpnd
->isExactlyValue(1.0) && FalseOpnd
->isExactlyValue(-1.0))
12239 return DAG
.getNode(ISD::FABS
, DL
, VT
, X
);
12246 // FMUL -> FMA combines:
12247 if (SDValue Fused
= visitFMULForFMADistributiveCombine(N
)) {
12248 AddToWorklist(Fused
.getNode());
12255 SDValue
DAGCombiner::visitFMA(SDNode
*N
) {
12256 SDValue N0
= N
->getOperand(0);
12257 SDValue N1
= N
->getOperand(1);
12258 SDValue N2
= N
->getOperand(2);
12259 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12260 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12261 EVT VT
= N
->getValueType(0);
12263 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12265 // FMA nodes have flags that propagate to the created nodes.
12266 const SDNodeFlags Flags
= N
->getFlags();
12267 bool UnsafeFPMath
= Options
.UnsafeFPMath
|| isContractable(N
);
12269 // Constant fold FMA.
12270 if (isa
<ConstantFPSDNode
>(N0
) &&
12271 isa
<ConstantFPSDNode
>(N1
) &&
12272 isa
<ConstantFPSDNode
>(N2
)) {
12273 return DAG
.getNode(ISD::FMA
, DL
, VT
, N0
, N1
, N2
);
12276 if (UnsafeFPMath
) {
12277 if (N0CFP
&& N0CFP
->isZero())
12279 if (N1CFP
&& N1CFP
->isZero())
12282 // TODO: The FMA node should have flags that propagate to these nodes.
12283 if (N0CFP
&& N0CFP
->isExactlyValue(1.0))
12284 return DAG
.getNode(ISD::FADD
, SDLoc(N
), VT
, N1
, N2
);
12285 if (N1CFP
&& N1CFP
->isExactlyValue(1.0))
12286 return DAG
.getNode(ISD::FADD
, SDLoc(N
), VT
, N0
, N2
);
12288 // Canonicalize (fma c, x, y) -> (fma x, c, y)
12289 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
12290 !isConstantFPBuildVectorOrConstantFP(N1
))
12291 return DAG
.getNode(ISD::FMA
, SDLoc(N
), VT
, N1
, N0
, N2
);
12293 if (UnsafeFPMath
) {
12294 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
12295 if (N2
.getOpcode() == ISD::FMUL
&& N0
== N2
.getOperand(0) &&
12296 isConstantFPBuildVectorOrConstantFP(N1
) &&
12297 isConstantFPBuildVectorOrConstantFP(N2
.getOperand(1))) {
12298 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12299 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
, N2
.getOperand(1),
12303 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
12304 if (N0
.getOpcode() == ISD::FMUL
&&
12305 isConstantFPBuildVectorOrConstantFP(N1
) &&
12306 isConstantFPBuildVectorOrConstantFP(N0
.getOperand(1))) {
12307 return DAG
.getNode(ISD::FMA
, DL
, VT
,
12309 DAG
.getNode(ISD::FMUL
, DL
, VT
, N1
, N0
.getOperand(1),
12315 // (fma x, 1, y) -> (fadd x, y)
12316 // (fma x, -1, y) -> (fadd (fneg x), y)
12318 if (N1CFP
->isExactlyValue(1.0))
12319 // TODO: The FMA node should have flags that propagate to this node.
12320 return DAG
.getNode(ISD::FADD
, DL
, VT
, N0
, N2
);
12322 if (N1CFP
->isExactlyValue(-1.0) &&
12323 (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))) {
12324 SDValue RHSNeg
= DAG
.getNode(ISD::FNEG
, DL
, VT
, N0
);
12325 AddToWorklist(RHSNeg
.getNode());
12326 // TODO: The FMA node should have flags that propagate to this node.
12327 return DAG
.getNode(ISD::FADD
, DL
, VT
, N2
, RHSNeg
);
12330 // fma (fneg x), K, y -> fma x -K, y
12331 if (N0
.getOpcode() == ISD::FNEG
&&
12332 (TLI
.isOperationLegal(ISD::ConstantFP
, VT
) ||
12333 (N1
.hasOneUse() && !TLI
.isFPImmLegal(N1CFP
->getValueAPF(), VT
,
12335 return DAG
.getNode(ISD::FMA
, DL
, VT
, N0
.getOperand(0),
12336 DAG
.getNode(ISD::FNEG
, DL
, VT
, N1
, Flags
), N2
);
12340 if (UnsafeFPMath
) {
12341 // (fma x, c, x) -> (fmul x, (c+1))
12342 if (N1CFP
&& N0
== N2
) {
12343 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12344 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
,
12345 DAG
.getConstantFP(1.0, DL
, VT
), Flags
),
12349 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
12350 if (N1CFP
&& N2
.getOpcode() == ISD::FNEG
&& N2
.getOperand(0) == N0
) {
12351 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12352 DAG
.getNode(ISD::FADD
, DL
, VT
, N1
,
12353 DAG
.getConstantFP(-1.0, DL
, VT
), Flags
),
12361 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12363 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
12364 // Notice that this is not always beneficial. One reason is different targets
12365 // may have different costs for FDIV and FMUL, so sometimes the cost of two
12366 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
12367 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
12368 SDValue
DAGCombiner::combineRepeatedFPDivisors(SDNode
*N
) {
12369 // TODO: Limit this transform based on optsize/minsize - it always creates at
12370 // least 1 extra instruction. But the perf win may be substantial enough
12371 // that only minsize should restrict this.
12372 bool UnsafeMath
= DAG
.getTarget().Options
.UnsafeFPMath
;
12373 const SDNodeFlags Flags
= N
->getFlags();
12374 if (!UnsafeMath
&& !Flags
.hasAllowReciprocal())
12377 // Skip if current node is a reciprocal/fneg-reciprocal.
12378 SDValue N0
= N
->getOperand(0);
12379 ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
, /* AllowUndefs */ true);
12380 if (N0CFP
&& (N0CFP
->isExactlyValue(1.0) || N0CFP
->isExactlyValue(-1.0)))
12383 // Exit early if the target does not want this transform or if there can't
12384 // possibly be enough uses of the divisor to make the transform worthwhile.
12385 SDValue N1
= N
->getOperand(1);
12386 unsigned MinUses
= TLI
.combineRepeatedFPDivisors();
12388 // For splat vectors, scale the number of uses by the splat factor. If we can
12389 // convert the division into a scalar op, that will likely be much faster.
12390 unsigned NumElts
= 1;
12391 EVT VT
= N
->getValueType(0);
12392 if (VT
.isVector() && DAG
.isSplatValue(N1
))
12393 NumElts
= VT
.getVectorNumElements();
12395 if (!MinUses
|| (N1
->use_size() * NumElts
) < MinUses
)
12398 // Find all FDIV users of the same divisor.
12399 // Use a set because duplicates may be present in the user list.
12400 SetVector
<SDNode
*> Users
;
12401 for (auto *U
: N1
->uses()) {
12402 if (U
->getOpcode() == ISD::FDIV
&& U
->getOperand(1) == N1
) {
12403 // This division is eligible for optimization only if global unsafe math
12404 // is enabled or if this division allows reciprocal formation.
12405 if (UnsafeMath
|| U
->getFlags().hasAllowReciprocal())
12410 // Now that we have the actual number of divisor uses, make sure it meets
12411 // the minimum threshold specified by the target.
12412 if ((Users
.size() * NumElts
) < MinUses
)
12416 SDValue FPOne
= DAG
.getConstantFP(1.0, DL
, VT
);
12417 SDValue Reciprocal
= DAG
.getNode(ISD::FDIV
, DL
, VT
, FPOne
, N1
, Flags
);
12419 // Dividend / Divisor -> Dividend * Reciprocal
12420 for (auto *U
: Users
) {
12421 SDValue Dividend
= U
->getOperand(0);
12422 if (Dividend
!= FPOne
) {
12423 SDValue NewNode
= DAG
.getNode(ISD::FMUL
, SDLoc(U
), VT
, Dividend
,
12424 Reciprocal
, Flags
);
12425 CombineTo(U
, NewNode
);
12426 } else if (U
!= Reciprocal
.getNode()) {
12427 // In the absence of fast-math-flags, this user node is always the
12428 // same node as Reciprocal, but with FMF they may be different nodes.
12429 CombineTo(U
, Reciprocal
);
12432 return SDValue(N
, 0); // N was replaced.
12435 SDValue
DAGCombiner::visitFDIV(SDNode
*N
) {
12436 SDValue N0
= N
->getOperand(0);
12437 SDValue N1
= N
->getOperand(1);
12438 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12439 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12440 EVT VT
= N
->getValueType(0);
12442 const TargetOptions
&Options
= DAG
.getTarget().Options
;
12443 SDNodeFlags Flags
= N
->getFlags();
12447 if (SDValue FoldedVOp
= SimplifyVBinOp(N
))
12450 // fold (fdiv c1, c2) -> c1/c2
12451 if (N0CFP
&& N1CFP
)
12452 return DAG
.getNode(ISD::FDIV
, SDLoc(N
), VT
, N0
, N1
, Flags
);
12454 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12457 if (SDValue V
= combineRepeatedFPDivisors(N
))
12460 if (Options
.UnsafeFPMath
|| Flags
.hasAllowReciprocal()) {
12461 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
12463 // Compute the reciprocal 1.0 / c2.
12464 const APFloat
&N1APF
= N1CFP
->getValueAPF();
12465 APFloat
Recip(N1APF
.getSemantics(), 1); // 1.0
12466 APFloat::opStatus st
= Recip
.divide(N1APF
, APFloat::rmNearestTiesToEven
);
12467 // Only do the transform if the reciprocal is a legal fp immediate that
12468 // isn't too nasty (eg NaN, denormal, ...).
12469 if ((st
== APFloat::opOK
|| st
== APFloat::opInexact
) && // Not too nasty
12470 (!LegalOperations
||
12471 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
12472 // backend)... we should handle this gracefully after Legalize.
12473 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
12474 TLI
.isOperationLegal(ISD::ConstantFP
, VT
) ||
12475 TLI
.isFPImmLegal(Recip
, VT
, ForCodeSize
)))
12476 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
,
12477 DAG
.getConstantFP(Recip
, DL
, VT
), Flags
);
12480 // If this FDIV is part of a reciprocal square root, it may be folded
12481 // into a target-specific square root estimate instruction.
12482 if (N1
.getOpcode() == ISD::FSQRT
) {
12483 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0), Flags
))
12484 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12485 } else if (N1
.getOpcode() == ISD::FP_EXTEND
&&
12486 N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12487 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0).getOperand(0),
12489 RV
= DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N1
), VT
, RV
);
12490 AddToWorklist(RV
.getNode());
12491 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12493 } else if (N1
.getOpcode() == ISD::FP_ROUND
&&
12494 N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12495 if (SDValue RV
= buildRsqrtEstimate(N1
.getOperand(0).getOperand(0),
12497 RV
= DAG
.getNode(ISD::FP_ROUND
, SDLoc(N1
), VT
, RV
, N1
.getOperand(1));
12498 AddToWorklist(RV
.getNode());
12499 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12501 } else if (N1
.getOpcode() == ISD::FMUL
) {
12502 // Look through an FMUL. Even though this won't remove the FDIV directly,
12503 // it's still worthwhile to get rid of the FSQRT if possible.
12506 if (N1
.getOperand(0).getOpcode() == ISD::FSQRT
) {
12507 SqrtOp
= N1
.getOperand(0);
12508 OtherOp
= N1
.getOperand(1);
12509 } else if (N1
.getOperand(1).getOpcode() == ISD::FSQRT
) {
12510 SqrtOp
= N1
.getOperand(1);
12511 OtherOp
= N1
.getOperand(0);
12513 if (SqrtOp
.getNode()) {
12514 // We found a FSQRT, so try to make this fold:
12515 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
12516 if (SDValue RV
= buildRsqrtEstimate(SqrtOp
.getOperand(0), Flags
)) {
12517 RV
= DAG
.getNode(ISD::FDIV
, SDLoc(N1
), VT
, RV
, OtherOp
, Flags
);
12518 AddToWorklist(RV
.getNode());
12519 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12524 // Fold into a reciprocal estimate and multiply instead of a real divide.
12525 if (SDValue RV
= BuildReciprocalEstimate(N1
, Flags
)) {
12526 AddToWorklist(RV
.getNode());
12527 return DAG
.getNode(ISD::FMUL
, DL
, VT
, N0
, RV
, Flags
);
12531 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
12532 if (char LHSNeg
= isNegatibleForFree(N0
, LegalOperations
, TLI
, &Options
,
12534 if (char RHSNeg
= isNegatibleForFree(N1
, LegalOperations
, TLI
, &Options
,
12536 // Both can be negated for free, check to see if at least one is cheaper
12538 if (LHSNeg
== 2 || RHSNeg
== 2)
12539 return DAG
.getNode(ISD::FDIV
, SDLoc(N
), VT
,
12540 GetNegatedExpression(N0
, DAG
, LegalOperations
,
12542 GetNegatedExpression(N1
, DAG
, LegalOperations
,
12551 SDValue
DAGCombiner::visitFREM(SDNode
*N
) {
12552 SDValue N0
= N
->getOperand(0);
12553 SDValue N1
= N
->getOperand(1);
12554 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12555 ConstantFPSDNode
*N1CFP
= dyn_cast
<ConstantFPSDNode
>(N1
);
12556 EVT VT
= N
->getValueType(0);
12558 // fold (frem c1, c2) -> fmod(c1,c2)
12559 if (N0CFP
&& N1CFP
)
12560 return DAG
.getNode(ISD::FREM
, SDLoc(N
), VT
, N0
, N1
, N
->getFlags());
12562 if (SDValue NewSel
= foldBinOpIntoSelect(N
))
12568 SDValue
DAGCombiner::visitFSQRT(SDNode
*N
) {
12569 SDNodeFlags Flags
= N
->getFlags();
12570 if (!DAG
.getTarget().Options
.UnsafeFPMath
&&
12571 !Flags
.hasApproximateFuncs())
12574 SDValue N0
= N
->getOperand(0);
12575 if (TLI
.isFsqrtCheap(N0
, DAG
))
12578 // FSQRT nodes have flags that propagate to the created nodes.
12579 return buildSqrtEstimate(N0
, Flags
);
12582 /// copysign(x, fp_extend(y)) -> copysign(x, y)
12583 /// copysign(x, fp_round(y)) -> copysign(x, y)
12584 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode
*N
) {
12585 SDValue N1
= N
->getOperand(1);
12586 if ((N1
.getOpcode() == ISD::FP_EXTEND
||
12587 N1
.getOpcode() == ISD::FP_ROUND
)) {
12588 // Do not optimize out type conversion of f128 type yet.
12589 // For some targets like x86_64, configuration is changed to keep one f128
12590 // value in one SSE register, but instruction selection cannot handle
12591 // FCOPYSIGN on SSE registers yet.
12592 EVT N1VT
= N1
->getValueType(0);
12593 EVT N1Op0VT
= N1
->getOperand(0).getValueType();
12594 return (N1VT
== N1Op0VT
|| N1Op0VT
!= MVT::f128
);
12599 SDValue
DAGCombiner::visitFCOPYSIGN(SDNode
*N
) {
12600 SDValue N0
= N
->getOperand(0);
12601 SDValue N1
= N
->getOperand(1);
12602 bool N0CFP
= isConstantFPBuildVectorOrConstantFP(N0
);
12603 bool N1CFP
= isConstantFPBuildVectorOrConstantFP(N1
);
12604 EVT VT
= N
->getValueType(0);
12606 if (N0CFP
&& N1CFP
) // Constant fold
12607 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
);
12609 if (ConstantFPSDNode
*N1C
= isConstOrConstSplatFP(N
->getOperand(1))) {
12610 const APFloat
&V
= N1C
->getValueAPF();
12611 // copysign(x, c1) -> fabs(x) iff ispos(c1)
12612 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
12613 if (!V
.isNegative()) {
12614 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FABS
, VT
))
12615 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
12617 if (!LegalOperations
|| TLI
.isOperationLegal(ISD::FNEG
, VT
))
12618 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
,
12619 DAG
.getNode(ISD::FABS
, SDLoc(N0
), VT
, N0
));
12623 // copysign(fabs(x), y) -> copysign(x, y)
12624 // copysign(fneg(x), y) -> copysign(x, y)
12625 // copysign(copysign(x,z), y) -> copysign(x, y)
12626 if (N0
.getOpcode() == ISD::FABS
|| N0
.getOpcode() == ISD::FNEG
||
12627 N0
.getOpcode() == ISD::FCOPYSIGN
)
12628 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
.getOperand(0), N1
);
12630 // copysign(x, abs(y)) -> abs(x)
12631 if (N1
.getOpcode() == ISD::FABS
)
12632 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
12634 // copysign(x, copysign(y,z)) -> copysign(x, z)
12635 if (N1
.getOpcode() == ISD::FCOPYSIGN
)
12636 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
.getOperand(1));
12638 // copysign(x, fp_extend(y)) -> copysign(x, y)
12639 // copysign(x, fp_round(y)) -> copysign(x, y)
12640 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N
))
12641 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
, N0
, N1
.getOperand(0));
12646 SDValue
DAGCombiner::visitFPOW(SDNode
*N
) {
12647 ConstantFPSDNode
*ExponentC
= isConstOrConstSplatFP(N
->getOperand(1));
12651 // Try to convert x ** (1/3) into cube root.
12652 // TODO: Handle the various flavors of long double.
12653 // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
12654 // Some range near 1/3 should be fine.
12655 EVT VT
= N
->getValueType(0);
12656 if ((VT
== MVT::f32
&& ExponentC
->getValueAPF().isExactlyValue(1.0f
/3.0f
)) ||
12657 (VT
== MVT::f64
&& ExponentC
->getValueAPF().isExactlyValue(1.0/3.0))) {
12658 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
12659 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
12660 // pow(-val, 1/3) = nan; cbrt(-val) = -num.
12661 // For regular numbers, rounding may cause the results to differ.
12662 // Therefore, we require { nsz ninf nnan afn } for this transform.
12663 // TODO: We could select out the special cases if we don't have nsz/ninf.
12664 SDNodeFlags Flags
= N
->getFlags();
12665 if (!Flags
.hasNoSignedZeros() || !Flags
.hasNoInfs() || !Flags
.hasNoNaNs() ||
12666 !Flags
.hasApproximateFuncs())
12669 // Do not create a cbrt() libcall if the target does not have it, and do not
12670 // turn a pow that has lowering support into a cbrt() libcall.
12671 if (!DAG
.getLibInfo().has(LibFunc_cbrt
) ||
12672 (!DAG
.getTargetLoweringInfo().isOperationExpand(ISD::FPOW
, VT
) &&
12673 DAG
.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT
, VT
)))
12676 return DAG
.getNode(ISD::FCBRT
, SDLoc(N
), VT
, N
->getOperand(0), Flags
);
12679 // Try to convert x ** (1/4) and x ** (3/4) into square roots.
12680 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
12681 // TODO: This could be extended (using a target hook) to handle smaller
12682 // power-of-2 fractional exponents.
12683 bool ExponentIs025
= ExponentC
->getValueAPF().isExactlyValue(0.25);
12684 bool ExponentIs075
= ExponentC
->getValueAPF().isExactlyValue(0.75);
12685 if (ExponentIs025
|| ExponentIs075
) {
12686 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
12687 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
12688 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
12689 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
12690 // For regular numbers, rounding may cause the results to differ.
12691 // Therefore, we require { nsz ninf afn } for this transform.
12692 // TODO: We could select out the special cases if we don't have nsz/ninf.
12693 SDNodeFlags Flags
= N
->getFlags();
12695 // We only need no signed zeros for the 0.25 case.
12696 if ((!Flags
.hasNoSignedZeros() && ExponentIs025
) || !Flags
.hasNoInfs() ||
12697 !Flags
.hasApproximateFuncs())
12700 // Don't double the number of libcalls. We are trying to inline fast code.
12701 if (!DAG
.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT
, VT
))
12704 // Assume that libcalls are the smallest code.
12705 // TODO: This restriction should probably be lifted for vectors.
12706 if (DAG
.getMachineFunction().getFunction().hasOptSize())
12709 // pow(X, 0.25) --> sqrt(sqrt(X))
12711 SDValue Sqrt
= DAG
.getNode(ISD::FSQRT
, DL
, VT
, N
->getOperand(0), Flags
);
12712 SDValue SqrtSqrt
= DAG
.getNode(ISD::FSQRT
, DL
, VT
, Sqrt
, Flags
);
12715 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
12716 return DAG
.getNode(ISD::FMUL
, DL
, VT
, Sqrt
, SqrtSqrt
, Flags
);
12722 static SDValue
foldFPToIntToFP(SDNode
*N
, SelectionDAG
&DAG
,
12723 const TargetLowering
&TLI
) {
12724 // This optimization is guarded by a function attribute because it may produce
12725 // unexpected results. Ie, programs may be relying on the platform-specific
12726 // undefined behavior when the float-to-int conversion overflows.
12727 const Function
&F
= DAG
.getMachineFunction().getFunction();
12728 Attribute StrictOverflow
= F
.getFnAttribute("strict-float-cast-overflow");
12729 if (StrictOverflow
.getValueAsString().equals("false"))
12732 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
12733 // replacing casts with a libcall. We also must be allowed to ignore -0.0
12734 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
12735 // conversions would return +0.0.
12736 // FIXME: We should be able to use node-level FMF here.
12737 // TODO: If strict math, should we use FABS (+ range check for signed cast)?
12738 EVT VT
= N
->getValueType(0);
12739 if (!TLI
.isOperationLegal(ISD::FTRUNC
, VT
) ||
12740 !DAG
.getTarget().Options
.NoSignedZerosFPMath
)
12743 // fptosi/fptoui round towards zero, so converting from FP to integer and
12744 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
12745 SDValue N0
= N
->getOperand(0);
12746 if (N
->getOpcode() == ISD::SINT_TO_FP
&& N0
.getOpcode() == ISD::FP_TO_SINT
&&
12747 N0
.getOperand(0).getValueType() == VT
)
12748 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
.getOperand(0));
12750 if (N
->getOpcode() == ISD::UINT_TO_FP
&& N0
.getOpcode() == ISD::FP_TO_UINT
&&
12751 N0
.getOperand(0).getValueType() == VT
)
12752 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
.getOperand(0));
12757 SDValue
DAGCombiner::visitSINT_TO_FP(SDNode
*N
) {
12758 SDValue N0
= N
->getOperand(0);
12759 EVT VT
= N
->getValueType(0);
12760 EVT OpVT
= N0
.getValueType();
12762 // [us]itofp(undef) = 0, because the result value is bounded.
12764 return DAG
.getConstantFP(0.0, SDLoc(N
), VT
);
12766 // fold (sint_to_fp c1) -> c1fp
12767 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
12768 // ...but only if the target supports immediate floating-point values
12769 (!LegalOperations
||
12770 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
)))
12771 return DAG
.getNode(ISD::SINT_TO_FP
, SDLoc(N
), VT
, N0
);
12773 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
12774 // but UINT_TO_FP is legal on this target, try to convert.
12775 if (!hasOperation(ISD::SINT_TO_FP
, OpVT
) &&
12776 hasOperation(ISD::UINT_TO_FP
, OpVT
)) {
12777 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
12778 if (DAG
.SignBitIsZero(N0
))
12779 return DAG
.getNode(ISD::UINT_TO_FP
, SDLoc(N
), VT
, N0
);
12782 // The next optimizations are desirable only if SELECT_CC can be lowered.
12783 if (TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
) || !LegalOperations
) {
12784 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12785 if (N0
.getOpcode() == ISD::SETCC
&& N0
.getValueType() == MVT::i1
&&
12787 (!LegalOperations
||
12788 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
12791 { N0
.getOperand(0), N0
.getOperand(1),
12792 DAG
.getConstantFP(-1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
12793 N0
.getOperand(2) };
12794 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
12797 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
12798 // (select_cc x, y, 1.0, 0.0,, cc)
12799 if (N0
.getOpcode() == ISD::ZERO_EXTEND
&&
12800 N0
.getOperand(0).getOpcode() == ISD::SETCC
&&!VT
.isVector() &&
12801 (!LegalOperations
||
12802 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
12805 { N0
.getOperand(0).getOperand(0), N0
.getOperand(0).getOperand(1),
12806 DAG
.getConstantFP(1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
12807 N0
.getOperand(0).getOperand(2) };
12808 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
12812 if (SDValue FTrunc
= foldFPToIntToFP(N
, DAG
, TLI
))
12818 SDValue
DAGCombiner::visitUINT_TO_FP(SDNode
*N
) {
12819 SDValue N0
= N
->getOperand(0);
12820 EVT VT
= N
->getValueType(0);
12821 EVT OpVT
= N0
.getValueType();
12823 // [us]itofp(undef) = 0, because the result value is bounded.
12825 return DAG
.getConstantFP(0.0, SDLoc(N
), VT
);
12827 // fold (uint_to_fp c1) -> c1fp
12828 if (DAG
.isConstantIntBuildVectorOrConstantInt(N0
) &&
12829 // ...but only if the target supports immediate floating-point values
12830 (!LegalOperations
||
12831 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
)))
12832 return DAG
.getNode(ISD::UINT_TO_FP
, SDLoc(N
), VT
, N0
);
12834 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
12835 // but SINT_TO_FP is legal on this target, try to convert.
12836 if (!hasOperation(ISD::UINT_TO_FP
, OpVT
) &&
12837 hasOperation(ISD::SINT_TO_FP
, OpVT
)) {
12838 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
12839 if (DAG
.SignBitIsZero(N0
))
12840 return DAG
.getNode(ISD::SINT_TO_FP
, SDLoc(N
), VT
, N0
);
12843 // The next optimizations are desirable only if SELECT_CC can be lowered.
12844 if (TLI
.isOperationLegalOrCustom(ISD::SELECT_CC
, VT
) || !LegalOperations
) {
12845 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
12846 if (N0
.getOpcode() == ISD::SETCC
&& !VT
.isVector() &&
12847 (!LegalOperations
||
12848 TLI
.isOperationLegalOrCustom(ISD::ConstantFP
, VT
))) {
12851 { N0
.getOperand(0), N0
.getOperand(1),
12852 DAG
.getConstantFP(1.0, DL
, VT
), DAG
.getConstantFP(0.0, DL
, VT
),
12853 N0
.getOperand(2) };
12854 return DAG
.getNode(ISD::SELECT_CC
, DL
, VT
, Ops
);
12858 if (SDValue FTrunc
= foldFPToIntToFP(N
, DAG
, TLI
))
12864 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
12865 static SDValue
FoldIntToFPToInt(SDNode
*N
, SelectionDAG
&DAG
) {
12866 SDValue N0
= N
->getOperand(0);
12867 EVT VT
= N
->getValueType(0);
12869 if (N0
.getOpcode() != ISD::UINT_TO_FP
&& N0
.getOpcode() != ISD::SINT_TO_FP
)
12872 SDValue Src
= N0
.getOperand(0);
12873 EVT SrcVT
= Src
.getValueType();
12874 bool IsInputSigned
= N0
.getOpcode() == ISD::SINT_TO_FP
;
12875 bool IsOutputSigned
= N
->getOpcode() == ISD::FP_TO_SINT
;
12877 // We can safely assume the conversion won't overflow the output range,
12878 // because (for example) (uint8_t)18293.f is undefined behavior.
12880 // Since we can assume the conversion won't overflow, our decision as to
12881 // whether the input will fit in the float should depend on the minimum
12882 // of the input range and output range.
12884 // This means this is also safe for a signed input and unsigned output, since
12885 // a negative input would lead to undefined behavior.
12886 unsigned InputSize
= (int)SrcVT
.getScalarSizeInBits() - IsInputSigned
;
12887 unsigned OutputSize
= (int)VT
.getScalarSizeInBits() - IsOutputSigned
;
12888 unsigned ActualSize
= std::min(InputSize
, OutputSize
);
12889 const fltSemantics
&sem
= DAG
.EVTToAPFloatSemantics(N0
.getValueType());
12891 // We can only fold away the float conversion if the input range can be
12892 // represented exactly in the float range.
12893 if (APFloat::semanticsPrecision(sem
) >= ActualSize
) {
12894 if (VT
.getScalarSizeInBits() > SrcVT
.getScalarSizeInBits()) {
12895 unsigned ExtOp
= IsInputSigned
&& IsOutputSigned
? ISD::SIGN_EXTEND
12896 : ISD::ZERO_EXTEND
;
12897 return DAG
.getNode(ExtOp
, SDLoc(N
), VT
, Src
);
12899 if (VT
.getScalarSizeInBits() < SrcVT
.getScalarSizeInBits())
12900 return DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), VT
, Src
);
12901 return DAG
.getBitcast(VT
, Src
);
12906 SDValue
DAGCombiner::visitFP_TO_SINT(SDNode
*N
) {
12907 SDValue N0
= N
->getOperand(0);
12908 EVT VT
= N
->getValueType(0);
12910 // fold (fp_to_sint undef) -> undef
12912 return DAG
.getUNDEF(VT
);
12914 // fold (fp_to_sint c1fp) -> c1
12915 if (isConstantFPBuildVectorOrConstantFP(N0
))
12916 return DAG
.getNode(ISD::FP_TO_SINT
, SDLoc(N
), VT
, N0
);
12918 return FoldIntToFPToInt(N
, DAG
);
12921 SDValue
DAGCombiner::visitFP_TO_UINT(SDNode
*N
) {
12922 SDValue N0
= N
->getOperand(0);
12923 EVT VT
= N
->getValueType(0);
12925 // fold (fp_to_uint undef) -> undef
12927 return DAG
.getUNDEF(VT
);
12929 // fold (fp_to_uint c1fp) -> c1
12930 if (isConstantFPBuildVectorOrConstantFP(N0
))
12931 return DAG
.getNode(ISD::FP_TO_UINT
, SDLoc(N
), VT
, N0
);
12933 return FoldIntToFPToInt(N
, DAG
);
12936 SDValue
DAGCombiner::visitFP_ROUND(SDNode
*N
) {
12937 SDValue N0
= N
->getOperand(0);
12938 SDValue N1
= N
->getOperand(1);
12939 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12940 EVT VT
= N
->getValueType(0);
12942 // fold (fp_round c1fp) -> c1fp
12944 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(N
), VT
, N0
, N1
);
12946 // fold (fp_round (fp_extend x)) -> x
12947 if (N0
.getOpcode() == ISD::FP_EXTEND
&& VT
== N0
.getOperand(0).getValueType())
12948 return N0
.getOperand(0);
12950 // fold (fp_round (fp_round x)) -> (fp_round x)
12951 if (N0
.getOpcode() == ISD::FP_ROUND
) {
12952 const bool NIsTrunc
= N
->getConstantOperandVal(1) == 1;
12953 const bool N0IsTrunc
= N0
.getConstantOperandVal(1) == 1;
12955 // Skip this folding if it results in an fp_round from f80 to f16.
12957 // f80 to f16 always generates an expensive (and as yet, unimplemented)
12958 // libcall to __truncxfhf2 instead of selecting native f16 conversion
12959 // instructions from f32 or f64. Moreover, the first (value-preserving)
12960 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
12962 if (N0
.getOperand(0).getValueType() == MVT::f80
&& VT
== MVT::f16
)
12965 // If the first fp_round isn't a value preserving truncation, it might
12966 // introduce a tie in the second fp_round, that wouldn't occur in the
12967 // single-step fp_round we want to fold to.
12968 // In other words, double rounding isn't the same as rounding.
12969 // Also, this is a value preserving truncation iff both fp_round's are.
12970 if (DAG
.getTarget().Options
.UnsafeFPMath
|| N0IsTrunc
) {
12972 return DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, N0
.getOperand(0),
12973 DAG
.getIntPtrConstant(NIsTrunc
&& N0IsTrunc
, DL
));
12977 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
12978 if (N0
.getOpcode() == ISD::FCOPYSIGN
&& N0
.getNode()->hasOneUse()) {
12979 SDValue Tmp
= DAG
.getNode(ISD::FP_ROUND
, SDLoc(N0
), VT
,
12980 N0
.getOperand(0), N1
);
12981 AddToWorklist(Tmp
.getNode());
12982 return DAG
.getNode(ISD::FCOPYSIGN
, SDLoc(N
), VT
,
12983 Tmp
, N0
.getOperand(1));
12986 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
12992 SDValue
DAGCombiner::visitFP_ROUND_INREG(SDNode
*N
) {
12993 SDValue N0
= N
->getOperand(0);
12994 EVT VT
= N
->getValueType(0);
12995 EVT EVT
= cast
<VTSDNode
>(N
->getOperand(1))->getVT();
12996 ConstantFPSDNode
*N0CFP
= dyn_cast
<ConstantFPSDNode
>(N0
);
12998 // fold (fp_round_inreg c1fp) -> c1fp
12999 if (N0CFP
&& isTypeLegal(EVT
)) {
13001 SDValue Round
= DAG
.getConstantFP(*N0CFP
->getConstantFPValue(), DL
, EVT
);
13002 return DAG
.getNode(ISD::FP_EXTEND
, DL
, VT
, Round
);
13008 SDValue
DAGCombiner::visitFP_EXTEND(SDNode
*N
) {
13009 SDValue N0
= N
->getOperand(0);
13010 EVT VT
= N
->getValueType(0);
13012 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
13013 if (N
->hasOneUse() &&
13014 N
->use_begin()->getOpcode() == ISD::FP_ROUND
)
13017 // fold (fp_extend c1fp) -> c1fp
13018 if (isConstantFPBuildVectorOrConstantFP(N0
))
13019 return DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N
), VT
, N0
);
13021 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
13022 if (N0
.getOpcode() == ISD::FP16_TO_FP
&&
13023 TLI
.getOperationAction(ISD::FP16_TO_FP
, VT
) == TargetLowering::Legal
)
13024 return DAG
.getNode(ISD::FP16_TO_FP
, SDLoc(N
), VT
, N0
.getOperand(0));
13026 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
13028 if (N0
.getOpcode() == ISD::FP_ROUND
13029 && N0
.getConstantOperandVal(1) == 1) {
13030 SDValue In
= N0
.getOperand(0);
13031 if (In
.getValueType() == VT
) return In
;
13032 if (VT
.bitsLT(In
.getValueType()))
13033 return DAG
.getNode(ISD::FP_ROUND
, SDLoc(N
), VT
,
13034 In
, N0
.getOperand(1));
13035 return DAG
.getNode(ISD::FP_EXTEND
, SDLoc(N
), VT
, In
);
13038 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
13039 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
13040 TLI
.isLoadExtLegal(ISD::EXTLOAD
, VT
, N0
.getValueType())) {
13041 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
13042 SDValue ExtLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, SDLoc(N
), VT
,
13044 LN0
->getBasePtr(), N0
.getValueType(),
13045 LN0
->getMemOperand());
13046 CombineTo(N
, ExtLoad
);
13047 CombineTo(N0
.getNode(),
13048 DAG
.getNode(ISD::FP_ROUND
, SDLoc(N0
),
13049 N0
.getValueType(), ExtLoad
,
13050 DAG
.getIntPtrConstant(1, SDLoc(N0
))),
13051 ExtLoad
.getValue(1));
13052 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
13055 if (SDValue NewVSel
= matchVSelectOpSizesWithSetCC(N
))
13061 SDValue
DAGCombiner::visitFCEIL(SDNode
*N
) {
13062 SDValue N0
= N
->getOperand(0);
13063 EVT VT
= N
->getValueType(0);
13065 // fold (fceil c1) -> fceil(c1)
13066 if (isConstantFPBuildVectorOrConstantFP(N0
))
13067 return DAG
.getNode(ISD::FCEIL
, SDLoc(N
), VT
, N0
);
13072 SDValue
DAGCombiner::visitFTRUNC(SDNode
*N
) {
13073 SDValue N0
= N
->getOperand(0);
13074 EVT VT
= N
->getValueType(0);
13076 // fold (ftrunc c1) -> ftrunc(c1)
13077 if (isConstantFPBuildVectorOrConstantFP(N0
))
13078 return DAG
.getNode(ISD::FTRUNC
, SDLoc(N
), VT
, N0
);
13080 // fold ftrunc (known rounded int x) -> x
13081 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
13082 // likely to be generated to extract integer from a rounded floating value.
13083 switch (N0
.getOpcode()) {
13087 case ISD::FNEARBYINT
:
13096 SDValue
DAGCombiner::visitFFLOOR(SDNode
*N
) {
13097 SDValue N0
= N
->getOperand(0);
13098 EVT VT
= N
->getValueType(0);
13100 // fold (ffloor c1) -> ffloor(c1)
13101 if (isConstantFPBuildVectorOrConstantFP(N0
))
13102 return DAG
.getNode(ISD::FFLOOR
, SDLoc(N
), VT
, N0
);
13107 // FIXME: FNEG and FABS have a lot in common; refactor.
13108 SDValue
DAGCombiner::visitFNEG(SDNode
*N
) {
13109 SDValue N0
= N
->getOperand(0);
13110 EVT VT
= N
->getValueType(0);
13112 // Constant fold FNEG.
13113 if (isConstantFPBuildVectorOrConstantFP(N0
))
13114 return DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, N0
);
13116 if (isNegatibleForFree(N0
, LegalOperations
, DAG
.getTargetLoweringInfo(),
13117 &DAG
.getTarget().Options
, ForCodeSize
))
13118 return GetNegatedExpression(N0
, DAG
, LegalOperations
, ForCodeSize
);
13120 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
13121 // constant pool values.
13122 if (!TLI
.isFNegFree(VT
) &&
13123 N0
.getOpcode() == ISD::BITCAST
&&
13124 N0
.getNode()->hasOneUse()) {
13125 SDValue Int
= N0
.getOperand(0);
13126 EVT IntVT
= Int
.getValueType();
13127 if (IntVT
.isInteger() && !IntVT
.isVector()) {
13129 if (N0
.getValueType().isVector()) {
13130 // For a vector, get a mask such as 0x80... per scalar element
13132 SignMask
= APInt::getSignMask(N0
.getScalarValueSizeInBits());
13133 SignMask
= APInt::getSplat(IntVT
.getSizeInBits(), SignMask
);
13135 // For a scalar, just generate 0x80...
13136 SignMask
= APInt::getSignMask(IntVT
.getSizeInBits());
13139 Int
= DAG
.getNode(ISD::XOR
, DL0
, IntVT
, Int
,
13140 DAG
.getConstant(SignMask
, DL0
, IntVT
));
13141 AddToWorklist(Int
.getNode());
13142 return DAG
.getBitcast(VT
, Int
);
13146 // (fneg (fmul c, x)) -> (fmul -c, x)
13147 if (N0
.getOpcode() == ISD::FMUL
&&
13148 (N0
.getNode()->hasOneUse() || !TLI
.isFNegFree(VT
))) {
13149 ConstantFPSDNode
*CFP1
= dyn_cast
<ConstantFPSDNode
>(N0
.getOperand(1));
13151 APFloat CVal
= CFP1
->getValueAPF();
13153 if (Level
>= AfterLegalizeDAG
&&
13154 (TLI
.isFPImmLegal(CVal
, VT
, ForCodeSize
) ||
13155 TLI
.isOperationLegal(ISD::ConstantFP
, VT
)))
13156 return DAG
.getNode(
13157 ISD::FMUL
, SDLoc(N
), VT
, N0
.getOperand(0),
13158 DAG
.getNode(ISD::FNEG
, SDLoc(N
), VT
, N0
.getOperand(1)),
13166 static SDValue
visitFMinMax(SelectionDAG
&DAG
, SDNode
*N
,
13167 APFloat (*Op
)(const APFloat
&, const APFloat
&)) {
13168 SDValue N0
= N
->getOperand(0);
13169 SDValue N1
= N
->getOperand(1);
13170 EVT VT
= N
->getValueType(0);
13171 const ConstantFPSDNode
*N0CFP
= isConstOrConstSplatFP(N0
);
13172 const ConstantFPSDNode
*N1CFP
= isConstOrConstSplatFP(N1
);
13174 if (N0CFP
&& N1CFP
) {
13175 const APFloat
&C0
= N0CFP
->getValueAPF();
13176 const APFloat
&C1
= N1CFP
->getValueAPF();
13177 return DAG
.getConstantFP(Op(C0
, C1
), SDLoc(N
), VT
);
13180 // Canonicalize to constant on RHS.
13181 if (isConstantFPBuildVectorOrConstantFP(N0
) &&
13182 !isConstantFPBuildVectorOrConstantFP(N1
))
13183 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, N1
, N0
);
13188 SDValue
DAGCombiner::visitFMINNUM(SDNode
*N
) {
13189 return visitFMinMax(DAG
, N
, minnum
);
13192 SDValue
DAGCombiner::visitFMAXNUM(SDNode
*N
) {
13193 return visitFMinMax(DAG
, N
, maxnum
);
13196 SDValue
DAGCombiner::visitFMINIMUM(SDNode
*N
) {
13197 return visitFMinMax(DAG
, N
, minimum
);
13200 SDValue
DAGCombiner::visitFMAXIMUM(SDNode
*N
) {
13201 return visitFMinMax(DAG
, N
, maximum
);
13204 SDValue
DAGCombiner::visitFABS(SDNode
*N
) {
13205 SDValue N0
= N
->getOperand(0);
13206 EVT VT
= N
->getValueType(0);
13208 // fold (fabs c1) -> fabs(c1)
13209 if (isConstantFPBuildVectorOrConstantFP(N0
))
13210 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
);
13212 // fold (fabs (fabs x)) -> (fabs x)
13213 if (N0
.getOpcode() == ISD::FABS
)
13214 return N
->getOperand(0);
13216 // fold (fabs (fneg x)) -> (fabs x)
13217 // fold (fabs (fcopysign x, y)) -> (fabs x)
13218 if (N0
.getOpcode() == ISD::FNEG
|| N0
.getOpcode() == ISD::FCOPYSIGN
)
13219 return DAG
.getNode(ISD::FABS
, SDLoc(N
), VT
, N0
.getOperand(0));
13221 // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads.
13222 if (!TLI
.isFAbsFree(VT
) && N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse()) {
13223 SDValue Int
= N0
.getOperand(0);
13224 EVT IntVT
= Int
.getValueType();
13225 if (IntVT
.isInteger() && !IntVT
.isVector()) {
13227 if (N0
.getValueType().isVector()) {
13228 // For a vector, get a mask such as 0x7f... per scalar element
13230 SignMask
= ~APInt::getSignMask(N0
.getScalarValueSizeInBits());
13231 SignMask
= APInt::getSplat(IntVT
.getSizeInBits(), SignMask
);
13233 // For a scalar, just generate 0x7f...
13234 SignMask
= ~APInt::getSignMask(IntVT
.getSizeInBits());
13237 Int
= DAG
.getNode(ISD::AND
, DL
, IntVT
, Int
,
13238 DAG
.getConstant(SignMask
, DL
, IntVT
));
13239 AddToWorklist(Int
.getNode());
13240 return DAG
.getBitcast(N
->getValueType(0), Int
);
13247 SDValue
DAGCombiner::visitBRCOND(SDNode
*N
) {
13248 SDValue Chain
= N
->getOperand(0);
13249 SDValue N1
= N
->getOperand(1);
13250 SDValue N2
= N
->getOperand(2);
13252 // If N is a constant we could fold this into a fallthrough or unconditional
13253 // branch. However that doesn't happen very often in normal code, because
13254 // Instcombine/SimplifyCFG should have handled the available opportunities.
13255 // If we did this folding here, it would be necessary to update the
13256 // MachineBasicBlock CFG, which is awkward.
13258 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
13260 if (N1
.getOpcode() == ISD::SETCC
&&
13261 TLI
.isOperationLegalOrCustom(ISD::BR_CC
,
13262 N1
.getOperand(0).getValueType())) {
13263 return DAG
.getNode(ISD::BR_CC
, SDLoc(N
), MVT::Other
,
13264 Chain
, N1
.getOperand(2),
13265 N1
.getOperand(0), N1
.getOperand(1), N2
);
13268 if (N1
.hasOneUse()) {
13269 if (SDValue NewN1
= rebuildSetCC(N1
))
13270 return DAG
.getNode(ISD::BRCOND
, SDLoc(N
), MVT::Other
, Chain
, NewN1
, N2
);
13276 SDValue
DAGCombiner::rebuildSetCC(SDValue N
) {
13277 if (N
.getOpcode() == ISD::SRL
||
13278 (N
.getOpcode() == ISD::TRUNCATE
&&
13279 (N
.getOperand(0).hasOneUse() &&
13280 N
.getOperand(0).getOpcode() == ISD::SRL
))) {
13281 // Look pass the truncate.
13282 if (N
.getOpcode() == ISD::TRUNCATE
)
13283 N
= N
.getOperand(0);
13285 // Match this pattern so that we can generate simpler code:
13288 // %b = and i32 %a, 2
13289 // %c = srl i32 %b, 1
13290 // brcond i32 %c ...
13295 // %b = and i32 %a, 2
13296 // %c = setcc eq %b, 0
13299 // This applies only when the AND constant value has one bit set and the
13300 // SRL constant is equal to the log2 of the AND constant. The back-end is
13301 // smart enough to convert the result into a TEST/JMP sequence.
13302 SDValue Op0
= N
.getOperand(0);
13303 SDValue Op1
= N
.getOperand(1);
13305 if (Op0
.getOpcode() == ISD::AND
&& Op1
.getOpcode() == ISD::Constant
) {
13306 SDValue AndOp1
= Op0
.getOperand(1);
13308 if (AndOp1
.getOpcode() == ISD::Constant
) {
13309 const APInt
&AndConst
= cast
<ConstantSDNode
>(AndOp1
)->getAPIntValue();
13311 if (AndConst
.isPowerOf2() &&
13312 cast
<ConstantSDNode
>(Op1
)->getAPIntValue() == AndConst
.logBase2()) {
13314 return DAG
.getSetCC(DL
, getSetCCResultType(Op0
.getValueType()),
13315 Op0
, DAG
.getConstant(0, DL
, Op0
.getValueType()),
13322 // Transform br(xor(x, y)) -> br(x != y)
13323 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
13324 if (N
.getOpcode() == ISD::XOR
) {
13325 // Because we may call this on a speculatively constructed
13326 // SimplifiedSetCC Node, we need to simplify this node first.
13327 // Ideally this should be folded into SimplifySetCC and not
13328 // here. For now, grab a handle to N so we don't lose it from
13329 // replacements interal to the visit.
13330 HandleSDNode
XORHandle(N
);
13331 while (N
.getOpcode() == ISD::XOR
) {
13332 SDValue Tmp
= visitXOR(N
.getNode());
13333 // No simplification done.
13334 if (!Tmp
.getNode())
13336 // Returning N is form in-visit replacement that may invalidated
13337 // N. Grab value from Handle.
13338 if (Tmp
.getNode() == N
.getNode())
13339 N
= XORHandle
.getValue();
13340 else // Node simplified. Try simplifying again.
13344 if (N
.getOpcode() != ISD::XOR
)
13347 SDNode
*TheXor
= N
.getNode();
13349 SDValue Op0
= TheXor
->getOperand(0);
13350 SDValue Op1
= TheXor
->getOperand(1);
13352 if (Op0
.getOpcode() != ISD::SETCC
&& Op1
.getOpcode() != ISD::SETCC
) {
13353 bool Equal
= false;
13354 if (isOneConstant(Op0
) && Op0
.hasOneUse() &&
13355 Op0
.getOpcode() == ISD::XOR
) {
13356 TheXor
= Op0
.getNode();
13360 EVT SetCCVT
= N
.getValueType();
13362 SetCCVT
= getSetCCResultType(SetCCVT
);
13363 // Replace the uses of XOR with SETCC
13364 return DAG
.getSetCC(SDLoc(TheXor
), SetCCVT
, Op0
, Op1
,
13365 Equal
? ISD::SETEQ
: ISD::SETNE
);
13372 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
13374 SDValue
DAGCombiner::visitBR_CC(SDNode
*N
) {
13375 CondCodeSDNode
*CC
= cast
<CondCodeSDNode
>(N
->getOperand(1));
13376 SDValue CondLHS
= N
->getOperand(2), CondRHS
= N
->getOperand(3);
13378 // If N is a constant we could fold this into a fallthrough or unconditional
13379 // branch. However that doesn't happen very often in normal code, because
13380 // Instcombine/SimplifyCFG should have handled the available opportunities.
13381 // If we did this folding here, it would be necessary to update the
13382 // MachineBasicBlock CFG, which is awkward.
13384 // Use SimplifySetCC to simplify SETCC's.
13385 SDValue Simp
= SimplifySetCC(getSetCCResultType(CondLHS
.getValueType()),
13386 CondLHS
, CondRHS
, CC
->get(), SDLoc(N
),
13388 if (Simp
.getNode()) AddToWorklist(Simp
.getNode());
13390 // fold to a simpler setcc
13391 if (Simp
.getNode() && Simp
.getOpcode() == ISD::SETCC
)
13392 return DAG
.getNode(ISD::BR_CC
, SDLoc(N
), MVT::Other
,
13393 N
->getOperand(0), Simp
.getOperand(2),
13394 Simp
.getOperand(0), Simp
.getOperand(1),
13400 /// Return true if 'Use' is a load or a store that uses N as its base pointer
13401 /// and that N may be folded in the load / store addressing mode.
13402 static bool canFoldInAddressingMode(SDNode
*N
, SDNode
*Use
,
13404 const TargetLowering
&TLI
) {
13408 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(Use
)) {
13409 if (LD
->isIndexed() || LD
->getBasePtr().getNode() != N
)
13411 VT
= LD
->getMemoryVT();
13412 AS
= LD
->getAddressSpace();
13413 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Use
)) {
13414 if (ST
->isIndexed() || ST
->getBasePtr().getNode() != N
)
13416 VT
= ST
->getMemoryVT();
13417 AS
= ST
->getAddressSpace();
13421 TargetLowering::AddrMode AM
;
13422 if (N
->getOpcode() == ISD::ADD
) {
13423 AM
.HasBaseReg
= true;
13424 ConstantSDNode
*Offset
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
13427 AM
.BaseOffs
= Offset
->getSExtValue();
13431 } else if (N
->getOpcode() == ISD::SUB
) {
13432 AM
.HasBaseReg
= true;
13433 ConstantSDNode
*Offset
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
13436 AM
.BaseOffs
= -Offset
->getSExtValue();
13443 return TLI
.isLegalAddressingMode(DAG
.getDataLayout(), AM
,
13444 VT
.getTypeForEVT(*DAG
.getContext()), AS
);
13447 /// Try turning a load/store into a pre-indexed load/store when the base
13448 /// pointer is an add or subtract and it has other uses besides the load/store.
13449 /// After the transformation, the new indexed load/store has effectively folded
13450 /// the add/subtract in and all of its other uses are redirected to the
13451 /// new load/store.
13452 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode
*N
) {
13453 if (Level
< AfterLegalizeDAG
)
13456 bool isLoad
= true;
13459 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
13460 if (LD
->isIndexed())
13462 VT
= LD
->getMemoryVT();
13463 if (!TLI
.isIndexedLoadLegal(ISD::PRE_INC
, VT
) &&
13464 !TLI
.isIndexedLoadLegal(ISD::PRE_DEC
, VT
))
13466 Ptr
= LD
->getBasePtr();
13467 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
13468 if (ST
->isIndexed())
13470 VT
= ST
->getMemoryVT();
13471 if (!TLI
.isIndexedStoreLegal(ISD::PRE_INC
, VT
) &&
13472 !TLI
.isIndexedStoreLegal(ISD::PRE_DEC
, VT
))
13474 Ptr
= ST
->getBasePtr();
13480 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
13481 // out. There is no reason to make this a preinc/predec.
13482 if ((Ptr
.getOpcode() != ISD::ADD
&& Ptr
.getOpcode() != ISD::SUB
) ||
13483 Ptr
.getNode()->hasOneUse())
13486 // Ask the target to do addressing mode selection.
13489 ISD::MemIndexedMode AM
= ISD::UNINDEXED
;
13490 if (!TLI
.getPreIndexedAddressParts(N
, BasePtr
, Offset
, AM
, DAG
))
13493 // Backends without true r+i pre-indexed forms may need to pass a
13494 // constant base with a variable offset so that constant coercion
13495 // will work with the patterns in canonical form.
13496 bool Swapped
= false;
13497 if (isa
<ConstantSDNode
>(BasePtr
)) {
13498 std::swap(BasePtr
, Offset
);
13502 // Don't create a indexed load / store with zero offset.
13503 if (isNullConstant(Offset
))
13506 // Try turning it into a pre-indexed load / store except when:
13507 // 1) The new base ptr is a frame index.
13508 // 2) If N is a store and the new base ptr is either the same as or is a
13509 // predecessor of the value being stored.
13510 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
13511 // that would create a cycle.
13512 // 4) All uses are load / store ops that use it as old base ptr.
13514 // Check #1. Preinc'ing a frame index would require copying the stack pointer
13515 // (plus the implicit offset) to a register to preinc anyway.
13516 if (isa
<FrameIndexSDNode
>(BasePtr
) || isa
<RegisterSDNode
>(BasePtr
))
13521 SDValue Val
= cast
<StoreSDNode
>(N
)->getValue();
13523 // Would require a copy.
13524 if (Val
== BasePtr
)
13527 // Would create a cycle.
13528 if (Val
== Ptr
|| Ptr
->isPredecessorOf(Val
.getNode()))
13532 // Caches for hasPredecessorHelper.
13533 SmallPtrSet
<const SDNode
*, 32> Visited
;
13534 SmallVector
<const SDNode
*, 16> Worklist
;
13535 Worklist
.push_back(N
);
13537 // If the offset is a constant, there may be other adds of constants that
13538 // can be folded with this one. We should do this to avoid having to keep
13539 // a copy of the original base pointer.
13540 SmallVector
<SDNode
*, 16> OtherUses
;
13541 if (isa
<ConstantSDNode
>(Offset
))
13542 for (SDNode::use_iterator UI
= BasePtr
.getNode()->use_begin(),
13543 UE
= BasePtr
.getNode()->use_end();
13545 SDUse
&Use
= UI
.getUse();
13546 // Skip the use that is Ptr and uses of other results from BasePtr's
13547 // node (important for nodes that return multiple results).
13548 if (Use
.getUser() == Ptr
.getNode() || Use
!= BasePtr
)
13551 if (SDNode::hasPredecessorHelper(Use
.getUser(), Visited
, Worklist
))
13554 if (Use
.getUser()->getOpcode() != ISD::ADD
&&
13555 Use
.getUser()->getOpcode() != ISD::SUB
) {
13560 SDValue Op1
= Use
.getUser()->getOperand((UI
.getOperandNo() + 1) & 1);
13561 if (!isa
<ConstantSDNode
>(Op1
)) {
13566 // FIXME: In some cases, we can be smarter about this.
13567 if (Op1
.getValueType() != Offset
.getValueType()) {
13572 OtherUses
.push_back(Use
.getUser());
13576 std::swap(BasePtr
, Offset
);
13578 // Now check for #3 and #4.
13579 bool RealUse
= false;
13581 for (SDNode
*Use
: Ptr
.getNode()->uses()) {
13584 if (SDNode::hasPredecessorHelper(Use
, Visited
, Worklist
))
13587 // If Ptr may be folded in addressing mode of other use, then it's
13588 // not profitable to do this transformation.
13589 if (!canFoldInAddressingMode(Ptr
.getNode(), Use
, DAG
, TLI
))
13598 Result
= DAG
.getIndexedLoad(SDValue(N
,0), SDLoc(N
),
13599 BasePtr
, Offset
, AM
);
13601 Result
= DAG
.getIndexedStore(SDValue(N
,0), SDLoc(N
),
13602 BasePtr
, Offset
, AM
);
13605 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N
->dump(&DAG
); dbgs() << "\nWith: ";
13606 Result
.getNode()->dump(&DAG
); dbgs() << '\n');
13607 WorklistRemover
DeadNodes(*this);
13609 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(0));
13610 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Result
.getValue(2));
13612 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(1));
13615 // Finally, since the node is now dead, remove it from the graph.
13616 deleteAndRecombine(N
);
13619 std::swap(BasePtr
, Offset
);
13621 // Replace other uses of BasePtr that can be updated to use Ptr
13622 for (unsigned i
= 0, e
= OtherUses
.size(); i
!= e
; ++i
) {
13623 unsigned OffsetIdx
= 1;
13624 if (OtherUses
[i
]->getOperand(OffsetIdx
).getNode() == BasePtr
.getNode())
13626 assert(OtherUses
[i
]->getOperand(!OffsetIdx
).getNode() ==
13627 BasePtr
.getNode() && "Expected BasePtr operand");
13629 // We need to replace ptr0 in the following expression:
13630 // x0 * offset0 + y0 * ptr0 = t0
13632 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
13634 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
13635 // indexed load/store and the expression that needs to be re-written.
13637 // Therefore, we have:
13638 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
13640 ConstantSDNode
*CN
=
13641 cast
<ConstantSDNode
>(OtherUses
[i
]->getOperand(OffsetIdx
));
13642 int X0
, X1
, Y0
, Y1
;
13643 const APInt
&Offset0
= CN
->getAPIntValue();
13644 APInt Offset1
= cast
<ConstantSDNode
>(Offset
)->getAPIntValue();
13646 X0
= (OtherUses
[i
]->getOpcode() == ISD::SUB
&& OffsetIdx
== 1) ? -1 : 1;
13647 Y0
= (OtherUses
[i
]->getOpcode() == ISD::SUB
&& OffsetIdx
== 0) ? -1 : 1;
13648 X1
= (AM
== ISD::PRE_DEC
&& !Swapped
) ? -1 : 1;
13649 Y1
= (AM
== ISD::PRE_DEC
&& Swapped
) ? -1 : 1;
13651 unsigned Opcode
= (Y0
* Y1
< 0) ? ISD::SUB
: ISD::ADD
;
13653 APInt CNV
= Offset0
;
13654 if (X0
< 0) CNV
= -CNV
;
13655 if (X1
* Y0
* Y1
< 0) CNV
= CNV
+ Offset1
;
13656 else CNV
= CNV
- Offset1
;
13658 SDLoc
DL(OtherUses
[i
]);
13660 // We can now generate the new expression.
13661 SDValue NewOp1
= DAG
.getConstant(CNV
, DL
, CN
->getValueType(0));
13662 SDValue NewOp2
= Result
.getValue(isLoad
? 1 : 0);
13664 SDValue NewUse
= DAG
.getNode(Opcode
,
13666 OtherUses
[i
]->getValueType(0), NewOp1
, NewOp2
);
13667 DAG
.ReplaceAllUsesOfValueWith(SDValue(OtherUses
[i
], 0), NewUse
);
13668 deleteAndRecombine(OtherUses
[i
]);
13671 // Replace the uses of Ptr with uses of the updated base value.
13672 DAG
.ReplaceAllUsesOfValueWith(Ptr
, Result
.getValue(isLoad
? 1 : 0));
13673 deleteAndRecombine(Ptr
.getNode());
13674 AddToWorklist(Result
.getNode());
13679 /// Try to combine a load/store with a add/sub of the base pointer node into a
13680 /// post-indexed load/store. The transformation folded the add/subtract into the
13681 /// new indexed load/store effectively and all of its uses are redirected to the
13682 /// new load/store.
13683 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode
*N
) {
13684 if (Level
< AfterLegalizeDAG
)
13687 bool isLoad
= true;
13690 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
13691 if (LD
->isIndexed())
13693 VT
= LD
->getMemoryVT();
13694 if (!TLI
.isIndexedLoadLegal(ISD::POST_INC
, VT
) &&
13695 !TLI
.isIndexedLoadLegal(ISD::POST_DEC
, VT
))
13697 Ptr
= LD
->getBasePtr();
13698 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
13699 if (ST
->isIndexed())
13701 VT
= ST
->getMemoryVT();
13702 if (!TLI
.isIndexedStoreLegal(ISD::POST_INC
, VT
) &&
13703 !TLI
.isIndexedStoreLegal(ISD::POST_DEC
, VT
))
13705 Ptr
= ST
->getBasePtr();
13711 if (Ptr
.getNode()->hasOneUse())
13714 for (SDNode
*Op
: Ptr
.getNode()->uses()) {
13716 (Op
->getOpcode() != ISD::ADD
&& Op
->getOpcode() != ISD::SUB
))
13721 ISD::MemIndexedMode AM
= ISD::UNINDEXED
;
13722 if (TLI
.getPostIndexedAddressParts(N
, Op
, BasePtr
, Offset
, AM
, DAG
)) {
13723 // Don't create a indexed load / store with zero offset.
13724 if (isNullConstant(Offset
))
13727 // Try turning it into a post-indexed load / store except when
13728 // 1) All uses are load / store ops that use it as base ptr (and
13729 // it may be folded as addressing mmode).
13730 // 2) Op must be independent of N, i.e. Op is neither a predecessor
13731 // nor a successor of N. Otherwise, if Op is folded that would
13734 if (isa
<FrameIndexSDNode
>(BasePtr
) || isa
<RegisterSDNode
>(BasePtr
))
13738 bool TryNext
= false;
13739 for (SDNode
*Use
: BasePtr
.getNode()->uses()) {
13740 if (Use
== Ptr
.getNode())
13743 // If all the uses are load / store addresses, then don't do the
13745 if (Use
->getOpcode() == ISD::ADD
|| Use
->getOpcode() == ISD::SUB
){
13746 bool RealUse
= false;
13747 for (SDNode
*UseUse
: Use
->uses()) {
13748 if (!canFoldInAddressingMode(Use
, UseUse
, DAG
, TLI
))
13763 SmallPtrSet
<const SDNode
*, 32> Visited
;
13764 SmallVector
<const SDNode
*, 8> Worklist
;
13765 // Ptr is predecessor to both N and Op.
13766 Visited
.insert(Ptr
.getNode());
13767 Worklist
.push_back(N
);
13768 Worklist
.push_back(Op
);
13769 if (!SDNode::hasPredecessorHelper(N
, Visited
, Worklist
) &&
13770 !SDNode::hasPredecessorHelper(Op
, Visited
, Worklist
)) {
13771 SDValue Result
= isLoad
13772 ? DAG
.getIndexedLoad(SDValue(N
,0), SDLoc(N
),
13773 BasePtr
, Offset
, AM
)
13774 : DAG
.getIndexedStore(SDValue(N
,0), SDLoc(N
),
13775 BasePtr
, Offset
, AM
);
13776 ++PostIndexedNodes
;
13778 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N
->dump(&DAG
);
13779 dbgs() << "\nWith: "; Result
.getNode()->dump(&DAG
);
13781 WorklistRemover
DeadNodes(*this);
13783 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(0));
13784 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Result
.getValue(2));
13786 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Result
.getValue(1));
13789 // Finally, since the node is now dead, remove it from the graph.
13790 deleteAndRecombine(N
);
13792 // Replace the uses of Use with uses of the updated base value.
13793 DAG
.ReplaceAllUsesOfValueWith(SDValue(Op
, 0),
13794 Result
.getValue(isLoad
? 1 : 0));
13795 deleteAndRecombine(Op
);
13804 /// Return the base-pointer arithmetic from an indexed \p LD.
13805 SDValue
DAGCombiner::SplitIndexingFromLoad(LoadSDNode
*LD
) {
13806 ISD::MemIndexedMode AM
= LD
->getAddressingMode();
13807 assert(AM
!= ISD::UNINDEXED
);
13808 SDValue BP
= LD
->getOperand(1);
13809 SDValue Inc
= LD
->getOperand(2);
13811 // Some backends use TargetConstants for load offsets, but don't expect
13812 // TargetConstants in general ADD nodes. We can convert these constants into
13813 // regular Constants (if the constant is not opaque).
13814 assert((Inc
.getOpcode() != ISD::TargetConstant
||
13815 !cast
<ConstantSDNode
>(Inc
)->isOpaque()) &&
13816 "Cannot split out indexing using opaque target constants");
13817 if (Inc
.getOpcode() == ISD::TargetConstant
) {
13818 ConstantSDNode
*ConstInc
= cast
<ConstantSDNode
>(Inc
);
13819 Inc
= DAG
.getConstant(*ConstInc
->getConstantIntValue(), SDLoc(Inc
),
13820 ConstInc
->getValueType(0));
13824 (AM
== ISD::PRE_INC
|| AM
== ISD::POST_INC
? ISD::ADD
: ISD::SUB
);
13825 return DAG
.getNode(Opc
, SDLoc(LD
), BP
.getSimpleValueType(), BP
, Inc
);
13828 static inline int numVectorEltsOrZero(EVT T
) {
13829 return T
.isVector() ? T
.getVectorNumElements() : 0;
13832 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode
*ST
, SDValue
&Val
) {
13833 Val
= ST
->getValue();
13834 EVT STType
= Val
.getValueType();
13835 EVT STMemType
= ST
->getMemoryVT();
13836 if (STType
== STMemType
)
13838 if (isTypeLegal(STMemType
))
13839 return false; // fail.
13840 if (STType
.isFloatingPoint() && STMemType
.isFloatingPoint() &&
13841 TLI
.isOperationLegal(ISD::FTRUNC
, STMemType
)) {
13842 Val
= DAG
.getNode(ISD::FTRUNC
, SDLoc(ST
), STMemType
, Val
);
13845 if (numVectorEltsOrZero(STType
) == numVectorEltsOrZero(STMemType
) &&
13846 STType
.isInteger() && STMemType
.isInteger()) {
13847 Val
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(ST
), STMemType
, Val
);
13850 if (STType
.getSizeInBits() == STMemType
.getSizeInBits()) {
13851 Val
= DAG
.getBitcast(STMemType
, Val
);
13854 return false; // fail.
13857 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode
*LD
, SDValue
&Val
) {
13858 EVT LDMemType
= LD
->getMemoryVT();
13859 EVT LDType
= LD
->getValueType(0);
13860 assert(Val
.getValueType() == LDMemType
&&
13861 "Attempting to extend value of non-matching type");
13862 if (LDType
== LDMemType
)
13864 if (LDMemType
.isInteger() && LDType
.isInteger()) {
13865 switch (LD
->getExtensionType()) {
13866 case ISD::NON_EXTLOAD
:
13867 Val
= DAG
.getBitcast(LDType
, Val
);
13870 Val
= DAG
.getNode(ISD::ANY_EXTEND
, SDLoc(LD
), LDType
, Val
);
13872 case ISD::SEXTLOAD
:
13873 Val
= DAG
.getNode(ISD::SIGN_EXTEND
, SDLoc(LD
), LDType
, Val
);
13875 case ISD::ZEXTLOAD
:
13876 Val
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(LD
), LDType
, Val
);
13883 SDValue
DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode
*LD
) {
13884 if (OptLevel
== CodeGenOpt::None
|| LD
->isVolatile())
13886 SDValue Chain
= LD
->getOperand(0);
13887 StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Chain
.getNode());
13888 if (!ST
|| ST
->isVolatile())
13891 EVT LDType
= LD
->getValueType(0);
13892 EVT LDMemType
= LD
->getMemoryVT();
13893 EVT STMemType
= ST
->getMemoryVT();
13894 EVT STType
= ST
->getValue().getValueType();
13896 BaseIndexOffset BasePtrLD
= BaseIndexOffset::match(LD
, DAG
);
13897 BaseIndexOffset BasePtrST
= BaseIndexOffset::match(ST
, DAG
);
13899 if (!BasePtrST
.equalBaseIndex(BasePtrLD
, DAG
, Offset
))
13902 // Normalize for Endianness. After this Offset=0 will denote that the least
13903 // significant bit in the loaded value maps to the least significant bit in
13904 // the stored value). With Offset=n (for n > 0) the loaded value starts at the
13905 // n:th least significant byte of the stored value.
13906 if (DAG
.getDataLayout().isBigEndian())
13907 Offset
= (STMemType
.getStoreSizeInBits() -
13908 LDMemType
.getStoreSizeInBits()) / 8 - Offset
;
13910 // Check that the stored value cover all bits that are loaded.
13913 (Offset
* 8 + LDMemType
.getSizeInBits() <= STMemType
.getSizeInBits());
13915 auto ReplaceLd
= [&](LoadSDNode
*LD
, SDValue Val
, SDValue Chain
) -> SDValue
{
13916 if (LD
->isIndexed()) {
13917 bool IsSub
= (LD
->getAddressingMode() == ISD::PRE_DEC
||
13918 LD
->getAddressingMode() == ISD::POST_DEC
);
13919 unsigned Opc
= IsSub
? ISD::SUB
: ISD::ADD
;
13920 SDValue Idx
= DAG
.getNode(Opc
, SDLoc(LD
), LD
->getOperand(1).getValueType(),
13921 LD
->getOperand(1), LD
->getOperand(2));
13922 SDValue Ops
[] = {Val
, Idx
, Chain
};
13923 return CombineTo(LD
, Ops
, 3);
13925 return CombineTo(LD
, Val
, Chain
);
13931 // Memory as copy space (potentially masked).
13932 if (Offset
== 0 && LDType
== STType
&& STMemType
== LDMemType
) {
13933 // Simple case: Direct non-truncating forwarding
13934 if (LDType
.getSizeInBits() == LDMemType
.getSizeInBits())
13935 return ReplaceLd(LD
, ST
->getValue(), Chain
);
13936 // Can we model the truncate and extension with an and mask?
13937 if (STType
.isInteger() && LDMemType
.isInteger() && !STType
.isVector() &&
13938 !LDMemType
.isVector() && LD
->getExtensionType() != ISD::SEXTLOAD
) {
13939 // Mask to size of LDMemType
13941 DAG
.getConstant(APInt::getLowBitsSet(STType
.getSizeInBits(),
13942 STMemType
.getSizeInBits()),
13943 SDLoc(ST
), STType
);
13944 auto Val
= DAG
.getNode(ISD::AND
, SDLoc(LD
), LDType
, ST
->getValue(), Mask
);
13945 return ReplaceLd(LD
, Val
, Chain
);
13949 // TODO: Deal with nonzero offset.
13950 if (LD
->getBasePtr().isUndef() || Offset
!= 0)
13952 // Model necessary truncations / extenstions.
13954 // Truncate Value To Stored Memory Size.
13956 if (!getTruncatedStoreValue(ST
, Val
))
13958 if (!isTypeLegal(LDMemType
))
13960 if (STMemType
!= LDMemType
) {
13961 // TODO: Support vectors? This requires extract_subvector/bitcast.
13962 if (!STMemType
.isVector() && !LDMemType
.isVector() &&
13963 STMemType
.isInteger() && LDMemType
.isInteger())
13964 Val
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(LD
), LDMemType
, Val
);
13968 if (!extendLoadedValueToExtension(LD
, Val
))
13970 return ReplaceLd(LD
, Val
, Chain
);
13973 // On failure, cleanup dead nodes we may have created.
13974 if (Val
->use_empty())
13975 deleteAndRecombine(Val
.getNode());
13979 SDValue
DAGCombiner::visitLOAD(SDNode
*N
) {
13980 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
13981 SDValue Chain
= LD
->getChain();
13982 SDValue Ptr
= LD
->getBasePtr();
13984 // If load is not volatile and there are no uses of the loaded value (and
13985 // the updated indexed value in case of indexed loads), change uses of the
13986 // chain value into uses of the chain input (i.e. delete the dead load).
13987 if (!LD
->isVolatile()) {
13988 if (N
->getValueType(1) == MVT::Other
) {
13989 // Unindexed loads.
13990 if (!N
->hasAnyUseOfValue(0)) {
13991 // It's not safe to use the two value CombineTo variant here. e.g.
13992 // v1, chain2 = load chain1, loc
13993 // v2, chain3 = load chain2, loc
13995 // Now we replace use of chain2 with chain1. This makes the second load
13996 // isomorphic to the one we are deleting, and thus makes this load live.
13997 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N
->dump(&DAG
);
13998 dbgs() << "\nWith chain: "; Chain
.getNode()->dump(&DAG
);
14000 WorklistRemover
DeadNodes(*this);
14001 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Chain
);
14002 AddUsersToWorklist(Chain
.getNode());
14003 if (N
->use_empty())
14004 deleteAndRecombine(N
);
14006 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
14010 assert(N
->getValueType(2) == MVT::Other
&& "Malformed indexed loads?");
14012 // If this load has an opaque TargetConstant offset, then we cannot split
14013 // the indexing into an add/sub directly (that TargetConstant may not be
14014 // valid for a different type of node, and we cannot convert an opaque
14015 // target constant into a regular constant).
14016 bool HasOTCInc
= LD
->getOperand(2).getOpcode() == ISD::TargetConstant
&&
14017 cast
<ConstantSDNode
>(LD
->getOperand(2))->isOpaque();
14019 if (!N
->hasAnyUseOfValue(0) &&
14020 ((MaySplitLoadIndex
&& !HasOTCInc
) || !N
->hasAnyUseOfValue(1))) {
14021 SDValue Undef
= DAG
.getUNDEF(N
->getValueType(0));
14023 if (N
->hasAnyUseOfValue(1) && MaySplitLoadIndex
&& !HasOTCInc
) {
14024 Index
= SplitIndexingFromLoad(LD
);
14025 // Try to fold the base pointer arithmetic into subsequent loads and
14027 AddUsersToWorklist(N
);
14029 Index
= DAG
.getUNDEF(N
->getValueType(1));
14030 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N
->dump(&DAG
);
14031 dbgs() << "\nWith: "; Undef
.getNode()->dump(&DAG
);
14032 dbgs() << " and 2 other values\n");
14033 WorklistRemover
DeadNodes(*this);
14034 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 0), Undef
);
14035 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Index
);
14036 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 2), Chain
);
14037 deleteAndRecombine(N
);
14038 return SDValue(N
, 0); // Return N so it doesn't get rechecked!
14043 // If this load is directly stored, replace the load value with the stored
14045 if (auto V
= ForwardStoreValueToDirectLoad(LD
))
14048 // Try to infer better alignment information than the load already has.
14049 if (OptLevel
!= CodeGenOpt::None
&& LD
->isUnindexed()) {
14050 if (unsigned Align
= DAG
.InferPtrAlignment(Ptr
)) {
14051 if (Align
> LD
->getAlignment() && LD
->getSrcValueOffset() % Align
== 0) {
14052 SDValue NewLoad
= DAG
.getExtLoad(
14053 LD
->getExtensionType(), SDLoc(N
), LD
->getValueType(0), Chain
, Ptr
,
14054 LD
->getPointerInfo(), LD
->getMemoryVT(), Align
,
14055 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
14056 // NewLoad will always be N as we are only refining the alignment
14057 assert(NewLoad
.getNode() == N
);
14063 if (LD
->isUnindexed()) {
14064 // Walk up chain skipping non-aliasing memory nodes.
14065 SDValue BetterChain
= FindBetterChain(LD
, Chain
);
14067 // If there is a better chain.
14068 if (Chain
!= BetterChain
) {
14071 // Replace the chain to void dependency.
14072 if (LD
->getExtensionType() == ISD::NON_EXTLOAD
) {
14073 ReplLoad
= DAG
.getLoad(N
->getValueType(0), SDLoc(LD
),
14074 BetterChain
, Ptr
, LD
->getMemOperand());
14076 ReplLoad
= DAG
.getExtLoad(LD
->getExtensionType(), SDLoc(LD
),
14077 LD
->getValueType(0),
14078 BetterChain
, Ptr
, LD
->getMemoryVT(),
14079 LD
->getMemOperand());
14082 // Create token factor to keep old chain connected.
14083 SDValue Token
= DAG
.getNode(ISD::TokenFactor
, SDLoc(N
),
14084 MVT::Other
, Chain
, ReplLoad
.getValue(1));
14086 // Replace uses with load result and token factor
14087 return CombineTo(N
, ReplLoad
.getValue(0), Token
);
14091 // Try transforming N to an indexed load.
14092 if (CombineToPreIndexedLoadStore(N
) || CombineToPostIndexedLoadStore(N
))
14093 return SDValue(N
, 0);
14095 // Try to slice up N to more direct loads if the slices are mapped to
14096 // different register banks or pairing can take place.
14097 if (SliceUpLoad(N
))
14098 return SDValue(N
, 0);
14105 /// Helper structure used to slice a load in smaller loads.
14106 /// Basically a slice is obtained from the following sequence:
14107 /// Origin = load Ty1, Base
14108 /// Shift = srl Ty1 Origin, CstTy Amount
14109 /// Inst = trunc Shift to Ty2
14111 /// Then, it will be rewritten into:
14112 /// Slice = load SliceTy, Base + SliceOffset
14113 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
14115 /// SliceTy is deduced from the number of bits that are actually used to
14117 struct LoadedSlice
{
14118 /// Helper structure used to compute the cost of a slice.
14120 /// Are we optimizing for code size.
14124 unsigned Loads
= 0;
14125 unsigned Truncates
= 0;
14126 unsigned CrossRegisterBanksCopies
= 0;
14127 unsigned ZExts
= 0;
14128 unsigned Shift
= 0;
14130 Cost(bool ForCodeSize
= false) : ForCodeSize(ForCodeSize
) {}
14132 /// Get the cost of one isolated slice.
14133 Cost(const LoadedSlice
&LS
, bool ForCodeSize
= false)
14134 : ForCodeSize(ForCodeSize
), Loads(1) {
14135 EVT TruncType
= LS
.Inst
->getValueType(0);
14136 EVT LoadedType
= LS
.getLoadedType();
14137 if (TruncType
!= LoadedType
&&
14138 !LS
.DAG
->getTargetLoweringInfo().isZExtFree(LoadedType
, TruncType
))
14142 /// Account for slicing gain in the current cost.
14143 /// Slicing provide a few gains like removing a shift or a
14144 /// truncate. This method allows to grow the cost of the original
14145 /// load with the gain from this slice.
14146 void addSliceGain(const LoadedSlice
&LS
) {
14147 // Each slice saves a truncate.
14148 const TargetLowering
&TLI
= LS
.DAG
->getTargetLoweringInfo();
14149 if (!TLI
.isTruncateFree(LS
.Inst
->getOperand(0).getValueType(),
14150 LS
.Inst
->getValueType(0)))
14152 // If there is a shift amount, this slice gets rid of it.
14155 // If this slice can merge a cross register bank copy, account for it.
14156 if (LS
.canMergeExpensiveCrossRegisterBankCopy())
14157 ++CrossRegisterBanksCopies
;
14160 Cost
&operator+=(const Cost
&RHS
) {
14161 Loads
+= RHS
.Loads
;
14162 Truncates
+= RHS
.Truncates
;
14163 CrossRegisterBanksCopies
+= RHS
.CrossRegisterBanksCopies
;
14164 ZExts
+= RHS
.ZExts
;
14165 Shift
+= RHS
.Shift
;
14169 bool operator==(const Cost
&RHS
) const {
14170 return Loads
== RHS
.Loads
&& Truncates
== RHS
.Truncates
&&
14171 CrossRegisterBanksCopies
== RHS
.CrossRegisterBanksCopies
&&
14172 ZExts
== RHS
.ZExts
&& Shift
== RHS
.Shift
;
14175 bool operator!=(const Cost
&RHS
) const { return !(*this == RHS
); }
14177 bool operator<(const Cost
&RHS
) const {
14178 // Assume cross register banks copies are as expensive as loads.
14179 // FIXME: Do we want some more target hooks?
14180 unsigned ExpensiveOpsLHS
= Loads
+ CrossRegisterBanksCopies
;
14181 unsigned ExpensiveOpsRHS
= RHS
.Loads
+ RHS
.CrossRegisterBanksCopies
;
14182 // Unless we are optimizing for code size, consider the
14183 // expensive operation first.
14184 if (!ForCodeSize
&& ExpensiveOpsLHS
!= ExpensiveOpsRHS
)
14185 return ExpensiveOpsLHS
< ExpensiveOpsRHS
;
14186 return (Truncates
+ ZExts
+ Shift
+ ExpensiveOpsLHS
) <
14187 (RHS
.Truncates
+ RHS
.ZExts
+ RHS
.Shift
+ ExpensiveOpsRHS
);
14190 bool operator>(const Cost
&RHS
) const { return RHS
< *this; }
14192 bool operator<=(const Cost
&RHS
) const { return !(RHS
< *this); }
14194 bool operator>=(const Cost
&RHS
) const { return !(*this < RHS
); }
14197 // The last instruction that represent the slice. This should be a
14198 // truncate instruction.
14201 // The original load instruction.
14202 LoadSDNode
*Origin
;
14204 // The right shift amount in bits from the original load.
14207 // The DAG from which Origin came from.
14208 // This is used to get some contextual information about legal types, etc.
14211 LoadedSlice(SDNode
*Inst
= nullptr, LoadSDNode
*Origin
= nullptr,
14212 unsigned Shift
= 0, SelectionDAG
*DAG
= nullptr)
14213 : Inst(Inst
), Origin(Origin
), Shift(Shift
), DAG(DAG
) {}
14215 /// Get the bits used in a chunk of bits \p BitWidth large.
14216 /// \return Result is \p BitWidth and has used bits set to 1 and
14217 /// not used bits set to 0.
14218 APInt
getUsedBits() const {
14219 // Reproduce the trunc(lshr) sequence:
14220 // - Start from the truncated value.
14221 // - Zero extend to the desired bit width.
14223 assert(Origin
&& "No original load to compare against.");
14224 unsigned BitWidth
= Origin
->getValueSizeInBits(0);
14225 assert(Inst
&& "This slice is not bound to an instruction");
14226 assert(Inst
->getValueSizeInBits(0) <= BitWidth
&&
14227 "Extracted slice is bigger than the whole type!");
14228 APInt
UsedBits(Inst
->getValueSizeInBits(0), 0);
14229 UsedBits
.setAllBits();
14230 UsedBits
= UsedBits
.zext(BitWidth
);
14231 UsedBits
<<= Shift
;
14235 /// Get the size of the slice to be loaded in bytes.
14236 unsigned getLoadedSize() const {
14237 unsigned SliceSize
= getUsedBits().countPopulation();
14238 assert(!(SliceSize
& 0x7) && "Size is not a multiple of a byte.");
14239 return SliceSize
/ 8;
14242 /// Get the type that will be loaded for this slice.
14243 /// Note: This may not be the final type for the slice.
14244 EVT
getLoadedType() const {
14245 assert(DAG
&& "Missing context");
14246 LLVMContext
&Ctxt
= *DAG
->getContext();
14247 return EVT::getIntegerVT(Ctxt
, getLoadedSize() * 8);
14250 /// Get the alignment of the load used for this slice.
14251 unsigned getAlignment() const {
14252 unsigned Alignment
= Origin
->getAlignment();
14253 uint64_t Offset
= getOffsetFromBase();
14255 Alignment
= MinAlign(Alignment
, Alignment
+ Offset
);
14259 /// Check if this slice can be rewritten with legal operations.
14260 bool isLegal() const {
14261 // An invalid slice is not legal.
14262 if (!Origin
|| !Inst
|| !DAG
)
14265 // Offsets are for indexed load only, we do not handle that.
14266 if (!Origin
->getOffset().isUndef())
14269 const TargetLowering
&TLI
= DAG
->getTargetLoweringInfo();
14271 // Check that the type is legal.
14272 EVT SliceType
= getLoadedType();
14273 if (!TLI
.isTypeLegal(SliceType
))
14276 // Check that the load is legal for this type.
14277 if (!TLI
.isOperationLegal(ISD::LOAD
, SliceType
))
14280 // Check that the offset can be computed.
14281 // 1. Check its type.
14282 EVT PtrType
= Origin
->getBasePtr().getValueType();
14283 if (PtrType
== MVT::Untyped
|| PtrType
.isExtended())
14286 // 2. Check that it fits in the immediate.
14287 if (!TLI
.isLegalAddImmediate(getOffsetFromBase()))
14290 // 3. Check that the computation is legal.
14291 if (!TLI
.isOperationLegal(ISD::ADD
, PtrType
))
14294 // Check that the zext is legal if it needs one.
14295 EVT TruncateType
= Inst
->getValueType(0);
14296 if (TruncateType
!= SliceType
&&
14297 !TLI
.isOperationLegal(ISD::ZERO_EXTEND
, TruncateType
))
14303 /// Get the offset in bytes of this slice in the original chunk of
14305 /// \pre DAG != nullptr.
14306 uint64_t getOffsetFromBase() const {
14307 assert(DAG
&& "Missing context.");
14308 bool IsBigEndian
= DAG
->getDataLayout().isBigEndian();
14309 assert(!(Shift
& 0x7) && "Shifts not aligned on Bytes are not supported.");
14310 uint64_t Offset
= Shift
/ 8;
14311 unsigned TySizeInBytes
= Origin
->getValueSizeInBits(0) / 8;
14312 assert(!(Origin
->getValueSizeInBits(0) & 0x7) &&
14313 "The size of the original loaded type is not a multiple of a"
14315 // If Offset is bigger than TySizeInBytes, it means we are loading all
14316 // zeros. This should have been optimized before in the process.
14317 assert(TySizeInBytes
> Offset
&&
14318 "Invalid shift amount for given loaded size");
14320 Offset
= TySizeInBytes
- Offset
- getLoadedSize();
14324 /// Generate the sequence of instructions to load the slice
14325 /// represented by this object and redirect the uses of this slice to
14326 /// this new sequence of instructions.
14327 /// \pre this->Inst && this->Origin are valid Instructions and this
14328 /// object passed the legal check: LoadedSlice::isLegal returned true.
14329 /// \return The last instruction of the sequence used to load the slice.
14330 SDValue
loadSlice() const {
14331 assert(Inst
&& Origin
&& "Unable to replace a non-existing slice.");
14332 const SDValue
&OldBaseAddr
= Origin
->getBasePtr();
14333 SDValue BaseAddr
= OldBaseAddr
;
14334 // Get the offset in that chunk of bytes w.r.t. the endianness.
14335 int64_t Offset
= static_cast<int64_t>(getOffsetFromBase());
14336 assert(Offset
>= 0 && "Offset too big to fit in int64_t!");
14338 // BaseAddr = BaseAddr + Offset.
14339 EVT ArithType
= BaseAddr
.getValueType();
14341 BaseAddr
= DAG
->getNode(ISD::ADD
, DL
, ArithType
, BaseAddr
,
14342 DAG
->getConstant(Offset
, DL
, ArithType
));
14345 // Create the type of the loaded slice according to its size.
14346 EVT SliceType
= getLoadedType();
14348 // Create the load for the slice.
14350 DAG
->getLoad(SliceType
, SDLoc(Origin
), Origin
->getChain(), BaseAddr
,
14351 Origin
->getPointerInfo().getWithOffset(Offset
),
14352 getAlignment(), Origin
->getMemOperand()->getFlags());
14353 // If the final type is not the same as the loaded type, this means that
14354 // we have to pad with zero. Create a zero extend for that.
14355 EVT FinalType
= Inst
->getValueType(0);
14356 if (SliceType
!= FinalType
)
14358 DAG
->getNode(ISD::ZERO_EXTEND
, SDLoc(LastInst
), FinalType
, LastInst
);
14362 /// Check if this slice can be merged with an expensive cross register
14363 /// bank copy. E.g.,
14365 /// f = bitcast i32 i to float
14366 bool canMergeExpensiveCrossRegisterBankCopy() const {
14367 if (!Inst
|| !Inst
->hasOneUse())
14369 SDNode
*Use
= *Inst
->use_begin();
14370 if (Use
->getOpcode() != ISD::BITCAST
)
14372 assert(DAG
&& "Missing context");
14373 const TargetLowering
&TLI
= DAG
->getTargetLoweringInfo();
14374 EVT ResVT
= Use
->getValueType(0);
14375 const TargetRegisterClass
*ResRC
=
14376 TLI
.getRegClassFor(ResVT
.getSimpleVT(), Use
->isDivergent());
14377 const TargetRegisterClass
*ArgRC
=
14378 TLI
.getRegClassFor(Use
->getOperand(0).getValueType().getSimpleVT(),
14379 Use
->getOperand(0)->isDivergent());
14380 if (ArgRC
== ResRC
|| !TLI
.isOperationLegal(ISD::LOAD
, ResVT
))
14383 // At this point, we know that we perform a cross-register-bank copy.
14384 // Check if it is expensive.
14385 const TargetRegisterInfo
*TRI
= DAG
->getSubtarget().getRegisterInfo();
14386 // Assume bitcasts are cheap, unless both register classes do not
14387 // explicitly share a common sub class.
14388 if (!TRI
|| TRI
->getCommonSubClass(ArgRC
, ResRC
))
14391 // Check if it will be merged with the load.
14392 // 1. Check the alignment constraint.
14393 unsigned RequiredAlignment
= DAG
->getDataLayout().getABITypeAlignment(
14394 ResVT
.getTypeForEVT(*DAG
->getContext()));
14396 if (RequiredAlignment
> getAlignment())
14399 // 2. Check that the load is a legal operation for that type.
14400 if (!TLI
.isOperationLegal(ISD::LOAD
, ResVT
))
14403 // 3. Check that we do not have a zext in the way.
14404 if (Inst
->getValueType(0) != getLoadedType())
14411 } // end anonymous namespace
14413 /// Check that all bits set in \p UsedBits form a dense region, i.e.,
14414 /// \p UsedBits looks like 0..0 1..1 0..0.
14415 static bool areUsedBitsDense(const APInt
&UsedBits
) {
14416 // If all the bits are one, this is dense!
14417 if (UsedBits
.isAllOnesValue())
14420 // Get rid of the unused bits on the right.
14421 APInt NarrowedUsedBits
= UsedBits
.lshr(UsedBits
.countTrailingZeros());
14422 // Get rid of the unused bits on the left.
14423 if (NarrowedUsedBits
.countLeadingZeros())
14424 NarrowedUsedBits
= NarrowedUsedBits
.trunc(NarrowedUsedBits
.getActiveBits());
14425 // Check that the chunk of bits is completely used.
14426 return NarrowedUsedBits
.isAllOnesValue();
14429 /// Check whether or not \p First and \p Second are next to each other
14430 /// in memory. This means that there is no hole between the bits loaded
14431 /// by \p First and the bits loaded by \p Second.
14432 static bool areSlicesNextToEachOther(const LoadedSlice
&First
,
14433 const LoadedSlice
&Second
) {
14434 assert(First
.Origin
== Second
.Origin
&& First
.Origin
&&
14435 "Unable to match different memory origins.");
14436 APInt UsedBits
= First
.getUsedBits();
14437 assert((UsedBits
& Second
.getUsedBits()) == 0 &&
14438 "Slices are not supposed to overlap.");
14439 UsedBits
|= Second
.getUsedBits();
14440 return areUsedBitsDense(UsedBits
);
14443 /// Adjust the \p GlobalLSCost according to the target
14444 /// paring capabilities and the layout of the slices.
14445 /// \pre \p GlobalLSCost should account for at least as many loads as
14446 /// there is in the slices in \p LoadedSlices.
14447 static void adjustCostForPairing(SmallVectorImpl
<LoadedSlice
> &LoadedSlices
,
14448 LoadedSlice::Cost
&GlobalLSCost
) {
14449 unsigned NumberOfSlices
= LoadedSlices
.size();
14450 // If there is less than 2 elements, no pairing is possible.
14451 if (NumberOfSlices
< 2)
14454 // Sort the slices so that elements that are likely to be next to each
14455 // other in memory are next to each other in the list.
14456 llvm::sort(LoadedSlices
, [](const LoadedSlice
&LHS
, const LoadedSlice
&RHS
) {
14457 assert(LHS
.Origin
== RHS
.Origin
&& "Different bases not implemented.");
14458 return LHS
.getOffsetFromBase() < RHS
.getOffsetFromBase();
14460 const TargetLowering
&TLI
= LoadedSlices
[0].DAG
->getTargetLoweringInfo();
14461 // First (resp. Second) is the first (resp. Second) potentially candidate
14462 // to be placed in a paired load.
14463 const LoadedSlice
*First
= nullptr;
14464 const LoadedSlice
*Second
= nullptr;
14465 for (unsigned CurrSlice
= 0; CurrSlice
< NumberOfSlices
; ++CurrSlice
,
14466 // Set the beginning of the pair.
14468 Second
= &LoadedSlices
[CurrSlice
];
14470 // If First is NULL, it means we start a new pair.
14471 // Get to the next slice.
14475 EVT LoadedType
= First
->getLoadedType();
14477 // If the types of the slices are different, we cannot pair them.
14478 if (LoadedType
!= Second
->getLoadedType())
14481 // Check if the target supplies paired loads for this type.
14482 unsigned RequiredAlignment
= 0;
14483 if (!TLI
.hasPairedLoad(LoadedType
, RequiredAlignment
)) {
14484 // move to the next pair, this type is hopeless.
14488 // Check if we meet the alignment requirement.
14489 if (RequiredAlignment
> First
->getAlignment())
14492 // Check that both loads are next to each other in memory.
14493 if (!areSlicesNextToEachOther(*First
, *Second
))
14496 assert(GlobalLSCost
.Loads
> 0 && "We save more loads than we created!");
14497 --GlobalLSCost
.Loads
;
14498 // Move to the next pair.
14503 /// Check the profitability of all involved LoadedSlice.
14504 /// Currently, it is considered profitable if there is exactly two
14505 /// involved slices (1) which are (2) next to each other in memory, and
14506 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
14508 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
14509 /// the elements themselves.
14511 /// FIXME: When the cost model will be mature enough, we can relax
14512 /// constraints (1) and (2).
14513 static bool isSlicingProfitable(SmallVectorImpl
<LoadedSlice
> &LoadedSlices
,
14514 const APInt
&UsedBits
, bool ForCodeSize
) {
14515 unsigned NumberOfSlices
= LoadedSlices
.size();
14516 if (StressLoadSlicing
)
14517 return NumberOfSlices
> 1;
14520 if (NumberOfSlices
!= 2)
14524 if (!areUsedBitsDense(UsedBits
))
14528 LoadedSlice::Cost
OrigCost(ForCodeSize
), GlobalSlicingCost(ForCodeSize
);
14529 // The original code has one big load.
14530 OrigCost
.Loads
= 1;
14531 for (unsigned CurrSlice
= 0; CurrSlice
< NumberOfSlices
; ++CurrSlice
) {
14532 const LoadedSlice
&LS
= LoadedSlices
[CurrSlice
];
14533 // Accumulate the cost of all the slices.
14534 LoadedSlice::Cost
SliceCost(LS
, ForCodeSize
);
14535 GlobalSlicingCost
+= SliceCost
;
14537 // Account as cost in the original configuration the gain obtained
14538 // with the current slices.
14539 OrigCost
.addSliceGain(LS
);
14542 // If the target supports paired load, adjust the cost accordingly.
14543 adjustCostForPairing(LoadedSlices
, GlobalSlicingCost
);
14544 return OrigCost
> GlobalSlicingCost
;
14547 /// If the given load, \p LI, is used only by trunc or trunc(lshr)
14548 /// operations, split it in the various pieces being extracted.
14550 /// This sort of thing is introduced by SROA.
14551 /// This slicing takes care not to insert overlapping loads.
14552 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
14553 bool DAGCombiner::SliceUpLoad(SDNode
*N
) {
14554 if (Level
< AfterLegalizeDAG
)
14557 LoadSDNode
*LD
= cast
<LoadSDNode
>(N
);
14558 if (LD
->isVolatile() || !ISD::isNormalLoad(LD
) ||
14559 !LD
->getValueType(0).isInteger())
14562 // Keep track of already used bits to detect overlapping values.
14563 // In that case, we will just abort the transformation.
14564 APInt
UsedBits(LD
->getValueSizeInBits(0), 0);
14566 SmallVector
<LoadedSlice
, 4> LoadedSlices
;
14568 // Check if this load is used as several smaller chunks of bits.
14569 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
14570 // of computation for each trunc.
14571 for (SDNode::use_iterator UI
= LD
->use_begin(), UIEnd
= LD
->use_end();
14572 UI
!= UIEnd
; ++UI
) {
14573 // Skip the uses of the chain.
14574 if (UI
.getUse().getResNo() != 0)
14577 SDNode
*User
= *UI
;
14578 unsigned Shift
= 0;
14580 // Check if this is a trunc(lshr).
14581 if (User
->getOpcode() == ISD::SRL
&& User
->hasOneUse() &&
14582 isa
<ConstantSDNode
>(User
->getOperand(1))) {
14583 Shift
= User
->getConstantOperandVal(1);
14584 User
= *User
->use_begin();
14587 // At this point, User is a Truncate, iff we encountered, trunc or
14589 if (User
->getOpcode() != ISD::TRUNCATE
)
14592 // The width of the type must be a power of 2 and greater than 8-bits.
14593 // Otherwise the load cannot be represented in LLVM IR.
14594 // Moreover, if we shifted with a non-8-bits multiple, the slice
14595 // will be across several bytes. We do not support that.
14596 unsigned Width
= User
->getValueSizeInBits(0);
14597 if (Width
< 8 || !isPowerOf2_32(Width
) || (Shift
& 0x7))
14600 // Build the slice for this chain of computations.
14601 LoadedSlice
LS(User
, LD
, Shift
, &DAG
);
14602 APInt CurrentUsedBits
= LS
.getUsedBits();
14604 // Check if this slice overlaps with another.
14605 if ((CurrentUsedBits
& UsedBits
) != 0)
14607 // Update the bits used globally.
14608 UsedBits
|= CurrentUsedBits
;
14610 // Check if the new slice would be legal.
14614 // Record the slice.
14615 LoadedSlices
.push_back(LS
);
14618 // Abort slicing if it does not seem to be profitable.
14619 if (!isSlicingProfitable(LoadedSlices
, UsedBits
, ForCodeSize
))
14624 // Rewrite each chain to use an independent load.
14625 // By construction, each chain can be represented by a unique load.
14627 // Prepare the argument for the new token factor for all the slices.
14628 SmallVector
<SDValue
, 8> ArgChains
;
14629 for (SmallVectorImpl
<LoadedSlice
>::const_iterator
14630 LSIt
= LoadedSlices
.begin(),
14631 LSItEnd
= LoadedSlices
.end();
14632 LSIt
!= LSItEnd
; ++LSIt
) {
14633 SDValue SliceInst
= LSIt
->loadSlice();
14634 CombineTo(LSIt
->Inst
, SliceInst
, true);
14635 if (SliceInst
.getOpcode() != ISD::LOAD
)
14636 SliceInst
= SliceInst
.getOperand(0);
14637 assert(SliceInst
->getOpcode() == ISD::LOAD
&&
14638 "It takes more than a zext to get to the loaded slice!!");
14639 ArgChains
.push_back(SliceInst
.getValue(1));
14642 SDValue Chain
= DAG
.getNode(ISD::TokenFactor
, SDLoc(LD
), MVT::Other
,
14644 DAG
.ReplaceAllUsesOfValueWith(SDValue(N
, 1), Chain
);
14645 AddToWorklist(Chain
.getNode());
14649 /// Check to see if V is (and load (ptr), imm), where the load is having
14650 /// specific bytes cleared out. If so, return the byte size being masked out
14651 /// and the shift amount.
14652 static std::pair
<unsigned, unsigned>
14653 CheckForMaskedLoad(SDValue V
, SDValue Ptr
, SDValue Chain
) {
14654 std::pair
<unsigned, unsigned> Result(0, 0);
14656 // Check for the structure we're looking for.
14657 if (V
->getOpcode() != ISD::AND
||
14658 !isa
<ConstantSDNode
>(V
->getOperand(1)) ||
14659 !ISD::isNormalLoad(V
->getOperand(0).getNode()))
14662 // Check the chain and pointer.
14663 LoadSDNode
*LD
= cast
<LoadSDNode
>(V
->getOperand(0));
14664 if (LD
->getBasePtr() != Ptr
) return Result
; // Not from same pointer.
14666 // This only handles simple types.
14667 if (V
.getValueType() != MVT::i16
&&
14668 V
.getValueType() != MVT::i32
&&
14669 V
.getValueType() != MVT::i64
)
14672 // Check the constant mask. Invert it so that the bits being masked out are
14673 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
14674 // follow the sign bit for uniformity.
14675 uint64_t NotMask
= ~cast
<ConstantSDNode
>(V
->getOperand(1))->getSExtValue();
14676 unsigned NotMaskLZ
= countLeadingZeros(NotMask
);
14677 if (NotMaskLZ
& 7) return Result
; // Must be multiple of a byte.
14678 unsigned NotMaskTZ
= countTrailingZeros(NotMask
);
14679 if (NotMaskTZ
& 7) return Result
; // Must be multiple of a byte.
14680 if (NotMaskLZ
== 64) return Result
; // All zero mask.
14682 // See if we have a continuous run of bits. If so, we have 0*1+0*
14683 if (countTrailingOnes(NotMask
>> NotMaskTZ
) + NotMaskTZ
+ NotMaskLZ
!= 64)
14686 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
14687 if (V
.getValueType() != MVT::i64
&& NotMaskLZ
)
14688 NotMaskLZ
-= 64-V
.getValueSizeInBits();
14690 unsigned MaskedBytes
= (V
.getValueSizeInBits()-NotMaskLZ
-NotMaskTZ
)/8;
14691 switch (MaskedBytes
) {
14695 default: return Result
; // All one mask, or 5-byte mask.
14698 // Verify that the first bit starts at a multiple of mask so that the access
14699 // is aligned the same as the access width.
14700 if (NotMaskTZ
&& NotMaskTZ
/8 % MaskedBytes
) return Result
;
14702 // For narrowing to be valid, it must be the case that the load the
14703 // immediately preceding memory operation before the store.
14704 if (LD
== Chain
.getNode())
14706 else if (Chain
->getOpcode() == ISD::TokenFactor
&&
14707 SDValue(LD
, 1).hasOneUse()) {
14708 // LD has only 1 chain use so they are no indirect dependencies.
14709 if (!LD
->isOperandOf(Chain
.getNode()))
14712 return Result
; // Fail.
14714 Result
.first
= MaskedBytes
;
14715 Result
.second
= NotMaskTZ
/8;
14719 /// Check to see if IVal is something that provides a value as specified by
14720 /// MaskInfo. If so, replace the specified store with a narrower store of
14721 /// truncated IVal.
14723 ShrinkLoadReplaceStoreWithStore(const std::pair
<unsigned, unsigned> &MaskInfo
,
14724 SDValue IVal
, StoreSDNode
*St
,
14726 unsigned NumBytes
= MaskInfo
.first
;
14727 unsigned ByteShift
= MaskInfo
.second
;
14728 SelectionDAG
&DAG
= DC
->getDAG();
14730 // Check to see if IVal is all zeros in the part being masked in by the 'or'
14731 // that uses this. If not, this is not a replacement.
14732 APInt Mask
= ~APInt::getBitsSet(IVal
.getValueSizeInBits(),
14733 ByteShift
*8, (ByteShift
+NumBytes
)*8);
14734 if (!DAG
.MaskedValueIsZero(IVal
, Mask
)) return SDValue();
14736 // Check that it is legal on the target to do this. It is legal if the new
14737 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
14739 MVT VT
= MVT::getIntegerVT(NumBytes
*8);
14740 if (!DC
->isTypeLegal(VT
))
14743 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
14744 // shifted by ByteShift and truncated down to NumBytes.
14747 IVal
= DAG
.getNode(ISD::SRL
, DL
, IVal
.getValueType(), IVal
,
14748 DAG
.getConstant(ByteShift
*8, DL
,
14749 DC
->getShiftAmountTy(IVal
.getValueType())));
14752 // Figure out the offset for the store and the alignment of the access.
14754 unsigned NewAlign
= St
->getAlignment();
14756 if (DAG
.getDataLayout().isLittleEndian())
14757 StOffset
= ByteShift
;
14759 StOffset
= IVal
.getValueType().getStoreSize() - ByteShift
- NumBytes
;
14761 SDValue Ptr
= St
->getBasePtr();
14764 Ptr
= DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(),
14765 Ptr
, DAG
.getConstant(StOffset
, DL
, Ptr
.getValueType()));
14766 NewAlign
= MinAlign(NewAlign
, StOffset
);
14769 // Truncate down to the new size.
14770 IVal
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(IVal
), VT
, IVal
);
14774 .getStore(St
->getChain(), SDLoc(St
), IVal
, Ptr
,
14775 St
->getPointerInfo().getWithOffset(StOffset
), NewAlign
);
14778 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
14779 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
14780 /// narrowing the load and store if it would end up being a win for performance
14782 SDValue
DAGCombiner::ReduceLoadOpStoreWidth(SDNode
*N
) {
14783 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
14784 if (ST
->isVolatile())
14787 SDValue Chain
= ST
->getChain();
14788 SDValue Value
= ST
->getValue();
14789 SDValue Ptr
= ST
->getBasePtr();
14790 EVT VT
= Value
.getValueType();
14792 if (ST
->isTruncatingStore() || VT
.isVector() || !Value
.hasOneUse())
14795 unsigned Opc
= Value
.getOpcode();
14797 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
14798 // is a byte mask indicating a consecutive number of bytes, check to see if
14799 // Y is known to provide just those bytes. If so, we try to replace the
14800 // load + replace + store sequence with a single (narrower) store, which makes
14802 if (Opc
== ISD::OR
) {
14803 std::pair
<unsigned, unsigned> MaskedLoad
;
14804 MaskedLoad
= CheckForMaskedLoad(Value
.getOperand(0), Ptr
, Chain
);
14805 if (MaskedLoad
.first
)
14806 if (SDValue NewST
= ShrinkLoadReplaceStoreWithStore(MaskedLoad
,
14807 Value
.getOperand(1), ST
,this))
14810 // Or is commutative, so try swapping X and Y.
14811 MaskedLoad
= CheckForMaskedLoad(Value
.getOperand(1), Ptr
, Chain
);
14812 if (MaskedLoad
.first
)
14813 if (SDValue NewST
= ShrinkLoadReplaceStoreWithStore(MaskedLoad
,
14814 Value
.getOperand(0), ST
,this))
14818 if ((Opc
!= ISD::OR
&& Opc
!= ISD::XOR
&& Opc
!= ISD::AND
) ||
14819 Value
.getOperand(1).getOpcode() != ISD::Constant
)
14822 SDValue N0
= Value
.getOperand(0);
14823 if (ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
14824 Chain
== SDValue(N0
.getNode(), 1)) {
14825 LoadSDNode
*LD
= cast
<LoadSDNode
>(N0
);
14826 if (LD
->getBasePtr() != Ptr
||
14827 LD
->getPointerInfo().getAddrSpace() !=
14828 ST
->getPointerInfo().getAddrSpace())
14831 // Find the type to narrow it the load / op / store to.
14832 SDValue N1
= Value
.getOperand(1);
14833 unsigned BitWidth
= N1
.getValueSizeInBits();
14834 APInt Imm
= cast
<ConstantSDNode
>(N1
)->getAPIntValue();
14835 if (Opc
== ISD::AND
)
14836 Imm
^= APInt::getAllOnesValue(BitWidth
);
14837 if (Imm
== 0 || Imm
.isAllOnesValue())
14839 unsigned ShAmt
= Imm
.countTrailingZeros();
14840 unsigned MSB
= BitWidth
- Imm
.countLeadingZeros() - 1;
14841 unsigned NewBW
= NextPowerOf2(MSB
- ShAmt
);
14842 EVT NewVT
= EVT::getIntegerVT(*DAG
.getContext(), NewBW
);
14843 // The narrowing should be profitable, the load/store operation should be
14844 // legal (or custom) and the store size should be equal to the NewVT width.
14845 while (NewBW
< BitWidth
&&
14846 (NewVT
.getStoreSizeInBits() != NewBW
||
14847 !TLI
.isOperationLegalOrCustom(Opc
, NewVT
) ||
14848 !TLI
.isNarrowingProfitable(VT
, NewVT
))) {
14849 NewBW
= NextPowerOf2(NewBW
);
14850 NewVT
= EVT::getIntegerVT(*DAG
.getContext(), NewBW
);
14852 if (NewBW
>= BitWidth
)
14855 // If the lsb changed does not start at the type bitwidth boundary,
14856 // start at the previous one.
14858 ShAmt
= (((ShAmt
+ NewBW
- 1) / NewBW
) * NewBW
) - NewBW
;
14859 APInt Mask
= APInt::getBitsSet(BitWidth
, ShAmt
,
14860 std::min(BitWidth
, ShAmt
+ NewBW
));
14861 if ((Imm
& Mask
) == Imm
) {
14862 APInt NewImm
= (Imm
& Mask
).lshr(ShAmt
).trunc(NewBW
);
14863 if (Opc
== ISD::AND
)
14864 NewImm
^= APInt::getAllOnesValue(NewBW
);
14865 uint64_t PtrOff
= ShAmt
/ 8;
14866 // For big endian targets, we need to adjust the offset to the pointer to
14867 // load the correct bytes.
14868 if (DAG
.getDataLayout().isBigEndian())
14869 PtrOff
= (BitWidth
+ 7 - NewBW
) / 8 - PtrOff
;
14871 unsigned NewAlign
= MinAlign(LD
->getAlignment(), PtrOff
);
14872 Type
*NewVTTy
= NewVT
.getTypeForEVT(*DAG
.getContext());
14873 if (NewAlign
< DAG
.getDataLayout().getABITypeAlignment(NewVTTy
))
14876 SDValue NewPtr
= DAG
.getNode(ISD::ADD
, SDLoc(LD
),
14877 Ptr
.getValueType(), Ptr
,
14878 DAG
.getConstant(PtrOff
, SDLoc(LD
),
14879 Ptr
.getValueType()));
14881 DAG
.getLoad(NewVT
, SDLoc(N0
), LD
->getChain(), NewPtr
,
14882 LD
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
,
14883 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
14884 SDValue NewVal
= DAG
.getNode(Opc
, SDLoc(Value
), NewVT
, NewLD
,
14885 DAG
.getConstant(NewImm
, SDLoc(Value
),
14888 DAG
.getStore(Chain
, SDLoc(N
), NewVal
, NewPtr
,
14889 ST
->getPointerInfo().getWithOffset(PtrOff
), NewAlign
);
14891 AddToWorklist(NewPtr
.getNode());
14892 AddToWorklist(NewLD
.getNode());
14893 AddToWorklist(NewVal
.getNode());
14894 WorklistRemover
DeadNodes(*this);
14895 DAG
.ReplaceAllUsesOfValueWith(N0
.getValue(1), NewLD
.getValue(1));
14904 /// For a given floating point load / store pair, if the load value isn't used
14905 /// by any other operations, then consider transforming the pair to integer
14906 /// load / store operations if the target deems the transformation profitable.
14907 SDValue
DAGCombiner::TransformFPLoadStorePair(SDNode
*N
) {
14908 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
14909 SDValue Value
= ST
->getValue();
14910 if (ISD::isNormalStore(ST
) && ISD::isNormalLoad(Value
.getNode()) &&
14911 Value
.hasOneUse()) {
14912 LoadSDNode
*LD
= cast
<LoadSDNode
>(Value
);
14913 EVT VT
= LD
->getMemoryVT();
14914 if (!VT
.isFloatingPoint() ||
14915 VT
!= ST
->getMemoryVT() ||
14916 LD
->isNonTemporal() ||
14917 ST
->isNonTemporal() ||
14918 LD
->getPointerInfo().getAddrSpace() != 0 ||
14919 ST
->getPointerInfo().getAddrSpace() != 0)
14922 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getSizeInBits());
14923 if (!TLI
.isOperationLegal(ISD::LOAD
, IntVT
) ||
14924 !TLI
.isOperationLegal(ISD::STORE
, IntVT
) ||
14925 !TLI
.isDesirableToTransformToIntegerOp(ISD::LOAD
, VT
) ||
14926 !TLI
.isDesirableToTransformToIntegerOp(ISD::STORE
, VT
))
14929 unsigned LDAlign
= LD
->getAlignment();
14930 unsigned STAlign
= ST
->getAlignment();
14931 Type
*IntVTTy
= IntVT
.getTypeForEVT(*DAG
.getContext());
14932 unsigned ABIAlign
= DAG
.getDataLayout().getABITypeAlignment(IntVTTy
);
14933 if (LDAlign
< ABIAlign
|| STAlign
< ABIAlign
)
14937 DAG
.getLoad(IntVT
, SDLoc(Value
), LD
->getChain(), LD
->getBasePtr(),
14938 LD
->getPointerInfo(), LDAlign
);
14941 DAG
.getStore(ST
->getChain(), SDLoc(N
), NewLD
, ST
->getBasePtr(),
14942 ST
->getPointerInfo(), STAlign
);
14944 AddToWorklist(NewLD
.getNode());
14945 AddToWorklist(NewST
.getNode());
14946 WorklistRemover
DeadNodes(*this);
14947 DAG
.ReplaceAllUsesOfValueWith(Value
.getValue(1), NewLD
.getValue(1));
14955 // This is a helper function for visitMUL to check the profitability
14956 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
14957 // MulNode is the original multiply, AddNode is (add x, c1),
14958 // and ConstNode is c2.
14960 // If the (add x, c1) has multiple uses, we could increase
14961 // the number of adds if we make this transformation.
14962 // It would only be worth doing this if we can remove a
14963 // multiply in the process. Check for that here.
14967 // We're checking for cases where we have common "c3 * A" expressions.
14968 bool DAGCombiner::isMulAddWithConstProfitable(SDNode
*MulNode
,
14970 SDValue
&ConstNode
) {
14973 // If the add only has one use, this would be OK to do.
14974 if (AddNode
.getNode()->hasOneUse())
14977 // Walk all the users of the constant with which we're multiplying.
14978 for (SDNode
*Use
: ConstNode
->uses()) {
14979 if (Use
== MulNode
) // This use is the one we're on right now. Skip it.
14982 if (Use
->getOpcode() == ISD::MUL
) { // We have another multiply use.
14984 SDNode
*MulVar
= AddNode
.getOperand(0).getNode();
14986 // OtherOp is what we're multiplying against the constant.
14987 if (Use
->getOperand(0) == ConstNode
)
14988 OtherOp
= Use
->getOperand(1).getNode();
14990 OtherOp
= Use
->getOperand(0).getNode();
14992 // Check to see if multiply is with the same operand of our "add".
14994 // ConstNode = CONST
14995 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
14997 // AddNode = (A + c1) <-- MulVar is A.
14998 // = AddNode * ConstNode <-- current visiting instruction.
15000 // If we make this transformation, we will have a common
15001 // multiply (ConstNode * A) that we can save.
15002 if (OtherOp
== MulVar
)
15005 // Now check to see if a future expansion will give us a common
15008 // ConstNode = CONST
15009 // AddNode = (A + c1)
15010 // ... = AddNode * ConstNode <-- current visiting instruction.
15012 // OtherOp = (A + c2)
15013 // Use = OtherOp * ConstNode <-- visiting Use.
15015 // If we make this transformation, we will have a common
15016 // multiply (CONST * A) after we also do the same transformation
15017 // to the "t2" instruction.
15018 if (OtherOp
->getOpcode() == ISD::ADD
&&
15019 DAG
.isConstantIntBuildVectorOrConstantInt(OtherOp
->getOperand(1)) &&
15020 OtherOp
->getOperand(0).getNode() == MulVar
)
15025 // Didn't find a case where this would be profitable.
15029 SDValue
DAGCombiner::getMergeStoreChains(SmallVectorImpl
<MemOpLink
> &StoreNodes
,
15030 unsigned NumStores
) {
15031 SmallVector
<SDValue
, 8> Chains
;
15032 SmallPtrSet
<const SDNode
*, 8> Visited
;
15033 SDLoc
StoreDL(StoreNodes
[0].MemNode
);
15035 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15036 Visited
.insert(StoreNodes
[i
].MemNode
);
15039 // don't include nodes that are children or repeated nodes.
15040 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15041 if (Visited
.insert(StoreNodes
[i
].MemNode
->getChain().getNode()).second
)
15042 Chains
.push_back(StoreNodes
[i
].MemNode
->getChain());
15045 assert(Chains
.size() > 0 && "Chain should have generated a chain");
15046 return DAG
.getTokenFactor(StoreDL
, Chains
);
15049 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
15050 SmallVectorImpl
<MemOpLink
> &StoreNodes
, EVT MemVT
, unsigned NumStores
,
15051 bool IsConstantSrc
, bool UseVector
, bool UseTrunc
) {
15052 // Make sure we have something to merge.
15056 // The latest Node in the DAG.
15057 SDLoc
DL(StoreNodes
[0].MemNode
);
15059 int64_t ElementSizeBits
= MemVT
.getStoreSizeInBits();
15060 unsigned SizeInBits
= NumStores
* ElementSizeBits
;
15061 unsigned NumMemElts
= MemVT
.isVector() ? MemVT
.getVectorNumElements() : 1;
15065 unsigned Elts
= NumStores
* NumMemElts
;
15066 // Get the type for the merged vector store.
15067 StoreTy
= EVT::getVectorVT(*DAG
.getContext(), MemVT
.getScalarType(), Elts
);
15069 StoreTy
= EVT::getIntegerVT(*DAG
.getContext(), SizeInBits
);
15073 if (IsConstantSrc
) {
15074 SmallVector
<SDValue
, 8> BuildVector
;
15075 for (unsigned I
= 0; I
!= NumStores
; ++I
) {
15076 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[I
].MemNode
);
15077 SDValue Val
= St
->getValue();
15078 // If constant is of the wrong type, convert it now.
15079 if (MemVT
!= Val
.getValueType()) {
15080 Val
= peekThroughBitcasts(Val
);
15081 // Deal with constants of wrong size.
15082 if (ElementSizeBits
!= Val
.getValueSizeInBits()) {
15084 EVT::getIntegerVT(*DAG
.getContext(), MemVT
.getSizeInBits());
15085 if (isa
<ConstantFPSDNode
>(Val
)) {
15086 // Not clear how to truncate FP values.
15088 } else if (auto *C
= dyn_cast
<ConstantSDNode
>(Val
))
15089 Val
= DAG
.getConstant(C
->getAPIntValue()
15090 .zextOrTrunc(Val
.getValueSizeInBits())
15091 .zextOrTrunc(ElementSizeBits
),
15092 SDLoc(C
), IntMemVT
);
15094 // Make sure correctly size type is the correct type.
15095 Val
= DAG
.getBitcast(MemVT
, Val
);
15097 BuildVector
.push_back(Val
);
15099 StoredVal
= DAG
.getNode(MemVT
.isVector() ? ISD::CONCAT_VECTORS
15100 : ISD::BUILD_VECTOR
,
15101 DL
, StoreTy
, BuildVector
);
15103 SmallVector
<SDValue
, 8> Ops
;
15104 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15105 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15106 SDValue Val
= peekThroughBitcasts(St
->getValue());
15107 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
15108 // type MemVT. If the underlying value is not the correct
15109 // type, but it is an extraction of an appropriate vector we
15110 // can recast Val to be of the correct type. This may require
15111 // converting between EXTRACT_VECTOR_ELT and
15112 // EXTRACT_SUBVECTOR.
15113 if ((MemVT
!= Val
.getValueType()) &&
15114 (Val
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15115 Val
.getOpcode() == ISD::EXTRACT_SUBVECTOR
)) {
15116 EVT MemVTScalarTy
= MemVT
.getScalarType();
15117 // We may need to add a bitcast here to get types to line up.
15118 if (MemVTScalarTy
!= Val
.getValueType().getScalarType()) {
15119 Val
= DAG
.getBitcast(MemVT
, Val
);
15121 unsigned OpC
= MemVT
.isVector() ? ISD::EXTRACT_SUBVECTOR
15122 : ISD::EXTRACT_VECTOR_ELT
;
15123 SDValue Vec
= Val
.getOperand(0);
15124 SDValue Idx
= Val
.getOperand(1);
15125 Val
= DAG
.getNode(OpC
, SDLoc(Val
), MemVT
, Vec
, Idx
);
15128 Ops
.push_back(Val
);
15131 // Build the extracted vector elements back into a vector.
15132 StoredVal
= DAG
.getNode(MemVT
.isVector() ? ISD::CONCAT_VECTORS
15133 : ISD::BUILD_VECTOR
,
15137 // We should always use a vector store when merging extracted vector
15138 // elements, so this path implies a store of constants.
15139 assert(IsConstantSrc
&& "Merged vector elements should use vector store");
15141 APInt
StoreInt(SizeInBits
, 0);
15143 // Construct a single integer constant which is made of the smaller
15144 // constant inputs.
15145 bool IsLE
= DAG
.getDataLayout().isLittleEndian();
15146 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15147 unsigned Idx
= IsLE
? (NumStores
- 1 - i
) : i
;
15148 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[Idx
].MemNode
);
15150 SDValue Val
= St
->getValue();
15151 Val
= peekThroughBitcasts(Val
);
15152 StoreInt
<<= ElementSizeBits
;
15153 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Val
)) {
15154 StoreInt
|= C
->getAPIntValue()
15155 .zextOrTrunc(ElementSizeBits
)
15156 .zextOrTrunc(SizeInBits
);
15157 } else if (ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(Val
)) {
15158 StoreInt
|= C
->getValueAPF()
15160 .zextOrTrunc(ElementSizeBits
)
15161 .zextOrTrunc(SizeInBits
);
15162 // If fp truncation is necessary give up for now.
15163 if (MemVT
.getSizeInBits() != ElementSizeBits
)
15166 llvm_unreachable("Invalid constant element type");
15170 // Create the new Load and Store operations.
15171 StoredVal
= DAG
.getConstant(StoreInt
, DL
, StoreTy
);
15174 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15175 SDValue NewChain
= getMergeStoreChains(StoreNodes
, NumStores
);
15177 // make sure we use trunc store if it's necessary to be legal.
15180 NewStore
= DAG
.getStore(NewChain
, DL
, StoredVal
, FirstInChain
->getBasePtr(),
15181 FirstInChain
->getPointerInfo(),
15182 FirstInChain
->getAlignment());
15183 } else { // Must be realized as a trunc store
15184 EVT LegalizedStoredValTy
=
15185 TLI
.getTypeToTransformTo(*DAG
.getContext(), StoredVal
.getValueType());
15186 unsigned LegalizedStoreSize
= LegalizedStoredValTy
.getSizeInBits();
15187 ConstantSDNode
*C
= cast
<ConstantSDNode
>(StoredVal
);
15188 SDValue ExtendedStoreVal
=
15189 DAG
.getConstant(C
->getAPIntValue().zextOrTrunc(LegalizedStoreSize
), DL
,
15190 LegalizedStoredValTy
);
15191 NewStore
= DAG
.getTruncStore(
15192 NewChain
, DL
, ExtendedStoreVal
, FirstInChain
->getBasePtr(),
15193 FirstInChain
->getPointerInfo(), StoredVal
.getValueType() /*TVT*/,
15194 FirstInChain
->getAlignment(),
15195 FirstInChain
->getMemOperand()->getFlags());
15198 // Replace all merged stores with the new store.
15199 for (unsigned i
= 0; i
< NumStores
; ++i
)
15200 CombineTo(StoreNodes
[i
].MemNode
, NewStore
);
15202 AddToWorklist(NewChain
.getNode());
15206 void DAGCombiner::getStoreMergeCandidates(
15207 StoreSDNode
*St
, SmallVectorImpl
<MemOpLink
> &StoreNodes
,
15208 SDNode
*&RootNode
) {
15209 // This holds the base pointer, index, and the offset in bytes from the base
15211 BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
15212 EVT MemVT
= St
->getMemoryVT();
15214 SDValue Val
= peekThroughBitcasts(St
->getValue());
15215 // We must have a base and an offset.
15216 if (!BasePtr
.getBase().getNode())
15219 // Do not handle stores to undef base pointers.
15220 if (BasePtr
.getBase().isUndef())
15223 bool IsConstantSrc
= isa
<ConstantSDNode
>(Val
) || isa
<ConstantFPSDNode
>(Val
);
15224 bool IsExtractVecSrc
= (Val
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15225 Val
.getOpcode() == ISD::EXTRACT_SUBVECTOR
);
15226 bool IsLoadSrc
= isa
<LoadSDNode
>(Val
);
15227 BaseIndexOffset LBasePtr
;
15228 // Match on loadbaseptr if relevant.
15231 auto *Ld
= cast
<LoadSDNode
>(Val
);
15232 LBasePtr
= BaseIndexOffset::match(Ld
, DAG
);
15233 LoadVT
= Ld
->getMemoryVT();
15234 // Load and store should be the same type.
15235 if (MemVT
!= LoadVT
)
15237 // Loads must only have one use.
15238 if (!Ld
->hasNUsesOfValue(1, 0))
15240 // The memory operands must not be volatile/indexed.
15241 if (Ld
->isVolatile() || Ld
->isIndexed())
15244 auto CandidateMatch
= [&](StoreSDNode
*Other
, BaseIndexOffset
&Ptr
,
15245 int64_t &Offset
) -> bool {
15246 // The memory operands must not be volatile/indexed.
15247 if (Other
->isVolatile() || Other
->isIndexed())
15249 // Don't mix temporal stores with non-temporal stores.
15250 if (St
->isNonTemporal() != Other
->isNonTemporal())
15252 SDValue OtherBC
= peekThroughBitcasts(Other
->getValue());
15253 // Allow merging constants of different types as integers.
15254 bool NoTypeMatch
= (MemVT
.isInteger()) ? !MemVT
.bitsEq(Other
->getMemoryVT())
15255 : Other
->getMemoryVT() != MemVT
;
15259 // The Load's Base Ptr must also match
15260 if (LoadSDNode
*OtherLd
= dyn_cast
<LoadSDNode
>(OtherBC
)) {
15261 BaseIndexOffset LPtr
= BaseIndexOffset::match(OtherLd
, DAG
);
15262 if (LoadVT
!= OtherLd
->getMemoryVT())
15264 // Loads must only have one use.
15265 if (!OtherLd
->hasNUsesOfValue(1, 0))
15267 // The memory operands must not be volatile/indexed.
15268 if (OtherLd
->isVolatile() || OtherLd
->isIndexed())
15270 // Don't mix temporal loads with non-temporal loads.
15271 if (cast
<LoadSDNode
>(Val
)->isNonTemporal() != OtherLd
->isNonTemporal())
15273 if (!(LBasePtr
.equalBaseIndex(LPtr
, DAG
)))
15278 if (IsConstantSrc
) {
15281 if (!(isa
<ConstantSDNode
>(OtherBC
) || isa
<ConstantFPSDNode
>(OtherBC
)))
15284 if (IsExtractVecSrc
) {
15285 // Do not merge truncated stores here.
15286 if (Other
->isTruncatingStore())
15288 if (!MemVT
.bitsEq(OtherBC
.getValueType()))
15290 if (OtherBC
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
&&
15291 OtherBC
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
15294 Ptr
= BaseIndexOffset::match(Other
, DAG
);
15295 return (BasePtr
.equalBaseIndex(Ptr
, DAG
, Offset
));
15298 // Check if the pair of StoreNode and the RootNode already bail out many
15299 // times which is over the limit in dependence check.
15300 auto OverLimitInDependenceCheck
= [&](SDNode
*StoreNode
,
15301 SDNode
*RootNode
) -> bool {
15302 auto RootCount
= StoreRootCountMap
.find(StoreNode
);
15303 if (RootCount
!= StoreRootCountMap
.end() &&
15304 RootCount
->second
.first
== RootNode
&&
15305 RootCount
->second
.second
> StoreMergeDependenceLimit
)
15310 // We looking for a root node which is an ancestor to all mergable
15311 // stores. We search up through a load, to our root and then down
15312 // through all children. For instance we will find Store{1,2,3} if
15313 // St is Store1, Store2. or Store3 where the root is not a load
15314 // which always true for nonvolatile ops. TODO: Expand
15315 // the search to find all valid candidates through multiple layers of loads.
15318 // |-------|-------|
15319 // Load Load Store3
15323 // FIXME: We should be able to climb and
15324 // descend TokenFactors to find candidates as well.
15326 RootNode
= St
->getChain().getNode();
15328 unsigned NumNodesExplored
= 0;
15329 if (LoadSDNode
*Ldn
= dyn_cast
<LoadSDNode
>(RootNode
)) {
15330 RootNode
= Ldn
->getChain().getNode();
15331 for (auto I
= RootNode
->use_begin(), E
= RootNode
->use_end();
15332 I
!= E
&& NumNodesExplored
< 1024; ++I
, ++NumNodesExplored
)
15333 if (I
.getOperandNo() == 0 && isa
<LoadSDNode
>(*I
)) // walk down chain
15334 for (auto I2
= (*I
)->use_begin(), E2
= (*I
)->use_end(); I2
!= E2
; ++I2
)
15335 if (I2
.getOperandNo() == 0)
15336 if (StoreSDNode
*OtherST
= dyn_cast
<StoreSDNode
>(*I2
)) {
15337 BaseIndexOffset Ptr
;
15339 if (CandidateMatch(OtherST
, Ptr
, PtrDiff
) &&
15340 !OverLimitInDependenceCheck(OtherST
, RootNode
))
15341 StoreNodes
.push_back(MemOpLink(OtherST
, PtrDiff
));
15344 for (auto I
= RootNode
->use_begin(), E
= RootNode
->use_end();
15345 I
!= E
&& NumNodesExplored
< 1024; ++I
, ++NumNodesExplored
)
15346 if (I
.getOperandNo() == 0)
15347 if (StoreSDNode
*OtherST
= dyn_cast
<StoreSDNode
>(*I
)) {
15348 BaseIndexOffset Ptr
;
15350 if (CandidateMatch(OtherST
, Ptr
, PtrDiff
) &&
15351 !OverLimitInDependenceCheck(OtherST
, RootNode
))
15352 StoreNodes
.push_back(MemOpLink(OtherST
, PtrDiff
));
15356 // We need to check that merging these stores does not cause a loop in
15357 // the DAG. Any store candidate may depend on another candidate
15358 // indirectly through its operand (we already consider dependencies
15359 // through the chain). Check in parallel by searching up from
15360 // non-chain operands of candidates.
15361 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
15362 SmallVectorImpl
<MemOpLink
> &StoreNodes
, unsigned NumStores
,
15363 SDNode
*RootNode
) {
15364 // FIXME: We should be able to truncate a full search of
15365 // predecessors by doing a BFS and keeping tabs the originating
15366 // stores from which worklist nodes come from in a similar way to
15367 // TokenFactor simplfication.
15369 SmallPtrSet
<const SDNode
*, 32> Visited
;
15370 SmallVector
<const SDNode
*, 8> Worklist
;
15372 // RootNode is a predecessor to all candidates so we need not search
15373 // past it. Add RootNode (peeking through TokenFactors). Do not count
15374 // these towards size check.
15376 Worklist
.push_back(RootNode
);
15377 while (!Worklist
.empty()) {
15378 auto N
= Worklist
.pop_back_val();
15379 if (!Visited
.insert(N
).second
)
15380 continue; // Already present in Visited.
15381 if (N
->getOpcode() == ISD::TokenFactor
) {
15382 for (SDValue Op
: N
->ops())
15383 Worklist
.push_back(Op
.getNode());
15387 // Don't count pruning nodes towards max.
15388 unsigned int Max
= 1024 + Visited
.size();
15389 // Search Ops of store candidates.
15390 for (unsigned i
= 0; i
< NumStores
; ++i
) {
15391 SDNode
*N
= StoreNodes
[i
].MemNode
;
15392 // Of the 4 Store Operands:
15393 // * Chain (Op 0) -> We have already considered these
15394 // in candidate selection and can be
15396 // * Value (Op 1) -> Cycles may happen (e.g. through load chains)
15397 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
15398 // but aren't necessarily fromt the same base node, so
15399 // cycles possible (e.g. via indexed store).
15400 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for
15401 // non-indexed stores). Not constant on all targets (e.g. ARM)
15402 // and so can participate in a cycle.
15403 for (unsigned j
= 1; j
< N
->getNumOperands(); ++j
)
15404 Worklist
.push_back(N
->getOperand(j
).getNode());
15406 // Search through DAG. We can stop early if we find a store node.
15407 for (unsigned i
= 0; i
< NumStores
; ++i
)
15408 if (SDNode::hasPredecessorHelper(StoreNodes
[i
].MemNode
, Visited
, Worklist
,
15410 // If the searching bail out, record the StoreNode and RootNode in the
15411 // StoreRootCountMap. If we have seen the pair many times over a limit,
15412 // we won't add the StoreNode into StoreNodes set again.
15413 if (Visited
.size() >= Max
) {
15414 auto &RootCount
= StoreRootCountMap
[StoreNodes
[i
].MemNode
];
15415 if (RootCount
.first
== RootNode
)
15416 RootCount
.second
++;
15418 RootCount
= {RootNode
, 1};
15425 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode
*St
) {
15426 if (OptLevel
== CodeGenOpt::None
|| !EnableStoreMerging
)
15429 EVT MemVT
= St
->getMemoryVT();
15430 int64_t ElementSizeBytes
= MemVT
.getStoreSize();
15431 unsigned NumMemElts
= MemVT
.isVector() ? MemVT
.getVectorNumElements() : 1;
15433 if (MemVT
.getSizeInBits() * 2 > MaximumLegalStoreInBits
)
15436 bool NoVectors
= DAG
.getMachineFunction().getFunction().hasFnAttribute(
15437 Attribute::NoImplicitFloat
);
15439 // This function cannot currently deal with non-byte-sized memory sizes.
15440 if (ElementSizeBytes
* 8 != MemVT
.getSizeInBits())
15443 if (!MemVT
.isSimple())
15446 // Perform an early exit check. Do not bother looking at stored values that
15447 // are not constants, loads, or extracted vector elements.
15448 SDValue StoredVal
= peekThroughBitcasts(St
->getValue());
15449 bool IsLoadSrc
= isa
<LoadSDNode
>(StoredVal
);
15450 bool IsConstantSrc
= isa
<ConstantSDNode
>(StoredVal
) ||
15451 isa
<ConstantFPSDNode
>(StoredVal
);
15452 bool IsExtractVecSrc
= (StoredVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
||
15453 StoredVal
.getOpcode() == ISD::EXTRACT_SUBVECTOR
);
15454 bool IsNonTemporalStore
= St
->isNonTemporal();
15455 bool IsNonTemporalLoad
=
15456 IsLoadSrc
&& cast
<LoadSDNode
>(StoredVal
)->isNonTemporal();
15458 if (!IsConstantSrc
&& !IsLoadSrc
&& !IsExtractVecSrc
)
15461 SmallVector
<MemOpLink
, 8> StoreNodes
;
15463 // Find potential store merge candidates by searching through chain sub-DAG
15464 getStoreMergeCandidates(St
, StoreNodes
, RootNode
);
15466 // Check if there is anything to merge.
15467 if (StoreNodes
.size() < 2)
15470 // Sort the memory operands according to their distance from the
15472 llvm::sort(StoreNodes
, [](MemOpLink LHS
, MemOpLink RHS
) {
15473 return LHS
.OffsetFromBase
< RHS
.OffsetFromBase
;
15476 // Store Merge attempts to merge the lowest stores. This generally
15477 // works out as if successful, as the remaining stores are checked
15478 // after the first collection of stores is merged. However, in the
15479 // case that a non-mergeable store is found first, e.g., {p[-2],
15480 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
15481 // mergeable cases. To prevent this, we prune such stores from the
15482 // front of StoreNodes here.
15485 while (StoreNodes
.size() > 1) {
15486 size_t StartIdx
= 0;
15487 while ((StartIdx
+ 1 < StoreNodes
.size()) &&
15488 StoreNodes
[StartIdx
].OffsetFromBase
+ ElementSizeBytes
!=
15489 StoreNodes
[StartIdx
+ 1].OffsetFromBase
)
15492 // Bail if we don't have enough candidates to merge.
15493 if (StartIdx
+ 1 >= StoreNodes
.size())
15497 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + StartIdx
);
15499 // Scan the memory operations on the chain and find the first
15500 // non-consecutive store memory address.
15501 unsigned NumConsecutiveStores
= 1;
15502 int64_t StartAddress
= StoreNodes
[0].OffsetFromBase
;
15503 // Check that the addresses are consecutive starting from the second
15504 // element in the list of stores.
15505 for (unsigned i
= 1, e
= StoreNodes
.size(); i
< e
; ++i
) {
15506 int64_t CurrAddress
= StoreNodes
[i
].OffsetFromBase
;
15507 if (CurrAddress
- StartAddress
!= (ElementSizeBytes
* i
))
15509 NumConsecutiveStores
= i
+ 1;
15512 if (NumConsecutiveStores
< 2) {
15513 StoreNodes
.erase(StoreNodes
.begin(),
15514 StoreNodes
.begin() + NumConsecutiveStores
);
15518 // The node with the lowest store address.
15519 LLVMContext
&Context
= *DAG
.getContext();
15520 const DataLayout
&DL
= DAG
.getDataLayout();
15522 // Store the constants into memory as one consecutive store.
15523 if (IsConstantSrc
) {
15524 while (NumConsecutiveStores
>= 2) {
15525 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15526 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15527 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15528 unsigned LastLegalType
= 1;
15529 unsigned LastLegalVectorType
= 1;
15530 bool LastIntegerTrunc
= false;
15531 bool NonZero
= false;
15532 unsigned FirstZeroAfterNonZero
= NumConsecutiveStores
;
15533 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15534 StoreSDNode
*ST
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15535 SDValue StoredVal
= ST
->getValue();
15536 bool IsElementZero
= false;
15537 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(StoredVal
))
15538 IsElementZero
= C
->isNullValue();
15539 else if (ConstantFPSDNode
*C
= dyn_cast
<ConstantFPSDNode
>(StoredVal
))
15540 IsElementZero
= C
->getConstantFPValue()->isNullValue();
15541 if (IsElementZero
) {
15542 if (NonZero
&& FirstZeroAfterNonZero
== NumConsecutiveStores
)
15543 FirstZeroAfterNonZero
= i
;
15545 NonZero
|= !IsElementZero
;
15547 // Find a legal type for the constant store.
15548 unsigned SizeInBits
= (i
+ 1) * ElementSizeBytes
* 8;
15549 EVT StoreTy
= EVT::getIntegerVT(Context
, SizeInBits
);
15550 bool IsFast
= false;
15552 // Break early when size is too large to be legal.
15553 if (StoreTy
.getSizeInBits() > MaximumLegalStoreInBits
)
15556 if (TLI
.isTypeLegal(StoreTy
) &&
15557 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15558 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15559 *FirstInChain
->getMemOperand(), &IsFast
) &&
15561 LastIntegerTrunc
= false;
15562 LastLegalType
= i
+ 1;
15563 // Or check whether a truncstore is legal.
15564 } else if (TLI
.getTypeAction(Context
, StoreTy
) ==
15565 TargetLowering::TypePromoteInteger
) {
15566 EVT LegalizedStoredValTy
=
15567 TLI
.getTypeToTransformTo(Context
, StoredVal
.getValueType());
15568 if (TLI
.isTruncStoreLegal(LegalizedStoredValTy
, StoreTy
) &&
15569 TLI
.canMergeStoresTo(FirstStoreAS
, LegalizedStoredValTy
, DAG
) &&
15570 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15571 *FirstInChain
->getMemOperand(),
15574 LastIntegerTrunc
= true;
15575 LastLegalType
= i
+ 1;
15579 // We only use vectors if the constant is known to be zero or the
15580 // target allows it and the function is not marked with the
15581 // noimplicitfloat attribute.
15583 TLI
.storeOfVectorConstantIsCheap(MemVT
, i
+ 1, FirstStoreAS
)) &&
15585 // Find a legal type for the vector store.
15586 unsigned Elts
= (i
+ 1) * NumMemElts
;
15587 EVT Ty
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
15588 if (TLI
.isTypeLegal(Ty
) && TLI
.isTypeLegal(MemVT
) &&
15589 TLI
.canMergeStoresTo(FirstStoreAS
, Ty
, DAG
) &&
15590 TLI
.allowsMemoryAccess(
15591 Context
, DL
, Ty
, *FirstInChain
->getMemOperand(), &IsFast
) &&
15593 LastLegalVectorType
= i
+ 1;
15597 bool UseVector
= (LastLegalVectorType
> LastLegalType
) && !NoVectors
;
15598 unsigned NumElem
= (UseVector
) ? LastLegalVectorType
: LastLegalType
;
15600 // Check if we found a legal integer type that creates a meaningful
15603 // We know that candidate stores are in order and of correct
15604 // shape. While there is no mergeable sequence from the
15605 // beginning one may start later in the sequence. The only
15606 // reason a merge of size N could have failed where another of
15607 // the same size would not have, is if the alignment has
15608 // improved or we've dropped a non-zero value. Drop as many
15609 // candidates as we can here.
15610 unsigned NumSkip
= 1;
15612 (NumSkip
< NumConsecutiveStores
) &&
15613 (NumSkip
< FirstZeroAfterNonZero
) &&
15614 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
15617 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
15618 NumConsecutiveStores
-= NumSkip
;
15622 // Check that we can merge these candidates without causing a cycle.
15623 if (!checkMergeStoreCandidatesForDependencies(StoreNodes
, NumElem
,
15625 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15626 NumConsecutiveStores
-= NumElem
;
15630 RV
|= MergeStoresOfConstantsOrVecElts(StoreNodes
, MemVT
, NumElem
, true,
15631 UseVector
, LastIntegerTrunc
);
15633 // Remove merged stores for next iteration.
15634 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15635 NumConsecutiveStores
-= NumElem
;
15640 // When extracting multiple vector elements, try to store them
15641 // in one vector store rather than a sequence of scalar stores.
15642 if (IsExtractVecSrc
) {
15643 // Loop on Consecutive Stores on success.
15644 while (NumConsecutiveStores
>= 2) {
15645 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15646 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15647 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15648 unsigned NumStoresToMerge
= 1;
15649 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15650 // Find a legal type for the vector store.
15651 unsigned Elts
= (i
+ 1) * NumMemElts
;
15653 EVT::getVectorVT(*DAG
.getContext(), MemVT
.getScalarType(), Elts
);
15656 // Break early when size is too large to be legal.
15657 if (Ty
.getSizeInBits() > MaximumLegalStoreInBits
)
15660 if (TLI
.isTypeLegal(Ty
) &&
15661 TLI
.canMergeStoresTo(FirstStoreAS
, Ty
, DAG
) &&
15662 TLI
.allowsMemoryAccess(Context
, DL
, Ty
,
15663 *FirstInChain
->getMemOperand(), &IsFast
) &&
15665 NumStoresToMerge
= i
+ 1;
15668 // Check if we found a legal integer type creating a meaningful
15670 if (NumStoresToMerge
< 2) {
15671 // We know that candidate stores are in order and of correct
15672 // shape. While there is no mergeable sequence from the
15673 // beginning one may start later in the sequence. The only
15674 // reason a merge of size N could have failed where another of
15675 // the same size would not have, is if the alignment has
15676 // improved. Drop as many candidates as we can here.
15677 unsigned NumSkip
= 1;
15679 (NumSkip
< NumConsecutiveStores
) &&
15680 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
15683 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
15684 NumConsecutiveStores
-= NumSkip
;
15688 // Check that we can merge these candidates without causing a cycle.
15689 if (!checkMergeStoreCandidatesForDependencies(
15690 StoreNodes
, NumStoresToMerge
, RootNode
)) {
15691 StoreNodes
.erase(StoreNodes
.begin(),
15692 StoreNodes
.begin() + NumStoresToMerge
);
15693 NumConsecutiveStores
-= NumStoresToMerge
;
15697 RV
|= MergeStoresOfConstantsOrVecElts(
15698 StoreNodes
, MemVT
, NumStoresToMerge
, false, true, false);
15700 StoreNodes
.erase(StoreNodes
.begin(),
15701 StoreNodes
.begin() + NumStoresToMerge
);
15702 NumConsecutiveStores
-= NumStoresToMerge
;
15707 // Below we handle the case of multiple consecutive stores that
15708 // come from multiple consecutive loads. We merge them into a single
15709 // wide load and a single wide store.
15711 // Look for load nodes which are used by the stored values.
15712 SmallVector
<MemOpLink
, 8> LoadNodes
;
15714 // Find acceptable loads. Loads need to have the same chain (token factor),
15715 // must not be zext, volatile, indexed, and they must be consecutive.
15716 BaseIndexOffset LdBasePtr
;
15718 for (unsigned i
= 0; i
< NumConsecutiveStores
; ++i
) {
15719 StoreSDNode
*St
= cast
<StoreSDNode
>(StoreNodes
[i
].MemNode
);
15720 SDValue Val
= peekThroughBitcasts(St
->getValue());
15721 LoadSDNode
*Ld
= cast
<LoadSDNode
>(Val
);
15723 BaseIndexOffset LdPtr
= BaseIndexOffset::match(Ld
, DAG
);
15724 // If this is not the first ptr that we check.
15725 int64_t LdOffset
= 0;
15726 if (LdBasePtr
.getBase().getNode()) {
15727 // The base ptr must be the same.
15728 if (!LdBasePtr
.equalBaseIndex(LdPtr
, DAG
, LdOffset
))
15731 // Check that all other base pointers are the same as this one.
15735 // We found a potential memory operand to merge.
15736 LoadNodes
.push_back(MemOpLink(Ld
, LdOffset
));
15739 while (NumConsecutiveStores
>= 2 && LoadNodes
.size() >= 2) {
15740 // If we have load/store pair instructions and we only have two values,
15741 // don't bother merging.
15742 unsigned RequiredAlignment
;
15743 if (LoadNodes
.size() == 2 &&
15744 TLI
.hasPairedLoad(MemVT
, RequiredAlignment
) &&
15745 StoreNodes
[0].MemNode
->getAlignment() >= RequiredAlignment
) {
15746 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + 2);
15747 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + 2);
15750 LSBaseSDNode
*FirstInChain
= StoreNodes
[0].MemNode
;
15751 unsigned FirstStoreAS
= FirstInChain
->getAddressSpace();
15752 unsigned FirstStoreAlign
= FirstInChain
->getAlignment();
15753 LoadSDNode
*FirstLoad
= cast
<LoadSDNode
>(LoadNodes
[0].MemNode
);
15754 unsigned FirstLoadAlign
= FirstLoad
->getAlignment();
15756 // Scan the memory operations on the chain and find the first
15757 // non-consecutive load memory address. These variables hold the index in
15758 // the store node array.
15760 unsigned LastConsecutiveLoad
= 1;
15762 // This variable refers to the size and not index in the array.
15763 unsigned LastLegalVectorType
= 1;
15764 unsigned LastLegalIntegerType
= 1;
15765 bool isDereferenceable
= true;
15766 bool DoIntegerTruncate
= false;
15767 StartAddress
= LoadNodes
[0].OffsetFromBase
;
15768 SDValue FirstChain
= FirstLoad
->getChain();
15769 for (unsigned i
= 1; i
< LoadNodes
.size(); ++i
) {
15770 // All loads must share the same chain.
15771 if (LoadNodes
[i
].MemNode
->getChain() != FirstChain
)
15774 int64_t CurrAddress
= LoadNodes
[i
].OffsetFromBase
;
15775 if (CurrAddress
- StartAddress
!= (ElementSizeBytes
* i
))
15777 LastConsecutiveLoad
= i
;
15779 if (isDereferenceable
&& !LoadNodes
[i
].MemNode
->isDereferenceable())
15780 isDereferenceable
= false;
15782 // Find a legal type for the vector store.
15783 unsigned Elts
= (i
+ 1) * NumMemElts
;
15784 EVT StoreTy
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
15786 // Break early when size is too large to be legal.
15787 if (StoreTy
.getSizeInBits() > MaximumLegalStoreInBits
)
15790 bool IsFastSt
, IsFastLd
;
15791 if (TLI
.isTypeLegal(StoreTy
) &&
15792 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15793 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15794 *FirstInChain
->getMemOperand(), &IsFastSt
) &&
15796 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15797 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15799 LastLegalVectorType
= i
+ 1;
15802 // Find a legal type for the integer store.
15803 unsigned SizeInBits
= (i
+ 1) * ElementSizeBytes
* 8;
15804 StoreTy
= EVT::getIntegerVT(Context
, SizeInBits
);
15805 if (TLI
.isTypeLegal(StoreTy
) &&
15806 TLI
.canMergeStoresTo(FirstStoreAS
, StoreTy
, DAG
) &&
15807 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15808 *FirstInChain
->getMemOperand(), &IsFastSt
) &&
15810 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15811 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15813 LastLegalIntegerType
= i
+ 1;
15814 DoIntegerTruncate
= false;
15815 // Or check whether a truncstore and extload is legal.
15816 } else if (TLI
.getTypeAction(Context
, StoreTy
) ==
15817 TargetLowering::TypePromoteInteger
) {
15818 EVT LegalizedStoredValTy
= TLI
.getTypeToTransformTo(Context
, StoreTy
);
15819 if (TLI
.isTruncStoreLegal(LegalizedStoredValTy
, StoreTy
) &&
15820 TLI
.canMergeStoresTo(FirstStoreAS
, LegalizedStoredValTy
, DAG
) &&
15821 TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, LegalizedStoredValTy
,
15823 TLI
.isLoadExtLegal(ISD::SEXTLOAD
, LegalizedStoredValTy
,
15825 TLI
.isLoadExtLegal(ISD::EXTLOAD
, LegalizedStoredValTy
, StoreTy
) &&
15826 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15827 *FirstInChain
->getMemOperand(),
15830 TLI
.allowsMemoryAccess(Context
, DL
, StoreTy
,
15831 *FirstLoad
->getMemOperand(), &IsFastLd
) &&
15833 LastLegalIntegerType
= i
+ 1;
15834 DoIntegerTruncate
= true;
15839 // Only use vector types if the vector type is larger than the integer
15840 // type. If they are the same, use integers.
15842 LastLegalVectorType
> LastLegalIntegerType
&& !NoVectors
;
15843 unsigned LastLegalType
=
15844 std::max(LastLegalVectorType
, LastLegalIntegerType
);
15846 // We add +1 here because the LastXXX variables refer to location while
15847 // the NumElem refers to array/index size.
15849 std::min(NumConsecutiveStores
, LastConsecutiveLoad
+ 1);
15850 NumElem
= std::min(LastLegalType
, NumElem
);
15853 // We know that candidate stores are in order and of correct
15854 // shape. While there is no mergeable sequence from the
15855 // beginning one may start later in the sequence. The only
15856 // reason a merge of size N could have failed where another of
15857 // the same size would not have is if the alignment or either
15858 // the load or store has improved. Drop as many candidates as we
15860 unsigned NumSkip
= 1;
15861 while ((NumSkip
< LoadNodes
.size()) &&
15862 (LoadNodes
[NumSkip
].MemNode
->getAlignment() <= FirstLoadAlign
) &&
15863 (StoreNodes
[NumSkip
].MemNode
->getAlignment() <= FirstStoreAlign
))
15865 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumSkip
);
15866 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumSkip
);
15867 NumConsecutiveStores
-= NumSkip
;
15871 // Check that we can merge these candidates without causing a cycle.
15872 if (!checkMergeStoreCandidatesForDependencies(StoreNodes
, NumElem
,
15874 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15875 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumElem
);
15876 NumConsecutiveStores
-= NumElem
;
15880 // Find if it is better to use vectors or integers to load and store
15884 // Find a legal type for the vector store.
15885 unsigned Elts
= NumElem
* NumMemElts
;
15886 JointMemOpVT
= EVT::getVectorVT(Context
, MemVT
.getScalarType(), Elts
);
15888 unsigned SizeInBits
= NumElem
* ElementSizeBytes
* 8;
15889 JointMemOpVT
= EVT::getIntegerVT(Context
, SizeInBits
);
15892 SDLoc
LoadDL(LoadNodes
[0].MemNode
);
15893 SDLoc
StoreDL(StoreNodes
[0].MemNode
);
15895 // The merged loads are required to have the same incoming chain, so
15896 // using the first's chain is acceptable.
15898 SDValue NewStoreChain
= getMergeStoreChains(StoreNodes
, NumElem
);
15899 AddToWorklist(NewStoreChain
.getNode());
15901 MachineMemOperand::Flags LdMMOFlags
=
15902 isDereferenceable
? MachineMemOperand::MODereferenceable
15903 : MachineMemOperand::MONone
;
15904 if (IsNonTemporalLoad
)
15905 LdMMOFlags
|= MachineMemOperand::MONonTemporal
;
15907 MachineMemOperand::Flags StMMOFlags
=
15908 IsNonTemporalStore
? MachineMemOperand::MONonTemporal
15909 : MachineMemOperand::MONone
;
15911 SDValue NewLoad
, NewStore
;
15912 if (UseVectorTy
|| !DoIntegerTruncate
) {
15914 DAG
.getLoad(JointMemOpVT
, LoadDL
, FirstLoad
->getChain(),
15915 FirstLoad
->getBasePtr(), FirstLoad
->getPointerInfo(),
15916 FirstLoadAlign
, LdMMOFlags
);
15917 NewStore
= DAG
.getStore(
15918 NewStoreChain
, StoreDL
, NewLoad
, FirstInChain
->getBasePtr(),
15919 FirstInChain
->getPointerInfo(), FirstStoreAlign
, StMMOFlags
);
15920 } else { // This must be the truncstore/extload case
15922 TLI
.getTypeToTransformTo(*DAG
.getContext(), JointMemOpVT
);
15923 NewLoad
= DAG
.getExtLoad(ISD::EXTLOAD
, LoadDL
, ExtendedTy
,
15924 FirstLoad
->getChain(), FirstLoad
->getBasePtr(),
15925 FirstLoad
->getPointerInfo(), JointMemOpVT
,
15926 FirstLoadAlign
, LdMMOFlags
);
15927 NewStore
= DAG
.getTruncStore(NewStoreChain
, StoreDL
, NewLoad
,
15928 FirstInChain
->getBasePtr(),
15929 FirstInChain
->getPointerInfo(),
15930 JointMemOpVT
, FirstInChain
->getAlignment(),
15931 FirstInChain
->getMemOperand()->getFlags());
15934 // Transfer chain users from old loads to the new load.
15935 for (unsigned i
= 0; i
< NumElem
; ++i
) {
15936 LoadSDNode
*Ld
= cast
<LoadSDNode
>(LoadNodes
[i
].MemNode
);
15937 DAG
.ReplaceAllUsesOfValueWith(SDValue(Ld
, 1),
15938 SDValue(NewLoad
.getNode(), 1));
15941 // Replace the all stores with the new store. Recursively remove
15942 // corresponding value if its no longer used.
15943 for (unsigned i
= 0; i
< NumElem
; ++i
) {
15944 SDValue Val
= StoreNodes
[i
].MemNode
->getOperand(1);
15945 CombineTo(StoreNodes
[i
].MemNode
, NewStore
);
15946 if (Val
.getNode()->use_empty())
15947 recursivelyDeleteUnusedNodes(Val
.getNode());
15951 StoreNodes
.erase(StoreNodes
.begin(), StoreNodes
.begin() + NumElem
);
15952 LoadNodes
.erase(LoadNodes
.begin(), LoadNodes
.begin() + NumElem
);
15953 NumConsecutiveStores
-= NumElem
;
15959 SDValue
DAGCombiner::replaceStoreChain(StoreSDNode
*ST
, SDValue BetterChain
) {
15963 // Replace the chain to avoid dependency.
15964 if (ST
->isTruncatingStore()) {
15965 ReplStore
= DAG
.getTruncStore(BetterChain
, SL
, ST
->getValue(),
15966 ST
->getBasePtr(), ST
->getMemoryVT(),
15967 ST
->getMemOperand());
15969 ReplStore
= DAG
.getStore(BetterChain
, SL
, ST
->getValue(), ST
->getBasePtr(),
15970 ST
->getMemOperand());
15973 // Create token to keep both nodes around.
15974 SDValue Token
= DAG
.getNode(ISD::TokenFactor
, SL
,
15975 MVT::Other
, ST
->getChain(), ReplStore
);
15977 // Make sure the new and old chains are cleaned up.
15978 AddToWorklist(Token
.getNode());
15980 // Don't add users to work list.
15981 return CombineTo(ST
, Token
, false);
15984 SDValue
DAGCombiner::replaceStoreOfFPConstant(StoreSDNode
*ST
) {
15985 SDValue Value
= ST
->getValue();
15986 if (Value
.getOpcode() == ISD::TargetConstantFP
)
15991 SDValue Chain
= ST
->getChain();
15992 SDValue Ptr
= ST
->getBasePtr();
15994 const ConstantFPSDNode
*CFP
= cast
<ConstantFPSDNode
>(Value
);
15996 // NOTE: If the original store is volatile, this transform must not increase
15997 // the number of stores. For example, on x86-32 an f64 can be stored in one
15998 // processor operation but an i64 (which is not legal) requires two. So the
15999 // transform should not be done in this case.
16002 switch (CFP
->getSimpleValueType(0).SimpleTy
) {
16004 llvm_unreachable("Unknown FP type");
16005 case MVT::f16
: // We don't do this for these yet.
16011 if ((isTypeLegal(MVT::i32
) && !LegalOperations
&& !ST
->isVolatile()) ||
16012 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i32
)) {
16014 Tmp
= DAG
.getConstant((uint32_t)CFP
->getValueAPF().
16015 bitcastToAPInt().getZExtValue(), SDLoc(CFP
),
16017 return DAG
.getStore(Chain
, DL
, Tmp
, Ptr
, ST
->getMemOperand());
16022 if ((TLI
.isTypeLegal(MVT::i64
) && !LegalOperations
&&
16023 !ST
->isVolatile()) ||
16024 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i64
)) {
16026 Tmp
= DAG
.getConstant(CFP
->getValueAPF().bitcastToAPInt().
16027 getZExtValue(), SDLoc(CFP
), MVT::i64
);
16028 return DAG
.getStore(Chain
, DL
, Tmp
,
16029 Ptr
, ST
->getMemOperand());
16032 if (!ST
->isVolatile() &&
16033 TLI
.isOperationLegalOrCustom(ISD::STORE
, MVT::i32
)) {
16034 // Many FP stores are not made apparent until after legalize, e.g. for
16035 // argument passing. Since this is so common, custom legalize the
16036 // 64-bit integer store into two 32-bit stores.
16037 uint64_t Val
= CFP
->getValueAPF().bitcastToAPInt().getZExtValue();
16038 SDValue Lo
= DAG
.getConstant(Val
& 0xFFFFFFFF, SDLoc(CFP
), MVT::i32
);
16039 SDValue Hi
= DAG
.getConstant(Val
>> 32, SDLoc(CFP
), MVT::i32
);
16040 if (DAG
.getDataLayout().isBigEndian())
16043 unsigned Alignment
= ST
->getAlignment();
16044 MachineMemOperand::Flags MMOFlags
= ST
->getMemOperand()->getFlags();
16045 AAMDNodes AAInfo
= ST
->getAAInfo();
16047 SDValue St0
= DAG
.getStore(Chain
, DL
, Lo
, Ptr
, ST
->getPointerInfo(),
16048 ST
->getAlignment(), MMOFlags
, AAInfo
);
16049 Ptr
= DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(), Ptr
,
16050 DAG
.getConstant(4, DL
, Ptr
.getValueType()));
16051 Alignment
= MinAlign(Alignment
, 4U);
16052 SDValue St1
= DAG
.getStore(Chain
, DL
, Hi
, Ptr
,
16053 ST
->getPointerInfo().getWithOffset(4),
16054 Alignment
, MMOFlags
, AAInfo
);
16055 return DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
,
16063 SDValue
DAGCombiner::visitSTORE(SDNode
*N
) {
16064 StoreSDNode
*ST
= cast
<StoreSDNode
>(N
);
16065 SDValue Chain
= ST
->getChain();
16066 SDValue Value
= ST
->getValue();
16067 SDValue Ptr
= ST
->getBasePtr();
16069 // If this is a store of a bit convert, store the input value if the
16070 // resultant store does not need a higher alignment than the original.
16071 if (Value
.getOpcode() == ISD::BITCAST
&& !ST
->isTruncatingStore() &&
16072 ST
->isUnindexed()) {
16073 EVT SVT
= Value
.getOperand(0).getValueType();
16074 // If the store is volatile, we only want to change the store type if the
16075 // resulting store is legal. Otherwise we might increase the number of
16076 // memory accesses. We don't care if the original type was legal or not
16077 // as we assume software couldn't rely on the number of accesses of an
16079 if (((!LegalOperations
&& !ST
->isVolatile()) ||
16080 TLI
.isOperationLegal(ISD::STORE
, SVT
)) &&
16081 TLI
.isStoreBitCastBeneficial(Value
.getValueType(), SVT
,
16082 DAG
, *ST
->getMemOperand())) {
16083 return DAG
.getStore(Chain
, SDLoc(N
), Value
.getOperand(0), Ptr
,
16084 ST
->getPointerInfo(), ST
->getAlignment(),
16085 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
16089 // Turn 'store undef, Ptr' -> nothing.
16090 if (Value
.isUndef() && ST
->isUnindexed())
16093 // Try to infer better alignment information than the store already has.
16094 if (OptLevel
!= CodeGenOpt::None
&& ST
->isUnindexed()) {
16095 if (unsigned Align
= DAG
.InferPtrAlignment(Ptr
)) {
16096 if (Align
> ST
->getAlignment() && ST
->getSrcValueOffset() % Align
== 0) {
16098 DAG
.getTruncStore(Chain
, SDLoc(N
), Value
, Ptr
, ST
->getPointerInfo(),
16099 ST
->getMemoryVT(), Align
,
16100 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
16101 // NewStore will always be N as we are only refining the alignment
16102 assert(NewStore
.getNode() == N
);
16108 // Try transforming a pair floating point load / store ops to integer
16109 // load / store ops.
16110 if (SDValue NewST
= TransformFPLoadStorePair(N
))
16113 // Try transforming several stores into STORE (BSWAP).
16114 if (SDValue Store
= MatchStoreCombine(ST
))
16117 if (ST
->isUnindexed()) {
16118 // Walk up chain skipping non-aliasing memory nodes, on this store and any
16119 // adjacent stores.
16120 if (findBetterNeighborChains(ST
)) {
16121 // replaceStoreChain uses CombineTo, which handled all of the worklist
16122 // manipulation. Return the original node to not do anything else.
16123 return SDValue(ST
, 0);
16125 Chain
= ST
->getChain();
16128 // FIXME: is there such a thing as a truncating indexed store?
16129 if (ST
->isTruncatingStore() && ST
->isUnindexed() &&
16130 Value
.getValueType().isInteger() &&
16131 (!isa
<ConstantSDNode
>(Value
) ||
16132 !cast
<ConstantSDNode
>(Value
)->isOpaque())) {
16133 APInt TruncDemandedBits
=
16134 APInt::getLowBitsSet(Value
.getScalarValueSizeInBits(),
16135 ST
->getMemoryVT().getScalarSizeInBits());
16137 // See if we can simplify the input to this truncstore with knowledge that
16138 // only the low bits are being used. For example:
16139 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
16140 AddToWorklist(Value
.getNode());
16141 if (SDValue Shorter
= DAG
.GetDemandedBits(Value
, TruncDemandedBits
))
16142 return DAG
.getTruncStore(Chain
, SDLoc(N
), Shorter
, Ptr
, ST
->getMemoryVT(),
16143 ST
->getMemOperand());
16145 // Otherwise, see if we can simplify the operation with
16146 // SimplifyDemandedBits, which only works if the value has a single use.
16147 if (SimplifyDemandedBits(Value
, TruncDemandedBits
)) {
16148 // Re-visit the store if anything changed and the store hasn't been merged
16149 // with another node (N is deleted) SimplifyDemandedBits will add Value's
16150 // node back to the worklist if necessary, but we also need to re-visit
16151 // the Store node itself.
16152 if (N
->getOpcode() != ISD::DELETED_NODE
)
16154 return SDValue(N
, 0);
16158 // If this is a load followed by a store to the same location, then the store
16160 if (LoadSDNode
*Ld
= dyn_cast
<LoadSDNode
>(Value
)) {
16161 if (Ld
->getBasePtr() == Ptr
&& ST
->getMemoryVT() == Ld
->getMemoryVT() &&
16162 ST
->isUnindexed() && !ST
->isVolatile() &&
16163 // There can't be any side effects between the load and store, such as
16164 // a call or store.
16165 Chain
.reachesChainWithoutSideEffects(SDValue(Ld
, 1))) {
16166 // The store is dead, remove it.
16171 if (StoreSDNode
*ST1
= dyn_cast
<StoreSDNode
>(Chain
)) {
16172 if (ST
->isUnindexed() && !ST
->isVolatile() && ST1
->isUnindexed() &&
16173 !ST1
->isVolatile()) {
16174 if (ST1
->getBasePtr() == Ptr
&& ST1
->getValue() == Value
&&
16175 ST
->getMemoryVT() == ST1
->getMemoryVT()) {
16176 // If this is a store followed by a store with the same value to the
16177 // same location, then the store is dead/noop.
16181 if (OptLevel
!= CodeGenOpt::None
&& ST1
->hasOneUse() &&
16182 !ST1
->getBasePtr().isUndef()) {
16183 const BaseIndexOffset STBase
= BaseIndexOffset::match(ST
, DAG
);
16184 const BaseIndexOffset ChainBase
= BaseIndexOffset::match(ST1
, DAG
);
16185 unsigned STBitSize
= ST
->getMemoryVT().getSizeInBits();
16186 unsigned ChainBitSize
= ST1
->getMemoryVT().getSizeInBits();
16187 // If this is a store who's preceding store to a subset of the current
16188 // location and no one other node is chained to that store we can
16189 // effectively drop the store. Do not remove stores to undef as they may
16190 // be used as data sinks.
16191 if (STBase
.contains(DAG
, STBitSize
, ChainBase
, ChainBitSize
)) {
16192 CombineTo(ST1
, ST1
->getChain());
16196 // If ST stores to a subset of preceding store's write set, we may be
16197 // able to fold ST's value into the preceding stored value. As we know
16198 // the other uses of ST1's chain are unconcerned with ST, this folding
16199 // will not affect those nodes.
16201 if (ChainBase
.contains(DAG
, ChainBitSize
, STBase
, STBitSize
,
16203 SDValue ChainValue
= ST1
->getValue();
16204 if (auto *C1
= dyn_cast
<ConstantSDNode
>(ChainValue
)) {
16205 if (auto *C
= dyn_cast
<ConstantSDNode
>(Value
)) {
16206 APInt Val
= C1
->getAPIntValue();
16207 APInt InsertVal
= C
->getAPIntValue().zextOrTrunc(STBitSize
);
16208 // FIXME: Handle Big-endian mode.
16209 if (!DAG
.getDataLayout().isBigEndian()) {
16210 Val
.insertBits(InsertVal
, BitOffset
);
16212 DAG
.getConstant(Val
, SDLoc(C
), ChainValue
.getValueType(),
16213 C1
->isTargetOpcode(), C1
->isOpaque());
16214 SDNode
*NewST1
= DAG
.UpdateNodeOperands(
16215 ST1
, ST1
->getChain(), NewSDVal
, ST1
->getOperand(2),
16216 ST1
->getOperand(3));
16217 return CombineTo(ST
, SDValue(NewST1
, 0));
16221 } // End ST subset of ST1 case.
16226 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
16227 // truncating store. We can do this even if this is already a truncstore.
16228 if ((Value
.getOpcode() == ISD::FP_ROUND
|| Value
.getOpcode() == ISD::TRUNCATE
)
16229 && Value
.getNode()->hasOneUse() && ST
->isUnindexed() &&
16230 TLI
.isTruncStoreLegal(Value
.getOperand(0).getValueType(),
16231 ST
->getMemoryVT())) {
16232 return DAG
.getTruncStore(Chain
, SDLoc(N
), Value
.getOperand(0),
16233 Ptr
, ST
->getMemoryVT(), ST
->getMemOperand());
16236 // Always perform this optimization before types are legal. If the target
16237 // prefers, also try this after legalization to catch stores that were created
16238 // by intrinsics or other nodes.
16239 if (!LegalTypes
|| (TLI
.mergeStoresAfterLegalization(ST
->getMemoryVT()))) {
16241 // There can be multiple store sequences on the same chain.
16242 // Keep trying to merge store sequences until we are unable to do so
16243 // or until we merge the last store on the chain.
16244 bool Changed
= MergeConsecutiveStores(ST
);
16245 if (!Changed
) break;
16246 // Return N as merge only uses CombineTo and no worklist clean
16247 // up is necessary.
16248 if (N
->getOpcode() == ISD::DELETED_NODE
|| !isa
<StoreSDNode
>(N
))
16249 return SDValue(N
, 0);
16253 // Try transforming N to an indexed store.
16254 if (CombineToPreIndexedLoadStore(N
) || CombineToPostIndexedLoadStore(N
))
16255 return SDValue(N
, 0);
16257 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
16259 // Make sure to do this only after attempting to merge stores in order to
16260 // avoid changing the types of some subset of stores due to visit order,
16261 // preventing their merging.
16262 if (isa
<ConstantFPSDNode
>(ST
->getValue())) {
16263 if (SDValue NewSt
= replaceStoreOfFPConstant(ST
))
16267 if (SDValue NewSt
= splitMergedValStore(ST
))
16270 return ReduceLoadOpStoreWidth(N
);
16273 SDValue
DAGCombiner::visitLIFETIME_END(SDNode
*N
) {
16274 const auto *LifetimeEnd
= cast
<LifetimeSDNode
>(N
);
16275 if (!LifetimeEnd
->hasOffset())
16278 const BaseIndexOffset
LifetimeEndBase(N
->getOperand(1), SDValue(),
16279 LifetimeEnd
->getOffset(), false);
16281 // We walk up the chains to find stores.
16282 SmallVector
<SDValue
, 8> Chains
= {N
->getOperand(0)};
16283 while (!Chains
.empty()) {
16284 SDValue Chain
= Chains
.back();
16286 if (!Chain
.hasOneUse())
16288 switch (Chain
.getOpcode()) {
16289 case ISD::TokenFactor
:
16290 for (unsigned Nops
= Chain
.getNumOperands(); Nops
;)
16291 Chains
.push_back(Chain
.getOperand(--Nops
));
16293 case ISD::LIFETIME_START
:
16294 case ISD::LIFETIME_END
:
16295 // We can forward past any lifetime start/end that can be proven not to
16297 if (!isAlias(Chain
.getNode(), N
))
16298 Chains
.push_back(Chain
.getOperand(0));
16301 StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(Chain
);
16302 if (ST
->isVolatile() || ST
->isIndexed())
16304 const BaseIndexOffset StoreBase
= BaseIndexOffset::match(ST
, DAG
);
16305 // If we store purely within object bounds just before its lifetime ends,
16306 // we can remove the store.
16307 if (LifetimeEndBase
.contains(DAG
, LifetimeEnd
->getSize() * 8, StoreBase
,
16308 ST
->getMemoryVT().getStoreSizeInBits())) {
16309 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase
.dump();
16310 dbgs() << "\nwithin LIFETIME_END of : ";
16311 LifetimeEndBase
.dump(); dbgs() << "\n");
16312 CombineTo(ST
, ST
->getChain());
16313 return SDValue(N
, 0);
16321 /// For the instruction sequence of store below, F and I values
16322 /// are bundled together as an i64 value before being stored into memory.
16323 /// Sometimes it is more efficent to generate separate stores for F and I,
16324 /// which can remove the bitwise instructions or sink them to colder places.
16326 /// (store (or (zext (bitcast F to i32) to i64),
16327 /// (shl (zext I to i64), 32)), addr) -->
16328 /// (store F, addr) and (store I, addr+4)
16330 /// Similarly, splitting for other merged store can also be beneficial, like:
16331 /// For pair of {i32, i32}, i64 store --> two i32 stores.
16332 /// For pair of {i32, i16}, i64 store --> two i32 stores.
16333 /// For pair of {i16, i16}, i32 store --> two i16 stores.
16334 /// For pair of {i16, i8}, i32 store --> two i16 stores.
16335 /// For pair of {i8, i8}, i16 store --> two i8 stores.
16337 /// We allow each target to determine specifically which kind of splitting is
16340 /// The store patterns are commonly seen from the simple code snippet below
16341 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
16342 /// void goo(const std::pair<int, float> &);
16345 /// goo(std::make_pair(tmp, ftmp));
16349 SDValue
DAGCombiner::splitMergedValStore(StoreSDNode
*ST
) {
16350 if (OptLevel
== CodeGenOpt::None
)
16353 SDValue Val
= ST
->getValue();
16356 // Match OR operand.
16357 if (!Val
.getValueType().isScalarInteger() || Val
.getOpcode() != ISD::OR
)
16360 // Match SHL operand and get Lower and Higher parts of Val.
16361 SDValue Op1
= Val
.getOperand(0);
16362 SDValue Op2
= Val
.getOperand(1);
16364 if (Op1
.getOpcode() != ISD::SHL
) {
16365 std::swap(Op1
, Op2
);
16366 if (Op1
.getOpcode() != ISD::SHL
)
16370 Hi
= Op1
.getOperand(0);
16371 if (!Op1
.hasOneUse())
16374 // Match shift amount to HalfValBitSize.
16375 unsigned HalfValBitSize
= Val
.getValueSizeInBits() / 2;
16376 ConstantSDNode
*ShAmt
= dyn_cast
<ConstantSDNode
>(Op1
.getOperand(1));
16377 if (!ShAmt
|| ShAmt
->getAPIntValue() != HalfValBitSize
)
16380 // Lo and Hi are zero-extended from int with size less equal than 32
16382 if (Lo
.getOpcode() != ISD::ZERO_EXTEND
|| !Lo
.hasOneUse() ||
16383 !Lo
.getOperand(0).getValueType().isScalarInteger() ||
16384 Lo
.getOperand(0).getValueSizeInBits() > HalfValBitSize
||
16385 Hi
.getOpcode() != ISD::ZERO_EXTEND
|| !Hi
.hasOneUse() ||
16386 !Hi
.getOperand(0).getValueType().isScalarInteger() ||
16387 Hi
.getOperand(0).getValueSizeInBits() > HalfValBitSize
)
16390 // Use the EVT of low and high parts before bitcast as the input
16391 // of target query.
16392 EVT LowTy
= (Lo
.getOperand(0).getOpcode() == ISD::BITCAST
)
16393 ? Lo
.getOperand(0).getValueType()
16394 : Lo
.getValueType();
16395 EVT HighTy
= (Hi
.getOperand(0).getOpcode() == ISD::BITCAST
)
16396 ? Hi
.getOperand(0).getValueType()
16397 : Hi
.getValueType();
16398 if (!TLI
.isMultiStoresCheaperThanBitsMerge(LowTy
, HighTy
))
16401 // Start to split store.
16402 unsigned Alignment
= ST
->getAlignment();
16403 MachineMemOperand::Flags MMOFlags
= ST
->getMemOperand()->getFlags();
16404 AAMDNodes AAInfo
= ST
->getAAInfo();
16406 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
16407 EVT VT
= EVT::getIntegerVT(*DAG
.getContext(), HalfValBitSize
);
16408 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Lo
.getOperand(0));
16409 Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VT
, Hi
.getOperand(0));
16411 SDValue Chain
= ST
->getChain();
16412 SDValue Ptr
= ST
->getBasePtr();
16413 // Lower value store.
16414 SDValue St0
= DAG
.getStore(Chain
, DL
, Lo
, Ptr
, ST
->getPointerInfo(),
16415 ST
->getAlignment(), MMOFlags
, AAInfo
);
16417 DAG
.getNode(ISD::ADD
, DL
, Ptr
.getValueType(), Ptr
,
16418 DAG
.getConstant(HalfValBitSize
/ 8, DL
, Ptr
.getValueType()));
16419 // Higher value store.
16421 DAG
.getStore(St0
, DL
, Hi
, Ptr
,
16422 ST
->getPointerInfo().getWithOffset(HalfValBitSize
/ 8),
16423 Alignment
/ 2, MMOFlags
, AAInfo
);
16427 /// Convert a disguised subvector insertion into a shuffle:
16428 /// insert_vector_elt V, (bitcast X from vector type), IdxC -->
16429 /// bitcast(shuffle (bitcast V), (extended X), Mask)
16430 /// Note: We do not use an insert_subvector node because that requires a legal
16431 /// subvector type.
16432 SDValue
DAGCombiner::combineInsertEltToShuffle(SDNode
*N
, unsigned InsIndex
) {
16433 SDValue InsertVal
= N
->getOperand(1);
16434 if (InsertVal
.getOpcode() != ISD::BITCAST
|| !InsertVal
.hasOneUse() ||
16435 !InsertVal
.getOperand(0).getValueType().isVector())
16438 SDValue SubVec
= InsertVal
.getOperand(0);
16439 SDValue DestVec
= N
->getOperand(0);
16440 EVT SubVecVT
= SubVec
.getValueType();
16441 EVT VT
= DestVec
.getValueType();
16442 unsigned NumSrcElts
= SubVecVT
.getVectorNumElements();
16443 unsigned ExtendRatio
= VT
.getSizeInBits() / SubVecVT
.getSizeInBits();
16444 unsigned NumMaskVals
= ExtendRatio
* NumSrcElts
;
16446 // Step 1: Create a shuffle mask that implements this insert operation. The
16447 // vector that we are inserting into will be operand 0 of the shuffle, so
16448 // those elements are just 'i'. The inserted subvector is in the first
16449 // positions of operand 1 of the shuffle. Example:
16450 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
16451 SmallVector
<int, 16> Mask(NumMaskVals
);
16452 for (unsigned i
= 0; i
!= NumMaskVals
; ++i
) {
16453 if (i
/ NumSrcElts
== InsIndex
)
16454 Mask
[i
] = (i
% NumSrcElts
) + NumMaskVals
;
16459 // Bail out if the target can not handle the shuffle we want to create.
16460 EVT SubVecEltVT
= SubVecVT
.getVectorElementType();
16461 EVT ShufVT
= EVT::getVectorVT(*DAG
.getContext(), SubVecEltVT
, NumMaskVals
);
16462 if (!TLI
.isShuffleMaskLegal(Mask
, ShufVT
))
16465 // Step 2: Create a wide vector from the inserted source vector by appending
16466 // undefined elements. This is the same size as our destination vector.
16468 SmallVector
<SDValue
, 8> ConcatOps(ExtendRatio
, DAG
.getUNDEF(SubVecVT
));
16469 ConcatOps
[0] = SubVec
;
16470 SDValue PaddedSubV
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, ShufVT
, ConcatOps
);
16472 // Step 3: Shuffle in the padded subvector.
16473 SDValue DestVecBC
= DAG
.getBitcast(ShufVT
, DestVec
);
16474 SDValue Shuf
= DAG
.getVectorShuffle(ShufVT
, DL
, DestVecBC
, PaddedSubV
, Mask
);
16475 AddToWorklist(PaddedSubV
.getNode());
16476 AddToWorklist(DestVecBC
.getNode());
16477 AddToWorklist(Shuf
.getNode());
16478 return DAG
.getBitcast(VT
, Shuf
);
16481 SDValue
DAGCombiner::visitINSERT_VECTOR_ELT(SDNode
*N
) {
16482 SDValue InVec
= N
->getOperand(0);
16483 SDValue InVal
= N
->getOperand(1);
16484 SDValue EltNo
= N
->getOperand(2);
16487 // If the inserted element is an UNDEF, just use the input vector.
16488 if (InVal
.isUndef())
16491 EVT VT
= InVec
.getValueType();
16492 unsigned NumElts
= VT
.getVectorNumElements();
16494 // Remove redundant insertions:
16495 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
16496 if (InVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
16497 InVec
== InVal
.getOperand(0) && EltNo
== InVal
.getOperand(1))
16500 auto *IndexC
= dyn_cast
<ConstantSDNode
>(EltNo
);
16502 // If this is variable insert to undef vector, it might be better to splat:
16503 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
16504 if (InVec
.isUndef() && TLI
.shouldSplatInsEltVarIndex(VT
)) {
16505 SmallVector
<SDValue
, 8> Ops(NumElts
, InVal
);
16506 return DAG
.getBuildVector(VT
, DL
, Ops
);
16511 // We must know which element is being inserted for folds below here.
16512 unsigned Elt
= IndexC
->getZExtValue();
16513 if (SDValue Shuf
= combineInsertEltToShuffle(N
, Elt
))
16516 // Canonicalize insert_vector_elt dag nodes.
16518 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
16519 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
16521 // Do this only if the child insert_vector node has one use; also
16522 // do this only if indices are both constants and Idx1 < Idx0.
16523 if (InVec
.getOpcode() == ISD::INSERT_VECTOR_ELT
&& InVec
.hasOneUse()
16524 && isa
<ConstantSDNode
>(InVec
.getOperand(2))) {
16525 unsigned OtherElt
= InVec
.getConstantOperandVal(2);
16526 if (Elt
< OtherElt
) {
16528 SDValue NewOp
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, DL
, VT
,
16529 InVec
.getOperand(0), InVal
, EltNo
);
16530 AddToWorklist(NewOp
.getNode());
16531 return DAG
.getNode(ISD::INSERT_VECTOR_ELT
, SDLoc(InVec
.getNode()),
16532 VT
, NewOp
, InVec
.getOperand(1), InVec
.getOperand(2));
16536 // If we can't generate a legal BUILD_VECTOR, exit
16537 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
))
16540 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
16541 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
16542 // vector elements.
16543 SmallVector
<SDValue
, 8> Ops
;
16544 // Do not combine these two vectors if the output vector will not replace
16545 // the input vector.
16546 if (InVec
.getOpcode() == ISD::BUILD_VECTOR
&& InVec
.hasOneUse()) {
16547 Ops
.append(InVec
.getNode()->op_begin(),
16548 InVec
.getNode()->op_end());
16549 } else if (InVec
.isUndef()) {
16550 Ops
.append(NumElts
, DAG
.getUNDEF(InVal
.getValueType()));
16554 assert(Ops
.size() == NumElts
&& "Unexpected vector size");
16556 // Insert the element
16557 if (Elt
< Ops
.size()) {
16558 // All the operands of BUILD_VECTOR must have the same type;
16559 // we enforce that here.
16560 EVT OpVT
= Ops
[0].getValueType();
16561 Ops
[Elt
] = OpVT
.isInteger() ? DAG
.getAnyExtOrTrunc(InVal
, DL
, OpVT
) : InVal
;
16564 // Return the new vector
16565 return DAG
.getBuildVector(VT
, DL
, Ops
);
16568 SDValue
DAGCombiner::scalarizeExtractedVectorLoad(SDNode
*EVE
, EVT InVecVT
,
16570 LoadSDNode
*OriginalLoad
) {
16571 assert(!OriginalLoad
->isVolatile());
16573 EVT ResultVT
= EVE
->getValueType(0);
16574 EVT VecEltVT
= InVecVT
.getVectorElementType();
16575 unsigned Align
= OriginalLoad
->getAlignment();
16576 unsigned NewAlign
= DAG
.getDataLayout().getABITypeAlignment(
16577 VecEltVT
.getTypeForEVT(*DAG
.getContext()));
16579 if (NewAlign
> Align
|| !TLI
.isOperationLegalOrCustom(ISD::LOAD
, VecEltVT
))
16582 ISD::LoadExtType ExtTy
= ResultVT
.bitsGT(VecEltVT
) ?
16583 ISD::NON_EXTLOAD
: ISD::EXTLOAD
;
16584 if (!TLI
.shouldReduceLoadWidth(OriginalLoad
, ExtTy
, VecEltVT
))
16589 SDValue NewPtr
= OriginalLoad
->getBasePtr();
16591 EVT PtrType
= NewPtr
.getValueType();
16592 MachinePointerInfo MPI
;
16594 if (auto *ConstEltNo
= dyn_cast
<ConstantSDNode
>(EltNo
)) {
16595 int Elt
= ConstEltNo
->getZExtValue();
16596 unsigned PtrOff
= VecEltVT
.getSizeInBits() * Elt
/ 8;
16597 Offset
= DAG
.getConstant(PtrOff
, DL
, PtrType
);
16598 MPI
= OriginalLoad
->getPointerInfo().getWithOffset(PtrOff
);
16600 Offset
= DAG
.getZExtOrTrunc(EltNo
, DL
, PtrType
);
16601 Offset
= DAG
.getNode(
16602 ISD::MUL
, DL
, PtrType
, Offset
,
16603 DAG
.getConstant(VecEltVT
.getStoreSize(), DL
, PtrType
));
16604 // Discard the pointer info except the address space because the memory
16605 // operand can't represent this new access since the offset is variable.
16606 MPI
= MachinePointerInfo(OriginalLoad
->getPointerInfo().getAddrSpace());
16608 NewPtr
= DAG
.getNode(ISD::ADD
, DL
, PtrType
, NewPtr
, Offset
);
16610 // The replacement we need to do here is a little tricky: we need to
16611 // replace an extractelement of a load with a load.
16612 // Use ReplaceAllUsesOfValuesWith to do the replacement.
16613 // Note that this replacement assumes that the extractvalue is the only
16614 // use of the load; that's okay because we don't want to perform this
16615 // transformation in other cases anyway.
16618 if (ResultVT
.bitsGT(VecEltVT
)) {
16619 // If the result type of vextract is wider than the load, then issue an
16620 // extending load instead.
16621 ISD::LoadExtType ExtType
= TLI
.isLoadExtLegal(ISD::ZEXTLOAD
, ResultVT
,
16625 Load
= DAG
.getExtLoad(ExtType
, SDLoc(EVE
), ResultVT
,
16626 OriginalLoad
->getChain(), NewPtr
, MPI
, VecEltVT
,
16627 Align
, OriginalLoad
->getMemOperand()->getFlags(),
16628 OriginalLoad
->getAAInfo());
16629 Chain
= Load
.getValue(1);
16631 Load
= DAG
.getLoad(VecEltVT
, SDLoc(EVE
), OriginalLoad
->getChain(), NewPtr
,
16632 MPI
, Align
, OriginalLoad
->getMemOperand()->getFlags(),
16633 OriginalLoad
->getAAInfo());
16634 Chain
= Load
.getValue(1);
16635 if (ResultVT
.bitsLT(VecEltVT
))
16636 Load
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(EVE
), ResultVT
, Load
);
16638 Load
= DAG
.getBitcast(ResultVT
, Load
);
16640 WorklistRemover
DeadNodes(*this);
16641 SDValue From
[] = { SDValue(EVE
, 0), SDValue(OriginalLoad
, 1) };
16642 SDValue To
[] = { Load
, Chain
};
16643 DAG
.ReplaceAllUsesOfValuesWith(From
, To
, 2);
16644 // Since we're explicitly calling ReplaceAllUses, add the new node to the
16645 // worklist explicitly as well.
16646 AddToWorklist(Load
.getNode());
16647 AddUsersToWorklist(Load
.getNode()); // Add users too
16648 // Make sure to revisit this node to clean it up; it will usually be dead.
16649 AddToWorklist(EVE
);
16651 return SDValue(EVE
, 0);
16654 /// Transform a vector binary operation into a scalar binary operation by moving
16655 /// the math/logic after an extract element of a vector.
16656 static SDValue
scalarizeExtractedBinop(SDNode
*ExtElt
, SelectionDAG
&DAG
,
16657 bool LegalOperations
) {
16658 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
16659 SDValue Vec
= ExtElt
->getOperand(0);
16660 SDValue Index
= ExtElt
->getOperand(1);
16661 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
16662 if (!IndexC
|| !TLI
.isBinOp(Vec
.getOpcode()) || !Vec
.hasOneUse() ||
16663 Vec
.getNode()->getNumValues() != 1)
16666 // Targets may want to avoid this to prevent an expensive register transfer.
16667 if (!TLI
.shouldScalarizeBinop(Vec
))
16670 // Extracting an element of a vector constant is constant-folded, so this
16671 // transform is just replacing a vector op with a scalar op while moving the
16673 SDValue Op0
= Vec
.getOperand(0);
16674 SDValue Op1
= Vec
.getOperand(1);
16675 if (isAnyConstantBuildVector(Op0
, true) ||
16676 isAnyConstantBuildVector(Op1
, true)) {
16677 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
16678 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
16680 EVT VT
= ExtElt
->getValueType(0);
16681 SDValue Ext0
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, Op0
, Index
);
16682 SDValue Ext1
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, VT
, Op1
, Index
);
16683 return DAG
.getNode(Vec
.getOpcode(), DL
, VT
, Ext0
, Ext1
);
16689 SDValue
DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode
*N
) {
16690 SDValue VecOp
= N
->getOperand(0);
16691 SDValue Index
= N
->getOperand(1);
16692 EVT ScalarVT
= N
->getValueType(0);
16693 EVT VecVT
= VecOp
.getValueType();
16694 if (VecOp
.isUndef())
16695 return DAG
.getUNDEF(ScalarVT
);
16697 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
16699 // This only really matters if the index is non-constant since other combines
16700 // on the constant elements already work.
16702 if (VecOp
.getOpcode() == ISD::INSERT_VECTOR_ELT
&&
16703 Index
== VecOp
.getOperand(2)) {
16704 SDValue Elt
= VecOp
.getOperand(1);
16705 return VecVT
.isInteger() ? DAG
.getAnyExtOrTrunc(Elt
, DL
, ScalarVT
) : Elt
;
16708 // (vextract (scalar_to_vector val, 0) -> val
16709 if (VecOp
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
16710 // Check if the result type doesn't match the inserted element type. A
16711 // SCALAR_TO_VECTOR may truncate the inserted element and the
16712 // EXTRACT_VECTOR_ELT may widen the extracted vector.
16713 SDValue InOp
= VecOp
.getOperand(0);
16714 if (InOp
.getValueType() != ScalarVT
) {
16715 assert(InOp
.getValueType().isInteger() && ScalarVT
.isInteger());
16716 return DAG
.getSExtOrTrunc(InOp
, DL
, ScalarVT
);
16721 // extract_vector_elt of out-of-bounds element -> UNDEF
16722 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
16723 unsigned NumElts
= VecVT
.getVectorNumElements();
16724 if (IndexC
&& IndexC
->getAPIntValue().uge(NumElts
))
16725 return DAG
.getUNDEF(ScalarVT
);
16727 // extract_vector_elt (build_vector x, y), 1 -> y
16728 if (IndexC
&& VecOp
.getOpcode() == ISD::BUILD_VECTOR
&&
16729 TLI
.isTypeLegal(VecVT
) &&
16730 (VecOp
.hasOneUse() || TLI
.aggressivelyPreferBuildVectorSources(VecVT
))) {
16731 SDValue Elt
= VecOp
.getOperand(IndexC
->getZExtValue());
16732 EVT InEltVT
= Elt
.getValueType();
16734 // Sometimes build_vector's scalar input types do not match result type.
16735 if (ScalarVT
== InEltVT
)
16738 // TODO: It may be useful to truncate if free if the build_vector implicitly
16742 // TODO: These transforms should not require the 'hasOneUse' restriction, but
16743 // there are regressions on multiple targets without it. We can end up with a
16744 // mess of scalar and vector code if we reduce only part of the DAG to scalar.
16745 if (IndexC
&& VecOp
.getOpcode() == ISD::BITCAST
&& VecVT
.isInteger() &&
16746 VecOp
.hasOneUse()) {
16747 // The vector index of the LSBs of the source depend on the endian-ness.
16748 bool IsLE
= DAG
.getDataLayout().isLittleEndian();
16749 unsigned ExtractIndex
= IndexC
->getZExtValue();
16750 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
16751 unsigned BCTruncElt
= IsLE
? 0 : NumElts
- 1;
16752 SDValue BCSrc
= VecOp
.getOperand(0);
16753 if (ExtractIndex
== BCTruncElt
&& BCSrc
.getValueType().isScalarInteger())
16754 return DAG
.getNode(ISD::TRUNCATE
, DL
, ScalarVT
, BCSrc
);
16756 if (LegalTypes
&& BCSrc
.getValueType().isInteger() &&
16757 BCSrc
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
16758 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
16759 // trunc i64 X to i32
16760 SDValue X
= BCSrc
.getOperand(0);
16761 assert(X
.getValueType().isScalarInteger() && ScalarVT
.isScalarInteger() &&
16762 "Extract element and scalar to vector can't change element type "
16763 "from FP to integer.");
16764 unsigned XBitWidth
= X
.getValueSizeInBits();
16765 unsigned VecEltBitWidth
= VecVT
.getScalarSizeInBits();
16766 BCTruncElt
= IsLE
? 0 : XBitWidth
/ VecEltBitWidth
- 1;
16768 // An extract element return value type can be wider than its vector
16769 // operand element type. In that case, the high bits are undefined, so
16770 // it's possible that we may need to extend rather than truncate.
16771 if (ExtractIndex
== BCTruncElt
&& XBitWidth
> VecEltBitWidth
) {
16772 assert(XBitWidth
% VecEltBitWidth
== 0 &&
16773 "Scalar bitwidth must be a multiple of vector element bitwidth");
16774 return DAG
.getAnyExtOrTrunc(X
, DL
, ScalarVT
);
16779 if (SDValue BO
= scalarizeExtractedBinop(N
, DAG
, LegalOperations
))
16782 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
16783 // We only perform this optimization before the op legalization phase because
16784 // we may introduce new vector instructions which are not backed by TD
16785 // patterns. For example on AVX, extracting elements from a wide vector
16786 // without using extract_subvector. However, if we can find an underlying
16787 // scalar value, then we can always use that.
16788 if (IndexC
&& VecOp
.getOpcode() == ISD::VECTOR_SHUFFLE
) {
16789 auto *Shuf
= cast
<ShuffleVectorSDNode
>(VecOp
);
16790 // Find the new index to extract from.
16791 int OrigElt
= Shuf
->getMaskElt(IndexC
->getZExtValue());
16793 // Extracting an undef index is undef.
16795 return DAG
.getUNDEF(ScalarVT
);
16797 // Select the right vector half to extract from.
16799 if (OrigElt
< (int)NumElts
) {
16800 SVInVec
= VecOp
.getOperand(0);
16802 SVInVec
= VecOp
.getOperand(1);
16803 OrigElt
-= NumElts
;
16806 if (SVInVec
.getOpcode() == ISD::BUILD_VECTOR
) {
16807 SDValue InOp
= SVInVec
.getOperand(OrigElt
);
16808 if (InOp
.getValueType() != ScalarVT
) {
16809 assert(InOp
.getValueType().isInteger() && ScalarVT
.isInteger());
16810 InOp
= DAG
.getSExtOrTrunc(InOp
, DL
, ScalarVT
);
16816 // FIXME: We should handle recursing on other vector shuffles and
16817 // scalar_to_vector here as well.
16819 if (!LegalOperations
||
16820 // FIXME: Should really be just isOperationLegalOrCustom.
16821 TLI
.isOperationLegal(ISD::EXTRACT_VECTOR_ELT
, VecVT
) ||
16822 TLI
.isOperationExpand(ISD::VECTOR_SHUFFLE
, VecVT
)) {
16823 EVT IndexTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
16824 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ScalarVT
, SVInVec
,
16825 DAG
.getConstant(OrigElt
, DL
, IndexTy
));
16829 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
16830 // simplify it based on the (valid) extraction indices.
16831 if (llvm::all_of(VecOp
->uses(), [&](SDNode
*Use
) {
16832 return Use
->getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
16833 Use
->getOperand(0) == VecOp
&&
16834 isa
<ConstantSDNode
>(Use
->getOperand(1));
16836 APInt DemandedElts
= APInt::getNullValue(NumElts
);
16837 for (SDNode
*Use
: VecOp
->uses()) {
16838 auto *CstElt
= cast
<ConstantSDNode
>(Use
->getOperand(1));
16839 if (CstElt
->getAPIntValue().ult(NumElts
))
16840 DemandedElts
.setBit(CstElt
->getZExtValue());
16842 if (SimplifyDemandedVectorElts(VecOp
, DemandedElts
, true)) {
16843 // We simplified the vector operand of this extract element. If this
16844 // extract is not dead, visit it again so it is folded properly.
16845 if (N
->getOpcode() != ISD::DELETED_NODE
)
16847 return SDValue(N
, 0);
16851 // Everything under here is trying to match an extract of a loaded value.
16852 // If the result of load has to be truncated, then it's not necessarily
16854 bool BCNumEltsChanged
= false;
16855 EVT ExtVT
= VecVT
.getVectorElementType();
16857 if (ScalarVT
.bitsLT(LVT
) && !TLI
.isTruncateFree(LVT
, ScalarVT
))
16860 if (VecOp
.getOpcode() == ISD::BITCAST
) {
16861 // Don't duplicate a load with other uses.
16862 if (!VecOp
.hasOneUse())
16865 EVT BCVT
= VecOp
.getOperand(0).getValueType();
16866 if (!BCVT
.isVector() || ExtVT
.bitsGT(BCVT
.getVectorElementType()))
16868 if (NumElts
!= BCVT
.getVectorNumElements())
16869 BCNumEltsChanged
= true;
16870 VecOp
= VecOp
.getOperand(0);
16871 ExtVT
= BCVT
.getVectorElementType();
16874 // extract (vector load $addr), i --> load $addr + i * size
16875 if (!LegalOperations
&& !IndexC
&& VecOp
.hasOneUse() &&
16876 ISD::isNormalLoad(VecOp
.getNode()) &&
16877 !Index
->hasPredecessor(VecOp
.getNode())) {
16878 auto *VecLoad
= dyn_cast
<LoadSDNode
>(VecOp
);
16879 if (VecLoad
&& !VecLoad
->isVolatile())
16880 return scalarizeExtractedVectorLoad(N
, VecVT
, Index
, VecLoad
);
16883 // Perform only after legalization to ensure build_vector / vector_shuffle
16884 // optimizations have already been done.
16885 if (!LegalOperations
|| !IndexC
)
16888 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
16889 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
16890 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
16891 int Elt
= IndexC
->getZExtValue();
16892 LoadSDNode
*LN0
= nullptr;
16893 if (ISD::isNormalLoad(VecOp
.getNode())) {
16894 LN0
= cast
<LoadSDNode
>(VecOp
);
16895 } else if (VecOp
.getOpcode() == ISD::SCALAR_TO_VECTOR
&&
16896 VecOp
.getOperand(0).getValueType() == ExtVT
&&
16897 ISD::isNormalLoad(VecOp
.getOperand(0).getNode())) {
16898 // Don't duplicate a load with other uses.
16899 if (!VecOp
.hasOneUse())
16902 LN0
= cast
<LoadSDNode
>(VecOp
.getOperand(0));
16904 if (auto *Shuf
= dyn_cast
<ShuffleVectorSDNode
>(VecOp
)) {
16905 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
16907 // (load $addr+1*size)
16909 // Don't duplicate a load with other uses.
16910 if (!VecOp
.hasOneUse())
16913 // If the bit convert changed the number of elements, it is unsafe
16914 // to examine the mask.
16915 if (BCNumEltsChanged
)
16918 // Select the input vector, guarding against out of range extract vector.
16919 int Idx
= (Elt
> (int)NumElts
) ? -1 : Shuf
->getMaskElt(Elt
);
16920 VecOp
= (Idx
< (int)NumElts
) ? VecOp
.getOperand(0) : VecOp
.getOperand(1);
16922 if (VecOp
.getOpcode() == ISD::BITCAST
) {
16923 // Don't duplicate a load with other uses.
16924 if (!VecOp
.hasOneUse())
16927 VecOp
= VecOp
.getOperand(0);
16929 if (ISD::isNormalLoad(VecOp
.getNode())) {
16930 LN0
= cast
<LoadSDNode
>(VecOp
);
16931 Elt
= (Idx
< (int)NumElts
) ? Idx
: Idx
- (int)NumElts
;
16932 Index
= DAG
.getConstant(Elt
, DL
, Index
.getValueType());
16936 // Make sure we found a non-volatile load and the extractelement is
16938 if (!LN0
|| !LN0
->hasNUsesOfValue(1,0) || LN0
->isVolatile())
16941 // If Idx was -1 above, Elt is going to be -1, so just return undef.
16943 return DAG
.getUNDEF(LVT
);
16945 return scalarizeExtractedVectorLoad(N
, VecVT
, Index
, LN0
);
16948 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
16949 SDValue
DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode
*N
) {
16950 // We perform this optimization post type-legalization because
16951 // the type-legalizer often scalarizes integer-promoted vectors.
16952 // Performing this optimization before may create bit-casts which
16953 // will be type-legalized to complex code sequences.
16954 // We perform this optimization only before the operation legalizer because we
16955 // may introduce illegal operations.
16956 if (Level
!= AfterLegalizeVectorOps
&& Level
!= AfterLegalizeTypes
)
16959 unsigned NumInScalars
= N
->getNumOperands();
16961 EVT VT
= N
->getValueType(0);
16963 // Check to see if this is a BUILD_VECTOR of a bunch of values
16964 // which come from any_extend or zero_extend nodes. If so, we can create
16965 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
16966 // optimizations. We do not handle sign-extend because we can't fill the sign
16968 EVT SourceType
= MVT::Other
;
16969 bool AllAnyExt
= true;
16971 for (unsigned i
= 0; i
!= NumInScalars
; ++i
) {
16972 SDValue In
= N
->getOperand(i
);
16973 // Ignore undef inputs.
16974 if (In
.isUndef()) continue;
16976 bool AnyExt
= In
.getOpcode() == ISD::ANY_EXTEND
;
16977 bool ZeroExt
= In
.getOpcode() == ISD::ZERO_EXTEND
;
16979 // Abort if the element is not an extension.
16980 if (!ZeroExt
&& !AnyExt
) {
16981 SourceType
= MVT::Other
;
16985 // The input is a ZeroExt or AnyExt. Check the original type.
16986 EVT InTy
= In
.getOperand(0).getValueType();
16988 // Check that all of the widened source types are the same.
16989 if (SourceType
== MVT::Other
)
16992 else if (InTy
!= SourceType
) {
16993 // Multiple income types. Abort.
16994 SourceType
= MVT::Other
;
16998 // Check if all of the extends are ANY_EXTENDs.
16999 AllAnyExt
&= AnyExt
;
17002 // In order to have valid types, all of the inputs must be extended from the
17003 // same source type and all of the inputs must be any or zero extend.
17004 // Scalar sizes must be a power of two.
17005 EVT OutScalarTy
= VT
.getScalarType();
17006 bool ValidTypes
= SourceType
!= MVT::Other
&&
17007 isPowerOf2_32(OutScalarTy
.getSizeInBits()) &&
17008 isPowerOf2_32(SourceType
.getSizeInBits());
17010 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
17011 // turn into a single shuffle instruction.
17015 bool isLE
= DAG
.getDataLayout().isLittleEndian();
17016 unsigned ElemRatio
= OutScalarTy
.getSizeInBits()/SourceType
.getSizeInBits();
17017 assert(ElemRatio
> 1 && "Invalid element size ratio");
17018 SDValue Filler
= AllAnyExt
? DAG
.getUNDEF(SourceType
):
17019 DAG
.getConstant(0, DL
, SourceType
);
17021 unsigned NewBVElems
= ElemRatio
* VT
.getVectorNumElements();
17022 SmallVector
<SDValue
, 8> Ops(NewBVElems
, Filler
);
17024 // Populate the new build_vector
17025 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
17026 SDValue Cast
= N
->getOperand(i
);
17027 assert((Cast
.getOpcode() == ISD::ANY_EXTEND
||
17028 Cast
.getOpcode() == ISD::ZERO_EXTEND
||
17029 Cast
.isUndef()) && "Invalid cast opcode");
17031 if (Cast
.isUndef())
17032 In
= DAG
.getUNDEF(SourceType
);
17034 In
= Cast
->getOperand(0);
17035 unsigned Index
= isLE
? (i
* ElemRatio
) :
17036 (i
* ElemRatio
+ (ElemRatio
- 1));
17038 assert(Index
< Ops
.size() && "Invalid index");
17042 // The type of the new BUILD_VECTOR node.
17043 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), SourceType
, NewBVElems
);
17044 assert(VecVT
.getSizeInBits() == VT
.getSizeInBits() &&
17045 "Invalid vector size");
17046 // Check if the new vector type is legal.
17047 if (!isTypeLegal(VecVT
) ||
17048 (!TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VecVT
) &&
17049 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, VT
)))
17052 // Make the new BUILD_VECTOR.
17053 SDValue BV
= DAG
.getBuildVector(VecVT
, DL
, Ops
);
17055 // The new BUILD_VECTOR node has the potential to be further optimized.
17056 AddToWorklist(BV
.getNode());
17057 // Bitcast to the desired type.
17058 return DAG
.getBitcast(VT
, BV
);
17061 SDValue
DAGCombiner::createBuildVecShuffle(const SDLoc
&DL
, SDNode
*N
,
17062 ArrayRef
<int> VectorMask
,
17063 SDValue VecIn1
, SDValue VecIn2
,
17064 unsigned LeftIdx
, bool DidSplitVec
) {
17065 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
17066 SDValue ZeroIdx
= DAG
.getConstant(0, DL
, IdxTy
);
17068 EVT VT
= N
->getValueType(0);
17069 EVT InVT1
= VecIn1
.getValueType();
17070 EVT InVT2
= VecIn2
.getNode() ? VecIn2
.getValueType() : InVT1
;
17072 unsigned NumElems
= VT
.getVectorNumElements();
17073 unsigned ShuffleNumElems
= NumElems
;
17075 // If we artificially split a vector in two already, then the offsets in the
17076 // operands will all be based off of VecIn1, even those in VecIn2.
17077 unsigned Vec2Offset
= DidSplitVec
? 0 : InVT1
.getVectorNumElements();
17079 // We can't generate a shuffle node with mismatched input and output types.
17080 // Try to make the types match the type of the output.
17081 if (InVT1
!= VT
|| InVT2
!= VT
) {
17082 if ((VT
.getSizeInBits() % InVT1
.getSizeInBits() == 0) && InVT1
== InVT2
) {
17083 // If the output vector length is a multiple of both input lengths,
17084 // we can concatenate them and pad the rest with undefs.
17085 unsigned NumConcats
= VT
.getSizeInBits() / InVT1
.getSizeInBits();
17086 assert(NumConcats
>= 2 && "Concat needs at least two inputs!");
17087 SmallVector
<SDValue
, 2> ConcatOps(NumConcats
, DAG
.getUNDEF(InVT1
));
17088 ConcatOps
[0] = VecIn1
;
17089 ConcatOps
[1] = VecIn2
? VecIn2
: DAG
.getUNDEF(InVT1
);
17090 VecIn1
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
);
17091 VecIn2
= SDValue();
17092 } else if (InVT1
.getSizeInBits() == VT
.getSizeInBits() * 2) {
17093 if (!TLI
.isExtractSubvectorCheap(VT
, InVT1
, NumElems
))
17096 if (!VecIn2
.getNode()) {
17097 // If we only have one input vector, and it's twice the size of the
17098 // output, split it in two.
17099 VecIn2
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, VecIn1
,
17100 DAG
.getConstant(NumElems
, DL
, IdxTy
));
17101 VecIn1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, VecIn1
, ZeroIdx
);
17102 // Since we now have shorter input vectors, adjust the offset of the
17103 // second vector's start.
17104 Vec2Offset
= NumElems
;
17105 } else if (InVT2
.getSizeInBits() <= InVT1
.getSizeInBits()) {
17106 // VecIn1 is wider than the output, and we have another, possibly
17107 // smaller input. Pad the smaller input with undefs, shuffle at the
17108 // input vector width, and extract the output.
17109 // The shuffle type is different than VT, so check legality again.
17110 if (LegalOperations
&&
17111 !TLI
.isOperationLegal(ISD::VECTOR_SHUFFLE
, InVT1
))
17114 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
17115 // lower it back into a BUILD_VECTOR. So if the inserted type is
17116 // illegal, don't even try.
17117 if (InVT1
!= InVT2
) {
17118 if (!TLI
.isTypeLegal(InVT2
))
17120 VecIn2
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, InVT1
,
17121 DAG
.getUNDEF(InVT1
), VecIn2
, ZeroIdx
);
17123 ShuffleNumElems
= NumElems
* 2;
17125 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
17126 // than VecIn1. We can't handle this for now - this case will disappear
17127 // when we start sorting the vectors by type.
17130 } else if (InVT2
.getSizeInBits() * 2 == VT
.getSizeInBits() &&
17131 InVT1
.getSizeInBits() == VT
.getSizeInBits()) {
17132 SmallVector
<SDValue
, 2> ConcatOps(2, DAG
.getUNDEF(InVT2
));
17133 ConcatOps
[0] = VecIn2
;
17134 VecIn2
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, ConcatOps
);
17136 // TODO: Support cases where the length mismatch isn't exactly by a
17138 // TODO: Move this check upwards, so that if we have bad type
17139 // mismatches, we don't create any DAG nodes.
17144 // Initialize mask to undef.
17145 SmallVector
<int, 8> Mask(ShuffleNumElems
, -1);
17147 // Only need to run up to the number of elements actually used, not the
17148 // total number of elements in the shuffle - if we are shuffling a wider
17149 // vector, the high lanes should be set to undef.
17150 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17151 if (VectorMask
[i
] <= 0)
17154 unsigned ExtIndex
= N
->getOperand(i
).getConstantOperandVal(1);
17155 if (VectorMask
[i
] == (int)LeftIdx
) {
17156 Mask
[i
] = ExtIndex
;
17157 } else if (VectorMask
[i
] == (int)LeftIdx
+ 1) {
17158 Mask
[i
] = Vec2Offset
+ ExtIndex
;
17162 // The type the input vectors may have changed above.
17163 InVT1
= VecIn1
.getValueType();
17165 // If we already have a VecIn2, it should have the same type as VecIn1.
17166 // If we don't, get an undef/zero vector of the appropriate type.
17167 VecIn2
= VecIn2
.getNode() ? VecIn2
: DAG
.getUNDEF(InVT1
);
17168 assert(InVT1
== VecIn2
.getValueType() && "Unexpected second input type.");
17170 SDValue Shuffle
= DAG
.getVectorShuffle(InVT1
, DL
, VecIn1
, VecIn2
, Mask
);
17171 if (ShuffleNumElems
> NumElems
)
17172 Shuffle
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, VT
, Shuffle
, ZeroIdx
);
17177 static SDValue
reduceBuildVecToShuffleWithZero(SDNode
*BV
, SelectionDAG
&DAG
) {
17178 assert(BV
->getOpcode() == ISD::BUILD_VECTOR
&& "Expected build vector");
17180 // First, determine where the build vector is not undef.
17181 // TODO: We could extend this to handle zero elements as well as undefs.
17182 int NumBVOps
= BV
->getNumOperands();
17184 for (int i
= 0; i
!= NumBVOps
; ++i
) {
17185 SDValue Op
= BV
->getOperand(i
);
17193 // Bail out if there's no non-undef element.
17197 // The build vector contains some number of undef elements and exactly
17198 // one other element. That other element must be a zero-extended scalar
17199 // extracted from a vector at a constant index to turn this into a shuffle.
17200 // Also, require that the build vector does not implicitly truncate/extend
17202 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
17203 EVT VT
= BV
->getValueType(0);
17204 SDValue Zext
= BV
->getOperand(ZextElt
);
17205 if (Zext
.getOpcode() != ISD::ZERO_EXTEND
|| !Zext
.hasOneUse() ||
17206 Zext
.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
17207 !isa
<ConstantSDNode
>(Zext
.getOperand(0).getOperand(1)) ||
17208 Zext
.getValueSizeInBits() != VT
.getScalarSizeInBits())
17211 // The zero-extend must be a multiple of the source size, and we must be
17212 // building a vector of the same size as the source of the extract element.
17213 SDValue Extract
= Zext
.getOperand(0);
17214 unsigned DestSize
= Zext
.getValueSizeInBits();
17215 unsigned SrcSize
= Extract
.getValueSizeInBits();
17216 if (DestSize
% SrcSize
!= 0 ||
17217 Extract
.getOperand(0).getValueSizeInBits() != VT
.getSizeInBits())
17220 // Create a shuffle mask that will combine the extracted element with zeros
17222 int ZextRatio
= DestSize
/ SrcSize
;
17223 int NumMaskElts
= NumBVOps
* ZextRatio
;
17224 SmallVector
<int, 32> ShufMask(NumMaskElts
, -1);
17225 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
17226 if (i
/ ZextRatio
== ZextElt
) {
17227 // The low bits of the (potentially translated) extracted element map to
17228 // the source vector. The high bits map to zero. We will use a zero vector
17229 // as the 2nd source operand of the shuffle, so use the 1st element of
17230 // that vector (mask value is number-of-elements) for the high bits.
17231 if (i
% ZextRatio
== 0)
17232 ShufMask
[i
] = Extract
.getConstantOperandVal(1);
17234 ShufMask
[i
] = NumMaskElts
;
17237 // Undef elements of the build vector remain undef because we initialize
17238 // the shuffle mask with -1.
17241 // Turn this into a shuffle with zero if that's legal.
17242 EVT VecVT
= Extract
.getOperand(0).getValueType();
17243 if (!DAG
.getTargetLoweringInfo().isShuffleMaskLegal(ShufMask
, VecVT
))
17246 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
17247 // bitcast (shuffle V, ZeroVec, VectorMask)
17249 SDValue ZeroVec
= DAG
.getConstant(0, DL
, VecVT
);
17250 SDValue Shuf
= DAG
.getVectorShuffle(VecVT
, DL
, Extract
.getOperand(0), ZeroVec
,
17252 return DAG
.getBitcast(VT
, Shuf
);
17255 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
17256 // operations. If the types of the vectors we're extracting from allow it,
17257 // turn this into a vector_shuffle node.
17258 SDValue
DAGCombiner::reduceBuildVecToShuffle(SDNode
*N
) {
17260 EVT VT
= N
->getValueType(0);
17262 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
17263 if (!isTypeLegal(VT
))
17266 if (SDValue V
= reduceBuildVecToShuffleWithZero(N
, DAG
))
17269 // May only combine to shuffle after legalize if shuffle is legal.
17270 if (LegalOperations
&& !TLI
.isOperationLegal(ISD::VECTOR_SHUFFLE
, VT
))
17273 bool UsesZeroVector
= false;
17274 unsigned NumElems
= N
->getNumOperands();
17276 // Record, for each element of the newly built vector, which input vector
17277 // that element comes from. -1 stands for undef, 0 for the zero vector,
17278 // and positive values for the input vectors.
17279 // VectorMask maps each element to its vector number, and VecIn maps vector
17280 // numbers to their initial SDValues.
17282 SmallVector
<int, 8> VectorMask(NumElems
, -1);
17283 SmallVector
<SDValue
, 8> VecIn
;
17284 VecIn
.push_back(SDValue());
17286 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17287 SDValue Op
= N
->getOperand(i
);
17292 // See if we can use a blend with a zero vector.
17293 // TODO: Should we generalize this to a blend with an arbitrary constant
17295 if (isNullConstant(Op
) || isNullFPConstant(Op
)) {
17296 UsesZeroVector
= true;
17301 // Not an undef or zero. If the input is something other than an
17302 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
17303 if (Op
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
17304 !isa
<ConstantSDNode
>(Op
.getOperand(1)))
17306 SDValue ExtractedFromVec
= Op
.getOperand(0);
17308 const APInt
&ExtractIdx
= Op
.getConstantOperandAPInt(1);
17309 if (ExtractIdx
.uge(ExtractedFromVec
.getValueType().getVectorNumElements()))
17312 // All inputs must have the same element type as the output.
17313 if (VT
.getVectorElementType() !=
17314 ExtractedFromVec
.getValueType().getVectorElementType())
17317 // Have we seen this input vector before?
17318 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
17319 // a map back from SDValues to numbers isn't worth it.
17320 unsigned Idx
= std::distance(
17321 VecIn
.begin(), std::find(VecIn
.begin(), VecIn
.end(), ExtractedFromVec
));
17322 if (Idx
== VecIn
.size())
17323 VecIn
.push_back(ExtractedFromVec
);
17325 VectorMask
[i
] = Idx
;
17328 // If we didn't find at least one input vector, bail out.
17329 if (VecIn
.size() < 2)
17332 // If all the Operands of BUILD_VECTOR extract from same
17333 // vector, then split the vector efficiently based on the maximum
17334 // vector access index and adjust the VectorMask and
17335 // VecIn accordingly.
17336 bool DidSplitVec
= false;
17337 if (VecIn
.size() == 2) {
17338 unsigned MaxIndex
= 0;
17339 unsigned NearestPow2
= 0;
17340 SDValue Vec
= VecIn
.back();
17341 EVT InVT
= Vec
.getValueType();
17342 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
17343 SmallVector
<unsigned, 8> IndexVec(NumElems
, 0);
17345 for (unsigned i
= 0; i
< NumElems
; i
++) {
17346 if (VectorMask
[i
] <= 0)
17348 unsigned Index
= N
->getOperand(i
).getConstantOperandVal(1);
17349 IndexVec
[i
] = Index
;
17350 MaxIndex
= std::max(MaxIndex
, Index
);
17353 NearestPow2
= PowerOf2Ceil(MaxIndex
);
17354 if (InVT
.isSimple() && NearestPow2
> 2 && MaxIndex
< NearestPow2
&&
17355 NumElems
* 2 < NearestPow2
) {
17356 unsigned SplitSize
= NearestPow2
/ 2;
17357 EVT SplitVT
= EVT::getVectorVT(*DAG
.getContext(),
17358 InVT
.getVectorElementType(), SplitSize
);
17359 if (TLI
.isTypeLegal(SplitVT
)) {
17360 SDValue VecIn2
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, SplitVT
, Vec
,
17361 DAG
.getConstant(SplitSize
, DL
, IdxTy
));
17362 SDValue VecIn1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, SplitVT
, Vec
,
17363 DAG
.getConstant(0, DL
, IdxTy
));
17365 VecIn
.push_back(VecIn1
);
17366 VecIn
.push_back(VecIn2
);
17367 DidSplitVec
= true;
17369 for (unsigned i
= 0; i
< NumElems
; i
++) {
17370 if (VectorMask
[i
] <= 0)
17372 VectorMask
[i
] = (IndexVec
[i
] < SplitSize
) ? 1 : 2;
17378 // TODO: We want to sort the vectors by descending length, so that adjacent
17379 // pairs have similar length, and the longer vector is always first in the
17382 // TODO: Should this fire if some of the input vectors has illegal type (like
17383 // it does now), or should we let legalization run its course first?
17386 // Take pairs of vectors, and shuffle them so that the result has elements
17387 // from these vectors in the correct places.
17388 // For example, given:
17389 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
17390 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
17391 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
17392 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
17393 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
17394 // We will generate:
17395 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
17396 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
17397 SmallVector
<SDValue
, 4> Shuffles
;
17398 for (unsigned In
= 0, Len
= (VecIn
.size() / 2); In
< Len
; ++In
) {
17399 unsigned LeftIdx
= 2 * In
+ 1;
17400 SDValue VecLeft
= VecIn
[LeftIdx
];
17402 (LeftIdx
+ 1) < VecIn
.size() ? VecIn
[LeftIdx
+ 1] : SDValue();
17404 if (SDValue Shuffle
= createBuildVecShuffle(DL
, N
, VectorMask
, VecLeft
,
17405 VecRight
, LeftIdx
, DidSplitVec
))
17406 Shuffles
.push_back(Shuffle
);
17411 // If we need the zero vector as an "ingredient" in the blend tree, add it
17412 // to the list of shuffles.
17413 if (UsesZeroVector
)
17414 Shuffles
.push_back(VT
.isInteger() ? DAG
.getConstant(0, DL
, VT
)
17415 : DAG
.getConstantFP(0.0, DL
, VT
));
17417 // If we only have one shuffle, we're done.
17418 if (Shuffles
.size() == 1)
17419 return Shuffles
[0];
17421 // Update the vector mask to point to the post-shuffle vectors.
17422 for (int &Vec
: VectorMask
)
17424 Vec
= Shuffles
.size() - 1;
17426 Vec
= (Vec
- 1) / 2;
17428 // More than one shuffle. Generate a binary tree of blends, e.g. if from
17429 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
17431 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
17432 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
17433 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
17434 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
17435 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
17436 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
17437 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
17439 // Make sure the initial size of the shuffle list is even.
17440 if (Shuffles
.size() % 2)
17441 Shuffles
.push_back(DAG
.getUNDEF(VT
));
17443 for (unsigned CurSize
= Shuffles
.size(); CurSize
> 1; CurSize
/= 2) {
17445 Shuffles
[CurSize
] = DAG
.getUNDEF(VT
);
17448 for (unsigned In
= 0, Len
= CurSize
/ 2; In
< Len
; ++In
) {
17450 int Right
= 2 * In
+ 1;
17451 SmallVector
<int, 8> Mask(NumElems
, -1);
17452 for (unsigned i
= 0; i
!= NumElems
; ++i
) {
17453 if (VectorMask
[i
] == Left
) {
17455 VectorMask
[i
] = In
;
17456 } else if (VectorMask
[i
] == Right
) {
17457 Mask
[i
] = i
+ NumElems
;
17458 VectorMask
[i
] = In
;
17463 DAG
.getVectorShuffle(VT
, DL
, Shuffles
[Left
], Shuffles
[Right
], Mask
);
17466 return Shuffles
[0];
17469 // Try to turn a build vector of zero extends of extract vector elts into a
17470 // a vector zero extend and possibly an extract subvector.
17471 // TODO: Support sign extend?
17472 // TODO: Allow undef elements?
17473 SDValue
DAGCombiner::convertBuildVecZextToZext(SDNode
*N
) {
17474 if (LegalOperations
)
17477 EVT VT
= N
->getValueType(0);
17479 bool FoundZeroExtend
= false;
17480 SDValue Op0
= N
->getOperand(0);
17481 auto checkElem
= [&](SDValue Op
) -> int64_t {
17482 unsigned Opc
= Op
.getOpcode();
17483 FoundZeroExtend
|= (Opc
== ISD::ZERO_EXTEND
);
17484 if ((Opc
== ISD::ZERO_EXTEND
|| Opc
== ISD::ANY_EXTEND
) &&
17485 Op
.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT
&&
17486 Op0
.getOperand(0).getOperand(0) == Op
.getOperand(0).getOperand(0))
17487 if (auto *C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0).getOperand(1)))
17488 return C
->getZExtValue();
17492 // Make sure the first element matches
17493 // (zext (extract_vector_elt X, C))
17494 int64_t Offset
= checkElem(Op0
);
17498 unsigned NumElems
= N
->getNumOperands();
17499 SDValue In
= Op0
.getOperand(0).getOperand(0);
17500 EVT InSVT
= In
.getValueType().getScalarType();
17501 EVT InVT
= EVT::getVectorVT(*DAG
.getContext(), InSVT
, NumElems
);
17503 // Don't create an illegal input type after type legalization.
17504 if (LegalTypes
&& !TLI
.isTypeLegal(InVT
))
17507 // Ensure all the elements come from the same vector and are adjacent.
17508 for (unsigned i
= 1; i
!= NumElems
; ++i
) {
17509 if ((Offset
+ i
) != checkElem(N
->getOperand(i
)))
17514 In
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InVT
, In
,
17515 Op0
.getOperand(0).getOperand(1));
17516 return DAG
.getNode(FoundZeroExtend
? ISD::ZERO_EXTEND
: ISD::ANY_EXTEND
, DL
,
17520 SDValue
DAGCombiner::visitBUILD_VECTOR(SDNode
*N
) {
17521 EVT VT
= N
->getValueType(0);
17523 // A vector built entirely of undefs is undef.
17524 if (ISD::allOperandsUndef(N
))
17525 return DAG
.getUNDEF(VT
);
17527 // If this is a splat of a bitcast from another vector, change to a
17530 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
17531 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
17533 // If X is a build_vector itself, the concat can become a larger build_vector.
17534 // TODO: Maybe this is useful for non-splat too?
17535 if (!LegalOperations
) {
17536 if (SDValue Splat
= cast
<BuildVectorSDNode
>(N
)->getSplatValue()) {
17537 Splat
= peekThroughBitcasts(Splat
);
17538 EVT SrcVT
= Splat
.getValueType();
17539 if (SrcVT
.isVector()) {
17540 unsigned NumElts
= N
->getNumOperands() * SrcVT
.getVectorNumElements();
17541 EVT NewVT
= EVT::getVectorVT(*DAG
.getContext(),
17542 SrcVT
.getVectorElementType(), NumElts
);
17543 if (!LegalTypes
|| TLI
.isTypeLegal(NewVT
)) {
17544 SmallVector
<SDValue
, 8> Ops(N
->getNumOperands(), Splat
);
17545 SDValue Concat
= DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
),
17547 return DAG
.getBitcast(VT
, Concat
);
17553 // Check if we can express BUILD VECTOR via subvector extract.
17554 if (!LegalTypes
&& (N
->getNumOperands() > 1)) {
17555 SDValue Op0
= N
->getOperand(0);
17556 auto checkElem
= [&](SDValue Op
) -> uint64_t {
17557 if ((Op
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) &&
17558 (Op0
.getOperand(0) == Op
.getOperand(0)))
17559 if (auto CNode
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1)))
17560 return CNode
->getZExtValue();
17564 int Offset
= checkElem(Op0
);
17565 for (unsigned i
= 0; i
< N
->getNumOperands(); ++i
) {
17566 if (Offset
+ i
!= checkElem(N
->getOperand(i
))) {
17572 if ((Offset
== 0) &&
17573 (Op0
.getOperand(0).getValueType() == N
->getValueType(0)))
17574 return Op0
.getOperand(0);
17575 if ((Offset
!= -1) &&
17576 ((Offset
% N
->getValueType(0).getVectorNumElements()) ==
17577 0)) // IDX must be multiple of output size.
17578 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), N
->getValueType(0),
17579 Op0
.getOperand(0), Op0
.getOperand(1));
17582 if (SDValue V
= convertBuildVecZextToZext(N
))
17585 if (SDValue V
= reduceBuildVecExtToExtBuildVec(N
))
17588 if (SDValue V
= reduceBuildVecToShuffle(N
))
17594 static SDValue
combineConcatVectorOfScalars(SDNode
*N
, SelectionDAG
&DAG
) {
17595 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17596 EVT OpVT
= N
->getOperand(0).getValueType();
17598 // If the operands are legal vectors, leave them alone.
17599 if (TLI
.isTypeLegal(OpVT
))
17603 EVT VT
= N
->getValueType(0);
17604 SmallVector
<SDValue
, 8> Ops
;
17606 EVT SVT
= EVT::getIntegerVT(*DAG
.getContext(), OpVT
.getSizeInBits());
17607 SDValue ScalarUndef
= DAG
.getNode(ISD::UNDEF
, DL
, SVT
);
17609 // Keep track of what we encounter.
17610 bool AnyInteger
= false;
17611 bool AnyFP
= false;
17612 for (const SDValue
&Op
: N
->ops()) {
17613 if (ISD::BITCAST
== Op
.getOpcode() &&
17614 !Op
.getOperand(0).getValueType().isVector())
17615 Ops
.push_back(Op
.getOperand(0));
17616 else if (ISD::UNDEF
== Op
.getOpcode())
17617 Ops
.push_back(ScalarUndef
);
17621 // Note whether we encounter an integer or floating point scalar.
17622 // If it's neither, bail out, it could be something weird like x86mmx.
17623 EVT LastOpVT
= Ops
.back().getValueType();
17624 if (LastOpVT
.isFloatingPoint())
17626 else if (LastOpVT
.isInteger())
17632 // If any of the operands is a floating point scalar bitcast to a vector,
17633 // use floating point types throughout, and bitcast everything.
17634 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
17636 SVT
= EVT::getFloatingPointVT(OpVT
.getSizeInBits());
17637 ScalarUndef
= DAG
.getNode(ISD::UNDEF
, DL
, SVT
);
17639 for (SDValue
&Op
: Ops
) {
17640 if (Op
.getValueType() == SVT
)
17645 Op
= DAG
.getBitcast(SVT
, Op
);
17650 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), SVT
,
17651 VT
.getSizeInBits() / SVT
.getSizeInBits());
17652 return DAG
.getBitcast(VT
, DAG
.getBuildVector(VecVT
, DL
, Ops
));
17655 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
17656 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
17657 // most two distinct vectors the same size as the result, attempt to turn this
17658 // into a legal shuffle.
17659 static SDValue
combineConcatVectorOfExtracts(SDNode
*N
, SelectionDAG
&DAG
) {
17660 EVT VT
= N
->getValueType(0);
17661 EVT OpVT
= N
->getOperand(0).getValueType();
17662 int NumElts
= VT
.getVectorNumElements();
17663 int NumOpElts
= OpVT
.getVectorNumElements();
17665 SDValue SV0
= DAG
.getUNDEF(VT
), SV1
= DAG
.getUNDEF(VT
);
17666 SmallVector
<int, 8> Mask
;
17668 for (SDValue Op
: N
->ops()) {
17669 Op
= peekThroughBitcasts(Op
);
17671 // UNDEF nodes convert to UNDEF shuffle mask values.
17672 if (Op
.isUndef()) {
17673 Mask
.append((unsigned)NumOpElts
, -1);
17677 if (Op
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
17680 // What vector are we extracting the subvector from and at what index?
17681 SDValue ExtVec
= Op
.getOperand(0);
17683 // We want the EVT of the original extraction to correctly scale the
17684 // extraction index.
17685 EVT ExtVT
= ExtVec
.getValueType();
17686 ExtVec
= peekThroughBitcasts(ExtVec
);
17688 // UNDEF nodes convert to UNDEF shuffle mask values.
17689 if (ExtVec
.isUndef()) {
17690 Mask
.append((unsigned)NumOpElts
, -1);
17694 if (!isa
<ConstantSDNode
>(Op
.getOperand(1)))
17696 int ExtIdx
= Op
.getConstantOperandVal(1);
17698 // Ensure that we are extracting a subvector from a vector the same
17699 // size as the result.
17700 if (ExtVT
.getSizeInBits() != VT
.getSizeInBits())
17703 // Scale the subvector index to account for any bitcast.
17704 int NumExtElts
= ExtVT
.getVectorNumElements();
17705 if (0 == (NumExtElts
% NumElts
))
17706 ExtIdx
/= (NumExtElts
/ NumElts
);
17707 else if (0 == (NumElts
% NumExtElts
))
17708 ExtIdx
*= (NumElts
/ NumExtElts
);
17712 // At most we can reference 2 inputs in the final shuffle.
17713 if (SV0
.isUndef() || SV0
== ExtVec
) {
17715 for (int i
= 0; i
!= NumOpElts
; ++i
)
17716 Mask
.push_back(i
+ ExtIdx
);
17717 } else if (SV1
.isUndef() || SV1
== ExtVec
) {
17719 for (int i
= 0; i
!= NumOpElts
; ++i
)
17720 Mask
.push_back(i
+ ExtIdx
+ NumElts
);
17726 if (!DAG
.getTargetLoweringInfo().isShuffleMaskLegal(Mask
, VT
))
17729 return DAG
.getVectorShuffle(VT
, SDLoc(N
), DAG
.getBitcast(VT
, SV0
),
17730 DAG
.getBitcast(VT
, SV1
), Mask
);
17733 SDValue
DAGCombiner::visitCONCAT_VECTORS(SDNode
*N
) {
17734 // If we only have one input vector, we don't need to do any concatenation.
17735 if (N
->getNumOperands() == 1)
17736 return N
->getOperand(0);
17738 // Check if all of the operands are undefs.
17739 EVT VT
= N
->getValueType(0);
17740 if (ISD::allOperandsUndef(N
))
17741 return DAG
.getUNDEF(VT
);
17743 // Optimize concat_vectors where all but the first of the vectors are undef.
17744 if (std::all_of(std::next(N
->op_begin()), N
->op_end(), [](const SDValue
&Op
) {
17745 return Op
.isUndef();
17747 SDValue In
= N
->getOperand(0);
17748 assert(In
.getValueType().isVector() && "Must concat vectors");
17750 // If the input is a concat_vectors, just make a larger concat by padding
17751 // with smaller undefs.
17752 if (In
.getOpcode() == ISD::CONCAT_VECTORS
&& In
.hasOneUse()) {
17753 unsigned NumOps
= N
->getNumOperands() * In
.getNumOperands();
17754 SmallVector
<SDValue
, 4> Ops(In
->op_begin(), In
->op_end());
17755 Ops
.resize(NumOps
, DAG
.getUNDEF(Ops
[0].getValueType()));
17756 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
17759 SDValue Scalar
= peekThroughOneUseBitcasts(In
);
17761 // concat_vectors(scalar_to_vector(scalar), undef) ->
17762 // scalar_to_vector(scalar)
17763 if (!LegalOperations
&& Scalar
.getOpcode() == ISD::SCALAR_TO_VECTOR
&&
17764 Scalar
.hasOneUse()) {
17765 EVT SVT
= Scalar
.getValueType().getVectorElementType();
17766 if (SVT
== Scalar
.getOperand(0).getValueType())
17767 Scalar
= Scalar
.getOperand(0);
17770 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
17771 if (!Scalar
.getValueType().isVector()) {
17772 // If the bitcast type isn't legal, it might be a trunc of a legal type;
17773 // look through the trunc so we can still do the transform:
17774 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
17775 if (Scalar
->getOpcode() == ISD::TRUNCATE
&&
17776 !TLI
.isTypeLegal(Scalar
.getValueType()) &&
17777 TLI
.isTypeLegal(Scalar
->getOperand(0).getValueType()))
17778 Scalar
= Scalar
->getOperand(0);
17780 EVT SclTy
= Scalar
.getValueType();
17782 if (!SclTy
.isFloatingPoint() && !SclTy
.isInteger())
17785 // Bail out if the vector size is not a multiple of the scalar size.
17786 if (VT
.getSizeInBits() % SclTy
.getSizeInBits())
17789 unsigned VNTNumElms
= VT
.getSizeInBits() / SclTy
.getSizeInBits();
17790 if (VNTNumElms
< 2)
17793 EVT NVT
= EVT::getVectorVT(*DAG
.getContext(), SclTy
, VNTNumElms
);
17794 if (!TLI
.isTypeLegal(NVT
) || !TLI
.isTypeLegal(Scalar
.getValueType()))
17797 SDValue Res
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, SDLoc(N
), NVT
, Scalar
);
17798 return DAG
.getBitcast(VT
, Res
);
17802 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
17803 // We have already tested above for an UNDEF only concatenation.
17804 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
17805 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
17806 auto IsBuildVectorOrUndef
= [](const SDValue
&Op
) {
17807 return ISD::UNDEF
== Op
.getOpcode() || ISD::BUILD_VECTOR
== Op
.getOpcode();
17809 if (llvm::all_of(N
->ops(), IsBuildVectorOrUndef
)) {
17810 SmallVector
<SDValue
, 8> Opnds
;
17811 EVT SVT
= VT
.getScalarType();
17814 if (!SVT
.isFloatingPoint()) {
17815 // If BUILD_VECTOR are from built from integer, they may have different
17816 // operand types. Get the smallest type and truncate all operands to it.
17817 bool FoundMinVT
= false;
17818 for (const SDValue
&Op
: N
->ops())
17819 if (ISD::BUILD_VECTOR
== Op
.getOpcode()) {
17820 EVT OpSVT
= Op
.getOperand(0).getValueType();
17821 MinVT
= (!FoundMinVT
|| OpSVT
.bitsLE(MinVT
)) ? OpSVT
: MinVT
;
17824 assert(FoundMinVT
&& "Concat vector type mismatch");
17827 for (const SDValue
&Op
: N
->ops()) {
17828 EVT OpVT
= Op
.getValueType();
17829 unsigned NumElts
= OpVT
.getVectorNumElements();
17831 if (ISD::UNDEF
== Op
.getOpcode())
17832 Opnds
.append(NumElts
, DAG
.getUNDEF(MinVT
));
17834 if (ISD::BUILD_VECTOR
== Op
.getOpcode()) {
17835 if (SVT
.isFloatingPoint()) {
17836 assert(SVT
== OpVT
.getScalarType() && "Concat vector type mismatch");
17837 Opnds
.append(Op
->op_begin(), Op
->op_begin() + NumElts
);
17839 for (unsigned i
= 0; i
!= NumElts
; ++i
)
17841 DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), MinVT
, Op
.getOperand(i
)));
17846 assert(VT
.getVectorNumElements() == Opnds
.size() &&
17847 "Concat vector type mismatch");
17848 return DAG
.getBuildVector(VT
, SDLoc(N
), Opnds
);
17851 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
17852 if (SDValue V
= combineConcatVectorOfScalars(N
, DAG
))
17855 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
17856 if (Level
< AfterLegalizeVectorOps
&& TLI
.isTypeLegal(VT
))
17857 if (SDValue V
= combineConcatVectorOfExtracts(N
, DAG
))
17860 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
17861 // nodes often generate nop CONCAT_VECTOR nodes.
17862 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
17863 // place the incoming vectors at the exact same location.
17864 SDValue SingleSource
= SDValue();
17865 unsigned PartNumElem
= N
->getOperand(0).getValueType().getVectorNumElements();
17867 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
17868 SDValue Op
= N
->getOperand(i
);
17873 // Check if this is the identity extract:
17874 if (Op
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
17877 // Find the single incoming vector for the extract_subvector.
17878 if (SingleSource
.getNode()) {
17879 if (Op
.getOperand(0) != SingleSource
)
17882 SingleSource
= Op
.getOperand(0);
17884 // Check the source type is the same as the type of the result.
17885 // If not, this concat may extend the vector, so we can not
17886 // optimize it away.
17887 if (SingleSource
.getValueType() != N
->getValueType(0))
17891 auto *CS
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
17892 // The extract index must be constant.
17896 // Check that we are reading from the identity index.
17897 unsigned IdentityIndex
= i
* PartNumElem
;
17898 if (CS
->getAPIntValue() != IdentityIndex
)
17902 if (SingleSource
.getNode())
17903 return SingleSource
;
17908 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
17909 // if the subvector can be sourced for free.
17910 static SDValue
getSubVectorSrc(SDValue V
, SDValue Index
, EVT SubVT
) {
17911 if (V
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
17912 V
.getOperand(1).getValueType() == SubVT
&& V
.getOperand(2) == Index
) {
17913 return V
.getOperand(1);
17915 auto *IndexC
= dyn_cast
<ConstantSDNode
>(Index
);
17916 if (IndexC
&& V
.getOpcode() == ISD::CONCAT_VECTORS
&&
17917 V
.getOperand(0).getValueType() == SubVT
&&
17918 (IndexC
->getZExtValue() % SubVT
.getVectorNumElements()) == 0) {
17919 uint64_t SubIdx
= IndexC
->getZExtValue() / SubVT
.getVectorNumElements();
17920 return V
.getOperand(SubIdx
);
17925 static SDValue
narrowInsertExtractVectorBinOp(SDNode
*Extract
,
17926 SelectionDAG
&DAG
) {
17927 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17928 SDValue BinOp
= Extract
->getOperand(0);
17929 unsigned BinOpcode
= BinOp
.getOpcode();
17930 if (!TLI
.isBinOp(BinOpcode
) || BinOp
.getNode()->getNumValues() != 1)
17933 EVT VecVT
= BinOp
.getValueType();
17934 SDValue Bop0
= BinOp
.getOperand(0), Bop1
= BinOp
.getOperand(1);
17935 if (VecVT
!= Bop0
.getValueType() || VecVT
!= Bop1
.getValueType())
17938 SDValue Index
= Extract
->getOperand(1);
17939 EVT SubVT
= Extract
->getValueType(0);
17940 if (!TLI
.isOperationLegalOrCustom(BinOpcode
, SubVT
))
17943 SDValue Sub0
= getSubVectorSrc(Bop0
, Index
, SubVT
);
17944 SDValue Sub1
= getSubVectorSrc(Bop1
, Index
, SubVT
);
17946 // TODO: We could handle the case where only 1 operand is being inserted by
17947 // creating an extract of the other operand, but that requires checking
17948 // number of uses and/or costs.
17949 if (!Sub0
|| !Sub1
)
17952 // We are inserting both operands of the wide binop only to extract back
17953 // to the narrow vector size. Eliminate all of the insert/extract:
17954 // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
17955 return DAG
.getNode(BinOpcode
, SDLoc(Extract
), SubVT
, Sub0
, Sub1
,
17956 BinOp
->getFlags());
17959 /// If we are extracting a subvector produced by a wide binary operator try
17960 /// to use a narrow binary operator and/or avoid concatenation and extraction.
17961 static SDValue
narrowExtractedVectorBinOp(SDNode
*Extract
, SelectionDAG
&DAG
) {
17962 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
17963 // some of these bailouts with other transforms.
17965 if (SDValue V
= narrowInsertExtractVectorBinOp(Extract
, DAG
))
17968 // The extract index must be a constant, so we can map it to a concat operand.
17969 auto *ExtractIndexC
= dyn_cast
<ConstantSDNode
>(Extract
->getOperand(1));
17970 if (!ExtractIndexC
)
17973 // We are looking for an optionally bitcasted wide vector binary operator
17974 // feeding an extract subvector.
17975 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
17976 SDValue BinOp
= peekThroughBitcasts(Extract
->getOperand(0));
17977 unsigned BOpcode
= BinOp
.getOpcode();
17978 if (!TLI
.isBinOp(BOpcode
) || BinOp
.getNode()->getNumValues() != 1)
17981 // The binop must be a vector type, so we can extract some fraction of it.
17982 EVT WideBVT
= BinOp
.getValueType();
17983 if (!WideBVT
.isVector())
17986 EVT VT
= Extract
->getValueType(0);
17987 unsigned ExtractIndex
= ExtractIndexC
->getZExtValue();
17988 assert(ExtractIndex
% VT
.getVectorNumElements() == 0 &&
17989 "Extract index is not a multiple of the vector length.");
17991 // Bail out if this is not a proper multiple width extraction.
17992 unsigned WideWidth
= WideBVT
.getSizeInBits();
17993 unsigned NarrowWidth
= VT
.getSizeInBits();
17994 if (WideWidth
% NarrowWidth
!= 0)
17997 // Bail out if we are extracting a fraction of a single operation. This can
17998 // occur because we potentially looked through a bitcast of the binop.
17999 unsigned NarrowingRatio
= WideWidth
/ NarrowWidth
;
18000 unsigned WideNumElts
= WideBVT
.getVectorNumElements();
18001 if (WideNumElts
% NarrowingRatio
!= 0)
18004 // Bail out if the target does not support a narrower version of the binop.
18005 EVT NarrowBVT
= EVT::getVectorVT(*DAG
.getContext(), WideBVT
.getScalarType(),
18006 WideNumElts
/ NarrowingRatio
);
18007 if (!TLI
.isOperationLegalOrCustomOrPromote(BOpcode
, NarrowBVT
))
18010 // If extraction is cheap, we don't need to look at the binop operands
18011 // for concat ops. The narrow binop alone makes this transform profitable.
18012 // We can't just reuse the original extract index operand because we may have
18014 unsigned ConcatOpNum
= ExtractIndex
/ VT
.getVectorNumElements();
18015 unsigned ExtBOIdx
= ConcatOpNum
* NarrowBVT
.getVectorNumElements();
18016 EVT ExtBOIdxVT
= Extract
->getOperand(1).getValueType();
18017 if (TLI
.isExtractSubvectorCheap(NarrowBVT
, WideBVT
, ExtBOIdx
) &&
18018 BinOp
.hasOneUse() && Extract
->getOperand(0)->hasOneUse()) {
18019 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
18021 SDValue NewExtIndex
= DAG
.getConstant(ExtBOIdx
, DL
, ExtBOIdxVT
);
18022 SDValue X
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18023 BinOp
.getOperand(0), NewExtIndex
);
18024 SDValue Y
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18025 BinOp
.getOperand(1), NewExtIndex
);
18026 SDValue NarrowBinOp
= DAG
.getNode(BOpcode
, DL
, NarrowBVT
, X
, Y
,
18027 BinOp
.getNode()->getFlags());
18028 return DAG
.getBitcast(VT
, NarrowBinOp
);
18031 // Only handle the case where we are doubling and then halving. A larger ratio
18032 // may require more than two narrow binops to replace the wide binop.
18033 if (NarrowingRatio
!= 2)
18036 // TODO: The motivating case for this transform is an x86 AVX1 target. That
18037 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
18038 // flavors, but no other 256-bit integer support. This could be extended to
18039 // handle any binop, but that may require fixing/adding other folds to avoid
18040 // codegen regressions.
18041 if (BOpcode
!= ISD::AND
&& BOpcode
!= ISD::OR
&& BOpcode
!= ISD::XOR
)
18044 // We need at least one concatenation operation of a binop operand to make
18045 // this transform worthwhile. The concat must double the input vector sizes.
18046 auto GetSubVector
= [ConcatOpNum
](SDValue V
) -> SDValue
{
18047 if (V
.getOpcode() == ISD::CONCAT_VECTORS
&& V
.getNumOperands() == 2)
18048 return V
.getOperand(ConcatOpNum
);
18051 SDValue SubVecL
= GetSubVector(peekThroughBitcasts(BinOp
.getOperand(0)));
18052 SDValue SubVecR
= GetSubVector(peekThroughBitcasts(BinOp
.getOperand(1)));
18054 if (SubVecL
|| SubVecR
) {
18055 // If a binop operand was not the result of a concat, we must extract a
18056 // half-sized operand for our new narrow binop:
18057 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
18058 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
18059 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
18061 SDValue IndexC
= DAG
.getConstant(ExtBOIdx
, DL
, ExtBOIdxVT
);
18062 SDValue X
= SubVecL
? DAG
.getBitcast(NarrowBVT
, SubVecL
)
18063 : DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18064 BinOp
.getOperand(0), IndexC
);
18066 SDValue Y
= SubVecR
? DAG
.getBitcast(NarrowBVT
, SubVecR
)
18067 : DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NarrowBVT
,
18068 BinOp
.getOperand(1), IndexC
);
18070 SDValue NarrowBinOp
= DAG
.getNode(BOpcode
, DL
, NarrowBVT
, X
, Y
);
18071 return DAG
.getBitcast(VT
, NarrowBinOp
);
18077 /// If we are extracting a subvector from a wide vector load, convert to a
18078 /// narrow load to eliminate the extraction:
18079 /// (extract_subvector (load wide vector)) --> (load narrow vector)
18080 static SDValue
narrowExtractedVectorLoad(SDNode
*Extract
, SelectionDAG
&DAG
) {
18081 // TODO: Add support for big-endian. The offset calculation must be adjusted.
18082 if (DAG
.getDataLayout().isBigEndian())
18085 auto *Ld
= dyn_cast
<LoadSDNode
>(Extract
->getOperand(0));
18086 auto *ExtIdx
= dyn_cast
<ConstantSDNode
>(Extract
->getOperand(1));
18087 if (!Ld
|| Ld
->getExtensionType() || Ld
->isVolatile() || !ExtIdx
)
18090 // Allow targets to opt-out.
18091 EVT VT
= Extract
->getValueType(0);
18092 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18093 if (!TLI
.shouldReduceLoadWidth(Ld
, Ld
->getExtensionType(), VT
))
18096 // The narrow load will be offset from the base address of the old load if
18097 // we are extracting from something besides index 0 (little-endian).
18099 SDValue BaseAddr
= Ld
->getOperand(1);
18100 unsigned Offset
= ExtIdx
->getZExtValue() * VT
.getScalarType().getStoreSize();
18102 // TODO: Use "BaseIndexOffset" to make this more effective.
18103 SDValue NewAddr
= DAG
.getMemBasePlusOffset(BaseAddr
, Offset
, DL
);
18104 MachineFunction
&MF
= DAG
.getMachineFunction();
18105 MachineMemOperand
*MMO
= MF
.getMachineMemOperand(Ld
->getMemOperand(), Offset
,
18106 VT
.getStoreSize());
18107 SDValue NewLd
= DAG
.getLoad(VT
, DL
, Ld
->getChain(), NewAddr
, MMO
);
18108 DAG
.makeEquivalentMemoryOrdering(Ld
, NewLd
);
18112 SDValue
DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode
*N
) {
18113 EVT NVT
= N
->getValueType(0);
18114 SDValue V
= N
->getOperand(0);
18116 // Extract from UNDEF is UNDEF.
18118 return DAG
.getUNDEF(NVT
);
18120 if (TLI
.isOperationLegalOrCustomOrPromote(ISD::LOAD
, NVT
))
18121 if (SDValue NarrowLoad
= narrowExtractedVectorLoad(N
, DAG
))
18124 // Combine an extract of an extract into a single extract_subvector.
18125 // ext (ext X, C), 0 --> ext X, C
18126 SDValue Index
= N
->getOperand(1);
18127 if (isNullConstant(Index
) && V
.getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
18128 V
.hasOneUse() && isa
<ConstantSDNode
>(V
.getOperand(1))) {
18129 if (TLI
.isExtractSubvectorCheap(NVT
, V
.getOperand(0).getValueType(),
18130 V
.getConstantOperandVal(1)) &&
18131 TLI
.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, NVT
)) {
18132 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), NVT
, V
.getOperand(0),
18137 // Try to move vector bitcast after extract_subv by scaling extraction index:
18138 // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
18139 if (isa
<ConstantSDNode
>(Index
) && V
.getOpcode() == ISD::BITCAST
&&
18140 V
.getOperand(0).getValueType().isVector()) {
18141 SDValue SrcOp
= V
.getOperand(0);
18142 EVT SrcVT
= SrcOp
.getValueType();
18143 unsigned SrcNumElts
= SrcVT
.getVectorNumElements();
18144 unsigned DestNumElts
= V
.getValueType().getVectorNumElements();
18145 if ((SrcNumElts
% DestNumElts
) == 0) {
18146 unsigned SrcDestRatio
= SrcNumElts
/ DestNumElts
;
18147 unsigned NewExtNumElts
= NVT
.getVectorNumElements() * SrcDestRatio
;
18148 EVT NewExtVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
.getScalarType(),
18150 if (TLI
.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, NewExtVT
)) {
18151 unsigned IndexValScaled
= N
->getConstantOperandVal(1) * SrcDestRatio
;
18153 SDValue NewIndex
= DAG
.getIntPtrConstant(IndexValScaled
, DL
);
18154 SDValue NewExtract
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, NewExtVT
,
18155 V
.getOperand(0), NewIndex
);
18156 return DAG
.getBitcast(NVT
, NewExtract
);
18159 // TODO - handle (DestNumElts % SrcNumElts) == 0
18163 // (extract_subvec (concat V1, V2, ...), i)
18166 // Only operand 0 is checked as 'concat' assumes all inputs of the same
18168 if (V
.getOpcode() == ISD::CONCAT_VECTORS
&& isa
<ConstantSDNode
>(Index
) &&
18169 V
.getOperand(0).getValueType() == NVT
) {
18170 unsigned Idx
= N
->getConstantOperandVal(1);
18171 unsigned NumElems
= NVT
.getVectorNumElements();
18172 assert((Idx
% NumElems
) == 0 &&
18173 "IDX in concat is not a multiple of the result vector length.");
18174 return V
->getOperand(Idx
/ NumElems
);
18177 V
= peekThroughBitcasts(V
);
18179 // If the input is a build vector. Try to make a smaller build vector.
18180 if (V
.getOpcode() == ISD::BUILD_VECTOR
) {
18181 if (auto *IdxC
= dyn_cast
<ConstantSDNode
>(Index
)) {
18182 EVT InVT
= V
.getValueType();
18183 unsigned ExtractSize
= NVT
.getSizeInBits();
18184 unsigned EltSize
= InVT
.getScalarSizeInBits();
18185 // Only do this if we won't split any elements.
18186 if (ExtractSize
% EltSize
== 0) {
18187 unsigned NumElems
= ExtractSize
/ EltSize
;
18188 EVT EltVT
= InVT
.getVectorElementType();
18189 EVT ExtractVT
= NumElems
== 1 ? EltVT
18190 : EVT::getVectorVT(*DAG
.getContext(),
18192 if ((Level
< AfterLegalizeDAG
||
18194 TLI
.isOperationLegal(ISD::BUILD_VECTOR
, ExtractVT
))) &&
18195 (!LegalTypes
|| TLI
.isTypeLegal(ExtractVT
))) {
18196 unsigned IdxVal
= IdxC
->getZExtValue();
18197 IdxVal
*= NVT
.getScalarSizeInBits();
18200 if (NumElems
== 1) {
18201 SDValue Src
= V
->getOperand(IdxVal
);
18202 if (EltVT
!= Src
.getValueType())
18203 Src
= DAG
.getNode(ISD::TRUNCATE
, SDLoc(N
), InVT
, Src
);
18204 return DAG
.getBitcast(NVT
, Src
);
18207 // Extract the pieces from the original build_vector.
18208 SDValue BuildVec
= DAG
.getBuildVector(
18209 ExtractVT
, SDLoc(N
), V
->ops().slice(IdxVal
, NumElems
));
18210 return DAG
.getBitcast(NVT
, BuildVec
);
18216 if (V
.getOpcode() == ISD::INSERT_SUBVECTOR
) {
18217 // Handle only simple case where vector being inserted and vector
18218 // being extracted are of same size.
18219 EVT SmallVT
= V
.getOperand(1).getValueType();
18220 if (!NVT
.bitsEq(SmallVT
))
18223 // Only handle cases where both indexes are constants.
18224 auto *ExtIdx
= dyn_cast
<ConstantSDNode
>(Index
);
18225 auto *InsIdx
= dyn_cast
<ConstantSDNode
>(V
.getOperand(2));
18226 if (InsIdx
&& ExtIdx
) {
18228 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
18230 // indices are equal or bit offsets are equal => V1
18231 // otherwise => (extract_subvec V1, ExtIdx)
18232 if (InsIdx
->getZExtValue() * SmallVT
.getScalarSizeInBits() ==
18233 ExtIdx
->getZExtValue() * NVT
.getScalarSizeInBits())
18234 return DAG
.getBitcast(NVT
, V
.getOperand(1));
18235 return DAG
.getNode(
18236 ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), NVT
,
18237 DAG
.getBitcast(N
->getOperand(0).getValueType(), V
.getOperand(0)),
18242 if (SDValue NarrowBOp
= narrowExtractedVectorBinOp(N
, DAG
))
18245 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
18246 return SDValue(N
, 0);
18251 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
18252 /// followed by concatenation. Narrow vector ops may have better performance
18253 /// than wide ops, and this can unlock further narrowing of other vector ops.
18254 /// Targets can invert this transform later if it is not profitable.
18255 static SDValue
foldShuffleOfConcatUndefs(ShuffleVectorSDNode
*Shuf
,
18256 SelectionDAG
&DAG
) {
18257 SDValue N0
= Shuf
->getOperand(0), N1
= Shuf
->getOperand(1);
18258 if (N0
.getOpcode() != ISD::CONCAT_VECTORS
|| N0
.getNumOperands() != 2 ||
18259 N1
.getOpcode() != ISD::CONCAT_VECTORS
|| N1
.getNumOperands() != 2 ||
18260 !N0
.getOperand(1).isUndef() || !N1
.getOperand(1).isUndef())
18263 // Split the wide shuffle mask into halves. Any mask element that is accessing
18264 // operand 1 is offset down to account for narrowing of the vectors.
18265 ArrayRef
<int> Mask
= Shuf
->getMask();
18266 EVT VT
= Shuf
->getValueType(0);
18267 unsigned NumElts
= VT
.getVectorNumElements();
18268 unsigned HalfNumElts
= NumElts
/ 2;
18269 SmallVector
<int, 16> Mask0(HalfNumElts
, -1);
18270 SmallVector
<int, 16> Mask1(HalfNumElts
, -1);
18271 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18274 int M
= Mask
[i
] < (int)NumElts
? Mask
[i
] : Mask
[i
] - (int)HalfNumElts
;
18275 if (i
< HalfNumElts
)
18278 Mask1
[i
- HalfNumElts
] = M
;
18281 // Ask the target if this is a valid transform.
18282 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
18283 EVT HalfVT
= EVT::getVectorVT(*DAG
.getContext(), VT
.getScalarType(),
18285 if (!TLI
.isShuffleMaskLegal(Mask0
, HalfVT
) ||
18286 !TLI
.isShuffleMaskLegal(Mask1
, HalfVT
))
18289 // shuffle (concat X, undef), (concat Y, undef), Mask -->
18290 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
18291 SDValue X
= N0
.getOperand(0), Y
= N1
.getOperand(0);
18293 SDValue Shuf0
= DAG
.getVectorShuffle(HalfVT
, DL
, X
, Y
, Mask0
);
18294 SDValue Shuf1
= DAG
.getVectorShuffle(HalfVT
, DL
, X
, Y
, Mask1
);
18295 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, Shuf0
, Shuf1
);
18298 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
18299 // or turn a shuffle of a single concat into simpler shuffle then concat.
18300 static SDValue
partitionShuffleOfConcats(SDNode
*N
, SelectionDAG
&DAG
) {
18301 EVT VT
= N
->getValueType(0);
18302 unsigned NumElts
= VT
.getVectorNumElements();
18304 SDValue N0
= N
->getOperand(0);
18305 SDValue N1
= N
->getOperand(1);
18306 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N
);
18307 ArrayRef
<int> Mask
= SVN
->getMask();
18309 SmallVector
<SDValue
, 4> Ops
;
18310 EVT ConcatVT
= N0
.getOperand(0).getValueType();
18311 unsigned NumElemsPerConcat
= ConcatVT
.getVectorNumElements();
18312 unsigned NumConcats
= NumElts
/ NumElemsPerConcat
;
18314 auto IsUndefMaskElt
= [](int i
) { return i
== -1; };
18316 // Special case: shuffle(concat(A,B)) can be more efficiently represented
18317 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
18318 // half vector elements.
18319 if (NumElemsPerConcat
* 2 == NumElts
&& N1
.isUndef() &&
18320 llvm::all_of(Mask
.slice(NumElemsPerConcat
, NumElemsPerConcat
),
18322 N0
= DAG
.getVectorShuffle(ConcatVT
, SDLoc(N
), N0
.getOperand(0),
18324 Mask
.slice(0, NumElemsPerConcat
));
18325 N1
= DAG
.getUNDEF(ConcatVT
);
18326 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, N0
, N1
);
18329 // Look at every vector that's inserted. We're looking for exact
18330 // subvector-sized copies from a concatenated vector
18331 for (unsigned I
= 0; I
!= NumConcats
; ++I
) {
18332 unsigned Begin
= I
* NumElemsPerConcat
;
18333 ArrayRef
<int> SubMask
= Mask
.slice(Begin
, NumElemsPerConcat
);
18335 // Make sure we're dealing with a copy.
18336 if (llvm::all_of(SubMask
, IsUndefMaskElt
)) {
18337 Ops
.push_back(DAG
.getUNDEF(ConcatVT
));
18342 for (int i
= 0; i
!= (int)NumElemsPerConcat
; ++i
) {
18343 if (IsUndefMaskElt(SubMask
[i
]))
18345 if ((SubMask
[i
] % (int)NumElemsPerConcat
) != i
)
18347 int EltOpIdx
= SubMask
[i
] / NumElemsPerConcat
;
18348 if (0 <= OpIdx
&& EltOpIdx
!= OpIdx
)
18352 assert(0 <= OpIdx
&& "Unknown concat_vectors op");
18354 if (OpIdx
< (int)N0
.getNumOperands())
18355 Ops
.push_back(N0
.getOperand(OpIdx
));
18357 Ops
.push_back(N1
.getOperand(OpIdx
- N0
.getNumOperands()));
18360 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
18363 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
18364 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
18366 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
18367 // a simplification in some sense, but it isn't appropriate in general: some
18368 // BUILD_VECTORs are substantially cheaper than others. The general case
18369 // of a BUILD_VECTOR requires inserting each element individually (or
18370 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
18371 // all constants is a single constant pool load. A BUILD_VECTOR where each
18372 // element is identical is a splat. A BUILD_VECTOR where most of the operands
18373 // are undef lowers to a small number of element insertions.
18375 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
18376 // We don't fold shuffles where one side is a non-zero constant, and we don't
18377 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
18378 // non-constant operands. This seems to work out reasonably well in practice.
18379 static SDValue
combineShuffleOfScalars(ShuffleVectorSDNode
*SVN
,
18381 const TargetLowering
&TLI
) {
18382 EVT VT
= SVN
->getValueType(0);
18383 unsigned NumElts
= VT
.getVectorNumElements();
18384 SDValue N0
= SVN
->getOperand(0);
18385 SDValue N1
= SVN
->getOperand(1);
18387 if (!N0
->hasOneUse())
18390 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
18391 // discussed above.
18392 if (!N1
.isUndef()) {
18393 if (!N1
->hasOneUse())
18396 bool N0AnyConst
= isAnyConstantBuildVector(N0
);
18397 bool N1AnyConst
= isAnyConstantBuildVector(N1
);
18398 if (N0AnyConst
&& !N1AnyConst
&& !ISD::isBuildVectorAllZeros(N0
.getNode()))
18400 if (!N0AnyConst
&& N1AnyConst
&& !ISD::isBuildVectorAllZeros(N1
.getNode()))
18404 // If both inputs are splats of the same value then we can safely merge this
18405 // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
18406 bool IsSplat
= false;
18407 auto *BV0
= dyn_cast
<BuildVectorSDNode
>(N0
);
18408 auto *BV1
= dyn_cast
<BuildVectorSDNode
>(N1
);
18410 if (SDValue Splat0
= BV0
->getSplatValue())
18411 IsSplat
= (Splat0
== BV1
->getSplatValue());
18413 SmallVector
<SDValue
, 8> Ops
;
18414 SmallSet
<SDValue
, 16> DuplicateOps
;
18415 for (int M
: SVN
->getMask()) {
18416 SDValue Op
= DAG
.getUNDEF(VT
.getScalarType());
18418 int Idx
= M
< (int)NumElts
? M
: M
- NumElts
;
18419 SDValue
&S
= (M
< (int)NumElts
? N0
: N1
);
18420 if (S
.getOpcode() == ISD::BUILD_VECTOR
) {
18421 Op
= S
.getOperand(Idx
);
18422 } else if (S
.getOpcode() == ISD::SCALAR_TO_VECTOR
) {
18423 SDValue Op0
= S
.getOperand(0);
18424 Op
= Idx
== 0 ? Op0
: DAG
.getUNDEF(Op0
.getValueType());
18426 // Operand can't be combined - bail out.
18431 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
18432 // generating a splat; semantically, this is fine, but it's likely to
18433 // generate low-quality code if the target can't reconstruct an appropriate
18435 if (!Op
.isUndef() && !isa
<ConstantSDNode
>(Op
) && !isa
<ConstantFPSDNode
>(Op
))
18436 if (!IsSplat
&& !DuplicateOps
.insert(Op
).second
)
18442 // BUILD_VECTOR requires all inputs to be of the same type, find the
18443 // maximum type and extend them all.
18444 EVT SVT
= VT
.getScalarType();
18445 if (SVT
.isInteger())
18446 for (SDValue
&Op
: Ops
)
18447 SVT
= (SVT
.bitsLT(Op
.getValueType()) ? Op
.getValueType() : SVT
);
18448 if (SVT
!= VT
.getScalarType())
18449 for (SDValue
&Op
: Ops
)
18450 Op
= TLI
.isZExtFree(Op
.getValueType(), SVT
)
18451 ? DAG
.getZExtOrTrunc(Op
, SDLoc(SVN
), SVT
)
18452 : DAG
.getSExtOrTrunc(Op
, SDLoc(SVN
), SVT
);
18453 return DAG
.getBuildVector(VT
, SDLoc(SVN
), Ops
);
18456 // Match shuffles that can be converted to any_vector_extend_in_reg.
18457 // This is often generated during legalization.
18458 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
18459 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
18460 static SDValue
combineShuffleToVectorExtend(ShuffleVectorSDNode
*SVN
,
18462 const TargetLowering
&TLI
,
18463 bool LegalOperations
) {
18464 EVT VT
= SVN
->getValueType(0);
18465 bool IsBigEndian
= DAG
.getDataLayout().isBigEndian();
18467 // TODO Add support for big-endian when we have a test case.
18468 if (!VT
.isInteger() || IsBigEndian
)
18471 unsigned NumElts
= VT
.getVectorNumElements();
18472 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
18473 ArrayRef
<int> Mask
= SVN
->getMask();
18474 SDValue N0
= SVN
->getOperand(0);
18476 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
18477 auto isAnyExtend
= [&Mask
, &NumElts
](unsigned Scale
) {
18478 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18481 if ((i
% Scale
) == 0 && Mask
[i
] == (int)(i
/ Scale
))
18488 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
18489 // power-of-2 extensions as they are the most likely.
18490 for (unsigned Scale
= 2; Scale
< NumElts
; Scale
*= 2) {
18491 // Check for non power of 2 vector sizes
18492 if (NumElts
% Scale
!= 0)
18494 if (!isAnyExtend(Scale
))
18497 EVT OutSVT
= EVT::getIntegerVT(*DAG
.getContext(), EltSizeInBits
* Scale
);
18498 EVT OutVT
= EVT::getVectorVT(*DAG
.getContext(), OutSVT
, NumElts
/ Scale
);
18499 // Never create an illegal type. Only create unsupported operations if we
18500 // are pre-legalization.
18501 if (TLI
.isTypeLegal(OutVT
))
18502 if (!LegalOperations
||
18503 TLI
.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG
, OutVT
))
18504 return DAG
.getBitcast(VT
,
18505 DAG
.getNode(ISD::ANY_EXTEND_VECTOR_INREG
,
18506 SDLoc(SVN
), OutVT
, N0
));
18512 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
18513 // each source element of a large type into the lowest elements of a smaller
18514 // destination type. This is often generated during legalization.
18515 // If the source node itself was a '*_extend_vector_inreg' node then we should
18516 // then be able to remove it.
18517 static SDValue
combineTruncationShuffle(ShuffleVectorSDNode
*SVN
,
18518 SelectionDAG
&DAG
) {
18519 EVT VT
= SVN
->getValueType(0);
18520 bool IsBigEndian
= DAG
.getDataLayout().isBigEndian();
18522 // TODO Add support for big-endian when we have a test case.
18523 if (!VT
.isInteger() || IsBigEndian
)
18526 SDValue N0
= peekThroughBitcasts(SVN
->getOperand(0));
18528 unsigned Opcode
= N0
.getOpcode();
18529 if (Opcode
!= ISD::ANY_EXTEND_VECTOR_INREG
&&
18530 Opcode
!= ISD::SIGN_EXTEND_VECTOR_INREG
&&
18531 Opcode
!= ISD::ZERO_EXTEND_VECTOR_INREG
)
18534 SDValue N00
= N0
.getOperand(0);
18535 ArrayRef
<int> Mask
= SVN
->getMask();
18536 unsigned NumElts
= VT
.getVectorNumElements();
18537 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
18538 unsigned ExtSrcSizeInBits
= N00
.getScalarValueSizeInBits();
18539 unsigned ExtDstSizeInBits
= N0
.getScalarValueSizeInBits();
18541 if (ExtDstSizeInBits
% ExtSrcSizeInBits
!= 0)
18543 unsigned ExtScale
= ExtDstSizeInBits
/ ExtSrcSizeInBits
;
18545 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
18546 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
18547 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
18548 auto isTruncate
= [&Mask
, &NumElts
](unsigned Scale
) {
18549 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18552 if ((i
* Scale
) < NumElts
&& Mask
[i
] == (int)(i
* Scale
))
18559 // At the moment we just handle the case where we've truncated back to the
18560 // same size as before the extension.
18561 // TODO: handle more extension/truncation cases as cases arise.
18562 if (EltSizeInBits
!= ExtSrcSizeInBits
)
18565 // We can remove *extend_vector_inreg only if the truncation happens at
18566 // the same scale as the extension.
18567 if (isTruncate(ExtScale
))
18568 return DAG
.getBitcast(VT
, N00
);
18573 // Combine shuffles of splat-shuffles of the form:
18574 // shuffle (shuffle V, undef, splat-mask), undef, M
18575 // If splat-mask contains undef elements, we need to be careful about
18576 // introducing undef's in the folded mask which are not the result of composing
18577 // the masks of the shuffles.
18578 static SDValue
combineShuffleOfSplatVal(ShuffleVectorSDNode
*Shuf
,
18579 SelectionDAG
&DAG
) {
18580 if (!Shuf
->getOperand(1).isUndef())
18582 auto *Splat
= dyn_cast
<ShuffleVectorSDNode
>(Shuf
->getOperand(0));
18583 if (!Splat
|| !Splat
->isSplat())
18586 ArrayRef
<int> ShufMask
= Shuf
->getMask();
18587 ArrayRef
<int> SplatMask
= Splat
->getMask();
18588 assert(ShufMask
.size() == SplatMask
.size() && "Mask length mismatch");
18590 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
18591 // every undef mask element in the splat-shuffle has a corresponding undef
18592 // element in the user-shuffle's mask or if the composition of mask elements
18593 // would result in undef.
18594 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
18595 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
18596 // In this case it is not legal to simplify to the splat-shuffle because we
18597 // may be exposing the users of the shuffle an undef element at index 1
18598 // which was not there before the combine.
18599 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
18600 // In this case the composition of masks yields SplatMask, so it's ok to
18601 // simplify to the splat-shuffle.
18602 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
18603 // In this case the composed mask includes all undef elements of SplatMask
18604 // and in addition sets element zero to undef. It is safe to simplify to
18605 // the splat-shuffle.
18606 auto CanSimplifyToExistingSplat
= [](ArrayRef
<int> UserMask
,
18607 ArrayRef
<int> SplatMask
) {
18608 for (unsigned i
= 0, e
= UserMask
.size(); i
!= e
; ++i
)
18609 if (UserMask
[i
] != -1 && SplatMask
[i
] == -1 &&
18610 SplatMask
[UserMask
[i
]] != -1)
18614 if (CanSimplifyToExistingSplat(ShufMask
, SplatMask
))
18615 return Shuf
->getOperand(0);
18617 // Create a new shuffle with a mask that is composed of the two shuffles'
18619 SmallVector
<int, 32> NewMask
;
18620 for (int Idx
: ShufMask
)
18621 NewMask
.push_back(Idx
== -1 ? -1 : SplatMask
[Idx
]);
18623 return DAG
.getVectorShuffle(Splat
->getValueType(0), SDLoc(Splat
),
18624 Splat
->getOperand(0), Splat
->getOperand(1),
18628 /// If the shuffle mask is taking exactly one element from the first vector
18629 /// operand and passing through all other elements from the second vector
18630 /// operand, return the index of the mask element that is choosing an element
18631 /// from the first operand. Otherwise, return -1.
18632 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef
<int> Mask
) {
18633 int MaskSize
= Mask
.size();
18634 int EltFromOp0
= -1;
18635 // TODO: This does not match if there are undef elements in the shuffle mask.
18636 // Should we ignore undefs in the shuffle mask instead? The trade-off is
18637 // removing an instruction (a shuffle), but losing the knowledge that some
18638 // vector lanes are not needed.
18639 for (int i
= 0; i
!= MaskSize
; ++i
) {
18640 if (Mask
[i
] >= 0 && Mask
[i
] < MaskSize
) {
18641 // We're looking for a shuffle of exactly one element from operand 0.
18642 if (EltFromOp0
!= -1)
18645 } else if (Mask
[i
] != i
+ MaskSize
) {
18646 // Nothing from operand 1 can change lanes.
18653 /// If a shuffle inserts exactly one element from a source vector operand into
18654 /// another vector operand and we can access the specified element as a scalar,
18655 /// then we can eliminate the shuffle.
18656 static SDValue
replaceShuffleOfInsert(ShuffleVectorSDNode
*Shuf
,
18657 SelectionDAG
&DAG
) {
18658 // First, check if we are taking one element of a vector and shuffling that
18659 // element into another vector.
18660 ArrayRef
<int> Mask
= Shuf
->getMask();
18661 SmallVector
<int, 16> CommutedMask(Mask
.begin(), Mask
.end());
18662 SDValue Op0
= Shuf
->getOperand(0);
18663 SDValue Op1
= Shuf
->getOperand(1);
18664 int ShufOp0Index
= getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask
);
18665 if (ShufOp0Index
== -1) {
18666 // Commute mask and check again.
18667 ShuffleVectorSDNode::commuteMask(CommutedMask
);
18668 ShufOp0Index
= getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask
);
18669 if (ShufOp0Index
== -1)
18671 // Commute operands to match the commuted shuffle mask.
18672 std::swap(Op0
, Op1
);
18673 Mask
= CommutedMask
;
18676 // The shuffle inserts exactly one element from operand 0 into operand 1.
18677 // Now see if we can access that element as a scalar via a real insert element
18679 // TODO: We can try harder to locate the element as a scalar. Examples: it
18680 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
18681 assert(Mask
[ShufOp0Index
] >= 0 && Mask
[ShufOp0Index
] < (int)Mask
.size() &&
18682 "Shuffle mask value must be from operand 0");
18683 if (Op0
.getOpcode() != ISD::INSERT_VECTOR_ELT
)
18686 auto *InsIndexC
= dyn_cast
<ConstantSDNode
>(Op0
.getOperand(2));
18687 if (!InsIndexC
|| InsIndexC
->getSExtValue() != Mask
[ShufOp0Index
])
18690 // There's an existing insertelement with constant insertion index, so we
18691 // don't need to check the legality/profitability of a replacement operation
18692 // that differs at most in the constant value. The target should be able to
18693 // lower any of those in a similar way. If not, legalization will expand this
18694 // to a scalar-to-vector plus shuffle.
18696 // Note that the shuffle may move the scalar from the position that the insert
18697 // element used. Therefore, our new insert element occurs at the shuffle's
18698 // mask index value, not the insert's index value.
18699 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
18700 SDValue NewInsIndex
= DAG
.getConstant(ShufOp0Index
, SDLoc(Shuf
),
18701 Op0
.getOperand(2).getValueType());
18702 return DAG
.getNode(ISD::INSERT_VECTOR_ELT
, SDLoc(Shuf
), Op0
.getValueType(),
18703 Op1
, Op0
.getOperand(1), NewInsIndex
);
18706 /// If we have a unary shuffle of a shuffle, see if it can be folded away
18707 /// completely. This has the potential to lose undef knowledge because the first
18708 /// shuffle may not have an undef mask element where the second one does. So
18709 /// only call this after doing simplifications based on demanded elements.
18710 static SDValue
simplifyShuffleOfShuffle(ShuffleVectorSDNode
*Shuf
) {
18711 // shuf (shuf0 X, Y, Mask0), undef, Mask
18712 auto *Shuf0
= dyn_cast
<ShuffleVectorSDNode
>(Shuf
->getOperand(0));
18713 if (!Shuf0
|| !Shuf
->getOperand(1).isUndef())
18716 ArrayRef
<int> Mask
= Shuf
->getMask();
18717 ArrayRef
<int> Mask0
= Shuf0
->getMask();
18718 for (int i
= 0, e
= (int)Mask
.size(); i
!= e
; ++i
) {
18719 // Ignore undef elements.
18722 assert(Mask
[i
] >= 0 && Mask
[i
] < e
&& "Unexpected shuffle mask value");
18724 // Is the element of the shuffle operand chosen by this shuffle the same as
18725 // the element chosen by the shuffle operand itself?
18726 if (Mask0
[Mask
[i
]] != Mask0
[i
])
18729 // Every element of this shuffle is identical to the result of the previous
18730 // shuffle, so we can replace this value.
18731 return Shuf
->getOperand(0);
18734 SDValue
DAGCombiner::visitVECTOR_SHUFFLE(SDNode
*N
) {
18735 EVT VT
= N
->getValueType(0);
18736 unsigned NumElts
= VT
.getVectorNumElements();
18738 SDValue N0
= N
->getOperand(0);
18739 SDValue N1
= N
->getOperand(1);
18741 assert(N0
.getValueType() == VT
&& "Vector shuffle must be normalized in DAG");
18743 // Canonicalize shuffle undef, undef -> undef
18744 if (N0
.isUndef() && N1
.isUndef())
18745 return DAG
.getUNDEF(VT
);
18747 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(N
);
18749 // Canonicalize shuffle v, v -> v, undef
18751 SmallVector
<int, 8> NewMask
;
18752 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18753 int Idx
= SVN
->getMaskElt(i
);
18754 if (Idx
>= (int)NumElts
) Idx
-= NumElts
;
18755 NewMask
.push_back(Idx
);
18757 return DAG
.getVectorShuffle(VT
, SDLoc(N
), N0
, DAG
.getUNDEF(VT
), NewMask
);
18760 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
18762 return DAG
.getCommutedVectorShuffle(*SVN
);
18764 // Remove references to rhs if it is undef
18765 if (N1
.isUndef()) {
18766 bool Changed
= false;
18767 SmallVector
<int, 8> NewMask
;
18768 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18769 int Idx
= SVN
->getMaskElt(i
);
18770 if (Idx
>= (int)NumElts
) {
18774 NewMask
.push_back(Idx
);
18777 return DAG
.getVectorShuffle(VT
, SDLoc(N
), N0
, N1
, NewMask
);
18780 if (SDValue InsElt
= replaceShuffleOfInsert(SVN
, DAG
))
18783 // A shuffle of a single vector that is a splatted value can always be folded.
18784 if (SDValue V
= combineShuffleOfSplatVal(SVN
, DAG
))
18787 // If it is a splat, check if the argument vector is another splat or a
18789 if (SVN
->isSplat() && SVN
->getSplatIndex() < (int)NumElts
) {
18790 int SplatIndex
= SVN
->getSplatIndex();
18791 if (TLI
.isExtractVecEltCheap(VT
, SplatIndex
) &&
18792 TLI
.isBinOp(N0
.getOpcode()) && N0
.getNode()->getNumValues() == 1) {
18793 // splat (vector_bo L, R), Index -->
18794 // splat (scalar_bo (extelt L, Index), (extelt R, Index))
18795 SDValue L
= N0
.getOperand(0), R
= N0
.getOperand(1);
18797 EVT EltVT
= VT
.getScalarType();
18798 SDValue Index
= DAG
.getIntPtrConstant(SplatIndex
, DL
);
18799 SDValue ExtL
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, L
, Index
);
18800 SDValue ExtR
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, R
, Index
);
18801 SDValue NewBO
= DAG
.getNode(N0
.getOpcode(), DL
, EltVT
, ExtL
, ExtR
,
18802 N0
.getNode()->getFlags());
18803 SDValue Insert
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, VT
, NewBO
);
18804 SmallVector
<int, 16> ZeroMask(VT
.getVectorNumElements(), 0);
18805 return DAG
.getVectorShuffle(VT
, DL
, Insert
, DAG
.getUNDEF(VT
), ZeroMask
);
18808 // If this is a bit convert that changes the element type of the vector but
18809 // not the number of vector elements, look through it. Be careful not to
18810 // look though conversions that change things like v4f32 to v2f64.
18811 SDNode
*V
= N0
.getNode();
18812 if (V
->getOpcode() == ISD::BITCAST
) {
18813 SDValue ConvInput
= V
->getOperand(0);
18814 if (ConvInput
.getValueType().isVector() &&
18815 ConvInput
.getValueType().getVectorNumElements() == NumElts
)
18816 V
= ConvInput
.getNode();
18819 if (V
->getOpcode() == ISD::BUILD_VECTOR
) {
18820 assert(V
->getNumOperands() == NumElts
&&
18821 "BUILD_VECTOR has wrong number of operands");
18823 bool AllSame
= true;
18824 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18825 if (!V
->getOperand(i
).isUndef()) {
18826 Base
= V
->getOperand(i
);
18830 // Splat of <u, u, u, u>, return <u, u, u, u>
18831 if (!Base
.getNode())
18833 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
18834 if (V
->getOperand(i
) != Base
) {
18839 // Splat of <x, x, x, x>, return <x, x, x, x>
18843 // Canonicalize any other splat as a build_vector.
18844 SDValue Splatted
= V
->getOperand(SplatIndex
);
18845 SmallVector
<SDValue
, 8> Ops(NumElts
, Splatted
);
18846 SDValue NewBV
= DAG
.getBuildVector(V
->getValueType(0), SDLoc(N
), Ops
);
18848 // We may have jumped through bitcasts, so the type of the
18849 // BUILD_VECTOR may not match the type of the shuffle.
18850 if (V
->getValueType(0) != VT
)
18851 NewBV
= DAG
.getBitcast(VT
, NewBV
);
18856 // Simplify source operands based on shuffle mask.
18857 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
18858 return SDValue(N
, 0);
18860 // This is intentionally placed after demanded elements simplification because
18861 // it could eliminate knowledge of undef elements created by this shuffle.
18862 if (SDValue ShufOp
= simplifyShuffleOfShuffle(SVN
))
18865 // Match shuffles that can be converted to any_vector_extend_in_reg.
18866 if (SDValue V
= combineShuffleToVectorExtend(SVN
, DAG
, TLI
, LegalOperations
))
18869 // Combine "truncate_vector_in_reg" style shuffles.
18870 if (SDValue V
= combineTruncationShuffle(SVN
, DAG
))
18873 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&&
18874 Level
< AfterLegalizeVectorOps
&&
18876 (N1
.getOpcode() == ISD::CONCAT_VECTORS
&&
18877 N0
.getOperand(0).getValueType() == N1
.getOperand(0).getValueType()))) {
18878 if (SDValue V
= partitionShuffleOfConcats(N
, DAG
))
18882 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
18883 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
18884 if (Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
))
18885 if (SDValue Res
= combineShuffleOfScalars(SVN
, DAG
, TLI
))
18888 // If this shuffle only has a single input that is a bitcasted shuffle,
18889 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
18890 // back to their original types.
18891 if (N0
.getOpcode() == ISD::BITCAST
&& N0
.hasOneUse() &&
18892 N1
.isUndef() && Level
< AfterLegalizeVectorOps
&&
18893 TLI
.isTypeLegal(VT
)) {
18894 auto ScaleShuffleMask
= [](ArrayRef
<int> Mask
, int Scale
) {
18896 return SmallVector
<int, 8>(Mask
.begin(), Mask
.end());
18898 SmallVector
<int, 8> NewMask
;
18900 for (int s
= 0; s
!= Scale
; ++s
)
18901 NewMask
.push_back(M
< 0 ? -1 : Scale
* M
+ s
);
18905 SDValue BC0
= peekThroughOneUseBitcasts(N0
);
18906 if (BC0
.getOpcode() == ISD::VECTOR_SHUFFLE
&& BC0
.hasOneUse()) {
18907 EVT SVT
= VT
.getScalarType();
18908 EVT InnerVT
= BC0
->getValueType(0);
18909 EVT InnerSVT
= InnerVT
.getScalarType();
18911 // Determine which shuffle works with the smaller scalar type.
18912 EVT ScaleVT
= SVT
.bitsLT(InnerSVT
) ? VT
: InnerVT
;
18913 EVT ScaleSVT
= ScaleVT
.getScalarType();
18915 if (TLI
.isTypeLegal(ScaleVT
) &&
18916 0 == (InnerSVT
.getSizeInBits() % ScaleSVT
.getSizeInBits()) &&
18917 0 == (SVT
.getSizeInBits() % ScaleSVT
.getSizeInBits())) {
18918 int InnerScale
= InnerSVT
.getSizeInBits() / ScaleSVT
.getSizeInBits();
18919 int OuterScale
= SVT
.getSizeInBits() / ScaleSVT
.getSizeInBits();
18921 // Scale the shuffle masks to the smaller scalar type.
18922 ShuffleVectorSDNode
*InnerSVN
= cast
<ShuffleVectorSDNode
>(BC0
);
18923 SmallVector
<int, 8> InnerMask
=
18924 ScaleShuffleMask(InnerSVN
->getMask(), InnerScale
);
18925 SmallVector
<int, 8> OuterMask
=
18926 ScaleShuffleMask(SVN
->getMask(), OuterScale
);
18928 // Merge the shuffle masks.
18929 SmallVector
<int, 8> NewMask
;
18930 for (int M
: OuterMask
)
18931 NewMask
.push_back(M
< 0 ? -1 : InnerMask
[M
]);
18933 // Test for shuffle mask legality over both commutations.
18934 SDValue SV0
= BC0
->getOperand(0);
18935 SDValue SV1
= BC0
->getOperand(1);
18936 bool LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, ScaleVT
);
18938 std::swap(SV0
, SV1
);
18939 ShuffleVectorSDNode::commuteMask(NewMask
);
18940 LegalMask
= TLI
.isShuffleMaskLegal(NewMask
, ScaleVT
);
18944 SV0
= DAG
.getBitcast(ScaleVT
, SV0
);
18945 SV1
= DAG
.getBitcast(ScaleVT
, SV1
);
18946 return DAG
.getBitcast(
18947 VT
, DAG
.getVectorShuffle(ScaleVT
, SDLoc(N
), SV0
, SV1
, NewMask
));
18953 // Canonicalize shuffles according to rules:
18954 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
18955 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
18956 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
18957 if (N1
.getOpcode() == ISD::VECTOR_SHUFFLE
&&
18958 N0
.getOpcode() != ISD::VECTOR_SHUFFLE
&& Level
< AfterLegalizeDAG
&&
18959 TLI
.isTypeLegal(VT
)) {
18960 // The incoming shuffle must be of the same type as the result of the
18961 // current shuffle.
18962 assert(N1
->getOperand(0).getValueType() == VT
&&
18963 "Shuffle types don't match");
18965 SDValue SV0
= N1
->getOperand(0);
18966 SDValue SV1
= N1
->getOperand(1);
18967 bool HasSameOp0
= N0
== SV0
;
18968 bool IsSV1Undef
= SV1
.isUndef();
18969 if (HasSameOp0
|| IsSV1Undef
|| N0
== SV1
)
18970 // Commute the operands of this shuffle so that next rule
18972 return DAG
.getCommutedVectorShuffle(*SVN
);
18975 // Try to fold according to rules:
18976 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
18977 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
18978 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
18979 // Don't try to fold shuffles with illegal type.
18980 // Only fold if this shuffle is the only user of the other shuffle.
18981 if (N0
.getOpcode() == ISD::VECTOR_SHUFFLE
&& N
->isOnlyUserOf(N0
.getNode()) &&
18982 Level
< AfterLegalizeDAG
&& TLI
.isTypeLegal(VT
)) {
18983 ShuffleVectorSDNode
*OtherSV
= cast
<ShuffleVectorSDNode
>(N0
);
18985 // Don't try to fold splats; they're likely to simplify somehow, or they
18987 if (OtherSV
->isSplat())
18990 // The incoming shuffle must be of the same type as the result of the
18991 // current shuffle.
18992 assert(OtherSV
->getOperand(0).getValueType() == VT
&&
18993 "Shuffle types don't match");
18996 SmallVector
<int, 4> Mask
;
18997 // Compute the combined shuffle mask for a shuffle with SV0 as the first
18998 // operand, and SV1 as the second operand.
18999 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
19000 int Idx
= SVN
->getMaskElt(i
);
19002 // Propagate Undef.
19003 Mask
.push_back(Idx
);
19007 SDValue CurrentVec
;
19008 if (Idx
< (int)NumElts
) {
19009 // This shuffle index refers to the inner shuffle N0. Lookup the inner
19010 // shuffle mask to identify which vector is actually referenced.
19011 Idx
= OtherSV
->getMaskElt(Idx
);
19013 // Propagate Undef.
19014 Mask
.push_back(Idx
);
19018 CurrentVec
= (Idx
< (int) NumElts
) ? OtherSV
->getOperand(0)
19019 : OtherSV
->getOperand(1);
19021 // This shuffle index references an element within N1.
19025 // Simple case where 'CurrentVec' is UNDEF.
19026 if (CurrentVec
.isUndef()) {
19027 Mask
.push_back(-1);
19031 // Canonicalize the shuffle index. We don't know yet if CurrentVec
19032 // will be the first or second operand of the combined shuffle.
19033 Idx
= Idx
% NumElts
;
19034 if (!SV0
.getNode() || SV0
== CurrentVec
) {
19035 // Ok. CurrentVec is the left hand side.
19036 // Update the mask accordingly.
19038 Mask
.push_back(Idx
);
19042 // Bail out if we cannot convert the shuffle pair into a single shuffle.
19043 if (SV1
.getNode() && SV1
!= CurrentVec
)
19046 // Ok. CurrentVec is the right hand side.
19047 // Update the mask accordingly.
19049 Mask
.push_back(Idx
+ NumElts
);
19052 // Check if all indices in Mask are Undef. In case, propagate Undef.
19053 bool isUndefMask
= true;
19054 for (unsigned i
= 0; i
!= NumElts
&& isUndefMask
; ++i
)
19055 isUndefMask
&= Mask
[i
] < 0;
19058 return DAG
.getUNDEF(VT
);
19060 if (!SV0
.getNode())
19061 SV0
= DAG
.getUNDEF(VT
);
19062 if (!SV1
.getNode())
19063 SV1
= DAG
.getUNDEF(VT
);
19065 // Avoid introducing shuffles with illegal mask.
19066 if (!TLI
.isShuffleMaskLegal(Mask
, VT
)) {
19067 ShuffleVectorSDNode::commuteMask(Mask
);
19069 if (!TLI
.isShuffleMaskLegal(Mask
, VT
))
19072 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
19073 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
19074 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
19075 std::swap(SV0
, SV1
);
19078 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
19079 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
19080 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
19081 return DAG
.getVectorShuffle(VT
, SDLoc(N
), SV0
, SV1
, Mask
);
19084 if (SDValue V
= foldShuffleOfConcatUndefs(SVN
, DAG
))
19090 SDValue
DAGCombiner::visitSCALAR_TO_VECTOR(SDNode
*N
) {
19091 SDValue InVal
= N
->getOperand(0);
19092 EVT VT
= N
->getValueType(0);
19094 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
19095 // with a VECTOR_SHUFFLE and possible truncate.
19096 if (InVal
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) {
19097 SDValue InVec
= InVal
->getOperand(0);
19098 SDValue EltNo
= InVal
->getOperand(1);
19099 auto InVecT
= InVec
.getValueType();
19100 if (ConstantSDNode
*C0
= dyn_cast
<ConstantSDNode
>(EltNo
)) {
19101 SmallVector
<int, 8> NewMask(InVecT
.getVectorNumElements(), -1);
19102 int Elt
= C0
->getZExtValue();
19105 // If we have an implict truncate do truncate here as long as it's legal.
19106 // if it's not legal, this should
19107 if (VT
.getScalarType() != InVal
.getValueType() &&
19108 InVal
.getValueType().isScalarInteger() &&
19109 isTypeLegal(VT
.getScalarType())) {
19111 DAG
.getNode(ISD::TRUNCATE
, SDLoc(InVal
), VT
.getScalarType(), InVal
);
19112 return DAG
.getNode(ISD::SCALAR_TO_VECTOR
, SDLoc(N
), VT
, Val
);
19114 if (VT
.getScalarType() == InVecT
.getScalarType() &&
19115 VT
.getVectorNumElements() <= InVecT
.getVectorNumElements() &&
19116 TLI
.isShuffleMaskLegal(NewMask
, VT
)) {
19117 Val
= DAG
.getVectorShuffle(InVecT
, SDLoc(N
), InVec
,
19118 DAG
.getUNDEF(InVecT
), NewMask
);
19119 // If the initial vector is the correct size this shuffle is a
19123 // If not we must truncate the vector.
19124 if (VT
.getVectorNumElements() != InVecT
.getVectorNumElements()) {
19125 MVT IdxTy
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
19126 SDValue ZeroIdx
= DAG
.getConstant(0, SDLoc(N
), IdxTy
);
19128 EVT::getVectorVT(*DAG
.getContext(), InVecT
.getVectorElementType(),
19129 VT
.getVectorNumElements());
19130 Val
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, SDLoc(N
), SubVT
, Val
,
19141 SDValue
DAGCombiner::visitINSERT_SUBVECTOR(SDNode
*N
) {
19142 EVT VT
= N
->getValueType(0);
19143 SDValue N0
= N
->getOperand(0);
19144 SDValue N1
= N
->getOperand(1);
19145 SDValue N2
= N
->getOperand(2);
19147 // If inserting an UNDEF, just return the original vector.
19151 // If this is an insert of an extracted vector into an undef vector, we can
19152 // just use the input to the extract.
19153 if (N0
.isUndef() && N1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
19154 N1
.getOperand(1) == N2
&& N1
.getOperand(0).getValueType() == VT
)
19155 return N1
.getOperand(0);
19157 // If we are inserting a bitcast value into an undef, with the same
19158 // number of elements, just use the bitcast input of the extract.
19159 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
19160 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
19161 if (N0
.isUndef() && N1
.getOpcode() == ISD::BITCAST
&&
19162 N1
.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR
&&
19163 N1
.getOperand(0).getOperand(1) == N2
&&
19164 N1
.getOperand(0).getOperand(0).getValueType().getVectorNumElements() ==
19165 VT
.getVectorNumElements() &&
19166 N1
.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
19167 VT
.getSizeInBits()) {
19168 return DAG
.getBitcast(VT
, N1
.getOperand(0).getOperand(0));
19171 // If both N1 and N2 are bitcast values on which insert_subvector
19172 // would makes sense, pull the bitcast through.
19173 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
19174 // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
19175 if (N0
.getOpcode() == ISD::BITCAST
&& N1
.getOpcode() == ISD::BITCAST
) {
19176 SDValue CN0
= N0
.getOperand(0);
19177 SDValue CN1
= N1
.getOperand(0);
19178 EVT CN0VT
= CN0
.getValueType();
19179 EVT CN1VT
= CN1
.getValueType();
19180 if (CN0VT
.isVector() && CN1VT
.isVector() &&
19181 CN0VT
.getVectorElementType() == CN1VT
.getVectorElementType() &&
19182 CN0VT
.getVectorNumElements() == VT
.getVectorNumElements()) {
19183 SDValue NewINSERT
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
),
19184 CN0
.getValueType(), CN0
, CN1
, N2
);
19185 return DAG
.getBitcast(VT
, NewINSERT
);
19189 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
19190 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
19191 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
19192 if (N0
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
19193 N0
.getOperand(1).getValueType() == N1
.getValueType() &&
19194 N0
.getOperand(2) == N2
)
19195 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
, N0
.getOperand(0),
19198 // Eliminate an intermediate insert into an undef vector:
19199 // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
19200 // insert_subvector undef, X, N2
19201 if (N0
.isUndef() && N1
.getOpcode() == ISD::INSERT_SUBVECTOR
&&
19202 N1
.getOperand(0).isUndef() && isNullConstant(N1
.getOperand(2)))
19203 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
, N0
,
19204 N1
.getOperand(1), N2
);
19206 if (!isa
<ConstantSDNode
>(N2
))
19209 uint64_t InsIdx
= cast
<ConstantSDNode
>(N2
)->getZExtValue();
19211 // Push subvector bitcasts to the output, adjusting the index as we go.
19212 // insert_subvector(bitcast(v), bitcast(s), c1)
19213 // -> bitcast(insert_subvector(v, s, c2))
19214 if ((N0
.isUndef() || N0
.getOpcode() == ISD::BITCAST
) &&
19215 N1
.getOpcode() == ISD::BITCAST
) {
19216 SDValue N0Src
= peekThroughBitcasts(N0
);
19217 SDValue N1Src
= peekThroughBitcasts(N1
);
19218 EVT N0SrcSVT
= N0Src
.getValueType().getScalarType();
19219 EVT N1SrcSVT
= N1Src
.getValueType().getScalarType();
19220 if ((N0
.isUndef() || N0SrcSVT
== N1SrcSVT
) &&
19221 N0Src
.getValueType().isVector() && N1Src
.getValueType().isVector()) {
19225 MVT IdxVT
= TLI
.getVectorIdxTy(DAG
.getDataLayout());
19226 LLVMContext
&Ctx
= *DAG
.getContext();
19227 unsigned NumElts
= VT
.getVectorNumElements();
19228 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
19229 if ((EltSizeInBits
% N1SrcSVT
.getSizeInBits()) == 0) {
19230 unsigned Scale
= EltSizeInBits
/ N1SrcSVT
.getSizeInBits();
19231 NewVT
= EVT::getVectorVT(Ctx
, N1SrcSVT
, NumElts
* Scale
);
19232 NewIdx
= DAG
.getConstant(InsIdx
* Scale
, DL
, IdxVT
);
19233 } else if ((N1SrcSVT
.getSizeInBits() % EltSizeInBits
) == 0) {
19234 unsigned Scale
= N1SrcSVT
.getSizeInBits() / EltSizeInBits
;
19235 if ((NumElts
% Scale
) == 0 && (InsIdx
% Scale
) == 0) {
19236 NewVT
= EVT::getVectorVT(Ctx
, N1SrcSVT
, NumElts
/ Scale
);
19237 NewIdx
= DAG
.getConstant(InsIdx
/ Scale
, DL
, IdxVT
);
19240 if (NewIdx
&& hasOperation(ISD::INSERT_SUBVECTOR
, NewVT
)) {
19241 SDValue Res
= DAG
.getBitcast(NewVT
, N0Src
);
19242 Res
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, NewVT
, Res
, N1Src
, NewIdx
);
19243 return DAG
.getBitcast(VT
, Res
);
19248 // Canonicalize insert_subvector dag nodes.
19250 // (insert_subvector (insert_subvector A, Idx0), Idx1)
19251 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
19252 if (N0
.getOpcode() == ISD::INSERT_SUBVECTOR
&& N0
.hasOneUse() &&
19253 N1
.getValueType() == N0
.getOperand(1).getValueType() &&
19254 isa
<ConstantSDNode
>(N0
.getOperand(2))) {
19255 unsigned OtherIdx
= N0
.getConstantOperandVal(2);
19256 if (InsIdx
< OtherIdx
) {
19258 SDValue NewOp
= DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N
), VT
,
19259 N0
.getOperand(0), N1
, N2
);
19260 AddToWorklist(NewOp
.getNode());
19261 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, SDLoc(N0
.getNode()),
19262 VT
, NewOp
, N0
.getOperand(1), N0
.getOperand(2));
19266 // If the input vector is a concatenation, and the insert replaces
19267 // one of the pieces, we can optimize into a single concat_vectors.
19268 if (N0
.getOpcode() == ISD::CONCAT_VECTORS
&& N0
.hasOneUse() &&
19269 N0
.getOperand(0).getValueType() == N1
.getValueType()) {
19270 unsigned Factor
= N1
.getValueType().getVectorNumElements();
19272 SmallVector
<SDValue
, 8> Ops(N0
->op_begin(), N0
->op_end());
19273 Ops
[cast
<ConstantSDNode
>(N2
)->getZExtValue() / Factor
] = N1
;
19275 return DAG
.getNode(ISD::CONCAT_VECTORS
, SDLoc(N
), VT
, Ops
);
19278 // Simplify source operands based on insertion.
19279 if (SimplifyDemandedVectorElts(SDValue(N
, 0)))
19280 return SDValue(N
, 0);
19285 SDValue
DAGCombiner::visitFP_TO_FP16(SDNode
*N
) {
19286 SDValue N0
= N
->getOperand(0);
19288 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
19289 if (N0
->getOpcode() == ISD::FP16_TO_FP
)
19290 return N0
->getOperand(0);
19295 SDValue
DAGCombiner::visitFP16_TO_FP(SDNode
*N
) {
19296 SDValue N0
= N
->getOperand(0);
19298 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
19299 if (N0
->getOpcode() == ISD::AND
) {
19300 ConstantSDNode
*AndConst
= getAsNonOpaqueConstant(N0
.getOperand(1));
19301 if (AndConst
&& AndConst
->getAPIntValue() == 0xffff) {
19302 return DAG
.getNode(ISD::FP16_TO_FP
, SDLoc(N
), N
->getValueType(0),
19310 SDValue
DAGCombiner::visitVECREDUCE(SDNode
*N
) {
19311 SDValue N0
= N
->getOperand(0);
19312 EVT VT
= N0
.getValueType();
19313 unsigned Opcode
= N
->getOpcode();
19315 // VECREDUCE over 1-element vector is just an extract.
19316 if (VT
.getVectorNumElements() == 1) {
19318 SDValue Res
= DAG
.getNode(
19319 ISD::EXTRACT_VECTOR_ELT
, dl
, VT
.getVectorElementType(), N0
,
19320 DAG
.getConstant(0, dl
, TLI
.getVectorIdxTy(DAG
.getDataLayout())));
19321 if (Res
.getValueType() != N
->getValueType(0))
19322 Res
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, N
->getValueType(0), Res
);
19326 // On an boolean vector an and/or reduction is the same as a umin/umax
19327 // reduction. Convert them if the latter is legal while the former isn't.
19328 if (Opcode
== ISD::VECREDUCE_AND
|| Opcode
== ISD::VECREDUCE_OR
) {
19329 unsigned NewOpcode
= Opcode
== ISD::VECREDUCE_AND
19330 ? ISD::VECREDUCE_UMIN
: ISD::VECREDUCE_UMAX
;
19331 if (!TLI
.isOperationLegalOrCustom(Opcode
, VT
) &&
19332 TLI
.isOperationLegalOrCustom(NewOpcode
, VT
) &&
19333 DAG
.ComputeNumSignBits(N0
) == VT
.getScalarSizeInBits())
19334 return DAG
.getNode(NewOpcode
, SDLoc(N
), N
->getValueType(0), N0
);
19340 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
19341 /// with the destination vector and a zero vector.
19342 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
19343 /// vector_shuffle V, Zero, <0, 4, 2, 4>
19344 SDValue
DAGCombiner::XformToShuffleWithZero(SDNode
*N
) {
19345 assert(N
->getOpcode() == ISD::AND
&& "Unexpected opcode!");
19347 EVT VT
= N
->getValueType(0);
19348 SDValue LHS
= N
->getOperand(0);
19349 SDValue RHS
= peekThroughBitcasts(N
->getOperand(1));
19352 // Make sure we're not running after operation legalization where it
19353 // may have custom lowered the vector shuffles.
19354 if (LegalOperations
)
19357 if (RHS
.getOpcode() != ISD::BUILD_VECTOR
)
19360 EVT RVT
= RHS
.getValueType();
19361 unsigned NumElts
= RHS
.getNumOperands();
19363 // Attempt to create a valid clear mask, splitting the mask into
19364 // sub elements and checking to see if each is
19365 // all zeros or all ones - suitable for shuffle masking.
19366 auto BuildClearMask
= [&](int Split
) {
19367 int NumSubElts
= NumElts
* Split
;
19368 int NumSubBits
= RVT
.getScalarSizeInBits() / Split
;
19370 SmallVector
<int, 8> Indices
;
19371 for (int i
= 0; i
!= NumSubElts
; ++i
) {
19372 int EltIdx
= i
/ Split
;
19373 int SubIdx
= i
% Split
;
19374 SDValue Elt
= RHS
.getOperand(EltIdx
);
19375 if (Elt
.isUndef()) {
19376 Indices
.push_back(-1);
19381 if (isa
<ConstantSDNode
>(Elt
))
19382 Bits
= cast
<ConstantSDNode
>(Elt
)->getAPIntValue();
19383 else if (isa
<ConstantFPSDNode
>(Elt
))
19384 Bits
= cast
<ConstantFPSDNode
>(Elt
)->getValueAPF().bitcastToAPInt();
19388 // Extract the sub element from the constant bit mask.
19389 if (DAG
.getDataLayout().isBigEndian()) {
19390 Bits
.lshrInPlace((Split
- SubIdx
- 1) * NumSubBits
);
19392 Bits
.lshrInPlace(SubIdx
* NumSubBits
);
19396 Bits
= Bits
.trunc(NumSubBits
);
19398 if (Bits
.isAllOnesValue())
19399 Indices
.push_back(i
);
19400 else if (Bits
== 0)
19401 Indices
.push_back(i
+ NumSubElts
);
19406 // Let's see if the target supports this vector_shuffle.
19407 EVT ClearSVT
= EVT::getIntegerVT(*DAG
.getContext(), NumSubBits
);
19408 EVT ClearVT
= EVT::getVectorVT(*DAG
.getContext(), ClearSVT
, NumSubElts
);
19409 if (!TLI
.isVectorClearMaskLegal(Indices
, ClearVT
))
19412 SDValue Zero
= DAG
.getConstant(0, DL
, ClearVT
);
19413 return DAG
.getBitcast(VT
, DAG
.getVectorShuffle(ClearVT
, DL
,
19414 DAG
.getBitcast(ClearVT
, LHS
),
19418 // Determine maximum split level (byte level masking).
19420 if (RVT
.getScalarSizeInBits() % 8 == 0)
19421 MaxSplit
= RVT
.getScalarSizeInBits() / 8;
19423 for (int Split
= 1; Split
<= MaxSplit
; ++Split
)
19424 if (RVT
.getScalarSizeInBits() % Split
== 0)
19425 if (SDValue S
= BuildClearMask(Split
))
19431 /// If a vector binop is performed on splat values, it may be profitable to
19432 /// extract, scalarize, and insert/splat.
19433 static SDValue
scalarizeBinOpOfSplats(SDNode
*N
, SelectionDAG
&DAG
) {
19434 SDValue N0
= N
->getOperand(0);
19435 SDValue N1
= N
->getOperand(1);
19436 unsigned Opcode
= N
->getOpcode();
19437 EVT VT
= N
->getValueType(0);
19438 EVT EltVT
= VT
.getVectorElementType();
19439 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
19441 // TODO: Remove/replace the extract cost check? If the elements are available
19442 // as scalars, then there may be no extract cost. Should we ask if
19443 // inserting a scalar back into a vector is cheap instead?
19444 int Index0
, Index1
;
19445 SDValue Src0
= DAG
.getSplatSourceVector(N0
, Index0
);
19446 SDValue Src1
= DAG
.getSplatSourceVector(N1
, Index1
);
19447 if (!Src0
|| !Src1
|| Index0
!= Index1
||
19448 Src0
.getValueType().getVectorElementType() != EltVT
||
19449 Src1
.getValueType().getVectorElementType() != EltVT
||
19450 !TLI
.isExtractVecEltCheap(VT
, Index0
) ||
19451 !TLI
.isOperationLegalOrCustom(Opcode
, EltVT
))
19456 DAG
.getConstant(Index0
, DL
, TLI
.getVectorIdxTy(DAG
.getDataLayout()));
19457 SDValue X
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, N0
, IndexC
);
19458 SDValue Y
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, EltVT
, N1
, IndexC
);
19459 SDValue ScalarBO
= DAG
.getNode(Opcode
, DL
, EltVT
, X
, Y
, N
->getFlags());
19461 // If all lanes but 1 are undefined, no need to splat the scalar result.
19462 // TODO: Keep track of undefs and use that info in the general case.
19463 if (N0
.getOpcode() == ISD::BUILD_VECTOR
&& N0
.getOpcode() == N1
.getOpcode() &&
19464 count_if(N0
->ops(), [](SDValue V
) { return !V
.isUndef(); }) == 1 &&
19465 count_if(N1
->ops(), [](SDValue V
) { return !V
.isUndef(); }) == 1) {
19466 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
19467 // build_vec ..undef, (bo X, Y), undef...
19468 SmallVector
<SDValue
, 8> Ops(VT
.getVectorNumElements(), DAG
.getUNDEF(EltVT
));
19469 Ops
[Index0
] = ScalarBO
;
19470 return DAG
.getBuildVector(VT
, DL
, Ops
);
19473 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
19474 SmallVector
<SDValue
, 8> Ops(VT
.getVectorNumElements(), ScalarBO
);
19475 return DAG
.getBuildVector(VT
, DL
, Ops
);
19478 /// Visit a binary vector operation, like ADD.
19479 SDValue
DAGCombiner::SimplifyVBinOp(SDNode
*N
) {
19480 assert(N
->getValueType(0).isVector() &&
19481 "SimplifyVBinOp only works on vectors!");
19483 SDValue LHS
= N
->getOperand(0);
19484 SDValue RHS
= N
->getOperand(1);
19485 SDValue Ops
[] = {LHS
, RHS
};
19486 EVT VT
= N
->getValueType(0);
19487 unsigned Opcode
= N
->getOpcode();
19489 // See if we can constant fold the vector operation.
19490 if (SDValue Fold
= DAG
.FoldConstantVectorArithmetic(
19491 Opcode
, SDLoc(LHS
), LHS
.getValueType(), Ops
, N
->getFlags()))
19494 // Move unary shuffles with identical masks after a vector binop:
19495 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
19496 // --> shuffle (VBinOp A, B), Undef, Mask
19497 // This does not require type legality checks because we are creating the
19498 // same types of operations that are in the original sequence. We do have to
19499 // restrict ops like integer div that have immediate UB (eg, div-by-zero)
19500 // though. This code is adapted from the identical transform in instcombine.
19501 if (Opcode
!= ISD::UDIV
&& Opcode
!= ISD::SDIV
&&
19502 Opcode
!= ISD::UREM
&& Opcode
!= ISD::SREM
&&
19503 Opcode
!= ISD::UDIVREM
&& Opcode
!= ISD::SDIVREM
) {
19504 auto *Shuf0
= dyn_cast
<ShuffleVectorSDNode
>(LHS
);
19505 auto *Shuf1
= dyn_cast
<ShuffleVectorSDNode
>(RHS
);
19506 if (Shuf0
&& Shuf1
&& Shuf0
->getMask().equals(Shuf1
->getMask()) &&
19507 LHS
.getOperand(1).isUndef() && RHS
.getOperand(1).isUndef() &&
19508 (LHS
.hasOneUse() || RHS
.hasOneUse() || LHS
== RHS
)) {
19510 SDValue NewBinOp
= DAG
.getNode(Opcode
, DL
, VT
, LHS
.getOperand(0),
19511 RHS
.getOperand(0), N
->getFlags());
19512 SDValue UndefV
= LHS
.getOperand(1);
19513 return DAG
.getVectorShuffle(VT
, DL
, NewBinOp
, UndefV
, Shuf0
->getMask());
19517 // The following pattern is likely to emerge with vector reduction ops. Moving
19518 // the binary operation ahead of insertion may allow using a narrower vector
19519 // instruction that has better performance than the wide version of the op:
19520 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
19521 if (LHS
.getOpcode() == ISD::INSERT_SUBVECTOR
&& LHS
.getOperand(0).isUndef() &&
19522 RHS
.getOpcode() == ISD::INSERT_SUBVECTOR
&& RHS
.getOperand(0).isUndef() &&
19523 LHS
.getOperand(2) == RHS
.getOperand(2) &&
19524 (LHS
.hasOneUse() || RHS
.hasOneUse())) {
19525 SDValue X
= LHS
.getOperand(1);
19526 SDValue Y
= RHS
.getOperand(1);
19527 SDValue Z
= LHS
.getOperand(2);
19528 EVT NarrowVT
= X
.getValueType();
19529 if (NarrowVT
== Y
.getValueType() &&
19530 TLI
.isOperationLegalOrCustomOrPromote(Opcode
, NarrowVT
)) {
19531 // (binop undef, undef) may not return undef, so compute that result.
19534 DAG
.getNode(Opcode
, DL
, VT
, DAG
.getUNDEF(VT
), DAG
.getUNDEF(VT
));
19535 SDValue NarrowBO
= DAG
.getNode(Opcode
, DL
, NarrowVT
, X
, Y
);
19536 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, VT
, VecC
, NarrowBO
, Z
);
19540 // Make sure all but the first op are undef or constant.
19541 auto ConcatWithConstantOrUndef
= [](SDValue Concat
) {
19542 return Concat
.getOpcode() == ISD::CONCAT_VECTORS
&&
19543 std::all_of(std::next(Concat
->op_begin()), Concat
->op_end(),
19544 [](const SDValue
&Op
) {
19545 return Op
.isUndef() ||
19546 ISD::isBuildVectorOfConstantSDNodes(Op
.getNode());
19550 // The following pattern is likely to emerge with vector reduction ops. Moving
19551 // the binary operation ahead of the concat may allow using a narrower vector
19552 // instruction that has better performance than the wide version of the op:
19553 // VBinOp (concat X, undef/constant), (concat Y, undef/constant) -->
19554 // concat (VBinOp X, Y), VecC
19555 if (ConcatWithConstantOrUndef(LHS
) && ConcatWithConstantOrUndef(RHS
) &&
19556 (LHS
.hasOneUse() || RHS
.hasOneUse())) {
19557 EVT NarrowVT
= LHS
.getOperand(0).getValueType();
19558 if (NarrowVT
== RHS
.getOperand(0).getValueType() &&
19559 TLI
.isOperationLegalOrCustomOrPromote(Opcode
, NarrowVT
)) {
19561 unsigned NumOperands
= LHS
.getNumOperands();
19562 SmallVector
<SDValue
, 4> Ops
;
19563 for (unsigned i
= 0; i
!= NumOperands
; ++i
) {
19564 // This constant fold for operands 1 and up.
19565 Ops
.push_back(DAG
.getNode(Opcode
, DL
, NarrowVT
, LHS
.getOperand(i
),
19566 RHS
.getOperand(i
)));
19569 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, Ops
);
19573 if (SDValue V
= scalarizeBinOpOfSplats(N
, DAG
))
19579 SDValue
DAGCombiner::SimplifySelect(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
19581 assert(N0
.getOpcode() ==ISD::SETCC
&& "First argument must be a SetCC node!");
19583 SDValue SCC
= SimplifySelectCC(DL
, N0
.getOperand(0), N0
.getOperand(1), N1
, N2
,
19584 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
19586 // If we got a simplified select_cc node back from SimplifySelectCC, then
19587 // break it down into a new SETCC node, and a new SELECT node, and then return
19588 // the SELECT node, since we were called with a SELECT node.
19589 if (SCC
.getNode()) {
19590 // Check to see if we got a select_cc back (to turn into setcc/select).
19591 // Otherwise, just return whatever node we got back, like fabs.
19592 if (SCC
.getOpcode() == ISD::SELECT_CC
) {
19593 const SDNodeFlags Flags
= N0
.getNode()->getFlags();
19594 SDValue SETCC
= DAG
.getNode(ISD::SETCC
, SDLoc(N0
),
19596 SCC
.getOperand(0), SCC
.getOperand(1),
19597 SCC
.getOperand(4), Flags
);
19598 AddToWorklist(SETCC
.getNode());
19599 SDValue SelectNode
= DAG
.getSelect(SDLoc(SCC
), SCC
.getValueType(), SETCC
,
19600 SCC
.getOperand(2), SCC
.getOperand(3));
19601 SelectNode
->setFlags(Flags
);
19610 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
19611 /// being selected between, see if we can simplify the select. Callers of this
19612 /// should assume that TheSelect is deleted if this returns true. As such, they
19613 /// should return the appropriate thing (e.g. the node) back to the top-level of
19614 /// the DAG combiner loop to avoid it being looked at.
19615 bool DAGCombiner::SimplifySelectOps(SDNode
*TheSelect
, SDValue LHS
,
19617 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19618 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
19619 if (const ConstantFPSDNode
*NaN
= isConstOrConstSplatFP(LHS
)) {
19620 if (NaN
->isNaN() && RHS
.getOpcode() == ISD::FSQRT
) {
19621 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
19622 SDValue Sqrt
= RHS
;
19625 const ConstantFPSDNode
*Zero
= nullptr;
19627 if (TheSelect
->getOpcode() == ISD::SELECT_CC
) {
19628 CC
= cast
<CondCodeSDNode
>(TheSelect
->getOperand(4))->get();
19629 CmpLHS
= TheSelect
->getOperand(0);
19630 Zero
= isConstOrConstSplatFP(TheSelect
->getOperand(1));
19632 // SELECT or VSELECT
19633 SDValue Cmp
= TheSelect
->getOperand(0);
19634 if (Cmp
.getOpcode() == ISD::SETCC
) {
19635 CC
= cast
<CondCodeSDNode
>(Cmp
.getOperand(2))->get();
19636 CmpLHS
= Cmp
.getOperand(0);
19637 Zero
= isConstOrConstSplatFP(Cmp
.getOperand(1));
19640 if (Zero
&& Zero
->isZero() &&
19641 Sqrt
.getOperand(0) == CmpLHS
&& (CC
== ISD::SETOLT
||
19642 CC
== ISD::SETULT
|| CC
== ISD::SETLT
)) {
19643 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
19644 CombineTo(TheSelect
, Sqrt
);
19649 // Cannot simplify select with vector condition
19650 if (TheSelect
->getOperand(0).getValueType().isVector()) return false;
19652 // If this is a select from two identical things, try to pull the operation
19653 // through the select.
19654 if (LHS
.getOpcode() != RHS
.getOpcode() ||
19655 !LHS
.hasOneUse() || !RHS
.hasOneUse())
19658 // If this is a load and the token chain is identical, replace the select
19659 // of two loads with a load through a select of the address to load from.
19660 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
19661 // constants have been dropped into the constant pool.
19662 if (LHS
.getOpcode() == ISD::LOAD
) {
19663 LoadSDNode
*LLD
= cast
<LoadSDNode
>(LHS
);
19664 LoadSDNode
*RLD
= cast
<LoadSDNode
>(RHS
);
19666 // Token chains must be identical.
19667 if (LHS
.getOperand(0) != RHS
.getOperand(0) ||
19668 // Do not let this transformation reduce the number of volatile loads.
19669 LLD
->isVolatile() || RLD
->isVolatile() ||
19670 // FIXME: If either is a pre/post inc/dec load,
19671 // we'd need to split out the address adjustment.
19672 LLD
->isIndexed() || RLD
->isIndexed() ||
19673 // If this is an EXTLOAD, the VT's must match.
19674 LLD
->getMemoryVT() != RLD
->getMemoryVT() ||
19675 // If this is an EXTLOAD, the kind of extension must match.
19676 (LLD
->getExtensionType() != RLD
->getExtensionType() &&
19677 // The only exception is if one of the extensions is anyext.
19678 LLD
->getExtensionType() != ISD::EXTLOAD
&&
19679 RLD
->getExtensionType() != ISD::EXTLOAD
) ||
19680 // FIXME: this discards src value information. This is
19681 // over-conservative. It would be beneficial to be able to remember
19682 // both potential memory locations. Since we are discarding
19683 // src value info, don't do the transformation if the memory
19684 // locations are not in the default address space.
19685 LLD
->getPointerInfo().getAddrSpace() != 0 ||
19686 RLD
->getPointerInfo().getAddrSpace() != 0 ||
19687 // We can't produce a CMOV of a TargetFrameIndex since we won't
19688 // generate the address generation required.
19689 LLD
->getBasePtr().getOpcode() == ISD::TargetFrameIndex
||
19690 RLD
->getBasePtr().getOpcode() == ISD::TargetFrameIndex
||
19691 !TLI
.isOperationLegalOrCustom(TheSelect
->getOpcode(),
19692 LLD
->getBasePtr().getValueType()))
19695 // The loads must not depend on one another.
19696 if (LLD
->isPredecessorOf(RLD
) || RLD
->isPredecessorOf(LLD
))
19699 // Check that the select condition doesn't reach either load. If so,
19700 // folding this will induce a cycle into the DAG. If not, this is safe to
19701 // xform, so create a select of the addresses.
19703 SmallPtrSet
<const SDNode
*, 32> Visited
;
19704 SmallVector
<const SDNode
*, 16> Worklist
;
19706 // Always fail if LLD and RLD are not independent. TheSelect is a
19707 // predecessor to all Nodes in question so we need not search past it.
19709 Visited
.insert(TheSelect
);
19710 Worklist
.push_back(LLD
);
19711 Worklist
.push_back(RLD
);
19713 if (SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
) ||
19714 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
))
19718 if (TheSelect
->getOpcode() == ISD::SELECT
) {
19719 // We cannot do this optimization if any pair of {RLD, LLD} is a
19720 // predecessor to {RLD, LLD, CondNode}. As we've already compared the
19721 // Loads, we only need to check if CondNode is a successor to one of the
19722 // loads. We can further avoid this if there's no use of their chain
19724 SDNode
*CondNode
= TheSelect
->getOperand(0).getNode();
19725 Worklist
.push_back(CondNode
);
19727 if ((LLD
->hasAnyUseOfValue(1) &&
19728 SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
)) ||
19729 (RLD
->hasAnyUseOfValue(1) &&
19730 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
)))
19733 Addr
= DAG
.getSelect(SDLoc(TheSelect
),
19734 LLD
->getBasePtr().getValueType(),
19735 TheSelect
->getOperand(0), LLD
->getBasePtr(),
19736 RLD
->getBasePtr());
19737 } else { // Otherwise SELECT_CC
19738 // We cannot do this optimization if any pair of {RLD, LLD} is a
19739 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
19740 // the Loads, we only need to check if CondLHS/CondRHS is a successor to
19741 // one of the loads. We can further avoid this if there's no use of their
19744 SDNode
*CondLHS
= TheSelect
->getOperand(0).getNode();
19745 SDNode
*CondRHS
= TheSelect
->getOperand(1).getNode();
19746 Worklist
.push_back(CondLHS
);
19747 Worklist
.push_back(CondRHS
);
19749 if ((LLD
->hasAnyUseOfValue(1) &&
19750 SDNode::hasPredecessorHelper(LLD
, Visited
, Worklist
)) ||
19751 (RLD
->hasAnyUseOfValue(1) &&
19752 SDNode::hasPredecessorHelper(RLD
, Visited
, Worklist
)))
19755 Addr
= DAG
.getNode(ISD::SELECT_CC
, SDLoc(TheSelect
),
19756 LLD
->getBasePtr().getValueType(),
19757 TheSelect
->getOperand(0),
19758 TheSelect
->getOperand(1),
19759 LLD
->getBasePtr(), RLD
->getBasePtr(),
19760 TheSelect
->getOperand(4));
19764 // It is safe to replace the two loads if they have different alignments,
19765 // but the new load must be the minimum (most restrictive) alignment of the
19767 unsigned Alignment
= std::min(LLD
->getAlignment(), RLD
->getAlignment());
19768 MachineMemOperand::Flags MMOFlags
= LLD
->getMemOperand()->getFlags();
19769 if (!RLD
->isInvariant())
19770 MMOFlags
&= ~MachineMemOperand::MOInvariant
;
19771 if (!RLD
->isDereferenceable())
19772 MMOFlags
&= ~MachineMemOperand::MODereferenceable
;
19773 if (LLD
->getExtensionType() == ISD::NON_EXTLOAD
) {
19774 // FIXME: Discards pointer and AA info.
19775 Load
= DAG
.getLoad(TheSelect
->getValueType(0), SDLoc(TheSelect
),
19776 LLD
->getChain(), Addr
, MachinePointerInfo(), Alignment
,
19779 // FIXME: Discards pointer and AA info.
19780 Load
= DAG
.getExtLoad(
19781 LLD
->getExtensionType() == ISD::EXTLOAD
? RLD
->getExtensionType()
19782 : LLD
->getExtensionType(),
19783 SDLoc(TheSelect
), TheSelect
->getValueType(0), LLD
->getChain(), Addr
,
19784 MachinePointerInfo(), LLD
->getMemoryVT(), Alignment
, MMOFlags
);
19787 // Users of the select now use the result of the load.
19788 CombineTo(TheSelect
, Load
);
19790 // Users of the old loads now use the new load's chain. We know the
19791 // old-load value is dead now.
19792 CombineTo(LHS
.getNode(), Load
.getValue(0), Load
.getValue(1));
19793 CombineTo(RHS
.getNode(), Load
.getValue(0), Load
.getValue(1));
19800 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
19802 SDValue
DAGCombiner::foldSelectCCToShiftAnd(const SDLoc
&DL
, SDValue N0
,
19803 SDValue N1
, SDValue N2
, SDValue N3
,
19804 ISD::CondCode CC
) {
19805 // If this is a select where the false operand is zero and the compare is a
19806 // check of the sign bit, see if we can perform the "gzip trick":
19807 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
19808 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
19809 EVT XType
= N0
.getValueType();
19810 EVT AType
= N2
.getValueType();
19811 if (!isNullConstant(N3
) || !XType
.bitsGE(AType
))
19814 // If the comparison is testing for a positive value, we have to invert
19815 // the sign bit mask, so only do that transform if the target has a bitwise
19816 // 'and not' instruction (the invert is free).
19817 if (CC
== ISD::SETGT
&& TLI
.hasAndNot(N2
)) {
19818 // (X > -1) ? A : 0
19819 // (X > 0) ? X : 0 <-- This is canonical signed max.
19820 if (!(isAllOnesConstant(N1
) || (isNullConstant(N1
) && N0
== N2
)))
19822 } else if (CC
== ISD::SETLT
) {
19824 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
19825 if (!(isNullConstant(N1
) || (isOneConstant(N1
) && N0
== N2
)))
19831 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
19833 EVT ShiftAmtTy
= getShiftAmountTy(N0
.getValueType());
19834 auto *N2C
= dyn_cast
<ConstantSDNode
>(N2
.getNode());
19835 if (N2C
&& ((N2C
->getAPIntValue() & (N2C
->getAPIntValue() - 1)) == 0)) {
19836 unsigned ShCt
= XType
.getSizeInBits() - N2C
->getAPIntValue().logBase2() - 1;
19837 SDValue ShiftAmt
= DAG
.getConstant(ShCt
, DL
, ShiftAmtTy
);
19838 SDValue Shift
= DAG
.getNode(ISD::SRL
, DL
, XType
, N0
, ShiftAmt
);
19839 AddToWorklist(Shift
.getNode());
19841 if (XType
.bitsGT(AType
)) {
19842 Shift
= DAG
.getNode(ISD::TRUNCATE
, DL
, AType
, Shift
);
19843 AddToWorklist(Shift
.getNode());
19846 if (CC
== ISD::SETGT
)
19847 Shift
= DAG
.getNOT(DL
, Shift
, AType
);
19849 return DAG
.getNode(ISD::AND
, DL
, AType
, Shift
, N2
);
19852 SDValue ShiftAmt
= DAG
.getConstant(XType
.getSizeInBits() - 1, DL
, ShiftAmtTy
);
19853 SDValue Shift
= DAG
.getNode(ISD::SRA
, DL
, XType
, N0
, ShiftAmt
);
19854 AddToWorklist(Shift
.getNode());
19856 if (XType
.bitsGT(AType
)) {
19857 Shift
= DAG
.getNode(ISD::TRUNCATE
, DL
, AType
, Shift
);
19858 AddToWorklist(Shift
.getNode());
19861 if (CC
== ISD::SETGT
)
19862 Shift
= DAG
.getNOT(DL
, Shift
, AType
);
19864 return DAG
.getNode(ISD::AND
, DL
, AType
, Shift
, N2
);
19867 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
19868 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
19869 /// in it. This may be a win when the constant is not otherwise available
19870 /// because it replaces two constant pool loads with one.
19871 SDValue
DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
19872 const SDLoc
&DL
, SDValue N0
, SDValue N1
, SDValue N2
, SDValue N3
,
19873 ISD::CondCode CC
) {
19874 if (!TLI
.reduceSelectOfFPConstantLoads(N0
.getValueType().isFloatingPoint()))
19877 // If we are before legalize types, we want the other legalization to happen
19878 // first (for example, to avoid messing with soft float).
19879 auto *TV
= dyn_cast
<ConstantFPSDNode
>(N2
);
19880 auto *FV
= dyn_cast
<ConstantFPSDNode
>(N3
);
19881 EVT VT
= N2
.getValueType();
19882 if (!TV
|| !FV
|| !TLI
.isTypeLegal(VT
))
19885 // If a constant can be materialized without loads, this does not make sense.
19886 if (TLI
.getOperationAction(ISD::ConstantFP
, VT
) == TargetLowering::Legal
||
19887 TLI
.isFPImmLegal(TV
->getValueAPF(), TV
->getValueType(0), ForCodeSize
) ||
19888 TLI
.isFPImmLegal(FV
->getValueAPF(), FV
->getValueType(0), ForCodeSize
))
19891 // If both constants have multiple uses, then we won't need to do an extra
19892 // load. The values are likely around in registers for other users.
19893 if (!TV
->hasOneUse() && !FV
->hasOneUse())
19896 Constant
*Elts
[] = { const_cast<ConstantFP
*>(FV
->getConstantFPValue()),
19897 const_cast<ConstantFP
*>(TV
->getConstantFPValue()) };
19898 Type
*FPTy
= Elts
[0]->getType();
19899 const DataLayout
&TD
= DAG
.getDataLayout();
19901 // Create a ConstantArray of the two constants.
19902 Constant
*CA
= ConstantArray::get(ArrayType::get(FPTy
, 2), Elts
);
19903 SDValue CPIdx
= DAG
.getConstantPool(CA
, TLI
.getPointerTy(DAG
.getDataLayout()),
19904 TD
.getPrefTypeAlignment(FPTy
));
19905 unsigned Alignment
= cast
<ConstantPoolSDNode
>(CPIdx
)->getAlignment();
19907 // Get offsets to the 0 and 1 elements of the array, so we can select between
19909 SDValue Zero
= DAG
.getIntPtrConstant(0, DL
);
19910 unsigned EltSize
= (unsigned)TD
.getTypeAllocSize(Elts
[0]->getType());
19911 SDValue One
= DAG
.getIntPtrConstant(EltSize
, SDLoc(FV
));
19913 DAG
.getSetCC(DL
, getSetCCResultType(N0
.getValueType()), N0
, N1
, CC
);
19914 AddToWorklist(Cond
.getNode());
19915 SDValue CstOffset
= DAG
.getSelect(DL
, Zero
.getValueType(), Cond
, One
, Zero
);
19916 AddToWorklist(CstOffset
.getNode());
19917 CPIdx
= DAG
.getNode(ISD::ADD
, DL
, CPIdx
.getValueType(), CPIdx
, CstOffset
);
19918 AddToWorklist(CPIdx
.getNode());
19919 return DAG
.getLoad(TV
->getValueType(0), DL
, DAG
.getEntryNode(), CPIdx
,
19920 MachinePointerInfo::getConstantPool(
19921 DAG
.getMachineFunction()), Alignment
);
19924 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
19925 /// where 'cond' is the comparison specified by CC.
19926 SDValue
DAGCombiner::SimplifySelectCC(const SDLoc
&DL
, SDValue N0
, SDValue N1
,
19927 SDValue N2
, SDValue N3
, ISD::CondCode CC
,
19928 bool NotExtCompare
) {
19929 // (x ? y : y) -> y.
19930 if (N2
== N3
) return N2
;
19932 EVT CmpOpVT
= N0
.getValueType();
19933 EVT CmpResVT
= getSetCCResultType(CmpOpVT
);
19934 EVT VT
= N2
.getValueType();
19935 auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode());
19936 auto *N2C
= dyn_cast
<ConstantSDNode
>(N2
.getNode());
19937 auto *N3C
= dyn_cast
<ConstantSDNode
>(N3
.getNode());
19939 // Determine if the condition we're dealing with is constant.
19940 if (SDValue SCC
= DAG
.FoldSetCC(CmpResVT
, N0
, N1
, CC
, DL
)) {
19941 AddToWorklist(SCC
.getNode());
19942 if (auto *SCCC
= dyn_cast
<ConstantSDNode
>(SCC
)) {
19943 // fold select_cc true, x, y -> x
19944 // fold select_cc false, x, y -> y
19945 return !(SCCC
->isNullValue()) ? N2
: N3
;
19950 convertSelectOfFPConstantsToLoadOffset(DL
, N0
, N1
, N2
, N3
, CC
))
19953 if (SDValue V
= foldSelectCCToShiftAnd(DL
, N0
, N1
, N2
, N3
, CC
))
19956 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
19957 // where y is has a single bit set.
19958 // A plaintext description would be, we can turn the SELECT_CC into an AND
19959 // when the condition can be materialized as an all-ones register. Any
19960 // single bit-test can be materialized as an all-ones register with
19961 // shift-left and shift-right-arith.
19962 if (CC
== ISD::SETEQ
&& N0
->getOpcode() == ISD::AND
&&
19963 N0
->getValueType(0) == VT
&& isNullConstant(N1
) && isNullConstant(N2
)) {
19964 SDValue AndLHS
= N0
->getOperand(0);
19965 auto *ConstAndRHS
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1));
19966 if (ConstAndRHS
&& ConstAndRHS
->getAPIntValue().countPopulation() == 1) {
19967 // Shift the tested bit over the sign bit.
19968 const APInt
&AndMask
= ConstAndRHS
->getAPIntValue();
19970 DAG
.getConstant(AndMask
.countLeadingZeros(), SDLoc(AndLHS
),
19971 getShiftAmountTy(AndLHS
.getValueType()));
19972 SDValue Shl
= DAG
.getNode(ISD::SHL
, SDLoc(N0
), VT
, AndLHS
, ShlAmt
);
19974 // Now arithmetic right shift it all the way over, so the result is either
19975 // all-ones, or zero.
19977 DAG
.getConstant(AndMask
.getBitWidth() - 1, SDLoc(Shl
),
19978 getShiftAmountTy(Shl
.getValueType()));
19979 SDValue Shr
= DAG
.getNode(ISD::SRA
, SDLoc(N0
), VT
, Shl
, ShrAmt
);
19981 return DAG
.getNode(ISD::AND
, DL
, VT
, Shr
, N3
);
19985 // fold select C, 16, 0 -> shl C, 4
19986 bool Fold
= N2C
&& isNullConstant(N3
) && N2C
->getAPIntValue().isPowerOf2();
19987 bool Swap
= N3C
&& isNullConstant(N2
) && N3C
->getAPIntValue().isPowerOf2();
19989 if ((Fold
|| Swap
) &&
19990 TLI
.getBooleanContents(CmpOpVT
) ==
19991 TargetLowering::ZeroOrOneBooleanContent
&&
19992 (!LegalOperations
|| TLI
.isOperationLegal(ISD::SETCC
, CmpOpVT
))) {
19995 CC
= ISD::getSetCCInverse(CC
, CmpOpVT
.isInteger());
19996 std::swap(N2C
, N3C
);
19999 // If the caller doesn't want us to simplify this into a zext of a compare,
20001 if (NotExtCompare
&& N2C
->isOne())
20005 // zext (setcc n0, n1)
20007 SCC
= DAG
.getSetCC(DL
, CmpResVT
, N0
, N1
, CC
);
20008 if (VT
.bitsLT(SCC
.getValueType()))
20009 Temp
= DAG
.getZeroExtendInReg(SCC
, SDLoc(N2
), VT
);
20011 Temp
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N2
), VT
, SCC
);
20013 SCC
= DAG
.getSetCC(SDLoc(N0
), MVT::i1
, N0
, N1
, CC
);
20014 Temp
= DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N2
), VT
, SCC
);
20017 AddToWorklist(SCC
.getNode());
20018 AddToWorklist(Temp
.getNode());
20023 // shl setcc result by log2 n2c
20024 return DAG
.getNode(ISD::SHL
, DL
, N2
.getValueType(), Temp
,
20025 DAG
.getConstant(N2C
->getAPIntValue().logBase2(),
20027 getShiftAmountTy(Temp
.getValueType())));
20030 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
20031 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
20032 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
20033 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
20034 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
20035 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
20036 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
20037 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
20038 if (N1C
&& N1C
->isNullValue() && (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
20039 SDValue ValueOnZero
= N2
;
20040 SDValue Count
= N3
;
20041 // If the condition is NE instead of E, swap the operands.
20042 if (CC
== ISD::SETNE
)
20043 std::swap(ValueOnZero
, Count
);
20044 // Check if the value on zero is a constant equal to the bits in the type.
20045 if (auto *ValueOnZeroC
= dyn_cast
<ConstantSDNode
>(ValueOnZero
)) {
20046 if (ValueOnZeroC
->getAPIntValue() == VT
.getSizeInBits()) {
20047 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
20048 // legal, combine to just cttz.
20049 if ((Count
.getOpcode() == ISD::CTTZ
||
20050 Count
.getOpcode() == ISD::CTTZ_ZERO_UNDEF
) &&
20051 N0
== Count
.getOperand(0) &&
20052 (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTTZ
, VT
)))
20053 return DAG
.getNode(ISD::CTTZ
, DL
, VT
, N0
);
20054 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
20055 // legal, combine to just ctlz.
20056 if ((Count
.getOpcode() == ISD::CTLZ
||
20057 Count
.getOpcode() == ISD::CTLZ_ZERO_UNDEF
) &&
20058 N0
== Count
.getOperand(0) &&
20059 (!LegalOperations
|| TLI
.isOperationLegal(ISD::CTLZ
, VT
)))
20060 return DAG
.getNode(ISD::CTLZ
, DL
, VT
, N0
);
20068 /// This is a stub for TargetLowering::SimplifySetCC.
20069 SDValue
DAGCombiner::SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
,
20070 ISD::CondCode Cond
, const SDLoc
&DL
,
20071 bool foldBooleans
) {
20072 TargetLowering::DAGCombinerInfo
20073 DagCombineInfo(DAG
, Level
, false, this);
20074 return TLI
.SimplifySetCC(VT
, N0
, N1
, Cond
, foldBooleans
, DagCombineInfo
, DL
);
20077 /// Given an ISD::SDIV node expressing a divide by constant, return
20078 /// a DAG expression to select that will generate the same value by multiplying
20079 /// by a magic number.
20080 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
20081 SDValue
DAGCombiner::BuildSDIV(SDNode
*N
) {
20082 // when optimising for minimum size, we don't want to expand a div to a mul
20084 if (DAG
.getMachineFunction().getFunction().hasMinSize())
20087 SmallVector
<SDNode
*, 8> Built
;
20088 if (SDValue S
= TLI
.BuildSDIV(N
, DAG
, LegalOperations
, Built
)) {
20089 for (SDNode
*N
: Built
)
20097 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
20098 /// DAG expression that will generate the same value by right shifting.
20099 SDValue
DAGCombiner::BuildSDIVPow2(SDNode
*N
) {
20100 ConstantSDNode
*C
= isConstOrConstSplat(N
->getOperand(1));
20104 // Avoid division by zero.
20105 if (C
->isNullValue())
20108 SmallVector
<SDNode
*, 8> Built
;
20109 if (SDValue S
= TLI
.BuildSDIVPow2(N
, C
->getAPIntValue(), DAG
, Built
)) {
20110 for (SDNode
*N
: Built
)
20118 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
20119 /// expression that will generate the same value by multiplying by a magic
20121 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
20122 SDValue
DAGCombiner::BuildUDIV(SDNode
*N
) {
20123 // when optimising for minimum size, we don't want to expand a div to a mul
20125 if (DAG
.getMachineFunction().getFunction().hasMinSize())
20128 SmallVector
<SDNode
*, 8> Built
;
20129 if (SDValue S
= TLI
.BuildUDIV(N
, DAG
, LegalOperations
, Built
)) {
20130 for (SDNode
*N
: Built
)
20138 /// Determines the LogBase2 value for a non-null input value using the
20139 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
20140 SDValue
DAGCombiner::BuildLogBase2(SDValue V
, const SDLoc
&DL
) {
20141 EVT VT
= V
.getValueType();
20142 unsigned EltBits
= VT
.getScalarSizeInBits();
20143 SDValue Ctlz
= DAG
.getNode(ISD::CTLZ
, DL
, VT
, V
);
20144 SDValue Base
= DAG
.getConstant(EltBits
- 1, DL
, VT
);
20145 SDValue LogBase2
= DAG
.getNode(ISD::SUB
, DL
, VT
, Base
, Ctlz
);
20149 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20150 /// For the reciprocal, we need to find the zero of the function:
20151 /// F(X) = A X - 1 [which has a zero at X = 1/A]
20153 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
20154 /// does not require additional intermediate precision]
20155 SDValue
DAGCombiner::BuildReciprocalEstimate(SDValue Op
, SDNodeFlags Flags
) {
20156 if (Level
>= AfterLegalizeDAG
)
20159 // TODO: Handle half and/or extended types?
20160 EVT VT
= Op
.getValueType();
20161 if (VT
.getScalarType() != MVT::f32
&& VT
.getScalarType() != MVT::f64
)
20164 // If estimates are explicitly disabled for this function, we're done.
20165 MachineFunction
&MF
= DAG
.getMachineFunction();
20166 int Enabled
= TLI
.getRecipEstimateDivEnabled(VT
, MF
);
20167 if (Enabled
== TLI
.ReciprocalEstimate::Disabled
)
20170 // Estimates may be explicitly enabled for this type with a custom number of
20171 // refinement steps.
20172 int Iterations
= TLI
.getDivRefinementSteps(VT
, MF
);
20173 if (SDValue Est
= TLI
.getRecipEstimate(Op
, DAG
, Enabled
, Iterations
)) {
20174 AddToWorklist(Est
.getNode());
20178 SDValue FPOne
= DAG
.getConstantFP(1.0, DL
, VT
);
20180 // Newton iterations: Est = Est + Est (1 - Arg * Est)
20181 for (int i
= 0; i
< Iterations
; ++i
) {
20182 SDValue NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Op
, Est
, Flags
);
20183 NewEst
= DAG
.getNode(ISD::FSUB
, DL
, VT
, FPOne
, NewEst
, Flags
);
20184 NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, NewEst
, Flags
);
20185 Est
= DAG
.getNode(ISD::FADD
, DL
, VT
, Est
, NewEst
, Flags
);
20194 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20195 /// For the reciprocal sqrt, we need to find the zero of the function:
20196 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20198 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
20199 /// As a result, we precompute A/2 prior to the iteration loop.
20200 SDValue
DAGCombiner::buildSqrtNROneConst(SDValue Arg
, SDValue Est
,
20201 unsigned Iterations
,
20202 SDNodeFlags Flags
, bool Reciprocal
) {
20203 EVT VT
= Arg
.getValueType();
20205 SDValue ThreeHalves
= DAG
.getConstantFP(1.5, DL
, VT
);
20207 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
20208 // this entire sequence requires only one FP constant.
20209 SDValue HalfArg
= DAG
.getNode(ISD::FMUL
, DL
, VT
, ThreeHalves
, Arg
, Flags
);
20210 HalfArg
= DAG
.getNode(ISD::FSUB
, DL
, VT
, HalfArg
, Arg
, Flags
);
20212 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
20213 for (unsigned i
= 0; i
< Iterations
; ++i
) {
20214 SDValue NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, Est
, Flags
);
20215 NewEst
= DAG
.getNode(ISD::FMUL
, DL
, VT
, HalfArg
, NewEst
, Flags
);
20216 NewEst
= DAG
.getNode(ISD::FSUB
, DL
, VT
, ThreeHalves
, NewEst
, Flags
);
20217 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, NewEst
, Flags
);
20220 // If non-reciprocal square root is requested, multiply the result by Arg.
20222 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, Arg
, Flags
);
20227 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
20228 /// For the reciprocal sqrt, we need to find the zero of the function:
20229 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
20231 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
20232 SDValue
DAGCombiner::buildSqrtNRTwoConst(SDValue Arg
, SDValue Est
,
20233 unsigned Iterations
,
20234 SDNodeFlags Flags
, bool Reciprocal
) {
20235 EVT VT
= Arg
.getValueType();
20237 SDValue MinusThree
= DAG
.getConstantFP(-3.0, DL
, VT
);
20238 SDValue MinusHalf
= DAG
.getConstantFP(-0.5, DL
, VT
);
20240 // This routine must enter the loop below to work correctly
20241 // when (Reciprocal == false).
20242 assert(Iterations
> 0);
20244 // Newton iterations for reciprocal square root:
20245 // E = (E * -0.5) * ((A * E) * E + -3.0)
20246 for (unsigned i
= 0; i
< Iterations
; ++i
) {
20247 SDValue AE
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Arg
, Est
, Flags
);
20248 SDValue AEE
= DAG
.getNode(ISD::FMUL
, DL
, VT
, AE
, Est
, Flags
);
20249 SDValue RHS
= DAG
.getNode(ISD::FADD
, DL
, VT
, AEE
, MinusThree
, Flags
);
20251 // When calculating a square root at the last iteration build:
20252 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
20253 // (notice a common subexpression)
20255 if (Reciprocal
|| (i
+ 1) < Iterations
) {
20256 // RSQRT: LHS = (E * -0.5)
20257 LHS
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Est
, MinusHalf
, Flags
);
20259 // SQRT: LHS = (A * E) * -0.5
20260 LHS
= DAG
.getNode(ISD::FMUL
, DL
, VT
, AE
, MinusHalf
, Flags
);
20263 Est
= DAG
.getNode(ISD::FMUL
, DL
, VT
, LHS
, RHS
, Flags
);
20269 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
20270 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
20271 /// Op can be zero.
20272 SDValue
DAGCombiner::buildSqrtEstimateImpl(SDValue Op
, SDNodeFlags Flags
,
20274 if (Level
>= AfterLegalizeDAG
)
20277 // TODO: Handle half and/or extended types?
20278 EVT VT
= Op
.getValueType();
20279 if (VT
.getScalarType() != MVT::f32
&& VT
.getScalarType() != MVT::f64
)
20282 // If estimates are explicitly disabled for this function, we're done.
20283 MachineFunction
&MF
= DAG
.getMachineFunction();
20284 int Enabled
= TLI
.getRecipEstimateSqrtEnabled(VT
, MF
);
20285 if (Enabled
== TLI
.ReciprocalEstimate::Disabled
)
20288 // Estimates may be explicitly enabled for this type with a custom number of
20289 // refinement steps.
20290 int Iterations
= TLI
.getSqrtRefinementSteps(VT
, MF
);
20292 bool UseOneConstNR
= false;
20294 TLI
.getSqrtEstimate(Op
, DAG
, Enabled
, Iterations
, UseOneConstNR
,
20296 AddToWorklist(Est
.getNode());
20299 Est
= UseOneConstNR
20300 ? buildSqrtNROneConst(Op
, Est
, Iterations
, Flags
, Reciprocal
)
20301 : buildSqrtNRTwoConst(Op
, Est
, Iterations
, Flags
, Reciprocal
);
20304 // The estimate is now completely wrong if the input was exactly 0.0 or
20305 // possibly a denormal. Force the answer to 0.0 for those cases.
20307 EVT CCVT
= getSetCCResultType(VT
);
20308 ISD::NodeType SelOpcode
= VT
.isVector() ? ISD::VSELECT
: ISD::SELECT
;
20309 const Function
&F
= DAG
.getMachineFunction().getFunction();
20310 Attribute Denorms
= F
.getFnAttribute("denormal-fp-math");
20311 if (Denorms
.getValueAsString().equals("ieee")) {
20312 // fabs(X) < SmallestNormal ? 0.0 : Est
20313 const fltSemantics
&FltSem
= DAG
.EVTToAPFloatSemantics(VT
);
20314 APFloat SmallestNorm
= APFloat::getSmallestNormalized(FltSem
);
20315 SDValue NormC
= DAG
.getConstantFP(SmallestNorm
, DL
, VT
);
20316 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
20317 SDValue Fabs
= DAG
.getNode(ISD::FABS
, DL
, VT
, Op
);
20318 SDValue IsDenorm
= DAG
.getSetCC(DL
, CCVT
, Fabs
, NormC
, ISD::SETLT
);
20319 Est
= DAG
.getNode(SelOpcode
, DL
, VT
, IsDenorm
, FPZero
, Est
);
20321 // X == 0.0 ? 0.0 : Est
20322 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
20323 SDValue IsZero
= DAG
.getSetCC(DL
, CCVT
, Op
, FPZero
, ISD::SETEQ
);
20324 Est
= DAG
.getNode(SelOpcode
, DL
, VT
, IsZero
, FPZero
, Est
);
20334 SDValue
DAGCombiner::buildRsqrtEstimate(SDValue Op
, SDNodeFlags Flags
) {
20335 return buildSqrtEstimateImpl(Op
, Flags
, true);
20338 SDValue
DAGCombiner::buildSqrtEstimate(SDValue Op
, SDNodeFlags Flags
) {
20339 return buildSqrtEstimateImpl(Op
, Flags
, false);
20342 /// Return true if there is any possibility that the two addresses overlap.
20343 bool DAGCombiner::isAlias(SDNode
*Op0
, SDNode
*Op1
) const {
20345 struct MemUseCharacteristics
{
20349 Optional
<int64_t> NumBytes
;
20350 MachineMemOperand
*MMO
;
20353 auto getCharacteristics
= [](SDNode
*N
) -> MemUseCharacteristics
{
20354 if (const auto *LSN
= dyn_cast
<LSBaseSDNode
>(N
)) {
20355 int64_t Offset
= 0;
20356 if (auto *C
= dyn_cast
<ConstantSDNode
>(LSN
->getOffset()))
20357 Offset
= (LSN
->getAddressingMode() == ISD::PRE_INC
)
20358 ? C
->getSExtValue()
20359 : (LSN
->getAddressingMode() == ISD::PRE_DEC
)
20360 ? -1 * C
->getSExtValue()
20362 return {LSN
->isVolatile(), LSN
->getBasePtr(), Offset
/*base offset*/,
20363 Optional
<int64_t>(LSN
->getMemoryVT().getStoreSize()),
20364 LSN
->getMemOperand()};
20366 if (const auto *LN
= cast
<LifetimeSDNode
>(N
))
20367 return {false /*isVolatile*/, LN
->getOperand(1),
20368 (LN
->hasOffset()) ? LN
->getOffset() : 0,
20369 (LN
->hasOffset()) ? Optional
<int64_t>(LN
->getSize())
20370 : Optional
<int64_t>(),
20371 (MachineMemOperand
*)nullptr};
20373 return {false /*isvolatile*/, SDValue(), (int64_t)0 /*offset*/,
20374 Optional
<int64_t>() /*size*/, (MachineMemOperand
*)nullptr};
20377 MemUseCharacteristics MUC0
= getCharacteristics(Op0
),
20378 MUC1
= getCharacteristics(Op1
);
20380 // If they are to the same address, then they must be aliases.
20381 if (MUC0
.BasePtr
.getNode() && MUC0
.BasePtr
== MUC1
.BasePtr
&&
20382 MUC0
.Offset
== MUC1
.Offset
)
20385 // If they are both volatile then they cannot be reordered.
20386 if (MUC0
.IsVolatile
&& MUC1
.IsVolatile
)
20389 if (MUC0
.MMO
&& MUC1
.MMO
) {
20390 if ((MUC0
.MMO
->isInvariant() && MUC1
.MMO
->isStore()) ||
20391 (MUC1
.MMO
->isInvariant() && MUC0
.MMO
->isStore()))
20395 // Try to prove that there is aliasing, or that there is no aliasing. Either
20396 // way, we can return now. If nothing can be proved, proceed with more tests.
20398 if (BaseIndexOffset::computeAliasing(Op0
, MUC0
.NumBytes
, Op1
, MUC1
.NumBytes
,
20402 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
20403 // either are not known.
20404 if (!MUC0
.MMO
|| !MUC1
.MMO
)
20407 // If one operation reads from invariant memory, and the other may store, they
20408 // cannot alias. These should really be checking the equivalent of mayWrite,
20409 // but it only matters for memory nodes other than load /store.
20410 if ((MUC0
.MMO
->isInvariant() && MUC1
.MMO
->isStore()) ||
20411 (MUC1
.MMO
->isInvariant() && MUC0
.MMO
->isStore()))
20414 // If we know required SrcValue1 and SrcValue2 have relatively large
20415 // alignment compared to the size and offset of the access, we may be able
20416 // to prove they do not alias. This check is conservative for now to catch
20417 // cases created by splitting vector types.
20418 int64_t SrcValOffset0
= MUC0
.MMO
->getOffset();
20419 int64_t SrcValOffset1
= MUC1
.MMO
->getOffset();
20420 unsigned OrigAlignment0
= MUC0
.MMO
->getBaseAlignment();
20421 unsigned OrigAlignment1
= MUC1
.MMO
->getBaseAlignment();
20422 if (OrigAlignment0
== OrigAlignment1
&& SrcValOffset0
!= SrcValOffset1
&&
20423 MUC0
.NumBytes
.hasValue() && MUC1
.NumBytes
.hasValue() &&
20424 *MUC0
.NumBytes
== *MUC1
.NumBytes
&& OrigAlignment0
> *MUC0
.NumBytes
) {
20425 int64_t OffAlign0
= SrcValOffset0
% OrigAlignment0
;
20426 int64_t OffAlign1
= SrcValOffset1
% OrigAlignment1
;
20428 // There is no overlap between these relatively aligned accesses of
20429 // similar size. Return no alias.
20430 if ((OffAlign0
+ *MUC0
.NumBytes
) <= OffAlign1
||
20431 (OffAlign1
+ *MUC1
.NumBytes
) <= OffAlign0
)
20435 bool UseAA
= CombinerGlobalAA
.getNumOccurrences() > 0
20437 : DAG
.getSubtarget().useAA();
20439 if (CombinerAAOnlyFunc
.getNumOccurrences() &&
20440 CombinerAAOnlyFunc
!= DAG
.getMachineFunction().getName())
20444 if (UseAA
&& AA
&& MUC0
.MMO
->getValue() && MUC1
.MMO
->getValue()) {
20445 // Use alias analysis information.
20446 int64_t MinOffset
= std::min(SrcValOffset0
, SrcValOffset1
);
20447 int64_t Overlap0
= *MUC0
.NumBytes
+ SrcValOffset0
- MinOffset
;
20448 int64_t Overlap1
= *MUC1
.NumBytes
+ SrcValOffset1
- MinOffset
;
20449 AliasResult AAResult
= AA
->alias(
20450 MemoryLocation(MUC0
.MMO
->getValue(), Overlap0
,
20451 UseTBAA
? MUC0
.MMO
->getAAInfo() : AAMDNodes()),
20452 MemoryLocation(MUC1
.MMO
->getValue(), Overlap1
,
20453 UseTBAA
? MUC1
.MMO
->getAAInfo() : AAMDNodes()));
20454 if (AAResult
== NoAlias
)
20458 // Otherwise we have to assume they alias.
20462 /// Walk up chain skipping non-aliasing memory nodes,
20463 /// looking for aliasing nodes and adding them to the Aliases vector.
20464 void DAGCombiner::GatherAllAliases(SDNode
*N
, SDValue OriginalChain
,
20465 SmallVectorImpl
<SDValue
> &Aliases
) {
20466 SmallVector
<SDValue
, 8> Chains
; // List of chains to visit.
20467 SmallPtrSet
<SDNode
*, 16> Visited
; // Visited node set.
20469 // Get alias information for node.
20470 const bool IsLoad
= isa
<LoadSDNode
>(N
) && !cast
<LoadSDNode
>(N
)->isVolatile();
20473 Chains
.push_back(OriginalChain
);
20474 unsigned Depth
= 0;
20476 // Attempt to improve chain by a single step
20477 std::function
<bool(SDValue
&)> ImproveChain
= [&](SDValue
&C
) -> bool {
20478 switch (C
.getOpcode()) {
20479 case ISD::EntryToken
:
20480 // No need to mark EntryToken.
20485 // Get alias information for C.
20486 bool IsOpLoad
= isa
<LoadSDNode
>(C
.getNode()) &&
20487 !cast
<LSBaseSDNode
>(C
.getNode())->isVolatile();
20488 if ((IsLoad
&& IsOpLoad
) || !isAlias(N
, C
.getNode())) {
20489 // Look further up the chain.
20490 C
= C
.getOperand(0);
20493 // Alias, so stop here.
20497 case ISD::CopyFromReg
:
20498 // Always forward past past CopyFromReg.
20499 C
= C
.getOperand(0);
20502 case ISD::LIFETIME_START
:
20503 case ISD::LIFETIME_END
: {
20504 // We can forward past any lifetime start/end that can be proven not to
20505 // alias the memory access.
20506 if (!isAlias(N
, C
.getNode())) {
20507 // Look further up the chain.
20508 C
= C
.getOperand(0);
20518 // Look at each chain and determine if it is an alias. If so, add it to the
20519 // aliases list. If not, then continue up the chain looking for the next
20521 while (!Chains
.empty()) {
20522 SDValue Chain
= Chains
.pop_back_val();
20524 // Don't bother if we've seen Chain before.
20525 if (!Visited
.insert(Chain
.getNode()).second
)
20528 // For TokenFactor nodes, look at each operand and only continue up the
20529 // chain until we reach the depth limit.
20531 // FIXME: The depth check could be made to return the last non-aliasing
20532 // chain we found before we hit a tokenfactor rather than the original
20534 if (Depth
> TLI
.getGatherAllAliasesMaxDepth()) {
20536 Aliases
.push_back(OriginalChain
);
20540 if (Chain
.getOpcode() == ISD::TokenFactor
) {
20541 // We have to check each of the operands of the token factor for "small"
20542 // token factors, so we queue them up. Adding the operands to the queue
20543 // (stack) in reverse order maintains the original order and increases the
20544 // likelihood that getNode will find a matching token factor (CSE.)
20545 if (Chain
.getNumOperands() > 16) {
20546 Aliases
.push_back(Chain
);
20549 for (unsigned n
= Chain
.getNumOperands(); n
;)
20550 Chains
.push_back(Chain
.getOperand(--n
));
20555 if (ImproveChain(Chain
)) {
20556 // Updated Chain Found, Consider new chain if one exists.
20557 if (Chain
.getNode())
20558 Chains
.push_back(Chain
);
20562 // No Improved Chain Possible, treat as Alias.
20563 Aliases
.push_back(Chain
);
20567 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
20568 /// (aliasing node.)
20569 SDValue
DAGCombiner::FindBetterChain(SDNode
*N
, SDValue OldChain
) {
20570 if (OptLevel
== CodeGenOpt::None
)
20573 // Ops for replacing token factor.
20574 SmallVector
<SDValue
, 8> Aliases
;
20576 // Accumulate all the aliases to this node.
20577 GatherAllAliases(N
, OldChain
, Aliases
);
20579 // If no operands then chain to entry token.
20580 if (Aliases
.size() == 0)
20581 return DAG
.getEntryNode();
20583 // If a single operand then chain to it. We don't need to revisit it.
20584 if (Aliases
.size() == 1)
20587 // Construct a custom tailored token factor.
20588 return DAG
.getTokenFactor(SDLoc(N
), Aliases
);
20592 // TODO: Replace with with std::monostate when we move to C++17.
20593 struct UnitT
{ } Unit
;
20594 bool operator==(const UnitT
&, const UnitT
&) { return true; }
20595 bool operator!=(const UnitT
&, const UnitT
&) { return false; }
20598 // This function tries to collect a bunch of potentially interesting
20599 // nodes to improve the chains of, all at once. This might seem
20600 // redundant, as this function gets called when visiting every store
20601 // node, so why not let the work be done on each store as it's visited?
20603 // I believe this is mainly important because MergeConsecutiveStores
20604 // is unable to deal with merging stores of different sizes, so unless
20605 // we improve the chains of all the potential candidates up-front
20606 // before running MergeConsecutiveStores, it might only see some of
20607 // the nodes that will eventually be candidates, and then not be able
20608 // to go from a partially-merged state to the desired final
20609 // fully-merged state.
20611 bool DAGCombiner::parallelizeChainedStores(StoreSDNode
*St
) {
20612 SmallVector
<StoreSDNode
*, 8> ChainedStores
;
20613 StoreSDNode
*STChain
= St
;
20614 // Intervals records which offsets from BaseIndex have been covered. In
20615 // the common case, every store writes to the immediately previous address
20616 // space and thus merged with the previous interval at insertion time.
20619 llvm::IntervalMap
<int64_t, UnitT
, 8, IntervalMapHalfOpenInfo
<int64_t>>;
20623 // This holds the base pointer, index, and the offset in bytes from the base
20625 const BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
20627 // We must have a base and an offset.
20628 if (!BasePtr
.getBase().getNode())
20631 // Do not handle stores to undef base pointers.
20632 if (BasePtr
.getBase().isUndef())
20635 // Add ST's interval.
20636 Intervals
.insert(0, (St
->getMemoryVT().getSizeInBits() + 7) / 8, Unit
);
20638 while (StoreSDNode
*Chain
= dyn_cast
<StoreSDNode
>(STChain
->getChain())) {
20639 // If the chain has more than one use, then we can't reorder the mem ops.
20640 if (!SDValue(Chain
, 0)->hasOneUse())
20642 if (Chain
->isVolatile() || Chain
->isIndexed())
20645 // Find the base pointer and offset for this memory node.
20646 const BaseIndexOffset Ptr
= BaseIndexOffset::match(Chain
, DAG
);
20647 // Check that the base pointer is the same as the original one.
20649 if (!BasePtr
.equalBaseIndex(Ptr
, DAG
, Offset
))
20651 int64_t Length
= (Chain
->getMemoryVT().getSizeInBits() + 7) / 8;
20652 // Make sure we don't overlap with other intervals by checking the ones to
20653 // the left or right before inserting.
20654 auto I
= Intervals
.find(Offset
);
20655 // If there's a next interval, we should end before it.
20656 if (I
!= Intervals
.end() && I
.start() < (Offset
+ Length
))
20658 // If there's a previous interval, we should start after it.
20659 if (I
!= Intervals
.begin() && (--I
).stop() <= Offset
)
20661 Intervals
.insert(Offset
, Offset
+ Length
, Unit
);
20663 ChainedStores
.push_back(Chain
);
20667 // If we didn't find a chained store, exit.
20668 if (ChainedStores
.size() == 0)
20671 // Improve all chained stores (St and ChainedStores members) starting from
20672 // where the store chain ended and return single TokenFactor.
20673 SDValue NewChain
= STChain
->getChain();
20674 SmallVector
<SDValue
, 8> TFOps
;
20675 for (unsigned I
= ChainedStores
.size(); I
;) {
20676 StoreSDNode
*S
= ChainedStores
[--I
];
20677 SDValue BetterChain
= FindBetterChain(S
, NewChain
);
20678 S
= cast
<StoreSDNode
>(DAG
.UpdateNodeOperands(
20679 S
, BetterChain
, S
->getOperand(1), S
->getOperand(2), S
->getOperand(3)));
20680 TFOps
.push_back(SDValue(S
, 0));
20681 ChainedStores
[I
] = S
;
20684 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
20685 SDValue BetterChain
= FindBetterChain(St
, NewChain
);
20687 if (St
->isTruncatingStore())
20688 NewST
= DAG
.getTruncStore(BetterChain
, SDLoc(St
), St
->getValue(),
20689 St
->getBasePtr(), St
->getMemoryVT(),
20690 St
->getMemOperand());
20692 NewST
= DAG
.getStore(BetterChain
, SDLoc(St
), St
->getValue(),
20693 St
->getBasePtr(), St
->getMemOperand());
20695 TFOps
.push_back(NewST
);
20697 // If we improved every element of TFOps, then we've lost the dependence on
20698 // NewChain to successors of St and we need to add it back to TFOps. Do so at
20699 // the beginning to keep relative order consistent with FindBetterChains.
20700 auto hasImprovedChain
= [&](SDValue ST
) -> bool {
20701 return ST
->getOperand(0) != NewChain
;
20703 bool AddNewChain
= llvm::all_of(TFOps
, hasImprovedChain
);
20705 TFOps
.insert(TFOps
.begin(), NewChain
);
20707 SDValue TF
= DAG
.getTokenFactor(SDLoc(STChain
), TFOps
);
20710 AddToWorklist(STChain
);
20711 // Add TF operands worklist in reverse order.
20712 for (auto I
= TF
->getNumOperands(); I
;)
20713 AddToWorklist(TF
->getOperand(--I
).getNode());
20714 AddToWorklist(TF
.getNode());
20718 bool DAGCombiner::findBetterNeighborChains(StoreSDNode
*St
) {
20719 if (OptLevel
== CodeGenOpt::None
)
20722 const BaseIndexOffset BasePtr
= BaseIndexOffset::match(St
, DAG
);
20724 // We must have a base and an offset.
20725 if (!BasePtr
.getBase().getNode())
20728 // Do not handle stores to undef base pointers.
20729 if (BasePtr
.getBase().isUndef())
20732 // Directly improve a chain of disjoint stores starting at St.
20733 if (parallelizeChainedStores(St
))
20736 // Improve St's Chain..
20737 SDValue BetterChain
= FindBetterChain(St
, St
->getChain());
20738 if (St
->getChain() != BetterChain
) {
20739 replaceStoreChain(St
, BetterChain
);
20745 /// This is the entry point for the file.
20746 void SelectionDAG::Combine(CombineLevel Level
, AliasAnalysis
*AA
,
20747 CodeGenOpt::Level OptLevel
) {
20748 /// This is the main entry point to this class.
20749 DAGCombiner(*this, AA
, OptLevel
).Run(Level
);