1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "dagcombine"
47 STATISTIC(NodesCombined , "Number of dag nodes combined");
48 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
49 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
50 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
51 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
52 STATISTIC(SlicedLoads, "Number of load sliced");
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
60 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61 cl::desc("Enable DAG combiner's use of TBAA"));
64 static cl::opt<std::string>
65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66 cl::desc("Only use DAG-combiner alias analysis in this"
70 /// Hidden option to stress test load slicing, i.e., when this option
71 /// is enabled, load slicing bypasses most of its profitability guards.
73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74 cl::desc("Bypass the profitability model of load "
79 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
80 cl::desc("DAG combiner may split indexing from loads"));
82 //------------------------------ DAGCombiner ---------------------------------//
86 const TargetLowering &TLI;
88 CodeGenOpt::Level OptLevel;
93 /// \brief Worklist of all of the nodes that need to be simplified.
95 /// This must behave as a stack -- new nodes to process are pushed onto the
96 /// back and when processing we pop off of the back.
98 /// The worklist will not contain duplicates but may contain null entries
99 /// due to nodes being deleted from the underlying DAG.
100 SmallVector<SDNode *, 64> Worklist;
102 /// \brief Mapping from an SDNode to its position on the worklist.
104 /// This is used to find and remove nodes from the worklist (by nulling
105 /// them) when they are deleted from the underlying DAG. It relies on
106 /// stable indices of nodes within the worklist.
107 DenseMap<SDNode *, unsigned> WorklistMap;
109 /// \brief Set of nodes which have been combined (at least once).
111 /// This is used to allow us to reliably add any operands of a DAG node
112 /// which have not yet been combined to the worklist.
113 SmallPtrSet<SDNode *, 32> CombinedNodes;
115 // AA - Used for DAG load/store alias analysis.
118 /// When an instruction is simplified, add all users of the instruction to
119 /// the work lists because they might get more simplified now.
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// Call the node-specific routine that folds each particular type of node.
126 SDValue visit(SDNode *N);
129 /// Add to the worklist making sure its instance is at the back (next to be
131 void AddToWorklist(SDNode *N) {
132 assert(N->getOpcode() != ISD::DELETED_NODE &&
133 "Deleted Node added to Worklist");
135 // Skip handle nodes as they can't usefully be combined and confuse the
136 // zero-use deletion strategy.
137 if (N->getOpcode() == ISD::HANDLENODE)
140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
141 Worklist.push_back(N);
144 /// Remove all instances of N from the worklist.
145 void removeFromWorklist(SDNode *N) {
146 CombinedNodes.erase(N);
148 auto It = WorklistMap.find(N);
149 if (It == WorklistMap.end())
150 return; // Not in the worklist.
152 // Null out the entry rather than erasing it to avoid a linear operation.
153 Worklist[It->second] = nullptr;
154 WorklistMap.erase(It);
157 void deleteAndRecombine(SDNode *N);
158 bool recursivelyDeleteUnusedNodes(SDNode *N);
160 /// Replaces all uses of the results of one DAG node with new values.
161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
164 /// Replaces all uses of the results of one DAG node with new values.
165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
166 return CombineTo(N, &Res, 1, AddTo);
169 /// Replaces all uses of the results of one DAG node with new values.
170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
172 SDValue To[] = { Res0, Res1 };
173 return CombineTo(N, To, 2, AddTo);
176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 unsigned MaximumLegalStoreInBits;
181 /// Check the specified integer node value to see if it can be simplified or
182 /// if things it uses can be simplified by bit propagation.
183 /// If so, return true.
184 bool SimplifyDemandedBits(SDValue Op) {
185 unsigned BitWidth = Op.getScalarValueSizeInBits();
186 APInt Demanded = APInt::getAllOnesValue(BitWidth);
187 return SimplifyDemandedBits(Op, Demanded);
190 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
192 bool CombineToPreIndexedLoadStore(SDNode *N);
193 bool CombineToPostIndexedLoadStore(SDNode *N);
194 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
195 bool SliceUpLoad(SDNode *N);
197 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
200 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
201 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
202 /// \param EltNo index of the vector element to load.
203 /// \param OriginalLoad load that EVE came from to be replaced.
204 /// \returns EVE on success SDValue() on failure.
205 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
206 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
207 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
208 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
209 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
210 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
211 SDValue PromoteIntBinOp(SDValue Op);
212 SDValue PromoteIntShiftOp(SDValue Op);
213 SDValue PromoteExtend(SDValue Op);
214 bool PromoteLoad(SDValue Op);
216 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
217 SDValue ExtLoad, const SDLoc &DL,
218 ISD::NodeType ExtType);
220 /// Call the node-specific routine that knows how to fold each
221 /// particular type of node. If that doesn't do anything, try the
222 /// target-specific DAG combines.
223 SDValue combine(SDNode *N);
225 // Visitation implementation - Implement dag node combining for different
226 // node types. The semantics are as follows:
228 // SDValue.getNode() == 0 - No change was made
229 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
230 // otherwise - N should be replaced by the returned Operand.
232 SDValue visitTokenFactor(SDNode *N);
233 SDValue visitMERGE_VALUES(SDNode *N);
234 SDValue visitADD(SDNode *N);
235 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
236 SDValue visitSUB(SDNode *N);
237 SDValue visitADDC(SDNode *N);
238 SDValue visitUADDO(SDNode *N);
239 SDValue visitSUBC(SDNode *N);
240 SDValue visitUSUBO(SDNode *N);
241 SDValue visitADDE(SDNode *N);
242 SDValue visitSUBE(SDNode *N);
243 SDValue visitMUL(SDNode *N);
244 SDValue useDivRem(SDNode *N);
245 SDValue visitSDIV(SDNode *N);
246 SDValue visitUDIV(SDNode *N);
247 SDValue visitREM(SDNode *N);
248 SDValue visitMULHU(SDNode *N);
249 SDValue visitMULHS(SDNode *N);
250 SDValue visitSMUL_LOHI(SDNode *N);
251 SDValue visitUMUL_LOHI(SDNode *N);
252 SDValue visitSMULO(SDNode *N);
253 SDValue visitUMULO(SDNode *N);
254 SDValue visitIMINMAX(SDNode *N);
255 SDValue visitAND(SDNode *N);
256 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
257 SDValue visitOR(SDNode *N);
258 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
259 SDValue visitXOR(SDNode *N);
260 SDValue SimplifyVBinOp(SDNode *N);
261 SDValue visitSHL(SDNode *N);
262 SDValue visitSRA(SDNode *N);
263 SDValue visitSRL(SDNode *N);
264 SDValue visitRotate(SDNode *N);
265 SDValue visitABS(SDNode *N);
266 SDValue visitBSWAP(SDNode *N);
267 SDValue visitBITREVERSE(SDNode *N);
268 SDValue visitCTLZ(SDNode *N);
269 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
270 SDValue visitCTTZ(SDNode *N);
271 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
272 SDValue visitCTPOP(SDNode *N);
273 SDValue visitSELECT(SDNode *N);
274 SDValue visitVSELECT(SDNode *N);
275 SDValue visitSELECT_CC(SDNode *N);
276 SDValue visitSETCC(SDNode *N);
277 SDValue visitSETCCE(SDNode *N);
278 SDValue visitSIGN_EXTEND(SDNode *N);
279 SDValue visitZERO_EXTEND(SDNode *N);
280 SDValue visitANY_EXTEND(SDNode *N);
281 SDValue visitAssertZext(SDNode *N);
282 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
283 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
284 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
285 SDValue visitTRUNCATE(SDNode *N);
286 SDValue visitBITCAST(SDNode *N);
287 SDValue visitBUILD_PAIR(SDNode *N);
288 SDValue visitFADD(SDNode *N);
289 SDValue visitFSUB(SDNode *N);
290 SDValue visitFMUL(SDNode *N);
291 SDValue visitFMA(SDNode *N);
292 SDValue visitFDIV(SDNode *N);
293 SDValue visitFREM(SDNode *N);
294 SDValue visitFSQRT(SDNode *N);
295 SDValue visitFCOPYSIGN(SDNode *N);
296 SDValue visitSINT_TO_FP(SDNode *N);
297 SDValue visitUINT_TO_FP(SDNode *N);
298 SDValue visitFP_TO_SINT(SDNode *N);
299 SDValue visitFP_TO_UINT(SDNode *N);
300 SDValue visitFP_ROUND(SDNode *N);
301 SDValue visitFP_ROUND_INREG(SDNode *N);
302 SDValue visitFP_EXTEND(SDNode *N);
303 SDValue visitFNEG(SDNode *N);
304 SDValue visitFABS(SDNode *N);
305 SDValue visitFCEIL(SDNode *N);
306 SDValue visitFTRUNC(SDNode *N);
307 SDValue visitFFLOOR(SDNode *N);
308 SDValue visitFMINNUM(SDNode *N);
309 SDValue visitFMAXNUM(SDNode *N);
310 SDValue visitBRCOND(SDNode *N);
311 SDValue visitBR_CC(SDNode *N);
312 SDValue visitLOAD(SDNode *N);
314 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
315 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
317 SDValue visitSTORE(SDNode *N);
318 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
319 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
320 SDValue visitBUILD_VECTOR(SDNode *N);
321 SDValue visitCONCAT_VECTORS(SDNode *N);
322 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
323 SDValue visitVECTOR_SHUFFLE(SDNode *N);
324 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
325 SDValue visitINSERT_SUBVECTOR(SDNode *N);
326 SDValue visitMLOAD(SDNode *N);
327 SDValue visitMSTORE(SDNode *N);
328 SDValue visitMGATHER(SDNode *N);
329 SDValue visitMSCATTER(SDNode *N);
330 SDValue visitFP_TO_FP16(SDNode *N);
331 SDValue visitFP16_TO_FP(SDNode *N);
333 SDValue visitFADDForFMACombine(SDNode *N);
334 SDValue visitFSUBForFMACombine(SDNode *N);
335 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
337 SDValue XformToShuffleWithZero(SDNode *N);
338 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
341 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
343 SDValue foldSelectOfConstants(SDNode *N);
344 SDValue foldBinOpIntoSelect(SDNode *BO);
345 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
346 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
347 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
348 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
349 SDValue N2, SDValue N3, ISD::CondCode CC,
350 bool NotExtCompare = false);
351 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
352 SDValue N2, SDValue N3, ISD::CondCode CC);
353 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
355 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
356 const SDLoc &DL, bool foldBooleans = true);
358 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
360 bool isOneUseSetCC(SDValue N) const;
362 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
364 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
365 SDValue CombineExtLoad(SDNode *N);
366 SDValue combineRepeatedFPDivisors(SDNode *N);
367 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
368 SDValue BuildSDIV(SDNode *N);
369 SDValue BuildSDIVPow2(SDNode *N);
370 SDValue BuildUDIV(SDNode *N);
371 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
372 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
373 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
374 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
375 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
376 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
377 SDNodeFlags *Flags, bool Reciprocal);
378 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
379 SDNodeFlags *Flags, bool Reciprocal);
380 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
381 bool DemandHighBits = true);
382 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
383 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
384 SDValue InnerPos, SDValue InnerNeg,
385 unsigned PosOpcode, unsigned NegOpcode,
387 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
388 SDValue MatchLoadCombine(SDNode *N);
389 SDValue ReduceLoadWidth(SDNode *N);
390 SDValue ReduceLoadOpStoreWidth(SDNode *N);
391 SDValue splitMergedValStore(StoreSDNode *ST);
392 SDValue TransformFPLoadStorePair(SDNode *N);
393 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
394 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
395 SDValue reduceBuildVecToShuffle(SDNode *N);
396 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
397 ArrayRef<int> VectorMask, SDValue VecIn1,
398 SDValue VecIn2, unsigned LeftIdx);
400 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
402 /// Walk up chain skipping non-aliasing memory nodes,
403 /// looking for aliasing nodes and adding them to the Aliases vector.
404 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
405 SmallVectorImpl<SDValue> &Aliases);
407 /// Return true if there is any possibility that the two addresses overlap.
408 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
410 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
411 /// chain (aliasing node.)
412 SDValue FindBetterChain(SDNode *N, SDValue Chain);
414 /// Try to replace a store and any possibly adjacent stores on
415 /// consecutive chains with better chains. Return true only if St is
418 /// Notice that other chains may still be replaced even if the function
420 bool findBetterNeighborChains(StoreSDNode *St);
422 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
423 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
425 /// Holds a pointer to an LSBaseSDNode as well as information on where it
426 /// is located in a sequence of memory operations connected by a chain.
428 MemOpLink(LSBaseSDNode *N, int64_t Offset)
429 : MemNode(N), OffsetFromBase(Offset) {}
430 // Ptr to the mem node.
431 LSBaseSDNode *MemNode;
432 // Offset from the base ptr.
433 int64_t OffsetFromBase;
436 /// This is a helper function for visitMUL to check the profitability
437 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
438 /// MulNode is the original multiply, AddNode is (add x, c1),
439 /// and ConstNode is c2.
440 bool isMulAddWithConstProfitable(SDNode *MulNode,
445 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
446 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
447 /// the type of the loaded value to be extended. LoadedVT returns the type
448 /// of the original loaded value. NarrowLoad returns whether the load would
449 /// need to be narrowed in order to match.
450 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
451 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
454 /// Helper function for MergeConsecutiveStores which merges the
455 /// component store chains.
456 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
459 /// This is a helper function for MergeConsecutiveStores. When the source
460 /// elements of the consecutive stores are all constants or all extracted
461 /// vector elements, try to merge them into one larger store.
462 /// \return True if a merged store was created.
463 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
464 EVT MemVT, unsigned NumStores,
465 bool IsConstantSrc, bool UseVector);
467 /// This is a helper function for MergeConsecutiveStores.
468 /// Stores that may be merged are placed in StoreNodes.
469 void getStoreMergeCandidates(StoreSDNode *St,
470 SmallVectorImpl<MemOpLink> &StoreNodes);
472 /// Helper function for MergeConsecutiveStores. Checks if
473 /// Candidate stores have indirect dependency through their
474 /// operands. \return True if safe to merge
475 bool checkMergeStoreCandidatesForDependencies(
476 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
478 /// Merge consecutive store operations into a wide store.
479 /// This optimization uses wide integers or vectors when possible.
480 /// \return number of stores that were merged into a merged store (the
481 /// affected nodes are stored as a prefix in \p StoreNodes).
482 bool MergeConsecutiveStores(StoreSDNode *N);
484 /// \brief Try to transform a truncation where C is a constant:
485 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
487 /// \p N needs to be a truncation and its first operand an AND. Other
488 /// requirements are checked by the function (e.g. that trunc is
489 /// single-use) and if missed an empty SDValue is returned.
490 SDValue distributeTruncateThroughAnd(SDNode *N);
493 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
494 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
495 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
496 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
498 MaximumLegalStoreInBits = 0;
499 for (MVT VT : MVT::all_valuetypes())
500 if (EVT(VT).isSimple() && VT != MVT::Other &&
501 TLI.isTypeLegal(EVT(VT)) &&
502 VT.getSizeInBits() >= MaximumLegalStoreInBits)
503 MaximumLegalStoreInBits = VT.getSizeInBits();
506 /// Runs the dag combiner on all nodes in the work list
507 void Run(CombineLevel AtLevel);
509 SelectionDAG &getDAG() const { return DAG; }
511 /// Returns a type large enough to hold any valid shift amount - before type
512 /// legalization these can be huge.
513 EVT getShiftAmountTy(EVT LHSTy) {
514 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
515 if (LHSTy.isVector())
517 auto &DL = DAG.getDataLayout();
518 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
519 : TLI.getPointerTy(DL);
522 /// This method returns true if we are running before type legalization or
523 /// if the specified VT is legal.
524 bool isTypeLegal(const EVT &VT) {
525 if (!LegalTypes) return true;
526 return TLI.isTypeLegal(VT);
529 /// Convenience wrapper around TargetLowering::getSetCCResultType
530 EVT getSetCCResultType(EVT VT) const {
531 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
538 /// This class is a DAGUpdateListener that removes any deleted
539 /// nodes from the worklist.
540 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
543 explicit WorklistRemover(DAGCombiner &dc)
544 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
546 void NodeDeleted(SDNode *N, SDNode *E) override {
547 DC.removeFromWorklist(N);
552 //===----------------------------------------------------------------------===//
553 // TargetLowering::DAGCombinerInfo implementation
554 //===----------------------------------------------------------------------===//
556 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
557 ((DAGCombiner*)DC)->AddToWorklist(N);
560 SDValue TargetLowering::DAGCombinerInfo::
561 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
562 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
565 SDValue TargetLowering::DAGCombinerInfo::
566 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
567 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
571 SDValue TargetLowering::DAGCombinerInfo::
572 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
573 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
576 void TargetLowering::DAGCombinerInfo::
577 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
578 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
581 //===----------------------------------------------------------------------===//
583 //===----------------------------------------------------------------------===//
585 void DAGCombiner::deleteAndRecombine(SDNode *N) {
586 removeFromWorklist(N);
588 // If the operands of this node are only used by the node, they will now be
589 // dead. Make sure to re-visit them and recursively delete dead nodes.
590 for (const SDValue &Op : N->ops())
591 // For an operand generating multiple values, one of the values may
592 // become dead allowing further simplification (e.g. split index
593 // arithmetic from an indexed load).
594 if (Op->hasOneUse() || Op->getNumValues() > 1)
595 AddToWorklist(Op.getNode());
600 /// Return 1 if we can compute the negated form of the specified expression for
601 /// the same cost as the expression itself, or 2 if we can compute the negated
602 /// form more cheaply than the expression itself.
603 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
604 const TargetLowering &TLI,
605 const TargetOptions *Options,
606 unsigned Depth = 0) {
607 // fneg is removable even if it has multiple uses.
608 if (Op.getOpcode() == ISD::FNEG) return 2;
610 // Don't allow anything with multiple uses.
611 if (!Op.hasOneUse()) return 0;
613 // Don't recurse exponentially.
614 if (Depth > 6) return 0;
616 switch (Op.getOpcode()) {
617 default: return false;
618 case ISD::ConstantFP: {
619 if (!LegalOperations)
622 // Don't invert constant FP values after legalization unless the target says
623 // the negated constant is legal.
624 EVT VT = Op.getValueType();
625 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
626 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
629 // FIXME: determine better conditions for this xform.
630 if (!Options->UnsafeFPMath) return 0;
632 // After operation legalization, it might not be legal to create new FSUBs.
633 if (LegalOperations &&
634 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
637 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
638 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
641 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
642 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
645 // We can't turn -(A-B) into B-A when we honor signed zeros.
646 if (!Options->NoSignedZerosFPMath &&
647 !Op.getNode()->getFlags()->hasNoSignedZeros())
650 // fold (fneg (fsub A, B)) -> (fsub B, A)
655 if (Options->HonorSignDependentRoundingFPMath()) return 0;
657 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
658 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
662 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
668 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
673 /// If isNegatibleForFree returns true, return the newly negated expression.
674 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
675 bool LegalOperations, unsigned Depth = 0) {
676 const TargetOptions &Options = DAG.getTarget().Options;
677 // fneg is removable even if it has multiple uses.
678 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
680 // Don't allow anything with multiple uses.
681 assert(Op.hasOneUse() && "Unknown reuse!");
683 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
685 const SDNodeFlags *Flags = Op.getNode()->getFlags();
687 switch (Op.getOpcode()) {
688 default: llvm_unreachable("Unknown code");
689 case ISD::ConstantFP: {
690 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
692 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
695 // FIXME: determine better conditions for this xform.
696 assert(Options.UnsafeFPMath);
698 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
699 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
700 DAG.getTargetLoweringInfo(), &Options, Depth+1))
701 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
702 GetNegatedExpression(Op.getOperand(0), DAG,
703 LegalOperations, Depth+1),
704 Op.getOperand(1), Flags);
705 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
706 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
707 GetNegatedExpression(Op.getOperand(1), DAG,
708 LegalOperations, Depth+1),
709 Op.getOperand(0), Flags);
711 // fold (fneg (fsub 0, B)) -> B
712 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
714 return Op.getOperand(1);
716 // fold (fneg (fsub A, B)) -> (fsub B, A)
717 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
718 Op.getOperand(1), Op.getOperand(0), Flags);
722 assert(!Options.HonorSignDependentRoundingFPMath());
724 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
725 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
726 DAG.getTargetLoweringInfo(), &Options, Depth+1))
727 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
728 GetNegatedExpression(Op.getOperand(0), DAG,
729 LegalOperations, Depth+1),
730 Op.getOperand(1), Flags);
732 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
733 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
735 GetNegatedExpression(Op.getOperand(1), DAG,
736 LegalOperations, Depth+1), Flags);
740 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
741 GetNegatedExpression(Op.getOperand(0), DAG,
742 LegalOperations, Depth+1));
744 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
745 GetNegatedExpression(Op.getOperand(0), DAG,
746 LegalOperations, Depth+1),
751 // APInts must be the same size for most operations, this helper
752 // function zero extends the shorter of the pair so that they match.
753 // We provide an Offset so that we can create bitwidths that won't overflow.
754 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
755 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
756 LHS = LHS.zextOrSelf(Bits);
757 RHS = RHS.zextOrSelf(Bits);
760 // Return true if this node is a setcc, or is a select_cc
761 // that selects between the target values used for true and false, making it
762 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
763 // the appropriate nodes based on the type of node we are checking. This
764 // simplifies life a bit for the callers.
765 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
767 if (N.getOpcode() == ISD::SETCC) {
768 LHS = N.getOperand(0);
769 RHS = N.getOperand(1);
770 CC = N.getOperand(2);
774 if (N.getOpcode() != ISD::SELECT_CC ||
775 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
776 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
779 if (TLI.getBooleanContents(N.getValueType()) ==
780 TargetLowering::UndefinedBooleanContent)
783 LHS = N.getOperand(0);
784 RHS = N.getOperand(1);
785 CC = N.getOperand(4);
789 /// Return true if this is a SetCC-equivalent operation with only one use.
790 /// If this is true, it allows the users to invert the operation for free when
791 /// it is profitable to do so.
792 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
794 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
799 // \brief Returns the SDNode if it is a constant float BuildVector
800 // or constant float.
801 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
802 if (isa<ConstantFPSDNode>(N))
804 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
809 // Determines if it is a constant integer or a build vector of constant
810 // integers (and undefs).
811 // Do not permit build vector implicit truncation.
812 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
813 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
814 return !(Const->isOpaque() && NoOpaques);
815 if (N.getOpcode() != ISD::BUILD_VECTOR)
817 unsigned BitWidth = N.getScalarValueSizeInBits();
818 for (const SDValue &Op : N->op_values()) {
821 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
822 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
823 (Const->isOpaque() && NoOpaques))
829 // Determines if it is a constant null integer or a splatted vector of a
830 // constant null integer (with no undefs).
831 // Build vector implicit truncation is not an issue for null values.
832 static bool isNullConstantOrNullSplatConstant(SDValue N) {
833 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
834 return Splat->isNullValue();
838 // Determines if it is a constant integer of one or a splatted vector of a
839 // constant integer of one (with no undefs).
840 // Do not permit build vector implicit truncation.
841 static bool isOneConstantOrOneSplatConstant(SDValue N) {
842 unsigned BitWidth = N.getScalarValueSizeInBits();
843 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
848 // Determines if it is a constant integer of all ones or a splatted vector of a
849 // constant integer of all ones (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
852 unsigned BitWidth = N.getScalarValueSizeInBits();
853 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854 return Splat->isAllOnesValue() &&
855 Splat->getAPIntValue().getBitWidth() == BitWidth;
859 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
861 static bool isAnyConstantBuildVector(const SDNode *N) {
862 return ISD::isBuildVectorOfConstantSDNodes(N) ||
863 ISD::isBuildVectorOfConstantFPSDNodes(N);
866 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
868 EVT VT = N0.getValueType();
869 if (N0.getOpcode() == Opc) {
870 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
871 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
872 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
873 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
874 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
877 if (N0.hasOneUse()) {
878 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
880 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
881 if (!OpNode.getNode())
883 AddToWorklist(OpNode.getNode());
884 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
889 if (N1.getOpcode() == Opc) {
890 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
891 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
892 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
893 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
894 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
897 if (N1.hasOneUse()) {
898 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
900 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
901 if (!OpNode.getNode())
903 AddToWorklist(OpNode.getNode());
904 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
912 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
914 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
916 DEBUG(dbgs() << "\nReplacing.1 ";
918 dbgs() << "\nWith: ";
919 To[0].getNode()->dump(&DAG);
920 dbgs() << " and " << NumTo-1 << " other values\n");
921 for (unsigned i = 0, e = NumTo; i != e; ++i)
922 assert((!To[i].getNode() ||
923 N->getValueType(i) == To[i].getValueType()) &&
924 "Cannot combine value to value of different type!");
926 WorklistRemover DeadNodes(*this);
927 DAG.ReplaceAllUsesWith(N, To);
929 // Push the new nodes and any users onto the worklist
930 for (unsigned i = 0, e = NumTo; i != e; ++i) {
931 if (To[i].getNode()) {
932 AddToWorklist(To[i].getNode());
933 AddUsersToWorklist(To[i].getNode());
938 // Finally, if the node is now dead, remove it from the graph. The node
939 // may not be dead if the replacement process recursively simplified to
940 // something else needing this node.
942 deleteAndRecombine(N);
943 return SDValue(N, 0);
947 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
948 // Replace all uses. If any nodes become isomorphic to other nodes and
949 // are deleted, make sure to remove them from our worklist.
950 WorklistRemover DeadNodes(*this);
951 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
953 // Push the new node and any (possibly new) users onto the worklist.
954 AddToWorklist(TLO.New.getNode());
955 AddUsersToWorklist(TLO.New.getNode());
957 // Finally, if the node is now dead, remove it from the graph. The node
958 // may not be dead if the replacement process recursively simplified to
959 // something else needing this node.
960 if (TLO.Old.getNode()->use_empty())
961 deleteAndRecombine(TLO.Old.getNode());
964 /// Check the specified integer node value to see if it can be simplified or if
965 /// things it uses can be simplified by bit propagation. If so, return true.
966 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
967 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
968 APInt KnownZero, KnownOne;
969 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
973 AddToWorklist(Op.getNode());
975 // Replace the old value with the new one.
977 DEBUG(dbgs() << "\nReplacing.2 ";
978 TLO.Old.getNode()->dump(&DAG);
979 dbgs() << "\nWith: ";
980 TLO.New.getNode()->dump(&DAG);
983 CommitTargetLoweringOpt(TLO);
987 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
989 EVT VT = Load->getValueType(0);
990 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
992 DEBUG(dbgs() << "\nReplacing.9 ";
994 dbgs() << "\nWith: ";
995 Trunc.getNode()->dump(&DAG);
997 WorklistRemover DeadNodes(*this);
998 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
999 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1000 deleteAndRecombine(Load);
1001 AddToWorklist(Trunc.getNode());
1004 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1007 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1008 LoadSDNode *LD = cast<LoadSDNode>(Op);
1009 EVT MemVT = LD->getMemoryVT();
1010 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1011 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1013 : LD->getExtensionType();
1015 return DAG.getExtLoad(ExtType, DL, PVT,
1016 LD->getChain(), LD->getBasePtr(),
1017 MemVT, LD->getMemOperand());
1020 unsigned Opc = Op.getOpcode();
1023 case ISD::AssertSext:
1024 return DAG.getNode(ISD::AssertSext, DL, PVT,
1025 SExtPromoteOperand(Op.getOperand(0), PVT),
1027 case ISD::AssertZext:
1028 return DAG.getNode(ISD::AssertZext, DL, PVT,
1029 ZExtPromoteOperand(Op.getOperand(0), PVT),
1031 case ISD::Constant: {
1033 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1034 return DAG.getNode(ExtOpc, DL, PVT, Op);
1038 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1040 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1043 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1044 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1046 EVT OldVT = Op.getValueType();
1048 bool Replace = false;
1049 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1050 if (!NewOp.getNode())
1052 AddToWorklist(NewOp.getNode());
1055 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1056 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1057 DAG.getValueType(OldVT));
1060 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1061 EVT OldVT = Op.getValueType();
1063 bool Replace = false;
1064 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1065 if (!NewOp.getNode())
1067 AddToWorklist(NewOp.getNode());
1070 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1071 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1074 /// Promote the specified integer binary operation if the target indicates it is
1075 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1076 /// i32 since i16 instructions are longer.
1077 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1078 if (!LegalOperations)
1081 EVT VT = Op.getValueType();
1082 if (VT.isVector() || !VT.isInteger())
1085 // If operation type is 'undesirable', e.g. i16 on x86, consider
1087 unsigned Opc = Op.getOpcode();
1088 if (TLI.isTypeDesirableForOp(Opc, VT))
1092 // Consult target whether it is a good idea to promote this operation and
1093 // what's the right type to promote it to.
1094 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095 assert(PVT != VT && "Don't know what type to promote to!");
1097 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1099 bool Replace0 = false;
1100 SDValue N0 = Op.getOperand(0);
1101 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1103 bool Replace1 = false;
1104 SDValue N1 = Op.getOperand(1);
1105 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1109 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1111 // New replace instances of N0 and N1
1112 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1113 NN0.getOpcode() != ISD::DELETED_NODE) {
1114 AddToWorklist(NN0.getNode());
1115 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1118 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1119 NN1.getOpcode() != ISD::DELETED_NODE) {
1120 AddToWorklist(NN1.getNode());
1121 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1124 // Deal with Op being deleted.
1125 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1131 /// Promote the specified integer shift operation if the target indicates it is
1132 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1133 /// i32 since i16 instructions are longer.
1134 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1135 if (!LegalOperations)
1138 EVT VT = Op.getValueType();
1139 if (VT.isVector() || !VT.isInteger())
1142 // If operation type is 'undesirable', e.g. i16 on x86, consider
1144 unsigned Opc = Op.getOpcode();
1145 if (TLI.isTypeDesirableForOp(Opc, VT))
1149 // Consult target whether it is a good idea to promote this operation and
1150 // what's the right type to promote it to.
1151 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1152 assert(PVT != VT && "Don't know what type to promote to!");
1154 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1156 bool Replace = false;
1157 SDValue N0 = Op.getOperand(0);
1158 SDValue N1 = Op.getOperand(1);
1159 if (Opc == ISD::SRA)
1160 N0 = SExtPromoteOperand(N0, PVT);
1161 else if (Opc == ISD::SRL)
1162 N0 = ZExtPromoteOperand(N0, PVT);
1164 N0 = PromoteOperand(N0, PVT, Replace);
1171 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1173 AddToWorklist(N0.getNode());
1175 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1177 // Deal with Op being deleted.
1178 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1184 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1185 if (!LegalOperations)
1188 EVT VT = Op.getValueType();
1189 if (VT.isVector() || !VT.isInteger())
1192 // If operation type is 'undesirable', e.g. i16 on x86, consider
1194 unsigned Opc = Op.getOpcode();
1195 if (TLI.isTypeDesirableForOp(Opc, VT))
1199 // Consult target whether it is a good idea to promote this operation and
1200 // what's the right type to promote it to.
1201 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1202 assert(PVT != VT && "Don't know what type to promote to!");
1203 // fold (aext (aext x)) -> (aext x)
1204 // fold (aext (zext x)) -> (zext x)
1205 // fold (aext (sext x)) -> (sext x)
1206 DEBUG(dbgs() << "\nPromoting ";
1207 Op.getNode()->dump(&DAG));
1208 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1213 bool DAGCombiner::PromoteLoad(SDValue Op) {
1214 if (!LegalOperations)
1217 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1220 EVT VT = Op.getValueType();
1221 if (VT.isVector() || !VT.isInteger())
1224 // If operation type is 'undesirable', e.g. i16 on x86, consider
1226 unsigned Opc = Op.getOpcode();
1227 if (TLI.isTypeDesirableForOp(Opc, VT))
1231 // Consult target whether it is a good idea to promote this operation and
1232 // what's the right type to promote it to.
1233 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1234 assert(PVT != VT && "Don't know what type to promote to!");
1237 SDNode *N = Op.getNode();
1238 LoadSDNode *LD = cast<LoadSDNode>(N);
1239 EVT MemVT = LD->getMemoryVT();
1240 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1241 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1243 : LD->getExtensionType();
1244 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1245 LD->getChain(), LD->getBasePtr(),
1246 MemVT, LD->getMemOperand());
1247 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1249 DEBUG(dbgs() << "\nPromoting ";
1252 Result.getNode()->dump(&DAG);
1254 WorklistRemover DeadNodes(*this);
1255 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1256 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1257 deleteAndRecombine(N);
1258 AddToWorklist(Result.getNode());
1264 /// \brief Recursively delete a node which has no uses and any operands for
1265 /// which it is the only use.
1267 /// Note that this both deletes the nodes and removes them from the worklist.
1268 /// It also adds any nodes who have had a user deleted to the worklist as they
1269 /// may now have only one use and subject to other combines.
1270 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1271 if (!N->use_empty())
1274 SmallSetVector<SDNode *, 16> Nodes;
1277 N = Nodes.pop_back_val();
1281 if (N->use_empty()) {
1282 for (const SDValue &ChildN : N->op_values())
1283 Nodes.insert(ChildN.getNode());
1285 removeFromWorklist(N);
1290 } while (!Nodes.empty());
1294 //===----------------------------------------------------------------------===//
1295 // Main DAG Combiner implementation
1296 //===----------------------------------------------------------------------===//
1298 void DAGCombiner::Run(CombineLevel AtLevel) {
1299 // set the instance variables, so that the various visit routines may use it.
1301 LegalOperations = Level >= AfterLegalizeVectorOps;
1302 LegalTypes = Level >= AfterLegalizeTypes;
1304 // Add all the dag nodes to the worklist.
1305 for (SDNode &Node : DAG.allnodes())
1306 AddToWorklist(&Node);
1308 // Create a dummy node (which is not added to allnodes), that adds a reference
1309 // to the root node, preventing it from being deleted, and tracking any
1310 // changes of the root.
1311 HandleSDNode Dummy(DAG.getRoot());
1313 // While the worklist isn't empty, find a node and try to combine it.
1314 while (!WorklistMap.empty()) {
1316 // The Worklist holds the SDNodes in order, but it may contain null entries.
1318 N = Worklist.pop_back_val();
1321 bool GoodWorklistEntry = WorklistMap.erase(N);
1322 (void)GoodWorklistEntry;
1323 assert(GoodWorklistEntry &&
1324 "Found a worklist entry without a corresponding map entry!");
1326 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1327 // N is deleted from the DAG, since they too may now be dead or may have a
1328 // reduced number of uses, allowing other xforms.
1329 if (recursivelyDeleteUnusedNodes(N))
1332 WorklistRemover DeadNodes(*this);
1334 // If this combine is running after legalizing the DAG, re-legalize any
1335 // nodes pulled off the worklist.
1336 if (Level == AfterLegalizeDAG) {
1337 SmallSetVector<SDNode *, 16> UpdatedNodes;
1338 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1340 for (SDNode *LN : UpdatedNodes) {
1342 AddUsersToWorklist(LN);
1348 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1350 // Add any operands of the new node which have not yet been combined to the
1351 // worklist as well. Because the worklist uniques things already, this
1352 // won't repeatedly process the same operand.
1353 CombinedNodes.insert(N);
1354 for (const SDValue &ChildN : N->op_values())
1355 if (!CombinedNodes.count(ChildN.getNode()))
1356 AddToWorklist(ChildN.getNode());
1358 SDValue RV = combine(N);
1365 // If we get back the same node we passed in, rather than a new node or
1366 // zero, we know that the node must have defined multiple values and
1367 // CombineTo was used. Since CombineTo takes care of the worklist
1368 // mechanics for us, we have no work to do in this case.
1369 if (RV.getNode() == N)
1372 assert(N->getOpcode() != ISD::DELETED_NODE &&
1373 RV.getOpcode() != ISD::DELETED_NODE &&
1374 "Node was deleted but visit returned new node!");
1376 DEBUG(dbgs() << " ... into: ";
1377 RV.getNode()->dump(&DAG));
1379 if (N->getNumValues() == RV.getNode()->getNumValues())
1380 DAG.ReplaceAllUsesWith(N, RV.getNode());
1382 assert(N->getValueType(0) == RV.getValueType() &&
1383 N->getNumValues() == 1 && "Type mismatch");
1384 DAG.ReplaceAllUsesWith(N, &RV);
1387 // Push the new node and any users onto the worklist
1388 AddToWorklist(RV.getNode());
1389 AddUsersToWorklist(RV.getNode());
1391 // Finally, if the node is now dead, remove it from the graph. The node
1392 // may not be dead if the replacement process recursively simplified to
1393 // something else needing this node. This will also take care of adding any
1394 // operands which have lost a user to the worklist.
1395 recursivelyDeleteUnusedNodes(N);
1398 // If the root changed (e.g. it was a dead load, update the root).
1399 DAG.setRoot(Dummy.getValue());
1400 DAG.RemoveDeadNodes();
1403 SDValue DAGCombiner::visit(SDNode *N) {
1404 switch (N->getOpcode()) {
1406 case ISD::TokenFactor: return visitTokenFactor(N);
1407 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1408 case ISD::ADD: return visitADD(N);
1409 case ISD::SUB: return visitSUB(N);
1410 case ISD::ADDC: return visitADDC(N);
1411 case ISD::UADDO: return visitUADDO(N);
1412 case ISD::SUBC: return visitSUBC(N);
1413 case ISD::USUBO: return visitUSUBO(N);
1414 case ISD::ADDE: return visitADDE(N);
1415 case ISD::SUBE: return visitSUBE(N);
1416 case ISD::MUL: return visitMUL(N);
1417 case ISD::SDIV: return visitSDIV(N);
1418 case ISD::UDIV: return visitUDIV(N);
1420 case ISD::UREM: return visitREM(N);
1421 case ISD::MULHU: return visitMULHU(N);
1422 case ISD::MULHS: return visitMULHS(N);
1423 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1424 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1425 case ISD::SMULO: return visitSMULO(N);
1426 case ISD::UMULO: return visitUMULO(N);
1430 case ISD::UMAX: return visitIMINMAX(N);
1431 case ISD::AND: return visitAND(N);
1432 case ISD::OR: return visitOR(N);
1433 case ISD::XOR: return visitXOR(N);
1434 case ISD::SHL: return visitSHL(N);
1435 case ISD::SRA: return visitSRA(N);
1436 case ISD::SRL: return visitSRL(N);
1438 case ISD::ROTL: return visitRotate(N);
1439 case ISD::ABS: return visitABS(N);
1440 case ISD::BSWAP: return visitBSWAP(N);
1441 case ISD::BITREVERSE: return visitBITREVERSE(N);
1442 case ISD::CTLZ: return visitCTLZ(N);
1443 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1444 case ISD::CTTZ: return visitCTTZ(N);
1445 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1446 case ISD::CTPOP: return visitCTPOP(N);
1447 case ISD::SELECT: return visitSELECT(N);
1448 case ISD::VSELECT: return visitVSELECT(N);
1449 case ISD::SELECT_CC: return visitSELECT_CC(N);
1450 case ISD::SETCC: return visitSETCC(N);
1451 case ISD::SETCCE: return visitSETCCE(N);
1452 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1453 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1454 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1455 case ISD::AssertZext: return visitAssertZext(N);
1456 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1457 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1458 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1459 case ISD::TRUNCATE: return visitTRUNCATE(N);
1460 case ISD::BITCAST: return visitBITCAST(N);
1461 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1462 case ISD::FADD: return visitFADD(N);
1463 case ISD::FSUB: return visitFSUB(N);
1464 case ISD::FMUL: return visitFMUL(N);
1465 case ISD::FMA: return visitFMA(N);
1466 case ISD::FDIV: return visitFDIV(N);
1467 case ISD::FREM: return visitFREM(N);
1468 case ISD::FSQRT: return visitFSQRT(N);
1469 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1470 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1471 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1472 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1473 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1474 case ISD::FP_ROUND: return visitFP_ROUND(N);
1475 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1476 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1477 case ISD::FNEG: return visitFNEG(N);
1478 case ISD::FABS: return visitFABS(N);
1479 case ISD::FFLOOR: return visitFFLOOR(N);
1480 case ISD::FMINNUM: return visitFMINNUM(N);
1481 case ISD::FMAXNUM: return visitFMAXNUM(N);
1482 case ISD::FCEIL: return visitFCEIL(N);
1483 case ISD::FTRUNC: return visitFTRUNC(N);
1484 case ISD::BRCOND: return visitBRCOND(N);
1485 case ISD::BR_CC: return visitBR_CC(N);
1486 case ISD::LOAD: return visitLOAD(N);
1487 case ISD::STORE: return visitSTORE(N);
1488 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1489 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1490 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1491 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1492 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1493 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1494 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1495 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1496 case ISD::MGATHER: return visitMGATHER(N);
1497 case ISD::MLOAD: return visitMLOAD(N);
1498 case ISD::MSCATTER: return visitMSCATTER(N);
1499 case ISD::MSTORE: return visitMSTORE(N);
1500 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1501 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1506 SDValue DAGCombiner::combine(SDNode *N) {
1507 SDValue RV = visit(N);
1509 // If nothing happened, try a target-specific DAG combine.
1510 if (!RV.getNode()) {
1511 assert(N->getOpcode() != ISD::DELETED_NODE &&
1512 "Node was deleted but visit returned NULL!");
1514 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1515 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1517 // Expose the DAG combiner to the target combiner impls.
1518 TargetLowering::DAGCombinerInfo
1519 DagCombineInfo(DAG, Level, false, this);
1521 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1525 // If nothing happened still, try promoting the operation.
1526 if (!RV.getNode()) {
1527 switch (N->getOpcode()) {
1535 RV = PromoteIntBinOp(SDValue(N, 0));
1540 RV = PromoteIntShiftOp(SDValue(N, 0));
1542 case ISD::SIGN_EXTEND:
1543 case ISD::ZERO_EXTEND:
1544 case ISD::ANY_EXTEND:
1545 RV = PromoteExtend(SDValue(N, 0));
1548 if (PromoteLoad(SDValue(N, 0)))
1554 // If N is a commutative binary node, try commuting it to enable more
1556 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1557 N->getNumValues() == 1) {
1558 SDValue N0 = N->getOperand(0);
1559 SDValue N1 = N->getOperand(1);
1561 // Constant operands are canonicalized to RHS.
1562 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1563 SDValue Ops[] = {N1, N0};
1564 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1567 return SDValue(CSENode, 0);
1574 /// Given a node, return its input chain if it has one, otherwise return a null
1576 static SDValue getInputChainForNode(SDNode *N) {
1577 if (unsigned NumOps = N->getNumOperands()) {
1578 if (N->getOperand(0).getValueType() == MVT::Other)
1579 return N->getOperand(0);
1580 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1581 return N->getOperand(NumOps-1);
1582 for (unsigned i = 1; i < NumOps-1; ++i)
1583 if (N->getOperand(i).getValueType() == MVT::Other)
1584 return N->getOperand(i);
1589 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1590 // If N has two operands, where one has an input chain equal to the other,
1591 // the 'other' chain is redundant.
1592 if (N->getNumOperands() == 2) {
1593 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1594 return N->getOperand(0);
1595 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1596 return N->getOperand(1);
1599 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1600 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1601 SmallPtrSet<SDNode*, 16> SeenOps;
1602 bool Changed = false; // If we should replace this token factor.
1604 // Start out with this token factor.
1607 // Iterate through token factors. The TFs grows when new token factors are
1609 for (unsigned i = 0; i < TFs.size(); ++i) {
1610 SDNode *TF = TFs[i];
1612 // Check each of the operands.
1613 for (const SDValue &Op : TF->op_values()) {
1615 switch (Op.getOpcode()) {
1616 case ISD::EntryToken:
1617 // Entry tokens don't need to be added to the list. They are
1622 case ISD::TokenFactor:
1623 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1624 // Queue up for processing.
1625 TFs.push_back(Op.getNode());
1626 // Clean up in case the token factor is removed.
1627 AddToWorklist(Op.getNode());
1634 // Only add if it isn't already in the list.
1635 if (SeenOps.insert(Op.getNode()).second)
1644 // Remove Nodes that are chained to another node in the list. Do so
1645 // by walking up chains breath-first stopping when we've seen
1646 // another operand. In general we must climb to the EntryNode, but we can exit
1647 // early if we find all remaining work is associated with just one operand as
1648 // no further pruning is possible.
1650 // List of nodes to search through and original Ops from which they originate.
1651 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1652 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1653 SmallPtrSet<SDNode *, 16> SeenChains;
1654 bool DidPruneOps = false;
1656 unsigned NumLeftToConsider = 0;
1657 for (const SDValue &Op : Ops) {
1658 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1659 OpWorkCount.push_back(1);
1662 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1663 // If this is an Op, we can remove the op from the list. Remark any
1664 // search associated with it as from the current OpNumber.
1665 if (SeenOps.count(Op) != 0) {
1668 unsigned OrigOpNumber = 0;
1669 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1671 assert((OrigOpNumber != Ops.size()) &&
1672 "expected to find TokenFactor Operand");
1673 // Re-mark worklist from OrigOpNumber to OpNumber
1674 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1675 if (Worklist[i].second == OrigOpNumber) {
1676 Worklist[i].second = OpNumber;
1679 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1680 OpWorkCount[OrigOpNumber] = 0;
1681 NumLeftToConsider--;
1683 // Add if it's a new chain
1684 if (SeenChains.insert(Op).second) {
1685 OpWorkCount[OpNumber]++;
1686 Worklist.push_back(std::make_pair(Op, OpNumber));
1690 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1691 // We need at least be consider at least 2 Ops to prune.
1692 if (NumLeftToConsider <= 1)
1694 auto CurNode = Worklist[i].first;
1695 auto CurOpNumber = Worklist[i].second;
1696 assert((OpWorkCount[CurOpNumber] > 0) &&
1697 "Node should not appear in worklist");
1698 switch (CurNode->getOpcode()) {
1699 case ISD::EntryToken:
1700 // Hitting EntryToken is the only way for the search to terminate without
1702 // another operand's search. Prevent us from marking this operand
1704 NumLeftToConsider++;
1706 case ISD::TokenFactor:
1707 for (const SDValue &Op : CurNode->op_values())
1708 AddToWorklist(i, Op.getNode(), CurOpNumber);
1710 case ISD::CopyFromReg:
1711 case ISD::CopyToReg:
1712 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1715 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1716 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1719 OpWorkCount[CurOpNumber]--;
1720 if (OpWorkCount[CurOpNumber] == 0)
1721 NumLeftToConsider--;
1726 // If we've changed things around then replace token factor.
1729 // The entry token is the only possible outcome.
1730 Result = DAG.getEntryNode();
1733 SmallVector<SDValue, 8> PrunedOps;
1735 for (const SDValue &Op : Ops) {
1736 if (SeenChains.count(Op.getNode()) == 0)
1737 PrunedOps.push_back(Op);
1739 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1741 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1745 // Add users to worklist, since we may introduce a lot of new
1746 // chained token factors while removing memory deps.
1747 return CombineTo(N, Result, true /*add to worklist*/);
1753 /// MERGE_VALUES can always be eliminated.
1754 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1755 WorklistRemover DeadNodes(*this);
1756 // Replacing results may cause a different MERGE_VALUES to suddenly
1757 // be CSE'd with N, and carry its uses with it. Iterate until no
1758 // uses remain, to ensure that the node can be safely deleted.
1759 // First add the users of this node to the work list so that they
1760 // can be tried again once they have new operands.
1761 AddUsersToWorklist(N);
1763 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1764 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1765 } while (!N->use_empty());
1766 deleteAndRecombine(N);
1767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1770 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1771 /// ConstantSDNode pointer else nullptr.
1772 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1773 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1774 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1777 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1778 auto BinOpcode = BO->getOpcode();
1779 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1780 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1781 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1782 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1783 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1784 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1785 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1786 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1787 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1788 "Unexpected binary operator");
1790 // Bail out if any constants are opaque because we can't constant fold those.
1791 SDValue C1 = BO->getOperand(1);
1792 if (!isConstantOrConstantVector(C1, true) &&
1793 !isConstantFPBuildVectorOrConstantFP(C1))
1796 // Don't do this unless the old select is going away. We want to eliminate the
1797 // binary operator, not replace a binop with a select.
1798 // TODO: Handle ISD::SELECT_CC.
1799 SDValue Sel = BO->getOperand(0);
1800 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1803 SDValue CT = Sel.getOperand(1);
1804 if (!isConstantOrConstantVector(CT, true) &&
1805 !isConstantFPBuildVectorOrConstantFP(CT))
1808 SDValue CF = Sel.getOperand(2);
1809 if (!isConstantOrConstantVector(CF, true) &&
1810 !isConstantFPBuildVectorOrConstantFP(CF))
1813 // We have a select-of-constants followed by a binary operator with a
1814 // constant. Eliminate the binop by pulling the constant math into the select.
1815 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1816 EVT VT = Sel.getValueType();
1818 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1819 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1820 isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1821 "Failed to constant fold a binop with constant operands");
1823 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1824 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1825 isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1826 "Failed to constant fold a binop with constant operands");
1828 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1831 SDValue DAGCombiner::visitADD(SDNode *N) {
1832 SDValue N0 = N->getOperand(0);
1833 SDValue N1 = N->getOperand(1);
1834 EVT VT = N0.getValueType();
1838 if (VT.isVector()) {
1839 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1842 // fold (add x, 0) -> x, vector edition
1843 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1845 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1849 // fold (add x, undef) -> undef
1856 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1857 // canonicalize constant to RHS
1858 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1859 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1860 // fold (add c1, c2) -> c1+c2
1861 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1865 // fold (add x, 0) -> x
1866 if (isNullConstant(N1))
1869 // fold ((c1-A)+c2) -> (c1+c2)-A
1870 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1871 if (N0.getOpcode() == ISD::SUB)
1872 if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1873 return DAG.getNode(ISD::SUB, DL, VT,
1874 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1879 if (SDValue NewSel = foldBinOpIntoSelect(N))
1883 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1886 // fold ((0-A) + B) -> B-A
1887 if (N0.getOpcode() == ISD::SUB &&
1888 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1889 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1891 // fold (A + (0-B)) -> A-B
1892 if (N1.getOpcode() == ISD::SUB &&
1893 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1894 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1896 // fold (A+(B-A)) -> B
1897 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1898 return N1.getOperand(0);
1900 // fold ((B-A)+A) -> B
1901 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1902 return N0.getOperand(0);
1904 // fold (A+(B-(A+C))) to (B-C)
1905 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1906 N0 == N1.getOperand(1).getOperand(0))
1907 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1908 N1.getOperand(1).getOperand(1));
1910 // fold (A+(B-(C+A))) to (B-C)
1911 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1912 N0 == N1.getOperand(1).getOperand(1))
1913 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1914 N1.getOperand(1).getOperand(0));
1916 // fold (A+((B-A)+or-C)) to (B+or-C)
1917 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1918 N1.getOperand(0).getOpcode() == ISD::SUB &&
1919 N0 == N1.getOperand(0).getOperand(1))
1920 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1923 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1924 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1925 SDValue N00 = N0.getOperand(0);
1926 SDValue N01 = N0.getOperand(1);
1927 SDValue N10 = N1.getOperand(0);
1928 SDValue N11 = N1.getOperand(1);
1930 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1931 return DAG.getNode(ISD::SUB, DL, VT,
1932 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1933 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1936 if (SimplifyDemandedBits(SDValue(N, 0)))
1937 return SDValue(N, 0);
1939 // fold (a+b) -> (a|b) iff a and b share no bits.
1940 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1941 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
1942 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1944 if (SDValue Combined = visitADDLike(N0, N1, N))
1947 if (SDValue Combined = visitADDLike(N1, N0, N))
1953 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
1954 EVT VT = N0.getValueType();
1955 SDLoc DL(LocReference);
1957 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1958 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1959 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
1960 return DAG.getNode(ISD::SUB, DL, VT, N0,
1961 DAG.getNode(ISD::SHL, DL, VT,
1962 N1.getOperand(0).getOperand(1),
1965 if (N1.getOpcode() == ISD::AND) {
1966 SDValue AndOp0 = N1.getOperand(0);
1967 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1968 unsigned DestBits = VT.getScalarSizeInBits();
1970 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1971 // and similar xforms where the inner op is either ~0 or 0.
1972 if (NumSignBits == DestBits &&
1973 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
1974 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
1977 // add (sext i1), X -> sub X, (zext i1)
1978 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1979 N0.getOperand(0).getValueType() == MVT::i1 &&
1980 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1981 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1982 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1985 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1986 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1987 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1988 if (TN->getVT() == MVT::i1) {
1989 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1990 DAG.getConstant(1, DL, VT));
1991 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1998 SDValue DAGCombiner::visitADDC(SDNode *N) {
1999 SDValue N0 = N->getOperand(0);
2000 SDValue N1 = N->getOperand(1);
2001 EVT VT = N0.getValueType();
2004 // If the flag result is dead, turn this into an ADD.
2005 if (!N->hasAnyUseOfValue(1))
2006 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2007 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2009 // canonicalize constant to RHS.
2010 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2011 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2013 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2015 // fold (addc x, 0) -> x + no carry out
2016 if (isNullConstant(N1))
2017 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2020 // If it cannot overflow, transform into an add.
2021 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2022 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2023 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2028 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 EVT VT = N0.getValueType();
2035 EVT CarryVT = N->getValueType(1);
2038 // If the flag result is dead, turn this into an ADD.
2039 if (!N->hasAnyUseOfValue(1))
2040 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2041 DAG.getUNDEF(CarryVT));
2043 // canonicalize constant to RHS.
2044 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2045 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2047 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2049 // fold (uaddo x, 0) -> x + no carry out
2050 if (isNullConstant(N1))
2051 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2053 // If it cannot overflow, transform into an add.
2054 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2055 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2056 DAG.getConstant(0, DL, CarryVT));
2061 SDValue DAGCombiner::visitADDE(SDNode *N) {
2062 SDValue N0 = N->getOperand(0);
2063 SDValue N1 = N->getOperand(1);
2064 SDValue CarryIn = N->getOperand(2);
2066 // canonicalize constant to RHS
2067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2070 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2073 // fold (adde x, y, false) -> (addc x, y)
2074 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2075 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2080 // Since it may not be valid to emit a fold to zero for vector initializers
2081 // check if we can before folding.
2082 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2083 SelectionDAG &DAG, bool LegalOperations,
2086 return DAG.getConstant(0, DL, VT);
2087 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2088 return DAG.getConstant(0, DL, VT);
2092 SDValue DAGCombiner::visitSUB(SDNode *N) {
2093 SDValue N0 = N->getOperand(0);
2094 SDValue N1 = N->getOperand(1);
2095 EVT VT = N0.getValueType();
2099 if (VT.isVector()) {
2100 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2103 // fold (sub x, 0) -> x, vector edition
2104 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2108 // fold (sub x, x) -> 0
2109 // FIXME: Refactor this and xor and other similar operations together.
2111 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2112 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2113 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2114 // fold (sub c1, c2) -> c1-c2
2115 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2119 if (SDValue NewSel = foldBinOpIntoSelect(N))
2122 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2124 // fold (sub x, c) -> (add x, -c)
2126 return DAG.getNode(ISD::ADD, DL, VT, N0,
2127 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2130 if (isNullConstantOrNullSplatConstant(N0)) {
2131 unsigned BitWidth = VT.getScalarSizeInBits();
2132 // Right-shifting everything out but the sign bit followed by negation is
2133 // the same as flipping arithmetic/logical shift type without the negation:
2134 // -(X >>u 31) -> (X >>s 31)
2135 // -(X >>s 31) -> (X >>u 31)
2136 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2137 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2138 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2139 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2140 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2141 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2145 // 0 - X --> 0 if the sub is NUW.
2146 if (N->getFlags()->hasNoUnsignedWrap())
2149 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2150 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2151 // N1 must be 0 because negating the minimum signed value is undefined.
2152 if (N->getFlags()->hasNoSignedWrap())
2155 // 0 - X --> X if X is 0 or the minimum signed value.
2160 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2161 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2162 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2164 // fold A-(A-B) -> B
2165 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2166 return N1.getOperand(1);
2168 // fold (A+B)-A -> B
2169 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2170 return N0.getOperand(1);
2172 // fold (A+B)-B -> A
2173 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2174 return N0.getOperand(0);
2176 // fold C2-(A+C1) -> (C2-C1)-A
2177 if (N1.getOpcode() == ISD::ADD) {
2178 SDValue N11 = N1.getOperand(1);
2179 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2180 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2181 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2182 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2186 // fold ((A+(B+or-C))-B) -> A+or-C
2187 if (N0.getOpcode() == ISD::ADD &&
2188 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2189 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2190 N0.getOperand(1).getOperand(0) == N1)
2191 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2192 N0.getOperand(1).getOperand(1));
2194 // fold ((A+(C+B))-B) -> A+C
2195 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2196 N0.getOperand(1).getOperand(1) == N1)
2197 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2198 N0.getOperand(1).getOperand(0));
2200 // fold ((A-(B-C))-C) -> A-B
2201 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2202 N0.getOperand(1).getOperand(1) == N1)
2203 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2204 N0.getOperand(1).getOperand(0));
2206 // If either operand of a sub is undef, the result is undef
2212 // If the relocation model supports it, consider symbol offsets.
2213 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2214 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2215 // fold (sub Sym, c) -> Sym-c
2216 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2217 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2219 (uint64_t)N1C->getSExtValue());
2220 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2221 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2222 if (GA->getGlobal() == GB->getGlobal())
2223 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2227 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2228 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2229 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2230 if (TN->getVT() == MVT::i1) {
2231 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2232 DAG.getConstant(1, DL, VT));
2233 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2240 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2241 SDValue N0 = N->getOperand(0);
2242 SDValue N1 = N->getOperand(1);
2243 EVT VT = N0.getValueType();
2246 // If the flag result is dead, turn this into an SUB.
2247 if (!N->hasAnyUseOfValue(1))
2248 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2249 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2251 // fold (subc x, x) -> 0 + no borrow
2253 return CombineTo(N, DAG.getConstant(0, DL, VT),
2254 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2256 // fold (subc x, 0) -> x + no borrow
2257 if (isNullConstant(N1))
2258 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2260 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2261 if (isAllOnesConstant(N0))
2262 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2263 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2268 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2269 SDValue N0 = N->getOperand(0);
2270 SDValue N1 = N->getOperand(1);
2271 EVT VT = N0.getValueType();
2275 EVT CarryVT = N->getValueType(1);
2278 // If the flag result is dead, turn this into an SUB.
2279 if (!N->hasAnyUseOfValue(1))
2280 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2281 DAG.getUNDEF(CarryVT));
2283 // fold (usubo x, x) -> 0 + no borrow
2285 return CombineTo(N, DAG.getConstant(0, DL, VT),
2286 DAG.getConstant(0, DL, CarryVT));
2288 // fold (usubo x, 0) -> x + no borrow
2289 if (isNullConstant(N1))
2290 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2292 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2293 if (isAllOnesConstant(N0))
2294 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2295 DAG.getConstant(0, DL, CarryVT));
2300 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2301 SDValue N0 = N->getOperand(0);
2302 SDValue N1 = N->getOperand(1);
2303 SDValue CarryIn = N->getOperand(2);
2305 // fold (sube x, y, false) -> (subc x, y)
2306 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2307 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2312 SDValue DAGCombiner::visitMUL(SDNode *N) {
2313 SDValue N0 = N->getOperand(0);
2314 SDValue N1 = N->getOperand(1);
2315 EVT VT = N0.getValueType();
2317 // fold (mul x, undef) -> 0
2318 if (N0.isUndef() || N1.isUndef())
2319 return DAG.getConstant(0, SDLoc(N), VT);
2321 bool N0IsConst = false;
2322 bool N1IsConst = false;
2323 bool N1IsOpaqueConst = false;
2324 bool N0IsOpaqueConst = false;
2325 APInt ConstValue0, ConstValue1;
2327 if (VT.isVector()) {
2328 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2331 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2332 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2334 N0IsConst = isa<ConstantSDNode>(N0);
2336 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2337 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2339 N1IsConst = isa<ConstantSDNode>(N1);
2341 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2342 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2346 // fold (mul c1, c2) -> c1*c2
2347 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2348 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2349 N0.getNode(), N1.getNode());
2351 // canonicalize constant to RHS (vector doesn't have to splat)
2352 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2353 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2354 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2355 // fold (mul x, 0) -> 0
2356 if (N1IsConst && ConstValue1 == 0)
2358 // We require a splat of the entire scalar bit width for non-contiguous
2361 ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2362 // fold (mul x, 1) -> x
2363 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2366 if (SDValue NewSel = foldBinOpIntoSelect(N))
2369 // fold (mul x, -1) -> 0-x
2370 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2372 return DAG.getNode(ISD::SUB, DL, VT,
2373 DAG.getConstant(0, DL, VT), N0);
2375 // fold (mul x, (1 << c)) -> x << c
2376 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2379 return DAG.getNode(ISD::SHL, DL, VT, N0,
2380 DAG.getConstant(ConstValue1.logBase2(), DL,
2381 getShiftAmountTy(N0.getValueType())));
2383 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2384 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2386 unsigned Log2Val = (-ConstValue1).logBase2();
2388 // FIXME: If the input is something that is easily negated (e.g. a
2389 // single-use add), we should put the negate there.
2390 return DAG.getNode(ISD::SUB, DL, VT,
2391 DAG.getConstant(0, DL, VT),
2392 DAG.getNode(ISD::SHL, DL, VT, N0,
2393 DAG.getConstant(Log2Val, DL,
2394 getShiftAmountTy(N0.getValueType()))));
2397 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2398 if (N0.getOpcode() == ISD::SHL &&
2399 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2400 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2401 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2402 if (isConstantOrConstantVector(C3))
2403 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2406 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2409 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2411 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2412 if (N0.getOpcode() == ISD::SHL &&
2413 isConstantOrConstantVector(N0.getOperand(1)) &&
2414 N0.getNode()->hasOneUse()) {
2416 } else if (N1.getOpcode() == ISD::SHL &&
2417 isConstantOrConstantVector(N1.getOperand(1)) &&
2418 N1.getNode()->hasOneUse()) {
2423 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2424 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2428 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2429 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2430 N0.getOpcode() == ISD::ADD &&
2431 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2432 isMulAddWithConstProfitable(N, N0, N1))
2433 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2434 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2435 N0.getOperand(0), N1),
2436 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2437 N0.getOperand(1), N1));
2440 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2446 /// Return true if divmod libcall is available.
2447 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2448 const TargetLowering &TLI) {
2450 EVT NodeType = Node->getValueType(0);
2451 if (!NodeType.isSimple())
2453 switch (NodeType.getSimpleVT().SimpleTy) {
2454 default: return false; // No libcall for vector types.
2455 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2456 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2457 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2458 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2459 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2462 return TLI.getLibcallName(LC) != nullptr;
2465 /// Issue divrem if both quotient and remainder are needed.
2466 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2467 if (Node->use_empty())
2468 return SDValue(); // This is a dead node, leave it alone.
2470 unsigned Opcode = Node->getOpcode();
2471 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2472 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2474 // DivMod lib calls can still work on non-legal types if using lib-calls.
2475 EVT VT = Node->getValueType(0);
2476 if (VT.isVector() || !VT.isInteger())
2479 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2482 // If DIVREM is going to get expanded into a libcall,
2483 // but there is no libcall available, then don't combine.
2484 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2485 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2488 // If div is legal, it's better to do the normal expansion
2489 unsigned OtherOpcode = 0;
2490 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2491 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2492 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2495 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2496 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2500 SDValue Op0 = Node->getOperand(0);
2501 SDValue Op1 = Node->getOperand(1);
2503 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2504 UE = Op0.getNode()->use_end(); UI != UE;) {
2505 SDNode *User = *UI++;
2506 if (User == Node || User->use_empty())
2508 // Convert the other matching node(s), too;
2509 // otherwise, the DIVREM may get target-legalized into something
2510 // target-specific that we won't be able to recognize.
2511 unsigned UserOpc = User->getOpcode();
2512 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2513 User->getOperand(0) == Op0 &&
2514 User->getOperand(1) == Op1) {
2516 if (UserOpc == OtherOpcode) {
2517 SDVTList VTs = DAG.getVTList(VT, VT);
2518 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2519 } else if (UserOpc == DivRemOpc) {
2520 combined = SDValue(User, 0);
2522 assert(UserOpc == Opcode);
2526 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2527 CombineTo(User, combined);
2528 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2529 CombineTo(User, combined.getValue(1));
2535 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2536 SDValue N0 = N->getOperand(0);
2537 SDValue N1 = N->getOperand(1);
2538 EVT VT = N->getValueType(0);
2541 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2542 return DAG.getUNDEF(VT);
2547 return DAG.getConstant(0, DL, VT);
2552 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2553 SDValue N0 = N->getOperand(0);
2554 SDValue N1 = N->getOperand(1);
2555 EVT VT = N->getValueType(0);
2559 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2564 // fold (sdiv c1, c2) -> c1/c2
2565 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2566 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2567 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2568 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2569 // fold (sdiv X, 1) -> X
2570 if (N1C && N1C->isOne())
2572 // fold (sdiv X, -1) -> 0-X
2573 if (N1C && N1C->isAllOnesValue())
2574 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2576 if (SDValue V = simplifyDivRem(N, DAG))
2579 if (SDValue NewSel = foldBinOpIntoSelect(N))
2582 // If we know the sign bits of both operands are zero, strength reduce to a
2583 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2584 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2585 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2587 // fold (sdiv X, pow2) -> simple ops after legalize
2588 // FIXME: We check for the exact bit here because the generic lowering gives
2589 // better results in that case. The target-specific lowering should learn how
2590 // to handle exact sdivs efficiently.
2591 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2592 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2593 (N1C->getAPIntValue().isPowerOf2() ||
2594 (-N1C->getAPIntValue()).isPowerOf2())) {
2595 // Target-specific implementation of sdiv x, pow2.
2596 if (SDValue Res = BuildSDIVPow2(N))
2599 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2601 // Splat the sign bit into the register
2603 DAG.getNode(ISD::SRA, DL, VT, N0,
2604 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2605 getShiftAmountTy(N0.getValueType())));
2606 AddToWorklist(SGN.getNode());
2608 // Add (N0 < 0) ? abs2 - 1 : 0;
2610 DAG.getNode(ISD::SRL, DL, VT, SGN,
2611 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2612 getShiftAmountTy(SGN.getValueType())));
2613 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2614 AddToWorklist(SRL.getNode());
2615 AddToWorklist(ADD.getNode()); // Divide by pow2
2616 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2617 DAG.getConstant(lg2, DL,
2618 getShiftAmountTy(ADD.getValueType())));
2620 // If we're dividing by a positive value, we're done. Otherwise, we must
2621 // negate the result.
2622 if (N1C->getAPIntValue().isNonNegative())
2625 AddToWorklist(SRA.getNode());
2626 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2629 // If integer divide is expensive and we satisfy the requirements, emit an
2630 // alternate sequence. Targets may check function attributes for size/speed
2632 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2633 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2634 if (SDValue Op = BuildSDIV(N))
2637 // sdiv, srem -> sdivrem
2638 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2639 // true. Otherwise, we break the simplification logic in visitREM().
2640 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2641 if (SDValue DivRem = useDivRem(N))
2647 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2648 SDValue N0 = N->getOperand(0);
2649 SDValue N1 = N->getOperand(1);
2650 EVT VT = N->getValueType(0);
2654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2659 // fold (udiv c1, c2) -> c1/c2
2660 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2661 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2663 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2667 if (SDValue V = simplifyDivRem(N, DAG))
2670 if (SDValue NewSel = foldBinOpIntoSelect(N))
2673 // fold (udiv x, (1 << c)) -> x >>u c
2674 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2675 DAG.isKnownToBeAPowerOfTwo(N1)) {
2676 SDValue LogBase2 = BuildLogBase2(N1, DL);
2677 AddToWorklist(LogBase2.getNode());
2679 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2680 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2681 AddToWorklist(Trunc.getNode());
2682 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2685 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2686 if (N1.getOpcode() == ISD::SHL) {
2687 SDValue N10 = N1.getOperand(0);
2688 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2689 DAG.isKnownToBeAPowerOfTwo(N10)) {
2690 SDValue LogBase2 = BuildLogBase2(N10, DL);
2691 AddToWorklist(LogBase2.getNode());
2693 EVT ADDVT = N1.getOperand(1).getValueType();
2694 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2695 AddToWorklist(Trunc.getNode());
2696 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2697 AddToWorklist(Add.getNode());
2698 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2702 // fold (udiv x, c) -> alternate
2703 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2704 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2705 if (SDValue Op = BuildUDIV(N))
2708 // sdiv, srem -> sdivrem
2709 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2710 // true. Otherwise, we break the simplification logic in visitREM().
2711 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2712 if (SDValue DivRem = useDivRem(N))
2718 // handles ISD::SREM and ISD::UREM
2719 SDValue DAGCombiner::visitREM(SDNode *N) {
2720 unsigned Opcode = N->getOpcode();
2721 SDValue N0 = N->getOperand(0);
2722 SDValue N1 = N->getOperand(1);
2723 EVT VT = N->getValueType(0);
2724 bool isSigned = (Opcode == ISD::SREM);
2727 // fold (rem c1, c2) -> c1%c2
2728 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2729 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2731 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2734 if (SDValue V = simplifyDivRem(N, DAG))
2737 if (SDValue NewSel = foldBinOpIntoSelect(N))
2741 // If we know the sign bits of both operands are zero, strength reduce to a
2742 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2743 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2744 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2746 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2747 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2748 // fold (urem x, pow2) -> (and x, pow2-1)
2749 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2750 AddToWorklist(Add.getNode());
2751 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2753 if (N1.getOpcode() == ISD::SHL &&
2754 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2755 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2756 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2757 AddToWorklist(Add.getNode());
2758 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2762 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2764 // If X/C can be simplified by the division-by-constant logic, lower
2765 // X%C to the equivalent of X-X/C*C.
2766 // To avoid mangling nodes, this simplification requires that the combine()
2767 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2768 // against this by skipping the simplification if isIntDivCheap(). When
2769 // div is not cheap, combine will not return a DIVREM. Regardless,
2770 // checking cheapness here makes sense since the simplification results in
2772 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2773 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2774 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2775 AddToWorklist(Div.getNode());
2776 SDValue OptimizedDiv = combine(Div.getNode());
2777 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2778 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2779 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2780 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2781 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2782 AddToWorklist(Mul.getNode());
2787 // sdiv, srem -> sdivrem
2788 if (SDValue DivRem = useDivRem(N))
2789 return DivRem.getValue(1);
2794 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2795 SDValue N0 = N->getOperand(0);
2796 SDValue N1 = N->getOperand(1);
2797 EVT VT = N->getValueType(0);
2800 // fold (mulhs x, 0) -> 0
2801 if (isNullConstant(N1))
2803 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2804 if (isOneConstant(N1)) {
2806 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2807 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
2808 getShiftAmountTy(N0.getValueType())));
2810 // fold (mulhs x, undef) -> 0
2811 if (N0.isUndef() || N1.isUndef())
2812 return DAG.getConstant(0, SDLoc(N), VT);
2814 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2816 if (VT.isSimple() && !VT.isVector()) {
2817 MVT Simple = VT.getSimpleVT();
2818 unsigned SimpleSize = Simple.getSizeInBits();
2819 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2820 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2821 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2822 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2823 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2824 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2825 DAG.getConstant(SimpleSize, DL,
2826 getShiftAmountTy(N1.getValueType())));
2827 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2834 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2835 SDValue N0 = N->getOperand(0);
2836 SDValue N1 = N->getOperand(1);
2837 EVT VT = N->getValueType(0);
2840 // fold (mulhu x, 0) -> 0
2841 if (isNullConstant(N1))
2843 // fold (mulhu x, 1) -> 0
2844 if (isOneConstant(N1))
2845 return DAG.getConstant(0, DL, N0.getValueType());
2846 // fold (mulhu x, undef) -> 0
2847 if (N0.isUndef() || N1.isUndef())
2848 return DAG.getConstant(0, DL, VT);
2850 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2852 if (VT.isSimple() && !VT.isVector()) {
2853 MVT Simple = VT.getSimpleVT();
2854 unsigned SimpleSize = Simple.getSizeInBits();
2855 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2856 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2857 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2858 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2859 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2860 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2861 DAG.getConstant(SimpleSize, DL,
2862 getShiftAmountTy(N1.getValueType())));
2863 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2870 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2871 /// give the opcodes for the two computations that are being performed. Return
2872 /// true if a simplification was made.
2873 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2875 // If the high half is not needed, just compute the low half.
2876 bool HiExists = N->hasAnyUseOfValue(1);
2878 (!LegalOperations ||
2879 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2880 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2881 return CombineTo(N, Res, Res);
2884 // If the low half is not needed, just compute the high half.
2885 bool LoExists = N->hasAnyUseOfValue(0);
2887 (!LegalOperations ||
2888 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2889 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2890 return CombineTo(N, Res, Res);
2893 // If both halves are used, return as it is.
2894 if (LoExists && HiExists)
2897 // If the two computed results can be simplified separately, separate them.
2899 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2900 AddToWorklist(Lo.getNode());
2901 SDValue LoOpt = combine(Lo.getNode());
2902 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2903 (!LegalOperations ||
2904 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2905 return CombineTo(N, LoOpt, LoOpt);
2909 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2910 AddToWorklist(Hi.getNode());
2911 SDValue HiOpt = combine(Hi.getNode());
2912 if (HiOpt.getNode() && HiOpt != Hi &&
2913 (!LegalOperations ||
2914 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2915 return CombineTo(N, HiOpt, HiOpt);
2921 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2922 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2925 EVT VT = N->getValueType(0);
2928 // If the type is twice as wide is legal, transform the mulhu to a wider
2929 // multiply plus a shift.
2930 if (VT.isSimple() && !VT.isVector()) {
2931 MVT Simple = VT.getSimpleVT();
2932 unsigned SimpleSize = Simple.getSizeInBits();
2933 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2934 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2935 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2936 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2937 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2938 // Compute the high part as N1.
2939 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2940 DAG.getConstant(SimpleSize, DL,
2941 getShiftAmountTy(Lo.getValueType())));
2942 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2943 // Compute the low part as N0.
2944 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2945 return CombineTo(N, Lo, Hi);
2952 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2953 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2956 EVT VT = N->getValueType(0);
2959 // If the type is twice as wide is legal, transform the mulhu to a wider
2960 // multiply plus a shift.
2961 if (VT.isSimple() && !VT.isVector()) {
2962 MVT Simple = VT.getSimpleVT();
2963 unsigned SimpleSize = Simple.getSizeInBits();
2964 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2965 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2966 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2967 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2968 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2969 // Compute the high part as N1.
2970 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2971 DAG.getConstant(SimpleSize, DL,
2972 getShiftAmountTy(Lo.getValueType())));
2973 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2974 // Compute the low part as N0.
2975 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2976 return CombineTo(N, Lo, Hi);
2983 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2984 // (smulo x, 2) -> (saddo x, x)
2985 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2986 if (C2->getAPIntValue() == 2)
2987 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2988 N->getOperand(0), N->getOperand(0));
2993 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2994 // (umulo x, 2) -> (uaddo x, x)
2995 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2996 if (C2->getAPIntValue() == 2)
2997 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2998 N->getOperand(0), N->getOperand(0));
3003 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3004 SDValue N0 = N->getOperand(0);
3005 SDValue N1 = N->getOperand(1);
3006 EVT VT = N0.getValueType();
3010 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3013 // fold (add c1, c2) -> c1+c2
3014 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3015 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3017 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3019 // canonicalize constant to RHS
3020 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3021 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3022 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3027 /// If this is a binary operator with two operands of the same opcode, try to
3029 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3030 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3031 EVT VT = N0.getValueType();
3032 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3034 // Bail early if none of these transforms apply.
3035 if (N0.getNumOperands() == 0) return SDValue();
3037 // For each of OP in AND/OR/XOR:
3038 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3039 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3040 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3041 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3042 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3044 // do not sink logical op inside of a vector extend, since it may combine
3046 EVT Op0VT = N0.getOperand(0).getValueType();
3047 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3048 N0.getOpcode() == ISD::SIGN_EXTEND ||
3049 N0.getOpcode() == ISD::BSWAP ||
3050 // Avoid infinite looping with PromoteIntBinOp.
3051 (N0.getOpcode() == ISD::ANY_EXTEND &&
3052 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3053 (N0.getOpcode() == ISD::TRUNCATE &&
3054 (!TLI.isZExtFree(VT, Op0VT) ||
3055 !TLI.isTruncateFree(Op0VT, VT)) &&
3056 TLI.isTypeLegal(Op0VT))) &&
3058 Op0VT == N1.getOperand(0).getValueType() &&
3059 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3060 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3061 N0.getOperand(0).getValueType(),
3062 N0.getOperand(0), N1.getOperand(0));
3063 AddToWorklist(ORNode.getNode());
3064 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3067 // For each of OP in SHL/SRL/SRA/AND...
3068 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3069 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3070 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3071 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3072 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3073 N0.getOperand(1) == N1.getOperand(1)) {
3074 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3075 N0.getOperand(0).getValueType(),
3076 N0.getOperand(0), N1.getOperand(0));
3077 AddToWorklist(ORNode.getNode());
3078 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3079 ORNode, N0.getOperand(1));
3082 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3083 // Only perform this optimization up until type legalization, before
3084 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3085 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3086 // we don't want to undo this promotion.
3087 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3089 if ((N0.getOpcode() == ISD::BITCAST ||
3090 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3091 Level <= AfterLegalizeTypes) {
3092 SDValue In0 = N0.getOperand(0);
3093 SDValue In1 = N1.getOperand(0);
3094 EVT In0Ty = In0.getValueType();
3095 EVT In1Ty = In1.getValueType();
3097 // If both incoming values are integers, and the original types are the
3099 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3100 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3101 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3102 AddToWorklist(Op.getNode());
3107 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3108 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3109 // If both shuffles use the same mask, and both shuffle within a single
3110 // vector, then it is worthwhile to move the swizzle after the operation.
3111 // The type-legalizer generates this pattern when loading illegal
3112 // vector types from memory. In many cases this allows additional shuffle
3114 // There are other cases where moving the shuffle after the xor/and/or
3115 // is profitable even if shuffles don't perform a swizzle.
3116 // If both shuffles use the same mask, and both shuffles have the same first
3117 // or second operand, then it might still be profitable to move the shuffle
3118 // after the xor/and/or operation.
3119 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3120 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3121 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3123 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3124 "Inputs to shuffles are not the same type");
3126 // Check that both shuffles use the same mask. The masks are known to be of
3127 // the same length because the result vector type is the same.
3128 // Check also that shuffles have only one use to avoid introducing extra
3130 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3131 SVN0->getMask().equals(SVN1->getMask())) {
3132 SDValue ShOp = N0->getOperand(1);
3134 // Don't try to fold this node if it requires introducing a
3135 // build vector of all zeros that might be illegal at this stage.
3136 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3138 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3143 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3144 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3145 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3146 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3147 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3148 N0->getOperand(0), N1->getOperand(0));
3149 AddToWorklist(NewNode.getNode());
3150 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3154 // Don't try to fold this node if it requires introducing a
3155 // build vector of all zeros that might be illegal at this stage.
3156 ShOp = N0->getOperand(0);
3157 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3159 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3164 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3165 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3166 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3167 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3168 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3169 N0->getOperand(1), N1->getOperand(1));
3170 AddToWorklist(NewNode.getNode());
3171 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3180 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3181 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3183 SDValue LL, LR, RL, RR, N0CC, N1CC;
3184 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3185 !isSetCCEquivalent(N1, RL, RR, N1CC))
3188 assert(N0.getValueType() == N1.getValueType() &&
3189 "Unexpected operand types for bitwise logic op");
3190 assert(LL.getValueType() == LR.getValueType() &&
3191 RL.getValueType() == RR.getValueType() &&
3192 "Unexpected operand types for setcc");
3194 // If we're here post-legalization or the logic op type is not i1, the logic
3195 // op type must match a setcc result type. Also, all folds require new
3196 // operations on the left and right operands, so those types must match.
3197 EVT VT = N0.getValueType();
3198 EVT OpVT = LL.getValueType();
3199 if (LegalOperations || VT != MVT::i1)
3200 if (VT != getSetCCResultType(OpVT))
3202 if (OpVT != RL.getValueType())
3205 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3206 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3207 bool IsInteger = OpVT.isInteger();
3208 if (LR == RR && CC0 == CC1 && IsInteger) {
3209 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3210 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3213 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3214 // All sign bits clear?
3215 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3217 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3218 // Any sign bits set?
3219 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3221 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3222 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3223 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3224 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3225 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3226 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3227 AddToWorklist(Or.getNode());
3228 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3232 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3233 // All sign bits set?
3234 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3236 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3237 // Any sign bits clear?
3238 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3240 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3241 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3242 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3243 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3244 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3245 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3246 AddToWorklist(And.getNode());
3247 return DAG.getSetCC(DL, VT, And, LR, CC1);
3251 // TODO: What is the 'or' equivalent of this fold?
3252 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3253 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3254 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3255 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3256 SDValue One = DAG.getConstant(1, DL, OpVT);
3257 SDValue Two = DAG.getConstant(2, DL, OpVT);
3258 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3259 AddToWorklist(Add.getNode());
3260 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3263 // Try more general transforms if the predicates match and the only user of
3264 // the compares is the 'and' or 'or'.
3265 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3266 N0.hasOneUse() && N1.hasOneUse()) {
3267 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3268 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3269 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3270 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3271 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3272 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3273 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3274 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3278 // Canonicalize equivalent operands to LL == RL.
3279 if (LL == RR && LR == RL) {
3280 CC1 = ISD::getSetCCSwappedOperands(CC1);
3284 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3285 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3286 if (LL == RL && LR == RR) {
3287 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3288 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3289 if (NewCC != ISD::SETCC_INVALID &&
3290 (!LegalOperations ||
3291 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3292 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3293 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3299 /// This contains all DAGCombine rules which reduce two values combined by
3300 /// an And operation to a single value. This makes them reusable in the context
3301 /// of visitSELECT(). Rules involving constants are not included as
3302 /// visitSELECT() already handles those cases.
3303 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3304 EVT VT = N1.getValueType();
3307 // fold (and x, undef) -> 0
3308 if (N0.isUndef() || N1.isUndef())
3309 return DAG.getConstant(0, DL, VT);
3311 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3314 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3315 VT.getSizeInBits() <= 64) {
3316 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3317 APInt ADDC = ADDI->getAPIntValue();
3318 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3319 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3320 // immediate for an add, but it is legal if its top c2 bits are set,
3321 // transform the ADD so the immediate doesn't need to be materialized
3323 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3324 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3325 SRLI->getZExtValue());
3326 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3328 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3331 DAG.getNode(ISD::ADD, DL0, VT,
3332 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3333 CombineTo(N0.getNode(), NewAdd);
3334 // Return N so it doesn't get rechecked!
3335 return SDValue(N, 0);
3343 // Reduce bit extract of low half of an integer to the narrower type.
3344 // (and (srl i64:x, K), KMask) ->
3345 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3346 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3347 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3348 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3349 unsigned Size = VT.getSizeInBits();
3350 const APInt &AndMask = CAnd->getAPIntValue();
3351 unsigned ShiftBits = CShift->getZExtValue();
3353 // Bail out, this node will probably disappear anyway.
3357 unsigned MaskBits = AndMask.countTrailingOnes();
3358 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3360 if (AndMask.isMask() &&
3361 // Required bits must not span the two halves of the integer and
3362 // must fit in the half size type.
3363 (ShiftBits + MaskBits <= Size / 2) &&
3364 TLI.isNarrowingProfitable(VT, HalfVT) &&
3365 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3366 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3367 TLI.isTruncateFree(VT, HalfVT) &&
3368 TLI.isZExtFree(HalfVT, VT)) {
3369 // The isNarrowingProfitable is to avoid regressions on PPC and
3370 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3371 // on downstream users of this. Those patterns could probably be
3372 // extended to handle extensions mixed in.
3375 assert(MaskBits <= Size);
3377 // Extracting the highest bit of the low half.
3378 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3379 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3382 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3383 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3384 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3385 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3386 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3395 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3396 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3398 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3400 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3403 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3404 LoadedVT = LoadN->getMemoryVT();
3406 if (ExtVT == LoadedVT &&
3407 (!LegalOperations ||
3408 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3409 // ZEXTLOAD will match without needing to change the size of the value being
3415 // Do not change the width of a volatile load.
3416 if (LoadN->isVolatile())
3419 // Do not generate loads of non-round integer types since these can
3420 // be expensive (and would be wrong if the type is not byte sized).
3421 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3424 if (LegalOperations &&
3425 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3428 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3435 SDValue DAGCombiner::visitAND(SDNode *N) {
3436 SDValue N0 = N->getOperand(0);
3437 SDValue N1 = N->getOperand(1);
3438 EVT VT = N1.getValueType();
3445 if (VT.isVector()) {
3446 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3449 // fold (and x, 0) -> 0, vector edition
3450 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3451 // do not return N0, because undef node may exist in N0
3452 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3453 SDLoc(N), N0.getValueType());
3454 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3455 // do not return N1, because undef node may exist in N1
3456 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3457 SDLoc(N), N1.getValueType());
3459 // fold (and x, -1) -> x, vector edition
3460 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3462 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3466 // fold (and c1, c2) -> c1&c2
3467 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3468 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3469 if (N0C && N1C && !N1C->isOpaque())
3470 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3471 // canonicalize constant to RHS
3472 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3473 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3474 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3475 // fold (and x, -1) -> x
3476 if (isAllOnesConstant(N1))
3478 // if (and x, c) is known to be zero, return 0
3479 unsigned BitWidth = VT.getScalarSizeInBits();
3480 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3481 APInt::getAllOnesValue(BitWidth)))
3482 return DAG.getConstant(0, SDLoc(N), VT);
3484 if (SDValue NewSel = foldBinOpIntoSelect(N))
3488 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3490 // fold (and (or x, C), D) -> D if (C & D) == D
3491 if (N1C && N0.getOpcode() == ISD::OR)
3492 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3493 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3495 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3496 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3497 SDValue N0Op0 = N0.getOperand(0);
3498 APInt Mask = ~N1C->getAPIntValue();
3499 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3500 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3501 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3502 N0.getValueType(), N0Op0);
3504 // Replace uses of the AND with uses of the Zero extend node.
3507 // We actually want to replace all uses of the any_extend with the
3508 // zero_extend, to avoid duplicating things. This will later cause this
3509 // AND to be folded.
3510 CombineTo(N0.getNode(), Zext);
3511 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3514 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3515 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3516 // already be zero by virtue of the width of the base type of the load.
3518 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3520 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3521 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3522 N0.getOperand(0).getOpcode() == ISD::LOAD &&
3523 N0.getOperand(0).getResNo() == 0) ||
3524 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3525 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3526 N0 : N0.getOperand(0) );
3528 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3529 // This can be a pure constant or a vector splat, in which case we treat the
3530 // vector as a scalar and use the splat value.
3531 APInt Constant = APInt::getNullValue(1);
3532 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3533 Constant = C->getAPIntValue();
3534 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3535 APInt SplatValue, SplatUndef;
3536 unsigned SplatBitSize;
3538 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3539 SplatBitSize, HasAnyUndefs);
3541 // Undef bits can contribute to a possible optimisation if set, so
3543 SplatValue |= SplatUndef;
3545 // The splat value may be something like "0x00FFFFFF", which means 0 for
3546 // the first vector value and FF for the rest, repeating. We need a mask
3547 // that will apply equally to all members of the vector, so AND all the
3548 // lanes of the constant together.
3549 EVT VT = Vector->getValueType(0);
3550 unsigned BitWidth = VT.getScalarSizeInBits();
3552 // If the splat value has been compressed to a bitlength lower
3553 // than the size of the vector lane, we need to re-expand it to
3555 if (BitWidth > SplatBitSize)
3556 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3557 SplatBitSize < BitWidth;
3558 SplatBitSize = SplatBitSize * 2)
3559 SplatValue |= SplatValue.shl(SplatBitSize);
3561 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3562 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3563 if (SplatBitSize % BitWidth == 0) {
3564 Constant = APInt::getAllOnesValue(BitWidth);
3565 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3566 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3571 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3572 // actually legal and isn't going to get expanded, else this is a false
3574 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3575 Load->getValueType(0),
3576 Load->getMemoryVT());
3578 // Resize the constant to the same size as the original memory access before
3579 // extension. If it is still the AllOnesValue then this AND is completely
3581 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3584 switch (Load->getExtensionType()) {
3585 default: B = false; break;
3586 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3588 case ISD::NON_EXTLOAD: B = true; break;
3591 if (B && Constant.isAllOnesValue()) {
3592 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3593 // preserve semantics once we get rid of the AND.
3594 SDValue NewLoad(Load, 0);
3596 // Fold the AND away. NewLoad may get replaced immediately.
3597 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3599 if (Load->getExtensionType() == ISD::EXTLOAD) {
3600 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3601 Load->getValueType(0), SDLoc(Load),
3602 Load->getChain(), Load->getBasePtr(),
3603 Load->getOffset(), Load->getMemoryVT(),
3604 Load->getMemOperand());
3605 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3606 if (Load->getNumValues() == 3) {
3607 // PRE/POST_INC loads have 3 values.
3608 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3609 NewLoad.getValue(2) };
3610 CombineTo(Load, To, 3, true);
3612 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3616 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3620 // fold (and (load x), 255) -> (zextload x, i8)
3621 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3622 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3623 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3624 (N0.getOpcode() == ISD::ANY_EXTEND &&
3625 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3626 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3627 LoadSDNode *LN0 = HasAnyExt
3628 ? cast<LoadSDNode>(N0.getOperand(0))
3629 : cast<LoadSDNode>(N0);
3630 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3631 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3632 auto NarrowLoad = false;
3633 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3634 EVT ExtVT, LoadedVT;
3635 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3639 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3640 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3641 LN0->getMemOperand());
3643 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3644 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3646 EVT PtrType = LN0->getOperand(1).getValueType();
3648 unsigned Alignment = LN0->getAlignment();
3649 SDValue NewPtr = LN0->getBasePtr();
3651 // For big endian targets, we need to add an offset to the pointer
3652 // to load the correct bytes. For little endian systems, we merely
3653 // need to read fewer bytes from the same pointer.
3654 if (DAG.getDataLayout().isBigEndian()) {
3655 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3656 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3657 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3659 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3660 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3661 Alignment = MinAlign(Alignment, PtrOff);
3664 AddToWorklist(NewPtr.getNode());
3666 SDValue Load = DAG.getExtLoad(
3667 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3668 LN0->getPointerInfo(), ExtVT, Alignment,
3669 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3671 CombineTo(LN0, Load, Load.getValue(1));
3672 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3678 if (SDValue Combined = visitANDLike(N0, N1, N))
3681 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3682 if (N0.getOpcode() == N1.getOpcode())
3683 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3686 // Masking the negated extension of a boolean is just the zero-extended
3688 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3689 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3691 // Note: the SimplifyDemandedBits fold below can make an information-losing
3692 // transform, and then we have no way to find this better fold.
3693 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3694 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
3695 SDValue SubRHS = N0.getOperand(1);
3696 if (SubLHS && SubLHS->isNullValue()) {
3697 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3698 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3700 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3701 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3702 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3706 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3707 // fold (and (sra)) -> (and (srl)) when possible.
3708 if (SimplifyDemandedBits(SDValue(N, 0)))
3709 return SDValue(N, 0);
3711 // fold (zext_inreg (extload x)) -> (zextload x)
3712 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3713 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3714 EVT MemVT = LN0->getMemoryVT();
3715 // If we zero all the possible extended bits, then we can turn this into
3716 // a zextload if we are running before legalize or the operation is legal.
3717 unsigned BitWidth = N1.getScalarValueSizeInBits();
3718 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3719 BitWidth - MemVT.getScalarSizeInBits())) &&
3720 ((!LegalOperations && !LN0->isVolatile()) ||
3721 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3722 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3723 LN0->getChain(), LN0->getBasePtr(),
3724 MemVT, LN0->getMemOperand());
3726 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3727 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3730 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3731 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3733 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3734 EVT MemVT = LN0->getMemoryVT();
3735 // If we zero all the possible extended bits, then we can turn this into
3736 // a zextload if we are running before legalize or the operation is legal.
3737 unsigned BitWidth = N1.getScalarValueSizeInBits();
3738 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3739 BitWidth - MemVT.getScalarSizeInBits())) &&
3740 ((!LegalOperations && !LN0->isVolatile()) ||
3741 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3742 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3743 LN0->getChain(), LN0->getBasePtr(),
3744 MemVT, LN0->getMemOperand());
3746 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3747 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3750 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3751 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3752 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3753 N0.getOperand(1), false))
3760 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3761 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3762 bool DemandHighBits) {
3763 if (!LegalOperations)
3766 EVT VT = N->getValueType(0);
3767 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3769 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3772 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3773 bool LookPassAnd0 = false;
3774 bool LookPassAnd1 = false;
3775 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3777 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3779 if (N0.getOpcode() == ISD::AND) {
3780 if (!N0.getNode()->hasOneUse())
3782 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3783 if (!N01C || N01C->getZExtValue() != 0xFF00)
3785 N0 = N0.getOperand(0);
3786 LookPassAnd0 = true;
3789 if (N1.getOpcode() == ISD::AND) {
3790 if (!N1.getNode()->hasOneUse())
3792 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3793 if (!N11C || N11C->getZExtValue() != 0xFF)
3795 N1 = N1.getOperand(0);
3796 LookPassAnd1 = true;
3799 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3801 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3803 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
3806 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3807 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3810 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3813 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3814 SDValue N00 = N0->getOperand(0);
3815 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3816 if (!N00.getNode()->hasOneUse())
3818 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3819 if (!N001C || N001C->getZExtValue() != 0xFF)
3821 N00 = N00.getOperand(0);
3822 LookPassAnd0 = true;
3825 SDValue N10 = N1->getOperand(0);
3826 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3827 if (!N10.getNode()->hasOneUse())
3829 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3830 if (!N101C || N101C->getZExtValue() != 0xFF00)
3832 N10 = N10.getOperand(0);
3833 LookPassAnd1 = true;
3839 // Make sure everything beyond the low halfword gets set to zero since the SRL
3840 // 16 will clear the top bits.
3841 unsigned OpSizeInBits = VT.getSizeInBits();
3842 if (DemandHighBits && OpSizeInBits > 16) {
3843 // If the left-shift isn't masked out then the only way this is a bswap is
3844 // if all bits beyond the low 8 are 0. In that case the entire pattern
3845 // reduces to a left shift anyway: leave it for other parts of the combiner.
3849 // However, if the right shift isn't masked out then it might be because
3850 // it's not needed. See if we can spot that too.
3851 if (!LookPassAnd1 &&
3852 !DAG.MaskedValueIsZero(
3853 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3857 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3858 if (OpSizeInBits > 16) {
3860 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3861 DAG.getConstant(OpSizeInBits - 16, DL,
3862 getShiftAmountTy(VT)));
3867 /// Return true if the specified node is an element that makes up a 32-bit
3868 /// packed halfword byteswap.
3869 /// ((x & 0x000000ff) << 8) |
3870 /// ((x & 0x0000ff00) >> 8) |
3871 /// ((x & 0x00ff0000) << 8) |
3872 /// ((x & 0xff000000) >> 8)
3873 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3874 if (!N.getNode()->hasOneUse())
3877 unsigned Opc = N.getOpcode();
3878 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3881 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3886 switch (N1C->getZExtValue()) {
3889 case 0xFF: Num = 0; break;
3890 case 0xFF00: Num = 1; break;
3891 case 0xFF0000: Num = 2; break;
3892 case 0xFF000000: Num = 3; break;
3895 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3896 SDValue N0 = N.getOperand(0);
3897 if (Opc == ISD::AND) {
3898 if (Num == 0 || Num == 2) {
3900 // (x >> 8) & 0xff0000
3901 if (N0.getOpcode() != ISD::SRL)
3903 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904 if (!C || C->getZExtValue() != 8)
3907 // (x << 8) & 0xff00
3908 // (x << 8) & 0xff000000
3909 if (N0.getOpcode() != ISD::SHL)
3911 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3912 if (!C || C->getZExtValue() != 8)
3915 } else if (Opc == ISD::SHL) {
3917 // (x & 0xff0000) << 8
3918 if (Num != 0 && Num != 2)
3920 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3921 if (!C || C->getZExtValue() != 8)
3923 } else { // Opc == ISD::SRL
3924 // (x & 0xff00) >> 8
3925 // (x & 0xff000000) >> 8
3926 if (Num != 1 && Num != 3)
3928 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3929 if (!C || C->getZExtValue() != 8)
3936 Parts[Num] = N0.getOperand(0).getNode();
3940 /// Match a 32-bit packed halfword bswap. That is
3941 /// ((x & 0x000000ff) << 8) |
3942 /// ((x & 0x0000ff00) >> 8) |
3943 /// ((x & 0x00ff0000) << 8) |
3944 /// ((x & 0xff000000) >> 8)
3945 /// => (rotl (bswap x), 16)
3946 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3947 if (!LegalOperations)
3950 EVT VT = N->getValueType(0);
3953 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3957 // (or (or (and), (and)), (or (and), (and)))
3958 // (or (or (or (and), (and)), (and)), (and))
3959 if (N0.getOpcode() != ISD::OR)
3961 SDValue N00 = N0.getOperand(0);
3962 SDValue N01 = N0.getOperand(1);
3963 SDNode *Parts[4] = {};
3965 if (N1.getOpcode() == ISD::OR &&
3966 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3967 // (or (or (and), (and)), (or (and), (and)))
3968 SDValue N000 = N00.getOperand(0);
3969 if (!isBSwapHWordElement(N000, Parts))
3972 SDValue N001 = N00.getOperand(1);
3973 if (!isBSwapHWordElement(N001, Parts))
3975 SDValue N010 = N01.getOperand(0);
3976 if (!isBSwapHWordElement(N010, Parts))
3978 SDValue N011 = N01.getOperand(1);
3979 if (!isBSwapHWordElement(N011, Parts))
3982 // (or (or (or (and), (and)), (and)), (and))
3983 if (!isBSwapHWordElement(N1, Parts))
3985 if (!isBSwapHWordElement(N01, Parts))
3987 if (N00.getOpcode() != ISD::OR)
3989 SDValue N000 = N00.getOperand(0);
3990 if (!isBSwapHWordElement(N000, Parts))
3992 SDValue N001 = N00.getOperand(1);
3993 if (!isBSwapHWordElement(N001, Parts))
3997 // Make sure the parts are all coming from the same node.
3998 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4002 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4003 SDValue(Parts[0], 0));
4005 // Result of the bswap should be rotated by 16. If it's not legal, then
4006 // do (x << 16) | (x >> 16).
4007 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4008 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4009 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4010 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4011 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4012 return DAG.getNode(ISD::OR, DL, VT,
4013 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4014 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4017 /// This contains all DAGCombine rules which reduce two values combined by
4018 /// an Or operation to a single value \see visitANDLike().
4019 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4020 EVT VT = N1.getValueType();
4023 // fold (or x, undef) -> -1
4024 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4025 return DAG.getAllOnesConstant(DL, VT);
4027 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4030 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4031 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4032 // Don't increase # computations.
4033 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4034 // We can only do this xform if we know that bits from X that are set in C2
4035 // but not in C1 are already zero. Likewise for Y.
4036 if (const ConstantSDNode *N0O1C =
4037 getAsNonOpaqueConstant(N0.getOperand(1))) {
4038 if (const ConstantSDNode *N1O1C =
4039 getAsNonOpaqueConstant(N1.getOperand(1))) {
4040 // We can only do this xform if we know that bits from X that are set in
4041 // C2 but not in C1 are already zero. Likewise for Y.
4042 const APInt &LHSMask = N0O1C->getAPIntValue();
4043 const APInt &RHSMask = N1O1C->getAPIntValue();
4045 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4046 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4047 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4048 N0.getOperand(0), N1.getOperand(0));
4049 return DAG.getNode(ISD::AND, DL, VT, X,
4050 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4056 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4057 if (N0.getOpcode() == ISD::AND &&
4058 N1.getOpcode() == ISD::AND &&
4059 N0.getOperand(0) == N1.getOperand(0) &&
4060 // Don't increase # computations.
4061 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4062 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4063 N0.getOperand(1), N1.getOperand(1));
4064 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4070 SDValue DAGCombiner::visitOR(SDNode *N) {
4071 SDValue N0 = N->getOperand(0);
4072 SDValue N1 = N->getOperand(1);
4073 EVT VT = N1.getValueType();
4080 if (VT.isVector()) {
4081 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4084 // fold (or x, 0) -> x, vector edition
4085 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4087 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4090 // fold (or x, -1) -> -1, vector edition
4091 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4092 // do not return N0, because undef node may exist in N0
4093 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4094 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4095 // do not return N1, because undef node may exist in N1
4096 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4098 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4099 // Do this only if the resulting shuffle is legal.
4100 if (isa<ShuffleVectorSDNode>(N0) &&
4101 isa<ShuffleVectorSDNode>(N1) &&
4102 // Avoid folding a node with illegal type.
4103 TLI.isTypeLegal(VT)) {
4104 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4105 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4106 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4107 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4108 // Ensure both shuffles have a zero input.
4109 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4110 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4111 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4112 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4113 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4114 bool CanFold = true;
4115 int NumElts = VT.getVectorNumElements();
4116 SmallVector<int, 4> Mask(NumElts);
4118 for (int i = 0; i != NumElts; ++i) {
4119 int M0 = SV0->getMaskElt(i);
4120 int M1 = SV1->getMaskElt(i);
4122 // Determine if either index is pointing to a zero vector.
4123 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4124 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4126 // If one element is zero and the otherside is undef, keep undef.
4127 // This also handles the case that both are undef.
4128 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4133 // Make sure only one of the elements is zero.
4134 if (M0Zero == M1Zero) {
4139 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4141 // We have a zero and non-zero element. If the non-zero came from
4142 // SV0 make the index a LHS index. If it came from SV1, make it
4143 // a RHS index. We need to mod by NumElts because we don't care
4144 // which operand it came from in the original shuffles.
4145 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4149 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4150 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4152 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4154 std::swap(NewLHS, NewRHS);
4155 ShuffleVectorSDNode::commuteMask(Mask);
4156 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4160 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4166 // fold (or c1, c2) -> c1|c2
4167 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4168 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4169 if (N0C && N1C && !N1C->isOpaque())
4170 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4171 // canonicalize constant to RHS
4172 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4173 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4174 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4175 // fold (or x, 0) -> x
4176 if (isNullConstant(N1))
4178 // fold (or x, -1) -> -1
4179 if (isAllOnesConstant(N1))
4182 if (SDValue NewSel = foldBinOpIntoSelect(N))
4185 // fold (or x, c) -> c iff (x & ~c) == 0
4186 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4189 if (SDValue Combined = visitORLike(N0, N1, N))
4192 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4193 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4195 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4199 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4201 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4202 // iff (c1 & c2) != 0.
4203 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4204 isa<ConstantSDNode>(N0.getOperand(1))) {
4205 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
4206 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
4207 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
4210 ISD::AND, SDLoc(N), VT,
4211 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4215 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4216 if (N0.getOpcode() == N1.getOpcode())
4217 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4220 // See if this is some rotate idiom.
4221 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4222 return SDValue(Rot, 0);
4224 if (SDValue Load = MatchLoadCombine(N))
4227 // Simplify the operands using demanded-bits information.
4228 if (SimplifyDemandedBits(SDValue(N, 0)))
4229 return SDValue(N, 0);
4234 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4235 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4236 if (Op.getOpcode() == ISD::AND) {
4237 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4238 Mask = Op.getOperand(1);
4239 Op = Op.getOperand(0);
4245 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4253 // Return true if we can prove that, whenever Neg and Pos are both in the
4254 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4255 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4257 // (or (shift1 X, Neg), (shift2 X, Pos))
4259 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4260 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4261 // to consider shift amounts with defined behavior.
4262 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4263 // If EltSize is a power of 2 then:
4265 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4266 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4268 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4269 // for the stronger condition:
4271 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4273 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4274 // we can just replace Neg with Neg' for the rest of the function.
4276 // In other cases we check for the even stronger condition:
4278 // Neg == EltSize - Pos [B]
4280 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4281 // behavior if Pos == 0 (and consequently Neg == EltSize).
4283 // We could actually use [A] whenever EltSize is a power of 2, but the
4284 // only extra cases that it would match are those uninteresting ones
4285 // where Neg and Pos are never in range at the same time. E.g. for
4286 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4287 // as well as (sub 32, Pos), but:
4289 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4291 // always invokes undefined behavior for 32-bit X.
4293 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4294 unsigned MaskLoBits = 0;
4295 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4296 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4297 if (NegC->getAPIntValue() == EltSize - 1) {
4298 Neg = Neg.getOperand(0);
4299 MaskLoBits = Log2_64(EltSize);
4304 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4305 if (Neg.getOpcode() != ISD::SUB)
4307 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4310 SDValue NegOp1 = Neg.getOperand(1);
4312 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4313 // Pos'. The truncation is redundant for the purpose of the equality.
4314 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4315 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4316 if (PosC->getAPIntValue() == EltSize - 1)
4317 Pos = Pos.getOperand(0);
4319 // The condition we need is now:
4321 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4323 // If NegOp1 == Pos then we need:
4325 // EltSize & Mask == NegC & Mask
4327 // (because "x & Mask" is a truncation and distributes through subtraction).
4330 Width = NegC->getAPIntValue();
4332 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4333 // Then the condition we want to prove becomes:
4335 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4337 // which, again because "x & Mask" is a truncation, becomes:
4339 // NegC & Mask == (EltSize - PosC) & Mask
4340 // EltSize & Mask == (NegC + PosC) & Mask
4341 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4342 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4343 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4349 // Now we just need to check that EltSize & Mask == Width & Mask.
4351 // EltSize & Mask is 0 since Mask is EltSize - 1.
4352 return Width.getLoBits(MaskLoBits) == 0;
4353 return Width == EltSize;
4356 // A subroutine of MatchRotate used once we have found an OR of two opposite
4357 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4358 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4359 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4360 // Neg with outer conversions stripped away.
4361 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4362 SDValue Neg, SDValue InnerPos,
4363 SDValue InnerNeg, unsigned PosOpcode,
4364 unsigned NegOpcode, const SDLoc &DL) {
4365 // fold (or (shl x, (*ext y)),
4366 // (srl x, (*ext (sub 32, y)))) ->
4367 // (rotl x, y) or (rotr x, (sub 32, y))
4369 // fold (or (shl x, (*ext (sub 32, y))),
4370 // (srl x, (*ext y))) ->
4371 // (rotr x, y) or (rotl x, (sub 32, y))
4372 EVT VT = Shifted.getValueType();
4373 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4374 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4375 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4376 HasPos ? Pos : Neg).getNode();
4382 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4383 // idioms for rotate, and if the target supports rotation instructions, generate
4385 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4386 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4387 EVT VT = LHS.getValueType();
4388 if (!TLI.isTypeLegal(VT)) return nullptr;
4390 // The target must have at least one rotate flavor.
4391 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4392 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4393 if (!HasROTL && !HasROTR) return nullptr;
4395 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4396 SDValue LHSShift; // The shift.
4397 SDValue LHSMask; // AND value if any.
4398 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4399 return nullptr; // Not part of a rotate.
4401 SDValue RHSShift; // The shift.
4402 SDValue RHSMask; // AND value if any.
4403 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4404 return nullptr; // Not part of a rotate.
4406 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4407 return nullptr; // Not shifting the same value.
4409 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4410 return nullptr; // Shifts must disagree.
4412 // Canonicalize shl to left side in a shl/srl pair.
4413 if (RHSShift.getOpcode() == ISD::SHL) {
4414 std::swap(LHS, RHS);
4415 std::swap(LHSShift, RHSShift);
4416 std::swap(LHSMask, RHSMask);
4419 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4420 SDValue LHSShiftArg = LHSShift.getOperand(0);
4421 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4422 SDValue RHSShiftArg = RHSShift.getOperand(0);
4423 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4425 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4426 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4427 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4428 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4429 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4430 if ((LShVal + RShVal) != EltSizeInBits)
4433 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4434 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4436 // If there is an AND of either shifted operand, apply it to the result.
4437 if (LHSMask.getNode() || RHSMask.getNode()) {
4438 SDValue Mask = DAG.getAllOnesConstant(DL, VT);
4440 if (LHSMask.getNode()) {
4441 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4442 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4443 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4444 DAG.getConstant(RHSBits, DL, VT)));
4446 if (RHSMask.getNode()) {
4447 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4448 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4449 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4450 DAG.getConstant(LHSBits, DL, VT)));
4453 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4456 return Rot.getNode();
4459 // If there is a mask here, and we have a variable shift, we can't be sure
4460 // that we're masking out the right stuff.
4461 if (LHSMask.getNode() || RHSMask.getNode())
4464 // If the shift amount is sign/zext/any-extended just peel it off.
4465 SDValue LExtOp0 = LHSShiftAmt;
4466 SDValue RExtOp0 = RHSShiftAmt;
4467 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4468 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4469 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4470 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4471 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4472 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4473 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4474 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4475 LExtOp0 = LHSShiftAmt.getOperand(0);
4476 RExtOp0 = RHSShiftAmt.getOperand(0);
4479 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4480 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4484 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4485 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4493 /// Helper struct to parse and store a memory address as base + index + offset.
4494 /// We ignore sign extensions when it is safe to do so.
4495 /// The following two expressions are not equivalent. To differentiate we need
4496 /// to store whether there was a sign extension involved in the index
4498 /// (load (i64 add (i64 copyfromreg %c)
4499 /// (i64 signextend (add (i8 load %index)
4503 /// (load (i64 add (i64 copyfromreg %c)
4504 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
4506 struct BaseIndexOffset {
4510 bool IsIndexSignExt;
4512 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
4514 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
4515 bool IsIndexSignExt) :
4516 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
4518 bool equalBaseIndex(const BaseIndexOffset &Other) {
4519 return Other.Base == Base && Other.Index == Index &&
4520 Other.IsIndexSignExt == IsIndexSignExt;
4523 /// Parses tree in Ptr for base, index, offset addresses.
4524 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
4525 int64_t PartialOffset = 0) {
4526 bool IsIndexSignExt = false;
4528 // Split up a folded GlobalAddress+Offset into its component parts.
4529 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
4530 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
4531 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
4533 GA->getValueType(0),
4534 /*Offset=*/PartialOffset,
4535 /*isTargetGA=*/false,
4536 GA->getTargetFlags()),
4542 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
4543 // instruction, then it could be just the BASE or everything else we don't
4544 // know how to handle. Just use Ptr as BASE and give up.
4545 if (Ptr->getOpcode() != ISD::ADD)
4546 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4548 // We know that we have at least an ADD instruction. Try to pattern match
4549 // the simple case of BASE + OFFSET.
4550 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
4551 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
4552 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
4555 // Inside a loop the current BASE pointer is calculated using an ADD and a
4556 // MUL instruction. In this case Ptr is the actual BASE pointer.
4557 // (i64 add (i64 %array_ptr)
4558 // (i64 mul (i64 %induction_var)
4559 // (i64 %element_size)))
4560 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
4561 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4563 // Look at Base + Index + Offset cases.
4564 SDValue Base = Ptr->getOperand(0);
4565 SDValue IndexOffset = Ptr->getOperand(1);
4567 // Skip signextends.
4568 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
4569 IndexOffset = IndexOffset->getOperand(0);
4570 IsIndexSignExt = true;
4573 // Either the case of Base + Index (no offset) or something else.
4574 if (IndexOffset->getOpcode() != ISD::ADD)
4575 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
4577 // Now we have the case of Base + Index + offset.
4578 SDValue Index = IndexOffset->getOperand(0);
4579 SDValue Offset = IndexOffset->getOperand(1);
4581 if (!isa<ConstantSDNode>(Offset))
4582 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
4584 // Ignore signextends.
4585 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
4586 Index = Index->getOperand(0);
4587 IsIndexSignExt = true;
4588 } else IsIndexSignExt = false;
4590 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
4591 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
4597 /// Represents known origin of an individual byte in load combine pattern. The
4598 /// value of the byte is either constant zero or comes from memory.
4599 struct ByteProvider {
4600 // For constant zero providers Load is set to nullptr. For memory providers
4601 // Load represents the node which loads the byte from memory.
4602 // ByteOffset is the offset of the byte in the value produced by the load.
4604 unsigned ByteOffset;
4606 ByteProvider() : Load(nullptr), ByteOffset(0) {}
4608 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4609 return ByteProvider(Load, ByteOffset);
4611 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4613 bool isConstantZero() const { return !Load; }
4614 bool isMemory() const { return Load; }
4616 bool operator==(const ByteProvider &Other) const {
4617 return Other.Load == Load && Other.ByteOffset == ByteOffset;
4621 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4622 : Load(Load), ByteOffset(ByteOffset) {}
4625 /// Recursively traverses the expression calculating the origin of the requested
4626 /// byte of the given value. Returns None if the provider can't be calculated.
4628 /// For all the values except the root of the expression verifies that the value
4629 /// has exactly one use and if it's not true return None. This way if the origin
4630 /// of the byte is returned it's guaranteed that the values which contribute to
4631 /// the byte are not used outside of this expression.
4633 /// Because the parts of the expression are not allowed to have more than one
4634 /// use this function iterates over trees, not DAGs. So it never visits the same
4635 /// node more than once.
4636 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4638 bool Root = false) {
4639 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4643 if (!Root && !Op.hasOneUse())
4646 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4647 unsigned BitWidth = Op.getValueSizeInBits();
4648 if (BitWidth % 8 != 0)
4650 unsigned ByteWidth = BitWidth / 8;
4651 assert(Index < ByteWidth && "invalid index requested");
4654 switch (Op.getOpcode()) {
4656 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4659 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4663 if (LHS->isConstantZero())
4665 if (RHS->isConstantZero())
4670 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4674 uint64_t BitShift = ShiftOp->getZExtValue();
4675 if (BitShift % 8 != 0)
4677 uint64_t ByteShift = BitShift / 8;
4679 return Index < ByteShift
4680 ? ByteProvider::getConstantZero()
4681 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4684 case ISD::ANY_EXTEND:
4685 case ISD::SIGN_EXTEND:
4686 case ISD::ZERO_EXTEND: {
4687 SDValue NarrowOp = Op->getOperand(0);
4688 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4689 if (NarrowBitWidth % 8 != 0)
4691 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4693 if (Index >= NarrowByteWidth)
4694 return Op.getOpcode() == ISD::ZERO_EXTEND
4695 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4697 return calculateByteProvider(NarrowOp, Index, Depth + 1);
4700 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4703 auto L = cast<LoadSDNode>(Op.getNode());
4704 if (L->isVolatile() || L->isIndexed())
4707 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4708 if (NarrowBitWidth % 8 != 0)
4710 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4712 if (Index >= NarrowByteWidth)
4713 return L->getExtensionType() == ISD::ZEXTLOAD
4714 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4716 return ByteProvider::getMemory(L, Index);
4724 /// Match a pattern where a wide type scalar value is loaded by several narrow
4725 /// loads and combined by shifts and ors. Fold it into a single load or a load
4726 /// and a BSWAP if the targets supports it.
4728 /// Assuming little endian target:
4730 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4732 /// i32 val = *((i32)a)
4735 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4737 /// i32 val = BSWAP(*((i32)a))
4739 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4740 /// interact well with the worklist mechanism. When a part of the pattern is
4741 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4742 /// but the root node of the pattern which triggers the load combine is not
4743 /// necessarily a direct user of the changed node. For example, once the address
4744 /// of t28 load is reassociated load combine won't be triggered:
4745 /// t25: i32 = add t4, Constant:i32<2>
4746 /// t26: i64 = sign_extend t25
4747 /// t27: i64 = add t2, t26
4748 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4749 /// t29: i32 = zero_extend t28
4750 /// t32: i32 = shl t29, Constant:i8<8>
4751 /// t33: i32 = or t23, t32
4752 /// As a possible fix visitLoad can check if the load can be a part of a load
4753 /// combine pattern and add corresponding OR roots to the worklist.
4754 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4755 assert(N->getOpcode() == ISD::OR &&
4756 "Can only match load combining against OR nodes");
4758 // Handles simple types only
4759 EVT VT = N->getValueType(0);
4760 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4762 unsigned ByteWidth = VT.getSizeInBits() / 8;
4764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4765 // Before legalize we can introduce too wide illegal loads which will be later
4766 // split into legal sized loads. This enables us to combine i64 load by i8
4767 // patterns to a couple of i32 loads on 32 bit targets.
4768 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4771 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4772 unsigned BW, unsigned i) { return i; };
4773 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4774 unsigned BW, unsigned i) { return BW - i - 1; };
4776 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4777 auto MemoryByteOffset = [&] (ByteProvider P) {
4778 assert(P.isMemory() && "Must be a memory byte provider");
4779 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4780 assert(LoadBitWidth % 8 == 0 &&
4781 "can only analyze providers for individual bytes not bit");
4782 unsigned LoadByteWidth = LoadBitWidth / 8;
4783 return IsBigEndianTarget
4784 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4785 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4788 Optional<BaseIndexOffset> Base;
4791 SmallSet<LoadSDNode *, 8> Loads;
4792 Optional<ByteProvider> FirstByteProvider;
4793 int64_t FirstOffset = INT64_MAX;
4795 // Check if all the bytes of the OR we are looking at are loaded from the same
4796 // base address. Collect bytes offsets from Base address in ByteOffsets.
4797 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4798 for (unsigned i = 0; i < ByteWidth; i++) {
4799 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4800 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4803 LoadSDNode *L = P->Load;
4804 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4805 "Must be enforced by calculateByteProvider");
4806 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4808 // All loads must share the same chain
4809 SDValue LChain = L->getChain();
4812 else if (Chain != LChain)
4815 // Loads must share the same base address
4816 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4819 else if (!Base->equalBaseIndex(Ptr))
4822 // Calculate the offset of the current byte from the base address
4823 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
4824 ByteOffsets[i] = ByteOffsetFromBase;
4826 // Remember the first byte load
4827 if (ByteOffsetFromBase < FirstOffset) {
4828 FirstByteProvider = P;
4829 FirstOffset = ByteOffsetFromBase;
4834 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4835 "memory, so there must be at least one load which produces the value");
4836 assert(Base && "Base address of the accessed memory location must be set");
4837 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4839 // Check if the bytes of the OR we are looking at match with either big or
4840 // little endian value load
4841 bool BigEndian = true, LittleEndian = true;
4842 for (unsigned i = 0; i < ByteWidth; i++) {
4843 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4844 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4845 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4846 if (!BigEndian && !LittleEndian)
4849 assert((BigEndian != LittleEndian) && "should be either or");
4850 assert(FirstByteProvider && "must be set");
4852 // Ensure that the first byte is loaded from zero offset of the first load.
4853 // So the combined value can be loaded from the first load address.
4854 if (MemoryByteOffset(*FirstByteProvider) != 0)
4856 LoadSDNode *FirstLoad = FirstByteProvider->Load;
4858 // The node we are looking at matches with the pattern, check if we can
4859 // replace it with a single load and bswap if needed.
4861 // If the load needs byte swap check if the target supports it
4862 bool NeedsBswap = IsBigEndianTarget != BigEndian;
4864 // Before legalize we can introduce illegal bswaps which will be later
4865 // converted to an explicit bswap sequence. This way we end up with a single
4866 // load and byte shuffling instead of several loads and byte shuffling.
4867 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4870 // Check that a load of the wide type is both allowed and fast on the target
4872 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4873 VT, FirstLoad->getAddressSpace(),
4874 FirstLoad->getAlignment(), &Fast);
4875 if (!Allowed || !Fast)
4879 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4880 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4882 // Transfer chain users from old loads to the new load.
4883 for (LoadSDNode *L : Loads)
4884 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4886 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
4889 SDValue DAGCombiner::visitXOR(SDNode *N) {
4890 SDValue N0 = N->getOperand(0);
4891 SDValue N1 = N->getOperand(1);
4892 EVT VT = N0.getValueType();
4895 if (VT.isVector()) {
4896 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4899 // fold (xor x, 0) -> x, vector edition
4900 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4902 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4906 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4907 if (N0.isUndef() && N1.isUndef())
4908 return DAG.getConstant(0, SDLoc(N), VT);
4909 // fold (xor x, undef) -> undef
4914 // fold (xor c1, c2) -> c1^c2
4915 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4916 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4918 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4919 // canonicalize constant to RHS
4920 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4921 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4922 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4923 // fold (xor x, 0) -> x
4924 if (isNullConstant(N1))
4927 if (SDValue NewSel = foldBinOpIntoSelect(N))
4931 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4934 // fold !(x cc y) -> (x !cc y)
4935 SDValue LHS, RHS, CC;
4936 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4937 bool isInt = LHS.getValueType().isInteger();
4938 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4941 if (!LegalOperations ||
4942 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4943 switch (N0.getOpcode()) {
4945 llvm_unreachable("Unhandled SetCC Equivalent!");
4947 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
4948 case ISD::SELECT_CC:
4949 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
4950 N0.getOperand(3), NotCC);
4955 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4956 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4957 N0.getNode()->hasOneUse() &&
4958 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4959 SDValue V = N0.getOperand(0);
4961 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4962 DAG.getConstant(1, DL, V.getValueType()));
4963 AddToWorklist(V.getNode());
4964 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4967 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4968 if (isOneConstant(N1) && VT == MVT::i1 &&
4969 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4970 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4971 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4972 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4973 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4974 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4975 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4976 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4979 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4980 if (isAllOnesConstant(N1) &&
4981 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4982 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4983 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4984 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4985 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4986 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4987 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4988 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4991 // fold (xor (and x, y), y) -> (and (not x), y)
4992 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4993 N0->getOperand(1) == N1) {
4994 SDValue X = N0->getOperand(0);
4995 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4996 AddToWorklist(NotX.getNode());
4997 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4999 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5000 if (N1C && N0.getOpcode() == ISD::XOR) {
5001 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5003 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5004 DAG.getConstant(N1C->getAPIntValue() ^
5005 N00C->getAPIntValue(), DL, VT));
5007 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5009 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5010 DAG.getConstant(N1C->getAPIntValue() ^
5011 N01C->getAPIntValue(), DL, VT));
5015 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5016 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5017 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5018 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5019 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5020 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5021 if (C->getAPIntValue() == (OpSizeInBits - 1))
5022 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5025 // fold (xor x, x) -> 0
5027 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5029 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5030 // Here is a concrete example of this equivalence:
5032 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5033 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5037 // i16 ~1 == 0b1111111111111110
5038 // i16 rol(~1, 14) == 0b1011111111111111
5040 // Some additional tips to help conceptualize this transform:
5041 // - Try to see the operation as placing a single zero in a value of all ones.
5042 // - There exists no value for x which would allow the result to contain zero.
5043 // - Values of x larger than the bitwidth are undefined and do not require a
5044 // consistent result.
5045 // - Pushing the zero left requires shifting one bits in from the right.
5046 // A rotate left of ~1 is a nice way of achieving the desired result.
5047 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5048 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5050 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5054 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5055 if (N0.getOpcode() == N1.getOpcode())
5056 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5059 // Simplify the expression using non-local knowledge.
5060 if (SimplifyDemandedBits(SDValue(N, 0)))
5061 return SDValue(N, 0);
5066 /// Handle transforms common to the three shifts, when the shift amount is a
5068 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5069 SDNode *LHS = N->getOperand(0).getNode();
5070 if (!LHS->hasOneUse()) return SDValue();
5072 // We want to pull some binops through shifts, so that we have (and (shift))
5073 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5074 // thing happens with address calculations, so it's important to canonicalize
5076 bool HighBitSet = false; // Can we transform this if the high bit is set?
5078 switch (LHS->getOpcode()) {
5079 default: return SDValue();
5082 HighBitSet = false; // We can only transform sra if the high bit is clear.
5085 HighBitSet = true; // We can only transform sra if the high bit is set.
5088 if (N->getOpcode() != ISD::SHL)
5089 return SDValue(); // only shl(add) not sr[al](add).
5090 HighBitSet = false; // We can only transform sra if the high bit is clear.
5094 // We require the RHS of the binop to be a constant and not opaque as well.
5095 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5096 if (!BinOpCst) return SDValue();
5098 // FIXME: disable this unless the input to the binop is a shift by a constant
5099 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5100 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5101 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5102 BinOpLHSVal->getOpcode() == ISD::SRA ||
5103 BinOpLHSVal->getOpcode() == ISD::SRL;
5104 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5105 BinOpLHSVal->getOpcode() == ISD::SELECT;
5107 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5111 if (isCopyOrSelect && N->hasOneUse())
5114 EVT VT = N->getValueType(0);
5116 // If this is a signed shift right, and the high bit is modified by the
5117 // logical operation, do not perform the transformation. The highBitSet
5118 // boolean indicates the value of the high bit of the constant which would
5119 // cause it to be modified for this operation.
5120 if (N->getOpcode() == ISD::SRA) {
5121 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5122 if (BinOpRHSSignSet != HighBitSet)
5126 if (!TLI.isDesirableToCommuteWithShift(LHS))
5129 // Fold the constants, shifting the binop RHS by the shift amount.
5130 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5132 LHS->getOperand(1), N->getOperand(1));
5133 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5135 // Create the new shift.
5136 SDValue NewShift = DAG.getNode(N->getOpcode(),
5137 SDLoc(LHS->getOperand(0)),
5138 VT, LHS->getOperand(0), N->getOperand(1));
5140 // Create the new binop.
5141 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5144 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5145 assert(N->getOpcode() == ISD::TRUNCATE);
5146 assert(N->getOperand(0).getOpcode() == ISD::AND);
5148 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5149 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5150 SDValue N01 = N->getOperand(0).getOperand(1);
5151 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5153 EVT TruncVT = N->getValueType(0);
5154 SDValue N00 = N->getOperand(0).getOperand(0);
5155 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5156 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5157 AddToWorklist(Trunc00.getNode());
5158 AddToWorklist(Trunc01.getNode());
5159 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5166 SDValue DAGCombiner::visitRotate(SDNode *N) {
5167 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5168 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
5169 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
5170 if (SDValue NewOp1 =
5171 distributeTruncateThroughAnd(N->getOperand(1).getNode()))
5172 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
5173 N->getOperand(0), NewOp1);
5178 SDValue DAGCombiner::visitSHL(SDNode *N) {
5179 SDValue N0 = N->getOperand(0);
5180 SDValue N1 = N->getOperand(1);
5181 EVT VT = N0.getValueType();
5182 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5185 if (VT.isVector()) {
5186 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5189 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5190 // If setcc produces all-one true value then:
5191 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5192 if (N1CV && N1CV->isConstant()) {
5193 if (N0.getOpcode() == ISD::AND) {
5194 SDValue N00 = N0->getOperand(0);
5195 SDValue N01 = N0->getOperand(1);
5196 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5198 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5199 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5200 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5201 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5203 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5209 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5211 // fold (shl c1, c2) -> c1<<c2
5212 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5213 if (N0C && N1C && !N1C->isOpaque())
5214 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5215 // fold (shl 0, x) -> 0
5216 if (isNullConstant(N0))
5218 // fold (shl x, c >= size(x)) -> undef
5219 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5220 return DAG.getUNDEF(VT);
5221 // fold (shl x, 0) -> x
5222 if (N1C && N1C->isNullValue())
5224 // fold (shl undef, x) -> 0
5226 return DAG.getConstant(0, SDLoc(N), VT);
5228 if (SDValue NewSel = foldBinOpIntoSelect(N))
5231 // if (shl x, c) is known to be zero, return 0
5232 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5233 APInt::getAllOnesValue(OpSizeInBits)))
5234 return DAG.getConstant(0, SDLoc(N), VT);
5235 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5236 if (N1.getOpcode() == ISD::TRUNCATE &&
5237 N1.getOperand(0).getOpcode() == ISD::AND) {
5238 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5239 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5242 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5243 return SDValue(N, 0);
5245 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5246 if (N1C && N0.getOpcode() == ISD::SHL) {
5247 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5249 APInt c1 = N0C1->getAPIntValue();
5250 APInt c2 = N1C->getAPIntValue();
5251 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5253 APInt Sum = c1 + c2;
5254 if (Sum.uge(OpSizeInBits))
5255 return DAG.getConstant(0, DL, VT);
5258 ISD::SHL, DL, VT, N0.getOperand(0),
5259 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5263 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5264 // For this to be valid, the second form must not preserve any of the bits
5265 // that are shifted out by the inner shift in the first form. This means
5266 // the outer shift size must be >= the number of bits added by the ext.
5267 // As a corollary, we don't care what kind of ext it is.
5268 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5269 N0.getOpcode() == ISD::ANY_EXTEND ||
5270 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5271 N0.getOperand(0).getOpcode() == ISD::SHL) {
5272 SDValue N0Op0 = N0.getOperand(0);
5273 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5274 APInt c1 = N0Op0C1->getAPIntValue();
5275 APInt c2 = N1C->getAPIntValue();
5276 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5278 EVT InnerShiftVT = N0Op0.getValueType();
5279 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5280 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5282 APInt Sum = c1 + c2;
5283 if (Sum.uge(OpSizeInBits))
5284 return DAG.getConstant(0, DL, VT);
5288 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5289 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5294 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5295 // Only fold this if the inner zext has no other uses to avoid increasing
5296 // the total number of instructions.
5297 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5298 N0.getOperand(0).getOpcode() == ISD::SRL) {
5299 SDValue N0Op0 = N0.getOperand(0);
5300 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5301 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5302 uint64_t c1 = N0Op0C1->getZExtValue();
5303 uint64_t c2 = N1C->getZExtValue();
5305 SDValue NewOp0 = N0.getOperand(0);
5306 EVT CountVT = NewOp0.getOperand(1).getValueType();
5308 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5310 DAG.getConstant(c2, DL, CountVT));
5311 AddToWorklist(NewSHL.getNode());
5312 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5318 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5319 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5320 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5321 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
5322 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5323 uint64_t C1 = N0C1->getZExtValue();
5324 uint64_t C2 = N1C->getZExtValue();
5327 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5328 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5329 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5330 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5334 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5335 // (and (srl x, (sub c1, c2), MASK)
5336 // Only fold this if the inner shift has no other uses -- if it does, folding
5337 // this will increase the total number of instructions.
5338 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5339 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5340 uint64_t c1 = N0C1->getZExtValue();
5341 if (c1 < OpSizeInBits) {
5342 uint64_t c2 = N1C->getZExtValue();
5343 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5346 Mask = Mask.shl(c2 - c1);
5348 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5349 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5351 Mask.lshrInPlace(c1 - c2);
5353 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5354 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5357 return DAG.getNode(ISD::AND, DL, VT, Shift,
5358 DAG.getConstant(Mask, DL, VT));
5363 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5364 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5365 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5367 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5368 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5369 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5372 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5373 // Variant of version done on multiply, except mul by a power of 2 is turned
5375 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5376 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5377 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5378 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5379 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5380 AddToWorklist(Shl0.getNode());
5381 AddToWorklist(Shl1.getNode());
5382 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5385 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5386 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5387 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5388 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5389 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5390 if (isConstantOrConstantVector(Shl))
5391 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5394 if (N1C && !N1C->isOpaque())
5395 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5401 SDValue DAGCombiner::visitSRA(SDNode *N) {
5402 SDValue N0 = N->getOperand(0);
5403 SDValue N1 = N->getOperand(1);
5404 EVT VT = N0.getValueType();
5405 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5407 // Arithmetic shifting an all-sign-bit value is a no-op.
5408 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5413 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5416 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5418 // fold (sra c1, c2) -> (sra c1, c2)
5419 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5420 if (N0C && N1C && !N1C->isOpaque())
5421 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5422 // fold (sra 0, x) -> 0
5423 if (isNullConstant(N0))
5425 // fold (sra -1, x) -> -1
5426 if (isAllOnesConstant(N0))
5428 // fold (sra x, c >= size(x)) -> undef
5429 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5430 return DAG.getUNDEF(VT);
5431 // fold (sra x, 0) -> x
5432 if (N1C && N1C->isNullValue())
5435 if (SDValue NewSel = foldBinOpIntoSelect(N))
5438 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5440 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5441 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5442 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5444 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5445 ExtVT, VT.getVectorNumElements());
5446 if ((!LegalOperations ||
5447 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5448 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5449 N0.getOperand(0), DAG.getValueType(ExtVT));
5452 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5453 if (N1C && N0.getOpcode() == ISD::SRA) {
5454 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5456 APInt c1 = N0C1->getAPIntValue();
5457 APInt c2 = N1C->getAPIntValue();
5458 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5460 APInt Sum = c1 + c2;
5461 if (Sum.uge(OpSizeInBits))
5462 Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5465 ISD::SRA, DL, VT, N0.getOperand(0),
5466 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5470 // fold (sra (shl X, m), (sub result_size, n))
5471 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5472 // result_size - n != m.
5473 // If truncate is free for the target sext(shl) is likely to result in better
5475 if (N0.getOpcode() == ISD::SHL && N1C) {
5476 // Get the two constanst of the shifts, CN0 = m, CN = n.
5477 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5479 LLVMContext &Ctx = *DAG.getContext();
5480 // Determine what the truncate's result bitsize and type would be.
5481 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5484 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5486 // Determine the residual right-shift amount.
5487 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5489 // If the shift is not a no-op (in which case this should be just a sign
5490 // extend already), the truncated to type is legal, sign_extend is legal
5491 // on that type, and the truncate to that type is both legal and free,
5492 // perform the transform.
5493 if ((ShiftAmt > 0) &&
5494 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5495 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5496 TLI.isTruncateFree(VT, TruncVT)) {
5499 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5500 getShiftAmountTy(N0.getOperand(0).getValueType()));
5501 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5502 N0.getOperand(0), Amt);
5503 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5505 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5506 N->getValueType(0), Trunc);
5511 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5512 if (N1.getOpcode() == ISD::TRUNCATE &&
5513 N1.getOperand(0).getOpcode() == ISD::AND) {
5514 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5515 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5518 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5519 // if c1 is equal to the number of bits the trunc removes
5520 if (N0.getOpcode() == ISD::TRUNCATE &&
5521 (N0.getOperand(0).getOpcode() == ISD::SRL ||
5522 N0.getOperand(0).getOpcode() == ISD::SRA) &&
5523 N0.getOperand(0).hasOneUse() &&
5524 N0.getOperand(0).getOperand(1).hasOneUse() &&
5526 SDValue N0Op0 = N0.getOperand(0);
5527 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5528 unsigned LargeShiftVal = LargeShift->getZExtValue();
5529 EVT LargeVT = N0Op0.getValueType();
5531 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5534 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5535 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5536 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5537 N0Op0.getOperand(0), Amt);
5538 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5543 // Simplify, based on bits shifted out of the LHS.
5544 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5545 return SDValue(N, 0);
5548 // If the sign bit is known to be zero, switch this to a SRL.
5549 if (DAG.SignBitIsZero(N0))
5550 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5552 if (N1C && !N1C->isOpaque())
5553 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5559 SDValue DAGCombiner::visitSRL(SDNode *N) {
5560 SDValue N0 = N->getOperand(0);
5561 SDValue N1 = N->getOperand(1);
5562 EVT VT = N0.getValueType();
5563 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5567 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5570 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5572 // fold (srl c1, c2) -> c1 >>u c2
5573 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5574 if (N0C && N1C && !N1C->isOpaque())
5575 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5576 // fold (srl 0, x) -> 0
5577 if (isNullConstant(N0))
5579 // fold (srl x, c >= size(x)) -> undef
5580 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5581 return DAG.getUNDEF(VT);
5582 // fold (srl x, 0) -> x
5583 if (N1C && N1C->isNullValue())
5586 if (SDValue NewSel = foldBinOpIntoSelect(N))
5589 // if (srl x, c) is known to be zero, return 0
5590 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5591 APInt::getAllOnesValue(OpSizeInBits)))
5592 return DAG.getConstant(0, SDLoc(N), VT);
5594 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5595 if (N1C && N0.getOpcode() == ISD::SRL) {
5596 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5598 APInt c1 = N0C1->getAPIntValue();
5599 APInt c2 = N1C->getAPIntValue();
5600 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5602 APInt Sum = c1 + c2;
5603 if (Sum.uge(OpSizeInBits))
5604 return DAG.getConstant(0, DL, VT);
5607 ISD::SRL, DL, VT, N0.getOperand(0),
5608 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5612 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5613 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5614 N0.getOperand(0).getOpcode() == ISD::SRL &&
5615 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
5617 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
5618 uint64_t c2 = N1C->getZExtValue();
5619 EVT InnerShiftVT = N0.getOperand(0).getValueType();
5620 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
5621 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5622 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5623 if (c1 + OpSizeInBits == InnerShiftSize) {
5625 if (c1 + c2 >= InnerShiftSize)
5626 return DAG.getConstant(0, DL, VT);
5627 return DAG.getNode(ISD::TRUNCATE, DL, VT,
5628 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5629 N0.getOperand(0)->getOperand(0),
5630 DAG.getConstant(c1 + c2, DL,
5635 // fold (srl (shl x, c), c) -> (and x, cst2)
5636 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5637 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5640 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5641 AddToWorklist(Mask.getNode());
5642 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5645 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5646 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5647 // Shifting in all undef bits?
5648 EVT SmallVT = N0.getOperand(0).getValueType();
5649 unsigned BitSize = SmallVT.getScalarSizeInBits();
5650 if (N1C->getZExtValue() >= BitSize)
5651 return DAG.getUNDEF(VT);
5653 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5654 uint64_t ShiftAmt = N1C->getZExtValue();
5656 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5658 DAG.getConstant(ShiftAmt, DL0,
5659 getShiftAmountTy(SmallVT)));
5660 AddToWorklist(SmallShift.getNode());
5661 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5663 return DAG.getNode(ISD::AND, DL, VT,
5664 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5665 DAG.getConstant(Mask, DL, VT));
5669 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
5670 // bit, which is unmodified by sra.
5671 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5672 if (N0.getOpcode() == ISD::SRA)
5673 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5676 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
5677 if (N1C && N0.getOpcode() == ISD::CTLZ &&
5678 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5679 APInt KnownZero, KnownOne;
5680 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
5682 // If any of the input bits are KnownOne, then the input couldn't be all
5683 // zeros, thus the result of the srl will always be zero.
5684 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5686 // If all of the bits input the to ctlz node are known to be zero, then
5687 // the result of the ctlz is "32" and the result of the shift is one.
5688 APInt UnknownBits = ~KnownZero;
5689 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5691 // Otherwise, check to see if there is exactly one bit input to the ctlz.
5692 if ((UnknownBits & (UnknownBits - 1)) == 0) {
5693 // Okay, we know that only that the single bit specified by UnknownBits
5694 // could be set on input to the CTLZ node. If this bit is set, the SRL
5695 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5696 // to an SRL/XOR pair, which is likely to simplify more.
5697 unsigned ShAmt = UnknownBits.countTrailingZeros();
5698 SDValue Op = N0.getOperand(0);
5702 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5703 DAG.getConstant(ShAmt, DL,
5704 getShiftAmountTy(Op.getValueType())));
5705 AddToWorklist(Op.getNode());
5709 return DAG.getNode(ISD::XOR, DL, VT,
5710 Op, DAG.getConstant(1, DL, VT));
5714 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5715 if (N1.getOpcode() == ISD::TRUNCATE &&
5716 N1.getOperand(0).getOpcode() == ISD::AND) {
5717 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5718 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5721 // fold operands of srl based on knowledge that the low bits are not
5723 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5724 return SDValue(N, 0);
5726 if (N1C && !N1C->isOpaque())
5727 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5730 // Attempt to convert a srl of a load into a narrower zero-extending load.
5731 if (SDValue NarrowLoad = ReduceLoadWidth(N))
5734 // Here is a common situation. We want to optimize:
5737 // %b = and i32 %a, 2
5738 // %c = srl i32 %b, 1
5739 // brcond i32 %c ...
5745 // %c = setcc eq %b, 0
5748 // However when after the source operand of SRL is optimized into AND, the SRL
5749 // itself may not be optimized further. Look for it and add the BRCOND into
5751 if (N->hasOneUse()) {
5752 SDNode *Use = *N->use_begin();
5753 if (Use->getOpcode() == ISD::BRCOND)
5755 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5756 // Also look pass the truncate.
5757 Use = *Use->use_begin();
5758 if (Use->getOpcode() == ISD::BRCOND)
5766 SDValue DAGCombiner::visitABS(SDNode *N) {
5767 SDValue N0 = N->getOperand(0);
5768 EVT VT = N->getValueType(0);
5770 // fold (abs c1) -> c2
5771 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5772 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5773 // fold (abs (abs x)) -> (abs x)
5774 if (N0.getOpcode() == ISD::ABS)
5776 // fold (abs x) -> x iff not-negative
5777 if (DAG.SignBitIsZero(N0))
5782 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5783 SDValue N0 = N->getOperand(0);
5784 EVT VT = N->getValueType(0);
5786 // fold (bswap c1) -> c2
5787 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5788 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5789 // fold (bswap (bswap x)) -> x
5790 if (N0.getOpcode() == ISD::BSWAP)
5791 return N0->getOperand(0);
5795 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5796 SDValue N0 = N->getOperand(0);
5797 EVT VT = N->getValueType(0);
5799 // fold (bitreverse c1) -> c2
5800 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5801 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5802 // fold (bitreverse (bitreverse x)) -> x
5803 if (N0.getOpcode() == ISD::BITREVERSE)
5804 return N0.getOperand(0);
5808 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5809 SDValue N0 = N->getOperand(0);
5810 EVT VT = N->getValueType(0);
5812 // fold (ctlz c1) -> c2
5813 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5814 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5818 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5819 SDValue N0 = N->getOperand(0);
5820 EVT VT = N->getValueType(0);
5822 // fold (ctlz_zero_undef c1) -> c2
5823 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5824 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5828 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5829 SDValue N0 = N->getOperand(0);
5830 EVT VT = N->getValueType(0);
5832 // fold (cttz c1) -> c2
5833 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5834 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5838 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5839 SDValue N0 = N->getOperand(0);
5840 EVT VT = N->getValueType(0);
5842 // fold (cttz_zero_undef c1) -> c2
5843 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5844 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5848 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5849 SDValue N0 = N->getOperand(0);
5850 EVT VT = N->getValueType(0);
5852 // fold (ctpop c1) -> c2
5853 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5854 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
5859 /// \brief Generate Min/Max node
5860 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
5861 SDValue RHS, SDValue True, SDValue False,
5862 ISD::CondCode CC, const TargetLowering &TLI,
5863 SelectionDAG &DAG) {
5864 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
5874 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
5875 if (TLI.isOperationLegal(Opcode, VT))
5876 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5885 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
5886 if (TLI.isOperationLegal(Opcode, VT))
5887 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5895 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
5896 SDValue Cond = N->getOperand(0);
5897 SDValue N1 = N->getOperand(1);
5898 SDValue N2 = N->getOperand(2);
5899 EVT VT = N->getValueType(0);
5900 EVT CondVT = Cond.getValueType();
5903 if (!VT.isInteger())
5906 auto *C1 = dyn_cast<ConstantSDNode>(N1);
5907 auto *C2 = dyn_cast<ConstantSDNode>(N2);
5911 // Only do this before legalization to avoid conflicting with target-specific
5912 // transforms in the other direction (create a select from a zext/sext). There
5913 // is also a target-independent combine here in DAGCombiner in the other
5914 // direction for (select Cond, -1, 0) when the condition is not i1.
5915 if (CondVT == MVT::i1 && !LegalOperations) {
5916 if (C1->isNullValue() && C2->isOne()) {
5917 // select Cond, 0, 1 --> zext (!Cond)
5918 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5920 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
5923 if (C1->isNullValue() && C2->isAllOnesValue()) {
5924 // select Cond, 0, -1 --> sext (!Cond)
5925 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
5927 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
5930 if (C1->isOne() && C2->isNullValue()) {
5931 // select Cond, 1, 0 --> zext (Cond)
5933 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5936 if (C1->isAllOnesValue() && C2->isNullValue()) {
5937 // select Cond, -1, 0 --> sext (Cond)
5939 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5943 // For any constants that differ by 1, we can transform the select into an
5944 // extend and add. Use a target hook because some targets may prefer to
5945 // transform in the other direction.
5946 if (TLI.convertSelectOfConstantsToMath()) {
5947 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
5948 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
5950 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
5951 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5953 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
5954 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
5956 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
5957 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
5964 // fold (select Cond, 0, 1) -> (xor Cond, 1)
5965 // We can't do this reliably if integer based booleans have different contents
5966 // to floating point based booleans. This is because we can't tell whether we
5967 // have an integer-based boolean or a floating-point-based boolean unless we
5968 // can find the SETCC that produced it and inspect its operands. This is
5969 // fairly easy if C is the SETCC node, but it can potentially be
5970 // undiscoverable (or not reasonably discoverable). For example, it could be
5971 // in another basic block or it could require searching a complicated
5973 if (CondVT.isInteger() &&
5974 TLI.getBooleanContents(false, true) ==
5975 TargetLowering::ZeroOrOneBooleanContent &&
5976 TLI.getBooleanContents(false, false) ==
5977 TargetLowering::ZeroOrOneBooleanContent &&
5978 C1->isNullValue() && C2->isOne()) {
5980 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
5981 if (VT.bitsEq(CondVT))
5983 return DAG.getZExtOrTrunc(NotCond, DL, VT);
5989 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5990 SDValue N0 = N->getOperand(0);
5991 SDValue N1 = N->getOperand(1);
5992 SDValue N2 = N->getOperand(2);
5993 EVT VT = N->getValueType(0);
5994 EVT VT0 = N0.getValueType();
5996 // fold (select C, X, X) -> X
5999 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6000 // fold (select true, X, Y) -> X
6001 // fold (select false, X, Y) -> Y
6002 return !N0C->isNullValue() ? N1 : N2;
6004 // fold (select X, X, Y) -> (or X, Y)
6005 // fold (select X, 1, Y) -> (or C, Y)
6006 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6007 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
6009 if (SDValue V = foldSelectOfConstants(N))
6012 // fold (select C, 0, X) -> (and (not C), X)
6013 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6014 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6015 AddToWorklist(NOTNode.getNode());
6016 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
6018 // fold (select C, X, 1) -> (or (not C), X)
6019 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6020 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6021 AddToWorklist(NOTNode.getNode());
6022 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
6024 // fold (select X, Y, X) -> (and X, Y)
6025 // fold (select X, Y, 0) -> (and X, Y)
6026 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6027 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
6029 // If we can fold this based on the true/false value, do so.
6030 if (SimplifySelectOps(N, N1, N2))
6031 return SDValue(N, 0); // Don't revisit N.
6033 if (VT0 == MVT::i1) {
6034 // The code in this block deals with the following 2 equivalences:
6035 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6036 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6037 // The target can specify its preferred form with the
6038 // shouldNormalizeToSelectSequence() callback. However we always transform
6039 // to the right anyway if we find the inner select exists in the DAG anyway
6040 // and we always transform to the left side if we know that we can further
6041 // optimize the combination of the conditions.
6042 bool normalizeToSequence
6043 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6044 // select (and Cond0, Cond1), X, Y
6045 // -> select Cond0, (select Cond1, X, Y), Y
6046 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6047 SDValue Cond0 = N0->getOperand(0);
6048 SDValue Cond1 = N0->getOperand(1);
6049 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6050 N1.getValueType(), Cond1, N1, N2);
6051 if (normalizeToSequence || !InnerSelect.use_empty())
6052 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
6055 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6056 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6057 SDValue Cond0 = N0->getOperand(0);
6058 SDValue Cond1 = N0->getOperand(1);
6059 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
6060 N1.getValueType(), Cond1, N1, N2);
6061 if (normalizeToSequence || !InnerSelect.use_empty())
6062 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
6066 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6067 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6068 SDValue N1_0 = N1->getOperand(0);
6069 SDValue N1_1 = N1->getOperand(1);
6070 SDValue N1_2 = N1->getOperand(2);
6071 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6072 // Create the actual and node if we can generate good code for it.
6073 if (!normalizeToSequence) {
6074 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
6076 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
6079 // Otherwise see if we can optimize the "and" to a better pattern.
6080 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6081 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6085 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6086 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6087 SDValue N2_0 = N2->getOperand(0);
6088 SDValue N2_1 = N2->getOperand(1);
6089 SDValue N2_2 = N2->getOperand(2);
6090 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6091 // Create the actual or node if we can generate good code for it.
6092 if (!normalizeToSequence) {
6093 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
6095 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
6098 // Otherwise see if we can optimize to a better pattern.
6099 if (SDValue Combined = visitORLike(N0, N2_0, N))
6100 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
6106 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6107 if (VT0 == MVT::i1) {
6108 if (N0->getOpcode() == ISD::XOR) {
6109 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6110 SDValue Cond0 = N0->getOperand(0);
6112 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
6118 // fold selects based on a setcc into other things, such as min/max/abs
6119 if (N0.getOpcode() == ISD::SETCC) {
6120 // select x, y (fcmp lt x, y) -> fminnum x, y
6121 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6123 // This is OK if we don't care about what happens if either operand is a
6127 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6128 // no signed zeros as well as no nans.
6129 const TargetOptions &Options = DAG.getTarget().Options;
6130 if (Options.UnsafeFPMath &&
6131 VT.isFloatingPoint() && N0.hasOneUse() &&
6132 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6133 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6135 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
6136 N0.getOperand(1), N1, N2, CC,
6141 if ((!LegalOperations &&
6142 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6143 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6144 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
6145 N0.getOperand(0), N0.getOperand(1),
6146 N1, N2, N0.getOperand(2));
6147 return SimplifySelect(SDLoc(N), N0, N1, N2);
6154 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6157 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6159 // Split the inputs.
6160 SDValue Lo, Hi, LL, LH, RL, RH;
6161 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6162 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6164 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6165 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6167 return std::make_pair(Lo, Hi);
6170 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6171 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6172 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6174 SDValue Cond = N->getOperand(0);
6175 SDValue LHS = N->getOperand(1);
6176 SDValue RHS = N->getOperand(2);
6177 EVT VT = N->getValueType(0);
6178 int NumElems = VT.getVectorNumElements();
6179 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6180 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6181 Cond.getOpcode() == ISD::BUILD_VECTOR);
6183 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6184 // binary ones here.
6185 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6188 // We're sure we have an even number of elements due to the
6189 // concat_vectors we have as arguments to vselect.
6190 // Skip BV elements until we find one that's not an UNDEF
6191 // After we find an UNDEF element, keep looping until we get to half the
6192 // length of the BV and see if all the non-undef nodes are the same.
6193 ConstantSDNode *BottomHalf = nullptr;
6194 for (int i = 0; i < NumElems / 2; ++i) {
6195 if (Cond->getOperand(i)->isUndef())
6198 if (BottomHalf == nullptr)
6199 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6200 else if (Cond->getOperand(i).getNode() != BottomHalf)
6204 // Do the same for the second half of the BuildVector
6205 ConstantSDNode *TopHalf = nullptr;
6206 for (int i = NumElems / 2; i < NumElems; ++i) {
6207 if (Cond->getOperand(i)->isUndef())
6210 if (TopHalf == nullptr)
6211 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6212 else if (Cond->getOperand(i).getNode() != TopHalf)
6216 assert(TopHalf && BottomHalf &&
6217 "One half of the selector was all UNDEFs and the other was all the "
6218 "same value. This should have been addressed before this function.");
6220 ISD::CONCAT_VECTORS, DL, VT,
6221 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6222 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6225 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6227 if (Level >= AfterLegalizeTypes)
6230 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6231 SDValue Mask = MSC->getMask();
6232 SDValue Data = MSC->getValue();
6235 // If the MSCATTER data type requires splitting and the mask is provided by a
6236 // SETCC, then split both nodes and its operands before legalization. This
6237 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6238 // and enables future optimizations (e.g. min/max pattern matching on X86).
6239 if (Mask.getOpcode() != ISD::SETCC)
6242 // Check if any splitting is required.
6243 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6244 TargetLowering::TypeSplitVector)
6246 SDValue MaskLo, MaskHi, Lo, Hi;
6247 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6250 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6252 SDValue Chain = MSC->getChain();
6254 EVT MemoryVT = MSC->getMemoryVT();
6255 unsigned Alignment = MSC->getOriginalAlignment();
6257 EVT LoMemVT, HiMemVT;
6258 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6260 SDValue DataLo, DataHi;
6261 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6263 SDValue BasePtr = MSC->getBasePtr();
6264 SDValue IndexLo, IndexHi;
6265 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6267 MachineMemOperand *MMO = DAG.getMachineFunction().
6268 getMachineMemOperand(MSC->getPointerInfo(),
6269 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6270 Alignment, MSC->getAAInfo(), MSC->getRanges());
6272 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6273 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6276 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6277 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6280 AddToWorklist(Lo.getNode());
6281 AddToWorklist(Hi.getNode());
6283 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6286 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6288 if (Level >= AfterLegalizeTypes)
6291 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6292 SDValue Mask = MST->getMask();
6293 SDValue Data = MST->getValue();
6294 EVT VT = Data.getValueType();
6297 // If the MSTORE data type requires splitting and the mask is provided by a
6298 // SETCC, then split both nodes and its operands before legalization. This
6299 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6300 // and enables future optimizations (e.g. min/max pattern matching on X86).
6301 if (Mask.getOpcode() == ISD::SETCC) {
6303 // Check if any splitting is required.
6304 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6305 TargetLowering::TypeSplitVector)
6308 SDValue MaskLo, MaskHi, Lo, Hi;
6309 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6311 SDValue Chain = MST->getChain();
6312 SDValue Ptr = MST->getBasePtr();
6314 EVT MemoryVT = MST->getMemoryVT();
6315 unsigned Alignment = MST->getOriginalAlignment();
6317 // if Alignment is equal to the vector size,
6318 // take the half of it for the second part
6319 unsigned SecondHalfAlignment =
6320 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6322 EVT LoMemVT, HiMemVT;
6323 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6325 SDValue DataLo, DataHi;
6326 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6328 MachineMemOperand *MMO = DAG.getMachineFunction().
6329 getMachineMemOperand(MST->getPointerInfo(),
6330 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6331 Alignment, MST->getAAInfo(), MST->getRanges());
6333 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6334 MST->isTruncatingStore(),
6335 MST->isCompressingStore());
6337 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6338 MST->isCompressingStore());
6340 MMO = DAG.getMachineFunction().
6341 getMachineMemOperand(MST->getPointerInfo(),
6342 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6343 SecondHalfAlignment, MST->getAAInfo(),
6346 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6347 MST->isTruncatingStore(),
6348 MST->isCompressingStore());
6350 AddToWorklist(Lo.getNode());
6351 AddToWorklist(Hi.getNode());
6353 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6358 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6360 if (Level >= AfterLegalizeTypes)
6363 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6364 SDValue Mask = MGT->getMask();
6367 // If the MGATHER result requires splitting and the mask is provided by a
6368 // SETCC, then split both nodes and its operands before legalization. This
6369 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6370 // and enables future optimizations (e.g. min/max pattern matching on X86).
6372 if (Mask.getOpcode() != ISD::SETCC)
6375 EVT VT = N->getValueType(0);
6377 // Check if any splitting is required.
6378 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6379 TargetLowering::TypeSplitVector)
6382 SDValue MaskLo, MaskHi, Lo, Hi;
6383 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6385 SDValue Src0 = MGT->getValue();
6386 SDValue Src0Lo, Src0Hi;
6387 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6392 SDValue Chain = MGT->getChain();
6393 EVT MemoryVT = MGT->getMemoryVT();
6394 unsigned Alignment = MGT->getOriginalAlignment();
6396 EVT LoMemVT, HiMemVT;
6397 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6399 SDValue BasePtr = MGT->getBasePtr();
6400 SDValue Index = MGT->getIndex();
6401 SDValue IndexLo, IndexHi;
6402 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6404 MachineMemOperand *MMO = DAG.getMachineFunction().
6405 getMachineMemOperand(MGT->getPointerInfo(),
6406 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6407 Alignment, MGT->getAAInfo(), MGT->getRanges());
6409 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6410 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6413 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6414 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6417 AddToWorklist(Lo.getNode());
6418 AddToWorklist(Hi.getNode());
6420 // Build a factor node to remember that this load is independent of the
6422 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6425 // Legalized the chain result - switch anything that used the old chain to
6427 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6429 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6431 SDValue RetOps[] = { GatherRes, Chain };
6432 return DAG.getMergeValues(RetOps, DL);
6435 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6437 if (Level >= AfterLegalizeTypes)
6440 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6441 SDValue Mask = MLD->getMask();
6444 // If the MLOAD result requires splitting and the mask is provided by a
6445 // SETCC, then split both nodes and its operands before legalization. This
6446 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6447 // and enables future optimizations (e.g. min/max pattern matching on X86).
6449 if (Mask.getOpcode() == ISD::SETCC) {
6450 EVT VT = N->getValueType(0);
6452 // Check if any splitting is required.
6453 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6454 TargetLowering::TypeSplitVector)
6457 SDValue MaskLo, MaskHi, Lo, Hi;
6458 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6460 SDValue Src0 = MLD->getSrc0();
6461 SDValue Src0Lo, Src0Hi;
6462 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6465 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6467 SDValue Chain = MLD->getChain();
6468 SDValue Ptr = MLD->getBasePtr();
6469 EVT MemoryVT = MLD->getMemoryVT();
6470 unsigned Alignment = MLD->getOriginalAlignment();
6472 // if Alignment is equal to the vector size,
6473 // take the half of it for the second part
6474 unsigned SecondHalfAlignment =
6475 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6476 Alignment/2 : Alignment;
6478 EVT LoMemVT, HiMemVT;
6479 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6481 MachineMemOperand *MMO = DAG.getMachineFunction().
6482 getMachineMemOperand(MLD->getPointerInfo(),
6483 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6484 Alignment, MLD->getAAInfo(), MLD->getRanges());
6486 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6487 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6489 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6490 MLD->isExpandingLoad());
6492 MMO = DAG.getMachineFunction().
6493 getMachineMemOperand(MLD->getPointerInfo(),
6494 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6495 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6497 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6498 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6500 AddToWorklist(Lo.getNode());
6501 AddToWorklist(Hi.getNode());
6503 // Build a factor node to remember that this load is independent of the
6505 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6508 // Legalized the chain result - switch anything that used the old chain to
6510 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6512 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6514 SDValue RetOps[] = { LoadRes, Chain };
6515 return DAG.getMergeValues(RetOps, DL);
6520 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6521 SDValue N0 = N->getOperand(0);
6522 SDValue N1 = N->getOperand(1);
6523 SDValue N2 = N->getOperand(2);
6526 // fold (vselect C, X, X) -> X
6530 // Canonicalize integer abs.
6531 // vselect (setg[te] X, 0), X, -X ->
6532 // vselect (setgt X, -1), X, -X ->
6533 // vselect (setl[te] X, 0), -X, X ->
6534 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6535 if (N0.getOpcode() == ISD::SETCC) {
6536 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6537 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6539 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6541 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6542 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6543 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6544 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6545 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6546 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6547 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6550 EVT VT = LHS.getValueType();
6551 SDValue Shift = DAG.getNode(
6552 ISD::SRA, DL, VT, LHS,
6553 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6554 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6555 AddToWorklist(Shift.getNode());
6556 AddToWorklist(Add.getNode());
6557 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6561 if (SimplifySelectOps(N, N1, N2))
6562 return SDValue(N, 0); // Don't revisit N.
6564 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6565 if (ISD::isBuildVectorAllOnes(N0.getNode()))
6567 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6568 if (ISD::isBuildVectorAllZeros(N0.getNode()))
6571 // The ConvertSelectToConcatVector function is assuming both the above
6572 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6574 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6575 N2.getOpcode() == ISD::CONCAT_VECTORS &&
6576 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6577 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6584 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6585 SDValue N0 = N->getOperand(0);
6586 SDValue N1 = N->getOperand(1);
6587 SDValue N2 = N->getOperand(2);
6588 SDValue N3 = N->getOperand(3);
6589 SDValue N4 = N->getOperand(4);
6590 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6592 // fold select_cc lhs, rhs, x, x, cc -> x
6596 // Determine if the condition we're dealing with is constant
6597 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6598 CC, SDLoc(N), false)) {
6599 AddToWorklist(SCC.getNode());
6601 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6602 if (!SCCC->isNullValue())
6603 return N2; // cond always true -> true val
6605 return N3; // cond always false -> false val
6606 } else if (SCC->isUndef()) {
6607 // When the condition is UNDEF, just return the first operand. This is
6608 // coherent the DAG creation, no setcc node is created in this case
6610 } else if (SCC.getOpcode() == ISD::SETCC) {
6611 // Fold to a simpler select_cc
6612 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6613 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6618 // If we can fold this based on the true/false value, do so.
6619 if (SimplifySelectOps(N, N2, N3))
6620 return SDValue(N, 0); // Don't revisit N.
6622 // fold select_cc into other things, such as min/max/abs
6623 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6626 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6627 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6628 cast<CondCodeSDNode>(N->getOperand(2))->get(),
6632 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6633 SDValue LHS = N->getOperand(0);
6634 SDValue RHS = N->getOperand(1);
6635 SDValue Carry = N->getOperand(2);
6636 SDValue Cond = N->getOperand(3);
6638 // If Carry is false, fold to a regular SETCC.
6639 if (Carry.getOpcode() == ISD::CARRY_FALSE)
6640 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6645 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6646 /// a build_vector of constants.
6647 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6648 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6649 /// Vector extends are not folded if operations are legal; this is to
6650 /// avoid introducing illegal build_vector dag nodes.
6651 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6652 SelectionDAG &DAG, bool LegalTypes,
6653 bool LegalOperations) {
6654 unsigned Opcode = N->getOpcode();
6655 SDValue N0 = N->getOperand(0);
6656 EVT VT = N->getValueType(0);
6658 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6659 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6660 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6661 && "Expected EXTEND dag node in input!");
6663 // fold (sext c1) -> c1
6664 // fold (zext c1) -> c1
6665 // fold (aext c1) -> c1
6666 if (isa<ConstantSDNode>(N0))
6667 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6669 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6670 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6671 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6672 EVT SVT = VT.getScalarType();
6673 if (!(VT.isVector() &&
6674 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6675 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6678 // We can fold this node into a build_vector.
6679 unsigned VTBits = SVT.getSizeInBits();
6680 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6681 SmallVector<SDValue, 8> Elts;
6682 unsigned NumElts = VT.getVectorNumElements();
6685 for (unsigned i=0; i != NumElts; ++i) {
6686 SDValue Op = N0->getOperand(i);
6687 if (Op->isUndef()) {
6688 Elts.push_back(DAG.getUNDEF(SVT));
6693 // Get the constant value and if needed trunc it to the size of the type.
6694 // Nodes like build_vector might have constants wider than the scalar type.
6695 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6696 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6697 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6699 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6702 return DAG.getBuildVector(VT, DL, Elts).getNode();
6705 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6706 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6707 // transformation. Returns true if extension are possible and the above
6708 // mentioned transformation is profitable.
6709 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6711 SmallVectorImpl<SDNode *> &ExtendNodes,
6712 const TargetLowering &TLI) {
6713 bool HasCopyToRegUses = false;
6714 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6715 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6716 UE = N0.getNode()->use_end();
6721 if (UI.getUse().getResNo() != N0.getResNo())
6723 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6724 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6725 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6726 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6727 // Sign bits will be lost after a zext.
6730 for (unsigned i = 0; i != 2; ++i) {
6731 SDValue UseOp = User->getOperand(i);
6734 if (!isa<ConstantSDNode>(UseOp))
6739 ExtendNodes.push_back(User);
6742 // If truncates aren't free and there are users we can't
6743 // extend, it isn't worthwhile.
6746 // Remember if this value is live-out.
6747 if (User->getOpcode() == ISD::CopyToReg)
6748 HasCopyToRegUses = true;
6751 if (HasCopyToRegUses) {
6752 bool BothLiveOut = false;
6753 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6755 SDUse &Use = UI.getUse();
6756 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6762 // Both unextended and extended values are live out. There had better be
6763 // a good reason for the transformation.
6764 return ExtendNodes.size();
6769 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6770 SDValue Trunc, SDValue ExtLoad,
6771 const SDLoc &DL, ISD::NodeType ExtType) {
6772 // Extend SetCC uses if necessary.
6773 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6774 SDNode *SetCC = SetCCs[i];
6775 SmallVector<SDValue, 4> Ops;
6777 for (unsigned j = 0; j != 2; ++j) {
6778 SDValue SOp = SetCC->getOperand(j);
6780 Ops.push_back(ExtLoad);
6782 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6785 Ops.push_back(SetCC->getOperand(2));
6786 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6790 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6791 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6792 SDValue N0 = N->getOperand(0);
6793 EVT DstVT = N->getValueType(0);
6794 EVT SrcVT = N0.getValueType();
6796 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6797 N->getOpcode() == ISD::ZERO_EXTEND) &&
6798 "Unexpected node type (not an extend)!");
6800 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6801 // For example, on a target with legal v4i32, but illegal v8i32, turn:
6802 // (v8i32 (sext (v8i16 (load x))))
6804 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6805 // (v4i32 (sextload (x + 16)))))
6806 // Where uses of the original load, i.e.:
6808 // are replaced with:
6810 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6811 // (v4i32 (sextload (x + 16)))))))
6813 // This combine is only applicable to illegal, but splittable, vectors.
6814 // All legal types, and illegal non-vector types, are handled elsewhere.
6815 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6817 if (N0->getOpcode() != ISD::LOAD)
6820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6822 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6823 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6824 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6827 SmallVector<SDNode *, 4> SetCCs;
6828 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6831 ISD::LoadExtType ExtType =
6832 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6834 // Try to split the vector types to get down to legal types.
6835 EVT SplitSrcVT = SrcVT;
6836 EVT SplitDstVT = DstVT;
6837 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6838 SplitSrcVT.getVectorNumElements() > 1) {
6839 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6840 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6843 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
6847 const unsigned NumSplits =
6848 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
6849 const unsigned Stride = SplitSrcVT.getStoreSize();
6850 SmallVector<SDValue, 4> Loads;
6851 SmallVector<SDValue, 4> Chains;
6853 SDValue BasePtr = LN0->getBasePtr();
6854 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
6855 const unsigned Offset = Idx * Stride;
6856 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
6858 SDValue SplitLoad = DAG.getExtLoad(
6859 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
6860 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
6861 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
6863 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
6864 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
6866 Loads.push_back(SplitLoad.getValue(0));
6867 Chains.push_back(SplitLoad.getValue(1));
6870 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
6871 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
6874 AddToWorklist(NewChain.getNode());
6876 CombineTo(N, NewValue);
6878 // Replace uses of the original load (before extension)
6879 // with a truncate of the concatenated sextloaded vectors.
6881 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
6882 CombineTo(N0.getNode(), Trunc, NewChain);
6883 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
6884 (ISD::NodeType)N->getOpcode());
6885 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6888 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
6890 EVT VT = N->getValueType(0);
6893 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6895 return SDValue(Res, 0);
6897 // fold (sext (sext x)) -> (sext x)
6898 // fold (sext (aext x)) -> (sext x)
6899 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6900 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
6902 if (N0.getOpcode() == ISD::TRUNCATE) {
6903 // fold (sext (truncate (load x))) -> (sext (smaller load x))
6904 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
6905 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6906 SDNode *oye = N0.getOperand(0).getNode();
6907 if (NarrowLoad.getNode() != N0.getNode()) {
6908 CombineTo(N0.getNode(), NarrowLoad);
6909 // CombineTo deleted the truncate, if needed, but not what's under it.
6912 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6915 // See if the value being truncated is already sign extended. If so, just
6916 // eliminate the trunc/sext pair.
6917 SDValue Op = N0.getOperand(0);
6918 unsigned OpBits = Op.getScalarValueSizeInBits();
6919 unsigned MidBits = N0.getScalarValueSizeInBits();
6920 unsigned DestBits = VT.getScalarSizeInBits();
6921 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
6923 if (OpBits == DestBits) {
6924 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
6925 // bits, it is already ready.
6926 if (NumSignBits > DestBits-MidBits)
6928 } else if (OpBits < DestBits) {
6929 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
6930 // bits, just sext from i32.
6931 if (NumSignBits > OpBits-MidBits)
6932 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
6934 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
6935 // bits, just truncate to i32.
6936 if (NumSignBits > OpBits-MidBits)
6937 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
6940 // fold (sext (truncate x)) -> (sextinreg x).
6941 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
6942 N0.getValueType())) {
6943 if (OpBits < DestBits)
6944 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
6945 else if (OpBits > DestBits)
6946 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
6947 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
6948 DAG.getValueType(N0.getValueType()));
6952 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6953 // Only generate vector extloads when 1) they're legal, and 2) they are
6954 // deemed desirable by the target.
6955 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6956 ((!LegalOperations && !VT.isVector() &&
6957 !cast<LoadSDNode>(N0)->isVolatile()) ||
6958 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6959 bool DoXform = true;
6960 SmallVector<SDNode*, 4> SetCCs;
6961 if (!N0.hasOneUse())
6962 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6964 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6966 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6967 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6968 LN0->getBasePtr(), N0.getValueType(),
6969 LN0->getMemOperand());
6970 CombineTo(N, ExtLoad);
6971 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6972 N0.getValueType(), ExtLoad);
6973 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6974 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
6975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6979 // fold (sext (load x)) to multiple smaller sextloads.
6980 // Only on illegal but splittable vectors.
6981 if (SDValue ExtLoad = CombineExtLoad(N))
6984 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6985 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6986 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6987 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6988 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6989 EVT MemVT = LN0->getMemoryVT();
6990 if ((!LegalOperations && !LN0->isVolatile()) ||
6991 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6992 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
6993 LN0->getBasePtr(), MemVT,
6994 LN0->getMemOperand());
6995 CombineTo(N, ExtLoad);
6996 CombineTo(N0.getNode(),
6997 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6998 N0.getValueType(), ExtLoad),
6999 ExtLoad.getValue(1));
7000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7004 // fold (sext (and/or/xor (load x), cst)) ->
7005 // (and/or/xor (sextload x), (sext cst))
7006 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7007 N0.getOpcode() == ISD::XOR) &&
7008 isa<LoadSDNode>(N0.getOperand(0)) &&
7009 N0.getOperand(1).getOpcode() == ISD::Constant &&
7010 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7011 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7012 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7013 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7014 bool DoXform = true;
7015 SmallVector<SDNode*, 4> SetCCs;
7016 if (!N0.hasOneUse())
7017 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7020 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7021 LN0->getChain(), LN0->getBasePtr(),
7023 LN0->getMemOperand());
7024 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7025 Mask = Mask.sext(VT.getSizeInBits());
7026 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7027 ExtLoad, DAG.getConstant(Mask, DL, VT));
7028 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7029 SDLoc(N0.getOperand(0)),
7030 N0.getOperand(0).getValueType(), ExtLoad);
7032 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7033 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7034 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7039 if (N0.getOpcode() == ISD::SETCC) {
7040 SDValue N00 = N0.getOperand(0);
7041 SDValue N01 = N0.getOperand(1);
7042 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7043 EVT N00VT = N0.getOperand(0).getValueType();
7045 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7046 // Only do this before legalize for now.
7047 if (VT.isVector() && !LegalOperations &&
7048 TLI.getBooleanContents(N00VT) ==
7049 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7050 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7051 // of the same size as the compared operands. Only optimize sext(setcc())
7052 // if this is the case.
7053 EVT SVT = getSetCCResultType(N00VT);
7055 // We know that the # elements of the results is the same as the
7056 // # elements of the compare (and the # elements of the compare result
7057 // for that matter). Check to see that they are the same size. If so,
7058 // we know that the element size of the sext'd result matches the
7059 // element size of the compare operands.
7060 if (VT.getSizeInBits() == SVT.getSizeInBits())
7061 return DAG.getSetCC(DL, VT, N00, N01, CC);
7063 // If the desired elements are smaller or larger than the source
7064 // elements, we can use a matching integer vector type and then
7065 // truncate/sign extend.
7066 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7067 if (SVT == MatchingVecType) {
7068 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7069 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7073 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7074 // Here, T can be 1 or -1, depending on the type of the setcc and
7075 // getBooleanContents().
7076 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7078 // To determine the "true" side of the select, we need to know the high bit
7079 // of the value returned by the setcc if it evaluates to true.
7080 // If the type of the setcc is i1, then the true case of the select is just
7081 // sext(i1 1), that is, -1.
7082 // If the type of the setcc is larger (say, i8) then the value of the high
7083 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7084 // of the appropriate width.
7085 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7086 : TLI.getConstTrueVal(DAG, VT, DL);
7087 SDValue Zero = DAG.getConstant(0, DL, VT);
7089 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7092 if (!VT.isVector()) {
7093 EVT SetCCVT = getSetCCResultType(N00VT);
7094 // Don't do this transform for i1 because there's a select transform
7095 // that would reverse it.
7096 // TODO: We should not do this transform at all without a target hook
7097 // because a sext is likely cheaper than a select?
7098 if (SetCCVT.getScalarSizeInBits() != 1 &&
7099 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7100 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7101 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7106 // fold (sext x) -> (zext x) if the sign bit is known zero.
7107 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7108 DAG.SignBitIsZero(N0))
7109 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7114 // isTruncateOf - If N is a truncate of some other value, return true, record
7115 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
7116 // This function computes KnownZero to avoid a duplicated call to
7117 // computeKnownBits in the caller.
7118 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7121 if (N->getOpcode() == ISD::TRUNCATE) {
7122 Op = N->getOperand(0);
7123 DAG.computeKnownBits(Op, KnownZero, KnownOne);
7127 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7128 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7131 SDValue Op0 = N->getOperand(0);
7132 SDValue Op1 = N->getOperand(1);
7133 assert(Op0.getValueType() == Op1.getValueType());
7135 if (isNullConstant(Op0))
7137 else if (isNullConstant(Op1))
7142 DAG.computeKnownBits(Op, KnownZero, KnownOne);
7144 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
7150 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7151 SDValue N0 = N->getOperand(0);
7152 EVT VT = N->getValueType(0);
7154 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7156 return SDValue(Res, 0);
7158 // fold (zext (zext x)) -> (zext x)
7159 // fold (zext (aext x)) -> (zext x)
7160 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7161 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7164 // fold (zext (truncate x)) -> (zext x) or
7165 // (zext (truncate x)) -> (truncate x)
7166 // This is valid when the truncated bits of x are already zero.
7167 // FIXME: We should extend this to work for vectors too.
7170 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
7171 APInt TruncatedBits =
7172 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7173 APInt(Op.getValueSizeInBits(), 0) :
7174 APInt::getBitsSet(Op.getValueSizeInBits(),
7175 N0.getValueSizeInBits(),
7176 std::min(Op.getValueSizeInBits(),
7177 VT.getSizeInBits()));
7178 if (TruncatedBits == (KnownZero & TruncatedBits)) {
7179 if (VT.bitsGT(Op.getValueType()))
7180 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
7181 if (VT.bitsLT(Op.getValueType()))
7182 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7188 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7189 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7190 if (N0.getOpcode() == ISD::TRUNCATE) {
7191 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7192 SDNode *oye = N0.getOperand(0).getNode();
7193 if (NarrowLoad.getNode() != N0.getNode()) {
7194 CombineTo(N0.getNode(), NarrowLoad);
7195 // CombineTo deleted the truncate, if needed, but not what's under it.
7198 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7202 // fold (zext (truncate x)) -> (and x, mask)
7203 if (N0.getOpcode() == ISD::TRUNCATE) {
7204 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7205 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7206 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7207 SDNode *oye = N0.getOperand(0).getNode();
7208 if (NarrowLoad.getNode() != N0.getNode()) {
7209 CombineTo(N0.getNode(), NarrowLoad);
7210 // CombineTo deleted the truncate, if needed, but not what's under it.
7213 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7216 EVT SrcVT = N0.getOperand(0).getValueType();
7217 EVT MinVT = N0.getValueType();
7219 // Try to mask before the extension to avoid having to generate a larger mask,
7220 // possibly over several sub-vectors.
7221 if (SrcVT.bitsLT(VT)) {
7222 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7223 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7224 SDValue Op = N0.getOperand(0);
7225 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7226 AddToWorklist(Op.getNode());
7227 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7231 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7232 SDValue Op = N0.getOperand(0);
7233 if (SrcVT.bitsLT(VT)) {
7234 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
7235 AddToWorklist(Op.getNode());
7236 } else if (SrcVT.bitsGT(VT)) {
7237 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
7238 AddToWorklist(Op.getNode());
7240 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7244 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7245 // if either of the casts is not free.
7246 if (N0.getOpcode() == ISD::AND &&
7247 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7248 N0.getOperand(1).getOpcode() == ISD::Constant &&
7249 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7250 N0.getValueType()) ||
7251 !TLI.isZExtFree(N0.getValueType(), VT))) {
7252 SDValue X = N0.getOperand(0).getOperand(0);
7253 if (X.getValueType().bitsLT(VT)) {
7254 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
7255 } else if (X.getValueType().bitsGT(VT)) {
7256 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7258 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7259 Mask = Mask.zext(VT.getSizeInBits());
7261 return DAG.getNode(ISD::AND, DL, VT,
7262 X, DAG.getConstant(Mask, DL, VT));
7265 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7266 // Only generate vector extloads when 1) they're legal, and 2) they are
7267 // deemed desirable by the target.
7268 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7269 ((!LegalOperations && !VT.isVector() &&
7270 !cast<LoadSDNode>(N0)->isVolatile()) ||
7271 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7272 bool DoXform = true;
7273 SmallVector<SDNode*, 4> SetCCs;
7274 if (!N0.hasOneUse())
7275 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7277 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7279 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7280 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7282 LN0->getBasePtr(), N0.getValueType(),
7283 LN0->getMemOperand());
7285 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7286 N0.getValueType(), ExtLoad);
7287 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7289 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7291 CombineTo(N, ExtLoad);
7292 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7296 // fold (zext (load x)) to multiple smaller zextloads.
7297 // Only on illegal but splittable vectors.
7298 if (SDValue ExtLoad = CombineExtLoad(N))
7301 // fold (zext (and/or/xor (load x), cst)) ->
7302 // (and/or/xor (zextload x), (zext cst))
7303 // Unless (and (load x) cst) will match as a zextload already and has
7304 // additional users.
7305 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7306 N0.getOpcode() == ISD::XOR) &&
7307 isa<LoadSDNode>(N0.getOperand(0)) &&
7308 N0.getOperand(1).getOpcode() == ISD::Constant &&
7309 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7310 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7311 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7312 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7313 bool DoXform = true;
7314 SmallVector<SDNode*, 4> SetCCs;
7315 if (!N0.hasOneUse()) {
7316 if (N0.getOpcode() == ISD::AND) {
7317 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7318 auto NarrowLoad = false;
7319 EVT LoadResultTy = AndC->getValueType(0);
7320 EVT ExtVT, LoadedVT;
7321 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7326 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7327 ISD::ZERO_EXTEND, SetCCs, TLI);
7330 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7331 LN0->getChain(), LN0->getBasePtr(),
7333 LN0->getMemOperand());
7334 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7335 Mask = Mask.zext(VT.getSizeInBits());
7337 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7338 ExtLoad, DAG.getConstant(Mask, DL, VT));
7339 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7340 SDLoc(N0.getOperand(0)),
7341 N0.getOperand(0).getValueType(), ExtLoad);
7343 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
7344 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
7346 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7351 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7352 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7353 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7354 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7355 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7356 EVT MemVT = LN0->getMemoryVT();
7357 if ((!LegalOperations && !LN0->isVolatile()) ||
7358 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7359 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7361 LN0->getBasePtr(), MemVT,
7362 LN0->getMemOperand());
7363 CombineTo(N, ExtLoad);
7364 CombineTo(N0.getNode(),
7365 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7367 ExtLoad.getValue(1));
7368 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7372 if (N0.getOpcode() == ISD::SETCC) {
7373 // Only do this before legalize for now.
7374 if (!LegalOperations && VT.isVector() &&
7375 N0.getValueType().getVectorElementType() == MVT::i1) {
7376 EVT N00VT = N0.getOperand(0).getValueType();
7377 if (getSetCCResultType(N00VT) == N0.getValueType())
7380 // We know that the # elements of the results is the same as the #
7381 // elements of the compare (and the # elements of the compare result for
7382 // that matter). Check to see that they are the same size. If so, we know
7383 // that the element size of the sext'd result matches the element size of
7384 // the compare operands.
7386 SDValue VecOnes = DAG.getConstant(1, DL, VT);
7387 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7388 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7389 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7390 N0.getOperand(1), N0.getOperand(2));
7391 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7394 // If the desired elements are smaller or larger than the source
7395 // elements we can use a matching integer vector type and then
7396 // truncate/sign extend.
7397 EVT MatchingElementType = EVT::getIntegerVT(
7398 *DAG.getContext(), N00VT.getScalarSizeInBits());
7399 EVT MatchingVectorType = EVT::getVectorVT(
7400 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7402 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7403 N0.getOperand(1), N0.getOperand(2));
7404 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7408 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7410 if (SDValue SCC = SimplifySelectCC(
7411 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7412 DAG.getConstant(0, DL, VT),
7413 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7417 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7418 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7419 isa<ConstantSDNode>(N0.getOperand(1)) &&
7420 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7422 SDValue ShAmt = N0.getOperand(1);
7423 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7424 if (N0.getOpcode() == ISD::SHL) {
7425 SDValue InnerZExt = N0.getOperand(0);
7426 // If the original shl may be shifting out bits, do not perform this
7428 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7429 InnerZExt.getOperand(0).getValueSizeInBits();
7430 if (ShAmtVal > KnownZeroBits)
7436 // Ensure that the shift amount is wide enough for the shifted value.
7437 if (VT.getSizeInBits() >= 256)
7438 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7440 return DAG.getNode(N0.getOpcode(), DL, VT,
7441 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7448 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7449 SDValue N0 = N->getOperand(0);
7450 EVT VT = N->getValueType(0);
7452 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7454 return SDValue(Res, 0);
7456 // fold (aext (aext x)) -> (aext x)
7457 // fold (aext (zext x)) -> (zext x)
7458 // fold (aext (sext x)) -> (sext x)
7459 if (N0.getOpcode() == ISD::ANY_EXTEND ||
7460 N0.getOpcode() == ISD::ZERO_EXTEND ||
7461 N0.getOpcode() == ISD::SIGN_EXTEND)
7462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7464 // fold (aext (truncate (load x))) -> (aext (smaller load x))
7465 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7466 if (N0.getOpcode() == ISD::TRUNCATE) {
7467 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7468 SDNode *oye = N0.getOperand(0).getNode();
7469 if (NarrowLoad.getNode() != N0.getNode()) {
7470 CombineTo(N0.getNode(), NarrowLoad);
7471 // CombineTo deleted the truncate, if needed, but not what's under it.
7474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7478 // fold (aext (truncate x))
7479 if (N0.getOpcode() == ISD::TRUNCATE) {
7480 SDValue TruncOp = N0.getOperand(0);
7481 if (TruncOp.getValueType() == VT)
7482 return TruncOp; // x iff x size == zext size.
7483 if (TruncOp.getValueType().bitsGT(VT))
7484 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
7485 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
7488 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7489 // if the trunc is not free.
7490 if (N0.getOpcode() == ISD::AND &&
7491 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7492 N0.getOperand(1).getOpcode() == ISD::Constant &&
7493 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7494 N0.getValueType())) {
7496 SDValue X = N0.getOperand(0).getOperand(0);
7497 if (X.getValueType().bitsLT(VT)) {
7498 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
7499 } else if (X.getValueType().bitsGT(VT)) {
7500 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
7502 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7503 Mask = Mask.zext(VT.getSizeInBits());
7504 return DAG.getNode(ISD::AND, DL, VT,
7505 X, DAG.getConstant(Mask, DL, VT));
7508 // fold (aext (load x)) -> (aext (truncate (extload x)))
7509 // None of the supported targets knows how to perform load and any_ext
7510 // on vectors in one instruction. We only perform this transformation on
7512 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7513 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7514 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7515 bool DoXform = true;
7516 SmallVector<SDNode*, 4> SetCCs;
7517 if (!N0.hasOneUse())
7518 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7520 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7521 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7523 LN0->getBasePtr(), N0.getValueType(),
7524 LN0->getMemOperand());
7525 CombineTo(N, ExtLoad);
7526 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7527 N0.getValueType(), ExtLoad);
7528 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
7529 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7531 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7535 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7536 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7537 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
7538 if (N0.getOpcode() == ISD::LOAD &&
7539 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7541 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7542 ISD::LoadExtType ExtType = LN0->getExtensionType();
7543 EVT MemVT = LN0->getMemoryVT();
7544 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7545 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7546 VT, LN0->getChain(), LN0->getBasePtr(),
7547 MemVT, LN0->getMemOperand());
7548 CombineTo(N, ExtLoad);
7549 CombineTo(N0.getNode(),
7550 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7551 N0.getValueType(), ExtLoad),
7552 ExtLoad.getValue(1));
7553 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7557 if (N0.getOpcode() == ISD::SETCC) {
7559 // aext(setcc) -> vsetcc
7560 // aext(setcc) -> truncate(vsetcc)
7561 // aext(setcc) -> aext(vsetcc)
7562 // Only do this before legalize for now.
7563 if (VT.isVector() && !LegalOperations) {
7564 EVT N0VT = N0.getOperand(0).getValueType();
7565 // We know that the # elements of the results is the same as the
7566 // # elements of the compare (and the # elements of the compare result
7567 // for that matter). Check to see that they are the same size. If so,
7568 // we know that the element size of the sext'd result matches the
7569 // element size of the compare operands.
7570 if (VT.getSizeInBits() == N0VT.getSizeInBits())
7571 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7573 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7574 // If the desired elements are smaller or larger than the source
7575 // elements we can use a matching integer vector type and then
7576 // truncate/any extend
7578 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7580 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7582 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7583 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7587 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7589 if (SDValue SCC = SimplifySelectCC(
7590 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7591 DAG.getConstant(0, DL, VT),
7592 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7599 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7600 SDValue N0 = N->getOperand(0);
7601 SDValue N1 = N->getOperand(1);
7602 EVT EVT = cast<VTSDNode>(N1)->getVT();
7604 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7605 if (N0.getOpcode() == ISD::AssertZext &&
7606 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7612 /// See if the specified operand can be simplified with the knowledge that only
7613 /// the bits specified by Mask are used. If so, return the simpler operand,
7614 /// otherwise return a null SDValue.
7616 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7617 /// simplify nodes with multiple uses more aggressively.)
7618 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7619 switch (V.getOpcode()) {
7621 case ISD::Constant: {
7622 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7623 assert(CV && "Const value should be ConstSDNode.");
7624 const APInt &CVal = CV->getAPIntValue();
7625 APInt NewVal = CVal & Mask;
7627 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7632 // If the LHS or RHS don't contribute bits to the or, drop them.
7633 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7634 return V.getOperand(1);
7635 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7636 return V.getOperand(0);
7639 // Only look at single-use SRLs.
7640 if (!V.getNode()->hasOneUse())
7642 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7643 // See if we can recursively simplify the LHS.
7644 unsigned Amt = RHSC->getZExtValue();
7646 // Watch out for shift count overflow though.
7647 if (Amt >= Mask.getBitWidth()) break;
7648 APInt NewMask = Mask << Amt;
7649 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7650 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7651 SimplifyLHS, V.getOperand(1));
7655 // X & -1 -> X (ignoring bits which aren't demanded).
7656 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7657 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7658 return V.getOperand(0);
7665 /// If the result of a wider load is shifted to right of N bits and then
7666 /// truncated to a narrower type and where N is a multiple of number of bits of
7667 /// the narrower type, transform it to a narrower load from address + N / num of
7668 /// bits of new type. If the result is to be extended, also fold the extension
7669 /// to form a extending load.
7670 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7671 unsigned Opc = N->getOpcode();
7673 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7674 SDValue N0 = N->getOperand(0);
7675 EVT VT = N->getValueType(0);
7678 // This transformation isn't valid for vector loads.
7682 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7684 if (Opc == ISD::SIGN_EXTEND_INREG) {
7685 ExtType = ISD::SEXTLOAD;
7686 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7687 } else if (Opc == ISD::SRL) {
7688 // Another special-case: SRL is basically zero-extending a narrower value.
7689 ExtType = ISD::ZEXTLOAD;
7691 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7692 if (!N01) return SDValue();
7693 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7694 VT.getSizeInBits() - N01->getZExtValue());
7696 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7699 unsigned EVTBits = ExtVT.getSizeInBits();
7701 // Do not generate loads of non-round integer types since these can
7702 // be expensive (and would be wrong if the type is not byte sized).
7703 if (!ExtVT.isRound())
7707 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7708 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7709 ShAmt = N01->getZExtValue();
7710 // Is the shift amount a multiple of size of VT?
7711 if ((ShAmt & (EVTBits-1)) == 0) {
7712 N0 = N0.getOperand(0);
7713 // Is the load width a multiple of size of VT?
7714 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7718 // At this point, we must have a load or else we can't do the transform.
7719 if (!isa<LoadSDNode>(N0)) return SDValue();
7721 // Because a SRL must be assumed to *need* to zero-extend the high bits
7722 // (as opposed to anyext the high bits), we can't combine the zextload
7723 // lowering of SRL and an sextload.
7724 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7727 // If the shift amount is larger than the input type then we're not
7728 // accessing any of the loaded bytes. If the load was a zextload/extload
7729 // then the result of the shift+trunc is zero/undef (handled elsewhere).
7730 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7735 // If the load is shifted left (and the result isn't shifted back right),
7736 // we can fold the truncate through the shift.
7737 unsigned ShLeftAmt = 0;
7738 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7739 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7740 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7741 ShLeftAmt = N01->getZExtValue();
7742 N0 = N0.getOperand(0);
7746 // If we haven't found a load, we can't narrow it. Don't transform one with
7747 // multiple uses, this would require adding a new load.
7748 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7751 // Don't change the width of a volatile load.
7752 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7753 if (LN0->isVolatile())
7756 // Verify that we are actually reducing a load width here.
7757 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7760 // For the transform to be legal, the load must produce only two values
7761 // (the value loaded and the chain). Don't transform a pre-increment
7762 // load, for example, which produces an extra value. Otherwise the
7763 // transformation is not equivalent, and the downstream logic to replace
7764 // uses gets things wrong.
7765 if (LN0->getNumValues() > 2)
7768 // If the load that we're shrinking is an extload and we're not just
7769 // discarding the extension we can't simply shrink the load. Bail.
7770 // TODO: It would be possible to merge the extensions in some cases.
7771 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7772 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7775 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7778 EVT PtrType = N0.getOperand(1).getValueType();
7780 if (PtrType == MVT::Untyped || PtrType.isExtended())
7781 // It's not possible to generate a constant of extended or untyped type.
7784 // For big endian targets, we need to adjust the offset to the pointer to
7785 // load the correct bytes.
7786 if (DAG.getDataLayout().isBigEndian()) {
7787 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7788 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7789 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7792 uint64_t PtrOff = ShAmt / 8;
7793 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7795 // The original load itself didn't wrap, so an offset within it doesn't.
7797 Flags.setNoUnsignedWrap(true);
7798 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7799 PtrType, LN0->getBasePtr(),
7800 DAG.getConstant(PtrOff, DL, PtrType),
7802 AddToWorklist(NewPtr.getNode());
7805 if (ExtType == ISD::NON_EXTLOAD)
7806 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
7807 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
7808 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7810 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
7811 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
7812 NewAlign, LN0->getMemOperand()->getFlags(),
7815 // Replace the old load's chain with the new load's chain.
7816 WorklistRemover DeadNodes(*this);
7817 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7819 // Shift the result left, if we've swallowed a left shift.
7820 SDValue Result = Load;
7821 if (ShLeftAmt != 0) {
7822 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
7823 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
7825 // If the shift amount is as large as the result size (but, presumably,
7826 // no larger than the source) then the useful bits of the result are
7827 // zero; we can't simply return the shortened shift, because the result
7828 // of that operation is undefined.
7830 if (ShLeftAmt >= VT.getSizeInBits())
7831 Result = DAG.getConstant(0, DL, VT);
7833 Result = DAG.getNode(ISD::SHL, DL, VT,
7834 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
7837 // Return the new loaded value.
7841 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
7842 SDValue N0 = N->getOperand(0);
7843 SDValue N1 = N->getOperand(1);
7844 EVT VT = N->getValueType(0);
7845 EVT EVT = cast<VTSDNode>(N1)->getVT();
7846 unsigned VTBits = VT.getScalarSizeInBits();
7847 unsigned EVTBits = EVT.getScalarSizeInBits();
7850 return DAG.getUNDEF(VT);
7852 // fold (sext_in_reg c1) -> c1
7853 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
7854 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
7856 // If the input is already sign extended, just drop the extension.
7857 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
7860 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
7861 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7862 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
7863 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7864 N0.getOperand(0), N1);
7866 // fold (sext_in_reg (sext x)) -> (sext x)
7867 // fold (sext_in_reg (aext x)) -> (sext x)
7868 // if x is small enough.
7869 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
7870 SDValue N00 = N0.getOperand(0);
7871 if (N00.getScalarValueSizeInBits() <= EVTBits &&
7872 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7873 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7876 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
7877 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
7878 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
7879 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
7880 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
7881 if (!LegalOperations ||
7882 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
7883 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
7886 // fold (sext_in_reg (zext x)) -> (sext x)
7887 // iff we are extending the source sign bit.
7888 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
7889 SDValue N00 = N0.getOperand(0);
7890 if (N00.getScalarValueSizeInBits() == EVTBits &&
7891 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
7892 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
7895 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
7896 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
7897 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
7899 // fold operands of sext_in_reg based on knowledge that the top bits are not
7901 if (SimplifyDemandedBits(SDValue(N, 0)))
7902 return SDValue(N, 0);
7904 // fold (sext_in_reg (load x)) -> (smaller sextload x)
7905 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
7906 if (SDValue NarrowLoad = ReduceLoadWidth(N))
7909 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
7910 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
7911 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
7912 if (N0.getOpcode() == ISD::SRL) {
7913 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
7914 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
7915 // We can turn this into an SRA iff the input to the SRL is already sign
7917 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
7918 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
7919 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
7920 N0.getOperand(0), N0.getOperand(1));
7924 // fold (sext_inreg (extload x)) -> (sextload x)
7925 if (ISD::isEXTLoad(N0.getNode()) &&
7926 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7927 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7928 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7929 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7931 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7933 LN0->getBasePtr(), EVT,
7934 LN0->getMemOperand());
7935 CombineTo(N, ExtLoad);
7936 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7937 AddToWorklist(ExtLoad.getNode());
7938 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7940 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
7941 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7943 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
7944 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7945 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
7946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7947 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
7949 LN0->getBasePtr(), EVT,
7950 LN0->getMemOperand());
7951 CombineTo(N, ExtLoad);
7952 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
7953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7956 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
7957 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
7958 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
7959 N0.getOperand(1), false))
7960 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
7967 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
7968 SDValue N0 = N->getOperand(0);
7969 EVT VT = N->getValueType(0);
7972 return DAG.getUNDEF(VT);
7974 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7976 return SDValue(Res, 0);
7981 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
7982 SDValue N0 = N->getOperand(0);
7983 EVT VT = N->getValueType(0);
7986 return DAG.getUNDEF(VT);
7988 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7990 return SDValue(Res, 0);
7995 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
7996 SDValue N0 = N->getOperand(0);
7997 EVT VT = N->getValueType(0);
7998 bool isLE = DAG.getDataLayout().isLittleEndian();
8001 if (N0.getValueType() == N->getValueType(0))
8003 // fold (truncate c1) -> c1
8004 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8005 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8006 // fold (truncate (truncate x)) -> (truncate x)
8007 if (N0.getOpcode() == ISD::TRUNCATE)
8008 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8009 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8010 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8011 N0.getOpcode() == ISD::SIGN_EXTEND ||
8012 N0.getOpcode() == ISD::ANY_EXTEND) {
8013 // if the source is smaller than the dest, we still need an extend.
8014 if (N0.getOperand(0).getValueType().bitsLT(VT))
8015 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8016 // if the source is larger than the dest, than we just need the truncate.
8017 if (N0.getOperand(0).getValueType().bitsGT(VT))
8018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8019 // if the source and dest are the same type, we can drop both the extend
8020 // and the truncate.
8021 return N0.getOperand(0);
8024 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8025 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8028 // Fold extract-and-trunc into a narrow extract. For example:
8029 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8030 // i32 y = TRUNCATE(i64 x)
8032 // v16i8 b = BITCAST (v2i64 val)
8033 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8035 // Note: We only run this optimization after type legalization (which often
8036 // creates this pattern) and before operation legalization after which
8037 // we need to be more careful about the vector instructions that we generate.
8038 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8039 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8041 EVT VecTy = N0.getOperand(0).getValueType();
8042 EVT ExTy = N0.getValueType();
8043 EVT TrTy = N->getValueType(0);
8045 unsigned NumElem = VecTy.getVectorNumElements();
8046 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8048 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8049 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8051 SDValue EltNo = N0->getOperand(1);
8052 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8053 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8054 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8055 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8058 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8059 DAG.getBitcast(NVT, N0.getOperand(0)),
8060 DAG.getConstant(Index, DL, IndexTy));
8064 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8065 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8066 EVT SrcVT = N0.getValueType();
8067 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8068 TLI.isTruncateFree(SrcVT, VT)) {
8070 SDValue Cond = N0.getOperand(0);
8071 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8072 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8073 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8077 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8078 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8079 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8080 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8081 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
8082 uint64_t Amt = CAmt->getZExtValue();
8083 unsigned Size = VT.getScalarSizeInBits();
8087 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8089 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8090 return DAG.getNode(ISD::SHL, SL, VT, Trunc,
8091 DAG.getConstant(Amt, SL, AmtVT));
8096 // Fold a series of buildvector, bitcast, and truncate if possible.
8098 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8099 // (2xi32 (buildvector x, y)).
8100 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8101 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8102 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8103 N0.getOperand(0).hasOneUse()) {
8105 SDValue BuildVect = N0.getOperand(0);
8106 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8107 EVT TruncVecEltTy = VT.getVectorElementType();
8109 // Check that the element types match.
8110 if (BuildVectEltTy == TruncVecEltTy) {
8111 // Now we only need to compute the offset of the truncated elements.
8112 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8113 unsigned TruncVecNumElts = VT.getVectorNumElements();
8114 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8116 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8117 "Invalid number of elements");
8119 SmallVector<SDValue, 8> Opnds;
8120 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8121 Opnds.push_back(BuildVect.getOperand(i));
8123 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8127 // See if we can simplify the input to this truncate through knowledge that
8128 // only the low bits are being used.
8129 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8130 // Currently we only perform this optimization on scalars because vectors
8131 // may have different active low bits.
8132 if (!VT.isVector()) {
8133 if (SDValue Shorter =
8134 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8135 VT.getSizeInBits())))
8136 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8139 // fold (truncate (load x)) -> (smaller load x)
8140 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8141 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8142 if (SDValue Reduced = ReduceLoadWidth(N))
8145 // Handle the case where the load remains an extending load even
8146 // after truncation.
8147 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8148 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8149 if (!LN0->isVolatile() &&
8150 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8151 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8152 VT, LN0->getChain(), LN0->getBasePtr(),
8154 LN0->getMemOperand());
8155 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8161 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8162 // where ... are all 'undef'.
8163 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8164 SmallVector<EVT, 8> VTs;
8167 unsigned NumDefs = 0;
8169 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8170 SDValue X = N0.getOperand(i);
8176 // Stop if more than one members are non-undef.
8179 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8180 VT.getVectorElementType(),
8181 X.getValueType().getVectorNumElements()));
8185 return DAG.getUNDEF(VT);
8188 assert(V.getNode() && "The single defined operand is empty!");
8189 SmallVector<SDValue, 8> Opnds;
8190 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8192 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8195 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8196 AddToWorklist(NV.getNode());
8197 Opnds.push_back(NV);
8199 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8203 // Fold truncate of a bitcast of a vector to an extract of the low vector
8206 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8207 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8208 SDValue VecSrc = N0.getOperand(0);
8209 EVT SrcVT = VecSrc.getValueType();
8210 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8211 (!LegalOperations ||
8212 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8215 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8216 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8217 VecSrc, DAG.getConstant(0, SL, IdxVT));
8221 // Simplify the operands using demanded-bits information.
8222 if (!VT.isVector() &&
8223 SimplifyDemandedBits(SDValue(N, 0)))
8224 return SDValue(N, 0);
8226 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8227 // When the adde's carry is not used.
8228 if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() &&
8229 !N0.getNode()->hasAnyUseOfValue(1) &&
8230 (!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) {
8232 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8233 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8234 return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue),
8235 X, Y, N0.getOperand(2));
8241 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8242 SDValue Elt = N->getOperand(i);
8243 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8244 return Elt.getNode();
8245 return Elt.getOperand(Elt.getResNo()).getNode();
8248 /// build_pair (load, load) -> load
8249 /// if load locations are consecutive.
8250 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8251 assert(N->getOpcode() == ISD::BUILD_PAIR);
8253 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8254 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8255 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8256 LD1->getAddressSpace() != LD2->getAddressSpace())
8258 EVT LD1VT = LD1->getValueType(0);
8259 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8260 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8261 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8262 unsigned Align = LD1->getAlignment();
8263 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8264 VT.getTypeForEVT(*DAG.getContext()));
8266 if (NewAlign <= Align &&
8267 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8268 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8269 LD1->getPointerInfo(), Align);
8275 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8276 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8277 // and Lo parts; on big-endian machines it doesn't.
8278 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8281 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8282 const TargetLowering &TLI) {
8283 // If this is not a bitcast to an FP type or if the target doesn't have
8284 // IEEE754-compliant FP logic, we're done.
8285 EVT VT = N->getValueType(0);
8286 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8289 // TODO: Use splat values for the constant-checking below and remove this
8291 SDValue N0 = N->getOperand(0);
8292 EVT SourceVT = N0.getValueType();
8293 if (SourceVT.isVector())
8298 switch (N0.getOpcode()) {
8300 FPOpcode = ISD::FABS;
8301 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8304 FPOpcode = ISD::FNEG;
8305 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8307 // TODO: ISD::OR --> ISD::FNABS?
8312 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8313 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8314 SDValue LogicOp0 = N0.getOperand(0);
8315 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8316 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8317 LogicOp0.getOpcode() == ISD::BITCAST &&
8318 LogicOp0->getOperand(0).getValueType() == VT)
8319 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8324 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8325 SDValue N0 = N->getOperand(0);
8326 EVT VT = N->getValueType(0);
8329 return DAG.getUNDEF(VT);
8331 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8332 // Only do this before legalize, since afterward the target may be depending
8333 // on the bitconvert.
8334 // First check to see if this is all constant.
8336 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8338 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8340 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8341 assert(!DestEltVT.isVector() &&
8342 "Element type of vector ValueType must not be vector!");
8344 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8347 // If the input is a constant, let getNode fold it.
8348 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8349 // If we can't allow illegal operations, we need to check that this is just
8350 // a fp -> int or int -> conversion and that the resulting operation will
8352 if (!LegalOperations ||
8353 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8354 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8355 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8356 TLI.isOperationLegal(ISD::Constant, VT)))
8357 return DAG.getBitcast(VT, N0);
8360 // (conv (conv x, t1), t2) -> (conv x, t2)
8361 if (N0.getOpcode() == ISD::BITCAST)
8362 return DAG.getBitcast(VT, N0.getOperand(0));
8364 // fold (conv (load x)) -> (load (conv*)x)
8365 // If the resultant load doesn't need a higher alignment than the original!
8366 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8367 // Do not change the width of a volatile load.
8368 !cast<LoadSDNode>(N0)->isVolatile() &&
8369 // Do not remove the cast if the types differ in endian layout.
8370 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8371 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8372 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8373 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8374 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8375 unsigned OrigAlign = LN0->getAlignment();
8378 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8379 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8382 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8383 LN0->getPointerInfo(), OrigAlign,
8384 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8385 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8390 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8393 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8394 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8397 // fold (bitcast (fneg x)) ->
8398 // flipbit = signbit
8399 // (xor (bitcast x) (build_pair flipbit, flipbit))
8401 // fold (bitcast (fabs x)) ->
8402 // flipbit = (and (extract_element (bitcast x), 0), signbit)
8403 // (xor (bitcast x) (build_pair flipbit, flipbit))
8404 // This often reduces constant pool loads.
8405 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8406 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8407 N0.getNode()->hasOneUse() && VT.isInteger() &&
8408 !VT.isVector() && !N0.getValueType().isVector()) {
8409 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8410 AddToWorklist(NewConv.getNode());
8413 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8414 assert(VT.getSizeInBits() == 128);
8415 SDValue SignBit = DAG.getConstant(
8416 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8418 if (N0.getOpcode() == ISD::FNEG) {
8420 AddToWorklist(FlipBit.getNode());
8422 assert(N0.getOpcode() == ISD::FABS);
8424 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8425 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8427 AddToWorklist(Hi.getNode());
8428 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8429 AddToWorklist(FlipBit.getNode());
8432 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8433 AddToWorklist(FlipBits.getNode());
8434 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8436 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8437 if (N0.getOpcode() == ISD::FNEG)
8438 return DAG.getNode(ISD::XOR, DL, VT,
8439 NewConv, DAG.getConstant(SignBit, DL, VT));
8440 assert(N0.getOpcode() == ISD::FABS);
8441 return DAG.getNode(ISD::AND, DL, VT,
8442 NewConv, DAG.getConstant(~SignBit, DL, VT));
8445 // fold (bitconvert (fcopysign cst, x)) ->
8446 // (or (and (bitconvert x), sign), (and cst, (not sign)))
8447 // Note that we don't handle (copysign x, cst) because this can always be
8448 // folded to an fneg or fabs.
8451 // fold (bitcast (fcopysign cst, x)) ->
8452 // flipbit = (and (extract_element
8453 // (xor (bitcast cst), (bitcast x)), 0),
8455 // (xor (bitcast cst) (build_pair flipbit, flipbit))
8456 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8457 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8458 VT.isInteger() && !VT.isVector()) {
8459 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8460 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8461 if (isTypeLegal(IntXVT)) {
8462 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8463 AddToWorklist(X.getNode());
8465 // If X has a different width than the result/lhs, sext it or truncate it.
8466 unsigned VTWidth = VT.getSizeInBits();
8467 if (OrigXWidth < VTWidth) {
8468 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8469 AddToWorklist(X.getNode());
8470 } else if (OrigXWidth > VTWidth) {
8471 // To get the sign bit in the right place, we have to shift it right
8472 // before truncating.
8474 X = DAG.getNode(ISD::SRL, DL,
8475 X.getValueType(), X,
8476 DAG.getConstant(OrigXWidth-VTWidth, DL,
8478 AddToWorklist(X.getNode());
8479 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8480 AddToWorklist(X.getNode());
8483 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8484 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8485 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8486 AddToWorklist(Cst.getNode());
8487 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8488 AddToWorklist(X.getNode());
8489 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8490 AddToWorklist(XorResult.getNode());
8491 SDValue XorResult64 = DAG.getNode(
8492 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8493 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8495 AddToWorklist(XorResult64.getNode());
8497 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8498 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8499 AddToWorklist(FlipBit.getNode());
8501 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8502 AddToWorklist(FlipBits.getNode());
8503 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8505 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8506 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8507 X, DAG.getConstant(SignBit, SDLoc(X), VT));
8508 AddToWorklist(X.getNode());
8510 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8511 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8512 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8513 AddToWorklist(Cst.getNode());
8515 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8519 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8520 if (N0.getOpcode() == ISD::BUILD_PAIR)
8521 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8524 // Remove double bitcasts from shuffles - this is often a legacy of
8525 // XformToShuffleWithZero being used to combine bitmaskings (of
8526 // float vectors bitcast to integer vectors) into shuffles.
8527 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8528 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8529 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8530 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8531 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8532 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8534 // If operands are a bitcast, peek through if it casts the original VT.
8535 // If operands are a constant, just bitcast back to original VT.
8536 auto PeekThroughBitcast = [&](SDValue Op) {
8537 if (Op.getOpcode() == ISD::BITCAST &&
8538 Op.getOperand(0).getValueType() == VT)
8539 return SDValue(Op.getOperand(0));
8540 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8541 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8542 return DAG.getBitcast(VT, Op);
8546 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8547 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8552 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8553 SmallVector<int, 8> NewMask;
8554 for (int M : SVN->getMask())
8555 for (int i = 0; i != MaskScale; ++i)
8556 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8558 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8560 std::swap(SV0, SV1);
8561 ShuffleVectorSDNode::commuteMask(NewMask);
8562 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8566 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8572 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8573 EVT VT = N->getValueType(0);
8574 return CombineConsecutiveLoads(N, VT);
8577 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8578 /// operands. DstEltVT indicates the destination element value type.
8579 SDValue DAGCombiner::
8580 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8581 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8583 // If this is already the right type, we're done.
8584 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8586 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8587 unsigned DstBitSize = DstEltVT.getSizeInBits();
8589 // If this is a conversion of N elements of one type to N elements of another
8590 // type, convert each element. This handles FP<->INT cases.
8591 if (SrcBitSize == DstBitSize) {
8592 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8593 BV->getValueType(0).getVectorNumElements());
8595 // Due to the FP element handling below calling this routine recursively,
8596 // we can end up with a scalar-to-vector node here.
8597 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8598 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8599 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8601 SmallVector<SDValue, 8> Ops;
8602 for (SDValue Op : BV->op_values()) {
8603 // If the vector element type is not legal, the BUILD_VECTOR operands
8604 // are promoted and implicitly truncated. Make that explicit here.
8605 if (Op.getValueType() != SrcEltVT)
8606 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8607 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8608 AddToWorklist(Ops.back().getNode());
8610 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8613 // Otherwise, we're growing or shrinking the elements. To avoid having to
8614 // handle annoying details of growing/shrinking FP values, we convert them to
8616 if (SrcEltVT.isFloatingPoint()) {
8617 // Convert the input float vector to a int vector where the elements are the
8619 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8620 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8624 // Now we know the input is an integer vector. If the output is a FP type,
8625 // convert to integer first, then to FP of the right size.
8626 if (DstEltVT.isFloatingPoint()) {
8627 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8628 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8630 // Next, convert to FP elements of the same size.
8631 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8636 // Okay, we know the src/dst types are both integers of differing types.
8637 // Handling growing first.
8638 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8639 if (SrcBitSize < DstBitSize) {
8640 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8642 SmallVector<SDValue, 8> Ops;
8643 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8644 i += NumInputsPerOutput) {
8645 bool isLE = DAG.getDataLayout().isLittleEndian();
8646 APInt NewBits = APInt(DstBitSize, 0);
8647 bool EltIsUndef = true;
8648 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8649 // Shift the previously computed bits over.
8650 NewBits <<= SrcBitSize;
8651 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8652 if (Op.isUndef()) continue;
8655 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8656 zextOrTrunc(SrcBitSize).zext(DstBitSize);
8660 Ops.push_back(DAG.getUNDEF(DstEltVT));
8662 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8665 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8666 return DAG.getBuildVector(VT, DL, Ops);
8669 // Finally, this must be the case where we are shrinking elements: each input
8670 // turns into multiple outputs.
8671 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8672 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8673 NumOutputsPerInput*BV->getNumOperands());
8674 SmallVector<SDValue, 8> Ops;
8676 for (const SDValue &Op : BV->op_values()) {
8678 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8682 APInt OpVal = cast<ConstantSDNode>(Op)->
8683 getAPIntValue().zextOrTrunc(SrcBitSize);
8685 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8686 APInt ThisVal = OpVal.trunc(DstBitSize);
8687 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8688 OpVal.lshrInPlace(DstBitSize);
8691 // For big endian targets, swap the order of the pieces of each element.
8692 if (DAG.getDataLayout().isBigEndian())
8693 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8696 return DAG.getBuildVector(VT, DL, Ops);
8699 static bool isContractable(SDNode *N) {
8700 SDNodeFlags F = cast<BinaryWithFlagsSDNode>(N)->Flags;
8701 return F.hasAllowContract() || F.hasUnsafeAlgebra();
8704 /// Try to perform FMA combining on a given FADD node.
8705 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8706 SDValue N0 = N->getOperand(0);
8707 SDValue N1 = N->getOperand(1);
8708 EVT VT = N->getValueType(0);
8711 const TargetOptions &Options = DAG.getTarget().Options;
8713 // Floating-point multiply-add with intermediate rounding.
8714 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8716 // Floating-point multiply-add without intermediate rounding.
8718 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8719 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8721 // No valid opcode, do not combine.
8722 if (!HasFMAD && !HasFMA)
8725 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8726 Options.UnsafeFPMath || HasFMAD);
8727 // If the addition is not contractable, do not combine.
8728 if (!AllowFusionGlobally && !isContractable(N))
8731 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8732 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8735 // Always prefer FMAD to FMA for precision.
8736 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8737 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8738 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8740 // Is the node an FMUL and contractable either due to global flags or
8742 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8743 if (N.getOpcode() != ISD::FMUL)
8745 return AllowFusionGlobally || isContractable(N.getNode());
8747 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8748 // prefer to fold the multiply with fewer uses.
8749 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8750 if (N0.getNode()->use_size() > N1.getNode()->use_size())
8754 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8755 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8756 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8757 N0.getOperand(0), N0.getOperand(1), N1);
8760 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8761 // Note: Commutes FADD operands.
8762 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8763 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8764 N1.getOperand(0), N1.getOperand(1), N0);
8767 // Look through FP_EXTEND nodes to do more combining.
8768 if (LookThroughFPExt) {
8769 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8770 if (N0.getOpcode() == ISD::FP_EXTEND) {
8771 SDValue N00 = N0.getOperand(0);
8772 if (isContractableFMUL(N00))
8773 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8774 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8777 N00.getOperand(1)), N1);
8780 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8781 // Note: Commutes FADD operands.
8782 if (N1.getOpcode() == ISD::FP_EXTEND) {
8783 SDValue N10 = N1.getOperand(0);
8784 if (isContractableFMUL(N10))
8785 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8786 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8788 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8789 N10.getOperand(1)), N0);
8793 // More folding opportunities when target permits.
8795 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
8796 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8797 // are currently only supported on binary nodes.
8798 if (Options.UnsafeFPMath &&
8799 N0.getOpcode() == PreferredFusedOpcode &&
8800 N0.getOperand(2).getOpcode() == ISD::FMUL &&
8801 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
8802 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8803 N0.getOperand(0), N0.getOperand(1),
8804 DAG.getNode(PreferredFusedOpcode, SL, VT,
8805 N0.getOperand(2).getOperand(0),
8806 N0.getOperand(2).getOperand(1),
8810 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
8811 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
8812 // are currently only supported on binary nodes.
8813 if (Options.UnsafeFPMath &&
8814 N1->getOpcode() == PreferredFusedOpcode &&
8815 N1.getOperand(2).getOpcode() == ISD::FMUL &&
8816 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
8817 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8818 N1.getOperand(0), N1.getOperand(1),
8819 DAG.getNode(PreferredFusedOpcode, SL, VT,
8820 N1.getOperand(2).getOperand(0),
8821 N1.getOperand(2).getOperand(1),
8825 if (LookThroughFPExt) {
8826 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
8827 // -> (fma x, y, (fma (fpext u), (fpext v), z))
8828 auto FoldFAddFMAFPExtFMul = [&] (
8829 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8830 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
8831 DAG.getNode(PreferredFusedOpcode, SL, VT,
8832 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8833 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8836 if (N0.getOpcode() == PreferredFusedOpcode) {
8837 SDValue N02 = N0.getOperand(2);
8838 if (N02.getOpcode() == ISD::FP_EXTEND) {
8839 SDValue N020 = N02.getOperand(0);
8840 if (isContractableFMUL(N020))
8841 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
8842 N020.getOperand(0), N020.getOperand(1),
8847 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
8848 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
8849 // FIXME: This turns two single-precision and one double-precision
8850 // operation into two double-precision operations, which might not be
8851 // interesting for all targets, especially GPUs.
8852 auto FoldFAddFPExtFMAFMul = [&] (
8853 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
8854 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8855 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
8856 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
8857 DAG.getNode(PreferredFusedOpcode, SL, VT,
8858 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
8859 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
8862 if (N0.getOpcode() == ISD::FP_EXTEND) {
8863 SDValue N00 = N0.getOperand(0);
8864 if (N00.getOpcode() == PreferredFusedOpcode) {
8865 SDValue N002 = N00.getOperand(2);
8866 if (isContractableFMUL(N002))
8867 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
8868 N002.getOperand(0), N002.getOperand(1),
8873 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
8874 // -> (fma y, z, (fma (fpext u), (fpext v), x))
8875 if (N1.getOpcode() == PreferredFusedOpcode) {
8876 SDValue N12 = N1.getOperand(2);
8877 if (N12.getOpcode() == ISD::FP_EXTEND) {
8878 SDValue N120 = N12.getOperand(0);
8879 if (isContractableFMUL(N120))
8880 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
8881 N120.getOperand(0), N120.getOperand(1),
8886 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
8887 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
8888 // FIXME: This turns two single-precision and one double-precision
8889 // operation into two double-precision operations, which might not be
8890 // interesting for all targets, especially GPUs.
8891 if (N1.getOpcode() == ISD::FP_EXTEND) {
8892 SDValue N10 = N1.getOperand(0);
8893 if (N10.getOpcode() == PreferredFusedOpcode) {
8894 SDValue N102 = N10.getOperand(2);
8895 if (isContractableFMUL(N102))
8896 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
8897 N102.getOperand(0), N102.getOperand(1),
8907 /// Try to perform FMA combining on a given FSUB node.
8908 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
8909 SDValue N0 = N->getOperand(0);
8910 SDValue N1 = N->getOperand(1);
8911 EVT VT = N->getValueType(0);
8914 const TargetOptions &Options = DAG.getTarget().Options;
8915 // Floating-point multiply-add with intermediate rounding.
8916 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8918 // Floating-point multiply-add without intermediate rounding.
8920 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8921 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8923 // No valid opcode, do not combine.
8924 if (!HasFMAD && !HasFMA)
8927 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8928 Options.UnsafeFPMath || HasFMAD);
8929 // If the subtraction is not contractable, do not combine.
8930 if (!AllowFusionGlobally && !isContractable(N))
8933 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8934 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8937 // Always prefer FMAD to FMA for precision.
8938 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8939 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8940 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8942 // Is the node an FMUL and contractable either due to global flags or
8944 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8945 if (N.getOpcode() != ISD::FMUL)
8947 return AllowFusionGlobally || isContractable(N.getNode());
8950 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
8951 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8952 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8953 N0.getOperand(0), N0.getOperand(1),
8954 DAG.getNode(ISD::FNEG, SL, VT, N1));
8957 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
8958 // Note: Commutes FSUB operands.
8959 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
8960 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8961 DAG.getNode(ISD::FNEG, SL, VT,
8963 N1.getOperand(1), N0);
8965 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
8966 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
8967 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
8968 SDValue N00 = N0.getOperand(0).getOperand(0);
8969 SDValue N01 = N0.getOperand(0).getOperand(1);
8970 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8971 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
8972 DAG.getNode(ISD::FNEG, SL, VT, N1));
8975 // Look through FP_EXTEND nodes to do more combining.
8976 if (LookThroughFPExt) {
8977 // fold (fsub (fpext (fmul x, y)), z)
8978 // -> (fma (fpext x), (fpext y), (fneg z))
8979 if (N0.getOpcode() == ISD::FP_EXTEND) {
8980 SDValue N00 = N0.getOperand(0);
8981 if (isContractableFMUL(N00))
8982 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8983 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8985 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8987 DAG.getNode(ISD::FNEG, SL, VT, N1));
8990 // fold (fsub x, (fpext (fmul y, z)))
8991 // -> (fma (fneg (fpext y)), (fpext z), x)
8992 // Note: Commutes FSUB operands.
8993 if (N1.getOpcode() == ISD::FP_EXTEND) {
8994 SDValue N10 = N1.getOperand(0);
8995 if (isContractableFMUL(N10))
8996 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8997 DAG.getNode(ISD::FNEG, SL, VT,
8998 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8999 N10.getOperand(0))),
9000 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9005 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9006 // -> (fneg (fma (fpext x), (fpext y), z))
9007 // Note: This could be removed with appropriate canonicalization of the
9008 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9009 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9010 // from implementing the canonicalization in visitFSUB.
9011 if (N0.getOpcode() == ISD::FP_EXTEND) {
9012 SDValue N00 = N0.getOperand(0);
9013 if (N00.getOpcode() == ISD::FNEG) {
9014 SDValue N000 = N00.getOperand(0);
9015 if (isContractableFMUL(N000)) {
9016 return DAG.getNode(ISD::FNEG, SL, VT,
9017 DAG.getNode(PreferredFusedOpcode, SL, VT,
9018 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9019 N000.getOperand(0)),
9020 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9021 N000.getOperand(1)),
9027 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9028 // -> (fneg (fma (fpext x)), (fpext y), z)
9029 // Note: This could be removed with appropriate canonicalization of the
9030 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9031 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9032 // from implementing the canonicalization in visitFSUB.
9033 if (N0.getOpcode() == ISD::FNEG) {
9034 SDValue N00 = N0.getOperand(0);
9035 if (N00.getOpcode() == ISD::FP_EXTEND) {
9036 SDValue N000 = N00.getOperand(0);
9037 if (isContractableFMUL(N000)) {
9038 return DAG.getNode(ISD::FNEG, SL, VT,
9039 DAG.getNode(PreferredFusedOpcode, SL, VT,
9040 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9041 N000.getOperand(0)),
9042 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9043 N000.getOperand(1)),
9051 // More folding opportunities when target permits.
9053 // fold (fsub (fma x, y, (fmul u, v)), z)
9054 // -> (fma x, y (fma u, v, (fneg z)))
9055 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9056 // are currently only supported on binary nodes.
9057 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9058 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9059 N0.getOperand(2)->hasOneUse()) {
9060 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9061 N0.getOperand(0), N0.getOperand(1),
9062 DAG.getNode(PreferredFusedOpcode, SL, VT,
9063 N0.getOperand(2).getOperand(0),
9064 N0.getOperand(2).getOperand(1),
9065 DAG.getNode(ISD::FNEG, SL, VT,
9069 // fold (fsub x, (fma y, z, (fmul u, v)))
9070 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9071 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9072 // are currently only supported on binary nodes.
9073 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9074 isContractableFMUL(N1.getOperand(2))) {
9075 SDValue N20 = N1.getOperand(2).getOperand(0);
9076 SDValue N21 = N1.getOperand(2).getOperand(1);
9077 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9078 DAG.getNode(ISD::FNEG, SL, VT,
9081 DAG.getNode(PreferredFusedOpcode, SL, VT,
9082 DAG.getNode(ISD::FNEG, SL, VT, N20),
9087 if (LookThroughFPExt) {
9088 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9089 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9090 if (N0.getOpcode() == PreferredFusedOpcode) {
9091 SDValue N02 = N0.getOperand(2);
9092 if (N02.getOpcode() == ISD::FP_EXTEND) {
9093 SDValue N020 = N02.getOperand(0);
9094 if (isContractableFMUL(N020))
9095 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9096 N0.getOperand(0), N0.getOperand(1),
9097 DAG.getNode(PreferredFusedOpcode, SL, VT,
9098 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9099 N020.getOperand(0)),
9100 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9101 N020.getOperand(1)),
9102 DAG.getNode(ISD::FNEG, SL, VT,
9107 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9108 // -> (fma (fpext x), (fpext y),
9109 // (fma (fpext u), (fpext v), (fneg z)))
9110 // FIXME: This turns two single-precision and one double-precision
9111 // operation into two double-precision operations, which might not be
9112 // interesting for all targets, especially GPUs.
9113 if (N0.getOpcode() == ISD::FP_EXTEND) {
9114 SDValue N00 = N0.getOperand(0);
9115 if (N00.getOpcode() == PreferredFusedOpcode) {
9116 SDValue N002 = N00.getOperand(2);
9117 if (isContractableFMUL(N002))
9118 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9119 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9121 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9123 DAG.getNode(PreferredFusedOpcode, SL, VT,
9124 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9125 N002.getOperand(0)),
9126 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9127 N002.getOperand(1)),
9128 DAG.getNode(ISD::FNEG, SL, VT,
9133 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9134 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9135 if (N1.getOpcode() == PreferredFusedOpcode &&
9136 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9137 SDValue N120 = N1.getOperand(2).getOperand(0);
9138 if (isContractableFMUL(N120)) {
9139 SDValue N1200 = N120.getOperand(0);
9140 SDValue N1201 = N120.getOperand(1);
9141 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9142 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9144 DAG.getNode(PreferredFusedOpcode, SL, VT,
9145 DAG.getNode(ISD::FNEG, SL, VT,
9146 DAG.getNode(ISD::FP_EXTEND, SL,
9148 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9154 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9155 // -> (fma (fneg (fpext y)), (fpext z),
9156 // (fma (fneg (fpext u)), (fpext v), x))
9157 // FIXME: This turns two single-precision and one double-precision
9158 // operation into two double-precision operations, which might not be
9159 // interesting for all targets, especially GPUs.
9160 if (N1.getOpcode() == ISD::FP_EXTEND &&
9161 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9162 SDValue N100 = N1.getOperand(0).getOperand(0);
9163 SDValue N101 = N1.getOperand(0).getOperand(1);
9164 SDValue N102 = N1.getOperand(0).getOperand(2);
9165 if (isContractableFMUL(N102)) {
9166 SDValue N1020 = N102.getOperand(0);
9167 SDValue N1021 = N102.getOperand(1);
9168 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9169 DAG.getNode(ISD::FNEG, SL, VT,
9170 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9172 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9173 DAG.getNode(PreferredFusedOpcode, SL, VT,
9174 DAG.getNode(ISD::FNEG, SL, VT,
9175 DAG.getNode(ISD::FP_EXTEND, SL,
9177 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9188 /// Try to perform FMA combining on a given FMUL node based on the distributive
9189 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9190 /// subtraction instead of addition).
9191 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9192 SDValue N0 = N->getOperand(0);
9193 SDValue N1 = N->getOperand(1);
9194 EVT VT = N->getValueType(0);
9197 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9199 const TargetOptions &Options = DAG.getTarget().Options;
9201 // The transforms below are incorrect when x == 0 and y == inf, because the
9202 // intermediate multiplication produces a nan.
9203 if (!Options.NoInfsFPMath)
9206 // Floating-point multiply-add without intermediate rounding.
9208 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9209 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9210 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9212 // Floating-point multiply-add with intermediate rounding. This can result
9213 // in a less precise result due to the changed rounding order.
9214 bool HasFMAD = Options.UnsafeFPMath &&
9215 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9217 // No valid opcode, do not combine.
9218 if (!HasFMAD && !HasFMA)
9221 // Always prefer FMAD to FMA for precision.
9222 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9223 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9225 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9226 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9227 auto FuseFADD = [&](SDValue X, SDValue Y) {
9228 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9229 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9230 if (XC1 && XC1->isExactlyValue(+1.0))
9231 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9232 if (XC1 && XC1->isExactlyValue(-1.0))
9233 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9234 DAG.getNode(ISD::FNEG, SL, VT, Y));
9239 if (SDValue FMA = FuseFADD(N0, N1))
9241 if (SDValue FMA = FuseFADD(N1, N0))
9244 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9245 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9246 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9247 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9248 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9249 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9250 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9251 if (XC0 && XC0->isExactlyValue(+1.0))
9252 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9253 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9255 if (XC0 && XC0->isExactlyValue(-1.0))
9256 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9257 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9258 DAG.getNode(ISD::FNEG, SL, VT, Y));
9260 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9261 if (XC1 && XC1->isExactlyValue(+1.0))
9262 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9263 DAG.getNode(ISD::FNEG, SL, VT, Y));
9264 if (XC1 && XC1->isExactlyValue(-1.0))
9265 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9270 if (SDValue FMA = FuseFSUB(N0, N1))
9272 if (SDValue FMA = FuseFSUB(N1, N0))
9278 SDValue DAGCombiner::visitFADD(SDNode *N) {
9279 SDValue N0 = N->getOperand(0);
9280 SDValue N1 = N->getOperand(1);
9281 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9282 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9283 EVT VT = N->getValueType(0);
9285 const TargetOptions &Options = DAG.getTarget().Options;
9286 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9290 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9293 // fold (fadd c1, c2) -> c1 + c2
9295 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9297 // canonicalize constant to RHS
9298 if (N0CFP && !N1CFP)
9299 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9301 if (SDValue NewSel = foldBinOpIntoSelect(N))
9304 // fold (fadd A, (fneg B)) -> (fsub A, B)
9305 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9306 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9307 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9308 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9310 // fold (fadd (fneg A), B) -> (fsub B, A)
9311 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9312 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9313 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9314 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9316 // FIXME: Auto-upgrade the target/function-level option.
9317 if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
9318 // fold (fadd A, 0) -> A
9319 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9324 // If 'unsafe math' is enabled, fold lots of things.
9325 if (Options.UnsafeFPMath) {
9326 // No FP constant should be created after legalization as Instruction
9327 // Selection pass has a hard time dealing with FP constants.
9328 bool AllowNewConst = (Level < AfterLegalizeDAG);
9330 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9331 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9332 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9333 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9334 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9338 // If allowed, fold (fadd (fneg x), x) -> 0.0
9339 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9340 return DAG.getConstantFP(0.0, DL, VT);
9342 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9343 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9344 return DAG.getConstantFP(0.0, DL, VT);
9346 // We can fold chains of FADD's of the same value into multiplications.
9347 // This transform is not safe in general because we are reducing the number
9348 // of rounding steps.
9349 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9350 if (N0.getOpcode() == ISD::FMUL) {
9351 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9352 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9354 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9355 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9356 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9357 DAG.getConstantFP(1.0, DL, VT), Flags);
9358 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9361 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9362 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9363 N1.getOperand(0) == N1.getOperand(1) &&
9364 N0.getOperand(0) == N1.getOperand(0)) {
9365 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9366 DAG.getConstantFP(2.0, DL, VT), Flags);
9367 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9371 if (N1.getOpcode() == ISD::FMUL) {
9372 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9373 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9375 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9376 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9377 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9378 DAG.getConstantFP(1.0, DL, VT), Flags);
9379 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9382 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9383 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9384 N0.getOperand(0) == N0.getOperand(1) &&
9385 N1.getOperand(0) == N0.getOperand(0)) {
9386 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9387 DAG.getConstantFP(2.0, DL, VT), Flags);
9388 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9392 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9393 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9394 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9395 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9396 (N0.getOperand(0) == N1)) {
9397 return DAG.getNode(ISD::FMUL, DL, VT,
9398 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9402 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9403 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9404 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9405 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9406 N1.getOperand(0) == N0) {
9407 return DAG.getNode(ISD::FMUL, DL, VT,
9408 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9412 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9413 if (AllowNewConst &&
9414 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9415 N0.getOperand(0) == N0.getOperand(1) &&
9416 N1.getOperand(0) == N1.getOperand(1) &&
9417 N0.getOperand(0) == N1.getOperand(0)) {
9418 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9419 DAG.getConstantFP(4.0, DL, VT), Flags);
9422 } // enable-unsafe-fp-math
9424 // FADD -> FMA combines:
9425 if (SDValue Fused = visitFADDForFMACombine(N)) {
9426 AddToWorklist(Fused.getNode());
9432 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9433 SDValue N0 = N->getOperand(0);
9434 SDValue N1 = N->getOperand(1);
9435 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9436 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9437 EVT VT = N->getValueType(0);
9439 const TargetOptions &Options = DAG.getTarget().Options;
9440 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9444 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9447 // fold (fsub c1, c2) -> c1-c2
9449 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9451 if (SDValue NewSel = foldBinOpIntoSelect(N))
9454 // fold (fsub A, (fneg B)) -> (fadd A, B)
9455 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9456 return DAG.getNode(ISD::FADD, DL, VT, N0,
9457 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9459 // FIXME: Auto-upgrade the target/function-level option.
9460 if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
9461 // (fsub 0, B) -> -B
9462 if (N0CFP && N0CFP->isZero()) {
9463 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9464 return GetNegatedExpression(N1, DAG, LegalOperations);
9465 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9466 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9470 // If 'unsafe math' is enabled, fold lots of things.
9471 if (Options.UnsafeFPMath) {
9473 if (N1CFP && N1CFP->isZero())
9476 // (fsub x, x) -> 0.0
9478 return DAG.getConstantFP(0.0f, DL, VT);
9480 // (fsub x, (fadd x, y)) -> (fneg y)
9481 // (fsub x, (fadd y, x)) -> (fneg y)
9482 if (N1.getOpcode() == ISD::FADD) {
9483 SDValue N10 = N1->getOperand(0);
9484 SDValue N11 = N1->getOperand(1);
9486 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9487 return GetNegatedExpression(N11, DAG, LegalOperations);
9489 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9490 return GetNegatedExpression(N10, DAG, LegalOperations);
9494 // FSUB -> FMA combines:
9495 if (SDValue Fused = visitFSUBForFMACombine(N)) {
9496 AddToWorklist(Fused.getNode());
9503 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9504 SDValue N0 = N->getOperand(0);
9505 SDValue N1 = N->getOperand(1);
9506 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9507 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9508 EVT VT = N->getValueType(0);
9510 const TargetOptions &Options = DAG.getTarget().Options;
9511 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9514 if (VT.isVector()) {
9515 // This just handles C1 * C2 for vectors. Other vector folds are below.
9516 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9520 // fold (fmul c1, c2) -> c1*c2
9522 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9524 // canonicalize constant to RHS
9525 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9526 !isConstantFPBuildVectorOrConstantFP(N1))
9527 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9529 // fold (fmul A, 1.0) -> A
9530 if (N1CFP && N1CFP->isExactlyValue(1.0))
9533 if (SDValue NewSel = foldBinOpIntoSelect(N))
9536 if (Options.UnsafeFPMath) {
9537 // fold (fmul A, 0) -> 0
9538 if (N1CFP && N1CFP->isZero())
9541 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9542 if (N0.getOpcode() == ISD::FMUL) {
9543 // Fold scalars or any vector constants (not just splats).
9544 // This fold is done in general by InstCombine, but extra fmul insts
9545 // may have been generated during lowering.
9546 SDValue N00 = N0.getOperand(0);
9547 SDValue N01 = N0.getOperand(1);
9548 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9549 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9550 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9552 // Check 1: Make sure that the first operand of the inner multiply is NOT
9553 // a constant. Otherwise, we may induce infinite looping.
9554 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9555 // Check 2: Make sure that the second operand of the inner multiply and
9556 // the second operand of the outer multiply are constants.
9557 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9558 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9559 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9560 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9565 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9566 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9567 // during an early run of DAGCombiner can prevent folding with fmuls
9568 // inserted during lowering.
9569 if (N0.getOpcode() == ISD::FADD &&
9570 (N0.getOperand(0) == N0.getOperand(1)) &&
9572 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9573 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9574 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9578 // fold (fmul X, 2.0) -> (fadd X, X)
9579 if (N1CFP && N1CFP->isExactlyValue(+2.0))
9580 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9582 // fold (fmul X, -1.0) -> (fneg X)
9583 if (N1CFP && N1CFP->isExactlyValue(-1.0))
9584 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9585 return DAG.getNode(ISD::FNEG, DL, VT, N0);
9587 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9588 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9589 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9590 // Both can be negated for free, check to see if at least one is cheaper
9592 if (LHSNeg == 2 || RHSNeg == 2)
9593 return DAG.getNode(ISD::FMUL, DL, VT,
9594 GetNegatedExpression(N0, DAG, LegalOperations),
9595 GetNegatedExpression(N1, DAG, LegalOperations),
9600 // FMUL -> FMA combines:
9601 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9602 AddToWorklist(Fused.getNode());
9609 SDValue DAGCombiner::visitFMA(SDNode *N) {
9610 SDValue N0 = N->getOperand(0);
9611 SDValue N1 = N->getOperand(1);
9612 SDValue N2 = N->getOperand(2);
9613 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9614 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9615 EVT VT = N->getValueType(0);
9617 const TargetOptions &Options = DAG.getTarget().Options;
9619 // Constant fold FMA.
9620 if (isa<ConstantFPSDNode>(N0) &&
9621 isa<ConstantFPSDNode>(N1) &&
9622 isa<ConstantFPSDNode>(N2)) {
9623 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9626 if (Options.UnsafeFPMath) {
9627 if (N0CFP && N0CFP->isZero())
9629 if (N1CFP && N1CFP->isZero())
9632 // TODO: The FMA node should have flags that propagate to these nodes.
9633 if (N0CFP && N0CFP->isExactlyValue(1.0))
9634 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9635 if (N1CFP && N1CFP->isExactlyValue(1.0))
9636 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9638 // Canonicalize (fma c, x, y) -> (fma x, c, y)
9639 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9640 !isConstantFPBuildVectorOrConstantFP(N1))
9641 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9643 // TODO: FMA nodes should have flags that propagate to the created nodes.
9644 // For now, create a Flags object for use with all unsafe math transforms.
9646 Flags.setUnsafeAlgebra(true);
9648 if (Options.UnsafeFPMath) {
9649 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9650 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9651 isConstantFPBuildVectorOrConstantFP(N1) &&
9652 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9653 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9654 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9658 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9659 if (N0.getOpcode() == ISD::FMUL &&
9660 isConstantFPBuildVectorOrConstantFP(N1) &&
9661 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9662 return DAG.getNode(ISD::FMA, DL, VT,
9664 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9670 // (fma x, 1, y) -> (fadd x, y)
9671 // (fma x, -1, y) -> (fadd (fneg x), y)
9673 if (N1CFP->isExactlyValue(1.0))
9674 // TODO: The FMA node should have flags that propagate to this node.
9675 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9677 if (N1CFP->isExactlyValue(-1.0) &&
9678 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9679 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9680 AddToWorklist(RHSNeg.getNode());
9681 // TODO: The FMA node should have flags that propagate to this node.
9682 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9686 if (Options.UnsafeFPMath) {
9687 // (fma x, c, x) -> (fmul x, (c+1))
9688 if (N1CFP && N0 == N2) {
9689 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9690 DAG.getNode(ISD::FADD, DL, VT, N1,
9691 DAG.getConstantFP(1.0, DL, VT), &Flags),
9695 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9696 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9697 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9698 DAG.getNode(ISD::FADD, DL, VT, N1,
9699 DAG.getConstantFP(-1.0, DL, VT), &Flags),
9707 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9709 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9710 // Notice that this is not always beneficial. One reason is different targets
9711 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9712 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9713 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9714 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9715 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9716 const SDNodeFlags *Flags = N->getFlags();
9717 if (!UnsafeMath && !Flags->hasAllowReciprocal())
9720 // Skip if current node is a reciprocal.
9721 SDValue N0 = N->getOperand(0);
9722 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9723 if (N0CFP && N0CFP->isExactlyValue(1.0))
9726 // Exit early if the target does not want this transform or if there can't
9727 // possibly be enough uses of the divisor to make the transform worthwhile.
9728 SDValue N1 = N->getOperand(1);
9729 unsigned MinUses = TLI.combineRepeatedFPDivisors();
9730 if (!MinUses || N1->use_size() < MinUses)
9733 // Find all FDIV users of the same divisor.
9734 // Use a set because duplicates may be present in the user list.
9735 SetVector<SDNode *> Users;
9736 for (auto *U : N1->uses()) {
9737 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
9738 // This division is eligible for optimization only if global unsafe math
9739 // is enabled or if this division allows reciprocal formation.
9740 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
9745 // Now that we have the actual number of divisor uses, make sure it meets
9746 // the minimum threshold specified by the target.
9747 if (Users.size() < MinUses)
9750 EVT VT = N->getValueType(0);
9752 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
9753 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
9755 // Dividend / Divisor -> Dividend * Reciprocal
9756 for (auto *U : Users) {
9757 SDValue Dividend = U->getOperand(0);
9758 if (Dividend != FPOne) {
9759 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
9761 CombineTo(U, NewNode);
9762 } else if (U != Reciprocal.getNode()) {
9763 // In the absence of fast-math-flags, this user node is always the
9764 // same node as Reciprocal, but with FMF they may be different nodes.
9765 CombineTo(U, Reciprocal);
9768 return SDValue(N, 0); // N was replaced.
9771 SDValue DAGCombiner::visitFDIV(SDNode *N) {
9772 SDValue N0 = N->getOperand(0);
9773 SDValue N1 = N->getOperand(1);
9774 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9775 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9776 EVT VT = N->getValueType(0);
9778 const TargetOptions &Options = DAG.getTarget().Options;
9779 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
9783 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9786 // fold (fdiv c1, c2) -> c1/c2
9788 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
9790 if (SDValue NewSel = foldBinOpIntoSelect(N))
9793 if (Options.UnsafeFPMath) {
9794 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
9796 // Compute the reciprocal 1.0 / c2.
9797 const APFloat &N1APF = N1CFP->getValueAPF();
9798 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
9799 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
9800 // Only do the transform if the reciprocal is a legal fp immediate that
9801 // isn't too nasty (eg NaN, denormal, ...).
9802 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
9803 (!LegalOperations ||
9804 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
9805 // backend)... we should handle this gracefully after Legalize.
9806 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
9807 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
9808 TLI.isFPImmLegal(Recip, VT)))
9809 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9810 DAG.getConstantFP(Recip, DL, VT), Flags);
9813 // If this FDIV is part of a reciprocal square root, it may be folded
9814 // into a target-specific square root estimate instruction.
9815 if (N1.getOpcode() == ISD::FSQRT) {
9816 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
9817 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9819 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
9820 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9821 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9823 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
9824 AddToWorklist(RV.getNode());
9825 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9827 } else if (N1.getOpcode() == ISD::FP_ROUND &&
9828 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9829 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
9831 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
9832 AddToWorklist(RV.getNode());
9833 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9835 } else if (N1.getOpcode() == ISD::FMUL) {
9836 // Look through an FMUL. Even though this won't remove the FDIV directly,
9837 // it's still worthwhile to get rid of the FSQRT if possible.
9840 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
9841 SqrtOp = N1.getOperand(0);
9842 OtherOp = N1.getOperand(1);
9843 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
9844 SqrtOp = N1.getOperand(1);
9845 OtherOp = N1.getOperand(0);
9847 if (SqrtOp.getNode()) {
9848 // We found a FSQRT, so try to make this fold:
9849 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
9850 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
9851 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
9852 AddToWorklist(RV.getNode());
9853 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9858 // Fold into a reciprocal estimate and multiply instead of a real divide.
9859 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
9860 AddToWorklist(RV.getNode());
9861 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
9865 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
9866 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9867 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9868 // Both can be negated for free, check to see if at least one is cheaper
9870 if (LHSNeg == 2 || RHSNeg == 2)
9871 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
9872 GetNegatedExpression(N0, DAG, LegalOperations),
9873 GetNegatedExpression(N1, DAG, LegalOperations),
9878 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
9879 return CombineRepeatedDivisors;
9884 SDValue DAGCombiner::visitFREM(SDNode *N) {
9885 SDValue N0 = N->getOperand(0);
9886 SDValue N1 = N->getOperand(1);
9887 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9888 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9889 EVT VT = N->getValueType(0);
9891 // fold (frem c1, c2) -> fmod(c1,c2)
9893 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
9894 &cast<BinaryWithFlagsSDNode>(N)->Flags);
9896 if (SDValue NewSel = foldBinOpIntoSelect(N))
9902 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
9903 if (!DAG.getTarget().Options.UnsafeFPMath)
9906 SDValue N0 = N->getOperand(0);
9907 if (TLI.isFsqrtCheap(N0, DAG))
9910 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
9911 // For now, create a Flags object for use with all unsafe math transforms.
9913 Flags.setUnsafeAlgebra(true);
9914 return buildSqrtEstimate(N0, &Flags);
9917 /// copysign(x, fp_extend(y)) -> copysign(x, y)
9918 /// copysign(x, fp_round(y)) -> copysign(x, y)
9919 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
9920 SDValue N1 = N->getOperand(1);
9921 if ((N1.getOpcode() == ISD::FP_EXTEND ||
9922 N1.getOpcode() == ISD::FP_ROUND)) {
9923 // Do not optimize out type conversion of f128 type yet.
9924 // For some targets like x86_64, configuration is changed to keep one f128
9925 // value in one SSE register, but instruction selection cannot handle
9926 // FCOPYSIGN on SSE registers yet.
9927 EVT N1VT = N1->getValueType(0);
9928 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
9929 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
9934 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
9935 SDValue N0 = N->getOperand(0);
9936 SDValue N1 = N->getOperand(1);
9937 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9938 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9939 EVT VT = N->getValueType(0);
9941 if (N0CFP && N1CFP) // Constant fold
9942 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
9945 const APFloat &V = N1CFP->getValueAPF();
9946 // copysign(x, c1) -> fabs(x) iff ispos(c1)
9947 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
9948 if (!V.isNegative()) {
9949 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
9950 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9952 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9953 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9954 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
9958 // copysign(fabs(x), y) -> copysign(x, y)
9959 // copysign(fneg(x), y) -> copysign(x, y)
9960 // copysign(copysign(x,z), y) -> copysign(x, y)
9961 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
9962 N0.getOpcode() == ISD::FCOPYSIGN)
9963 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
9965 // copysign(x, abs(y)) -> abs(x)
9966 if (N1.getOpcode() == ISD::FABS)
9967 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9969 // copysign(x, copysign(y,z)) -> copysign(x, z)
9970 if (N1.getOpcode() == ISD::FCOPYSIGN)
9971 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
9973 // copysign(x, fp_extend(y)) -> copysign(x, y)
9974 // copysign(x, fp_round(y)) -> copysign(x, y)
9975 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
9976 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
9981 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
9982 SDValue N0 = N->getOperand(0);
9983 EVT VT = N->getValueType(0);
9984 EVT OpVT = N0.getValueType();
9986 // fold (sint_to_fp c1) -> c1fp
9987 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
9988 // ...but only if the target supports immediate floating-point values
9989 (!LegalOperations ||
9990 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
9991 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
9993 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
9994 // but UINT_TO_FP is legal on this target, try to convert.
9995 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
9996 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
9997 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
9998 if (DAG.SignBitIsZero(N0))
9999 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10002 // The next optimizations are desirable only if SELECT_CC can be lowered.
10003 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10004 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10005 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10007 (!LegalOperations ||
10008 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10011 { N0.getOperand(0), N0.getOperand(1),
10012 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10013 N0.getOperand(2) };
10014 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10017 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10018 // (select_cc x, y, 1.0, 0.0,, cc)
10019 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10020 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10021 (!LegalOperations ||
10022 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10025 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10026 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10027 N0.getOperand(0).getOperand(2) };
10028 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10035 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10036 SDValue N0 = N->getOperand(0);
10037 EVT VT = N->getValueType(0);
10038 EVT OpVT = N0.getValueType();
10040 // fold (uint_to_fp c1) -> c1fp
10041 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10042 // ...but only if the target supports immediate floating-point values
10043 (!LegalOperations ||
10044 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10045 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10047 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10048 // but SINT_TO_FP is legal on this target, try to convert.
10049 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10050 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10051 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10052 if (DAG.SignBitIsZero(N0))
10053 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10056 // The next optimizations are desirable only if SELECT_CC can be lowered.
10057 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10058 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10060 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10061 (!LegalOperations ||
10062 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10065 { N0.getOperand(0), N0.getOperand(1),
10066 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10067 N0.getOperand(2) };
10068 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10075 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10076 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10077 SDValue N0 = N->getOperand(0);
10078 EVT VT = N->getValueType(0);
10080 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10083 SDValue Src = N0.getOperand(0);
10084 EVT SrcVT = Src.getValueType();
10085 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10086 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10088 // We can safely assume the conversion won't overflow the output range,
10089 // because (for example) (uint8_t)18293.f is undefined behavior.
10091 // Since we can assume the conversion won't overflow, our decision as to
10092 // whether the input will fit in the float should depend on the minimum
10093 // of the input range and output range.
10095 // This means this is also safe for a signed input and unsigned output, since
10096 // a negative input would lead to undefined behavior.
10097 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10098 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10099 unsigned ActualSize = std::min(InputSize, OutputSize);
10100 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10102 // We can only fold away the float conversion if the input range can be
10103 // represented exactly in the float range.
10104 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10105 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10106 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10107 : ISD::ZERO_EXTEND;
10108 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10110 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10111 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10112 return DAG.getBitcast(VT, Src);
10117 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10118 SDValue N0 = N->getOperand(0);
10119 EVT VT = N->getValueType(0);
10121 // fold (fp_to_sint c1fp) -> c1
10122 if (isConstantFPBuildVectorOrConstantFP(N0))
10123 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10125 return FoldIntToFPToInt(N, DAG);
10128 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10129 SDValue N0 = N->getOperand(0);
10130 EVT VT = N->getValueType(0);
10132 // fold (fp_to_uint c1fp) -> c1
10133 if (isConstantFPBuildVectorOrConstantFP(N0))
10134 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10136 return FoldIntToFPToInt(N, DAG);
10139 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10140 SDValue N0 = N->getOperand(0);
10141 SDValue N1 = N->getOperand(1);
10142 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10143 EVT VT = N->getValueType(0);
10145 // fold (fp_round c1fp) -> c1fp
10147 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10149 // fold (fp_round (fp_extend x)) -> x
10150 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10151 return N0.getOperand(0);
10153 // fold (fp_round (fp_round x)) -> (fp_round x)
10154 if (N0.getOpcode() == ISD::FP_ROUND) {
10155 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10156 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10158 // Skip this folding if it results in an fp_round from f80 to f16.
10160 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10161 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10162 // instructions from f32 or f64. Moreover, the first (value-preserving)
10163 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10165 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10168 // If the first fp_round isn't a value preserving truncation, it might
10169 // introduce a tie in the second fp_round, that wouldn't occur in the
10170 // single-step fp_round we want to fold to.
10171 // In other words, double rounding isn't the same as rounding.
10172 // Also, this is a value preserving truncation iff both fp_round's are.
10173 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10175 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10176 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10180 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10181 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10182 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10183 N0.getOperand(0), N1);
10184 AddToWorklist(Tmp.getNode());
10185 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10186 Tmp, N0.getOperand(1));
10192 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10193 SDValue N0 = N->getOperand(0);
10194 EVT VT = N->getValueType(0);
10195 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10196 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10198 // fold (fp_round_inreg c1fp) -> c1fp
10199 if (N0CFP && isTypeLegal(EVT)) {
10201 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10202 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10208 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10209 SDValue N0 = N->getOperand(0);
10210 EVT VT = N->getValueType(0);
10212 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10213 if (N->hasOneUse() &&
10214 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10217 // fold (fp_extend c1fp) -> c1fp
10218 if (isConstantFPBuildVectorOrConstantFP(N0))
10219 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10221 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10222 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10223 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10224 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10226 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10228 if (N0.getOpcode() == ISD::FP_ROUND
10229 && N0.getConstantOperandVal(1) == 1) {
10230 SDValue In = N0.getOperand(0);
10231 if (In.getValueType() == VT) return In;
10232 if (VT.bitsLT(In.getValueType()))
10233 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10234 In, N0.getOperand(1));
10235 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10238 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10239 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10240 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10241 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10242 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10244 LN0->getBasePtr(), N0.getValueType(),
10245 LN0->getMemOperand());
10246 CombineTo(N, ExtLoad);
10247 CombineTo(N0.getNode(),
10248 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10249 N0.getValueType(), ExtLoad,
10250 DAG.getIntPtrConstant(1, SDLoc(N0))),
10251 ExtLoad.getValue(1));
10252 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10258 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10259 SDValue N0 = N->getOperand(0);
10260 EVT VT = N->getValueType(0);
10262 // fold (fceil c1) -> fceil(c1)
10263 if (isConstantFPBuildVectorOrConstantFP(N0))
10264 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10269 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10270 SDValue N0 = N->getOperand(0);
10271 EVT VT = N->getValueType(0);
10273 // fold (ftrunc c1) -> ftrunc(c1)
10274 if (isConstantFPBuildVectorOrConstantFP(N0))
10275 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10280 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10281 SDValue N0 = N->getOperand(0);
10282 EVT VT = N->getValueType(0);
10284 // fold (ffloor c1) -> ffloor(c1)
10285 if (isConstantFPBuildVectorOrConstantFP(N0))
10286 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10291 // FIXME: FNEG and FABS have a lot in common; refactor.
10292 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10293 SDValue N0 = N->getOperand(0);
10294 EVT VT = N->getValueType(0);
10296 // Constant fold FNEG.
10297 if (isConstantFPBuildVectorOrConstantFP(N0))
10298 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10300 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10301 &DAG.getTarget().Options))
10302 return GetNegatedExpression(N0, DAG, LegalOperations);
10304 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10305 // constant pool values.
10306 if (!TLI.isFNegFree(VT) &&
10307 N0.getOpcode() == ISD::BITCAST &&
10308 N0.getNode()->hasOneUse()) {
10309 SDValue Int = N0.getOperand(0);
10310 EVT IntVT = Int.getValueType();
10311 if (IntVT.isInteger() && !IntVT.isVector()) {
10313 if (N0.getValueType().isVector()) {
10314 // For a vector, get a mask such as 0x80... per scalar element
10316 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10317 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10319 // For a scalar, just generate 0x80...
10320 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10323 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10324 DAG.getConstant(SignMask, DL0, IntVT));
10325 AddToWorklist(Int.getNode());
10326 return DAG.getBitcast(VT, Int);
10330 // (fneg (fmul c, x)) -> (fmul -c, x)
10331 if (N0.getOpcode() == ISD::FMUL &&
10332 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10333 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10335 APFloat CVal = CFP1->getValueAPF();
10337 if (Level >= AfterLegalizeDAG &&
10338 (TLI.isFPImmLegal(CVal, VT) ||
10339 TLI.isOperationLegal(ISD::ConstantFP, VT)))
10340 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10341 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10343 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
10350 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10351 SDValue N0 = N->getOperand(0);
10352 SDValue N1 = N->getOperand(1);
10353 EVT VT = N->getValueType(0);
10354 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10355 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10357 if (N0CFP && N1CFP) {
10358 const APFloat &C0 = N0CFP->getValueAPF();
10359 const APFloat &C1 = N1CFP->getValueAPF();
10360 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10363 // Canonicalize to constant on RHS.
10364 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10365 !isConstantFPBuildVectorOrConstantFP(N1))
10366 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10371 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10372 SDValue N0 = N->getOperand(0);
10373 SDValue N1 = N->getOperand(1);
10374 EVT VT = N->getValueType(0);
10375 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10376 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10378 if (N0CFP && N1CFP) {
10379 const APFloat &C0 = N0CFP->getValueAPF();
10380 const APFloat &C1 = N1CFP->getValueAPF();
10381 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10384 // Canonicalize to constant on RHS.
10385 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10386 !isConstantFPBuildVectorOrConstantFP(N1))
10387 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10392 SDValue DAGCombiner::visitFABS(SDNode *N) {
10393 SDValue N0 = N->getOperand(0);
10394 EVT VT = N->getValueType(0);
10396 // fold (fabs c1) -> fabs(c1)
10397 if (isConstantFPBuildVectorOrConstantFP(N0))
10398 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10400 // fold (fabs (fabs x)) -> (fabs x)
10401 if (N0.getOpcode() == ISD::FABS)
10402 return N->getOperand(0);
10404 // fold (fabs (fneg x)) -> (fabs x)
10405 // fold (fabs (fcopysign x, y)) -> (fabs x)
10406 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10407 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10409 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10410 // constant pool values.
10411 if (!TLI.isFAbsFree(VT) &&
10412 N0.getOpcode() == ISD::BITCAST &&
10413 N0.getNode()->hasOneUse()) {
10414 SDValue Int = N0.getOperand(0);
10415 EVT IntVT = Int.getValueType();
10416 if (IntVT.isInteger() && !IntVT.isVector()) {
10418 if (N0.getValueType().isVector()) {
10419 // For a vector, get a mask such as 0x7f... per scalar element
10421 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10422 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10424 // For a scalar, just generate 0x7f...
10425 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10428 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10429 DAG.getConstant(SignMask, DL, IntVT));
10430 AddToWorklist(Int.getNode());
10431 return DAG.getBitcast(N->getValueType(0), Int);
10438 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10439 SDValue Chain = N->getOperand(0);
10440 SDValue N1 = N->getOperand(1);
10441 SDValue N2 = N->getOperand(2);
10443 // If N is a constant we could fold this into a fallthrough or unconditional
10444 // branch. However that doesn't happen very often in normal code, because
10445 // Instcombine/SimplifyCFG should have handled the available opportunities.
10446 // If we did this folding here, it would be necessary to update the
10447 // MachineBasicBlock CFG, which is awkward.
10449 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10451 if (N1.getOpcode() == ISD::SETCC &&
10452 TLI.isOperationLegalOrCustom(ISD::BR_CC,
10453 N1.getOperand(0).getValueType())) {
10454 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10455 Chain, N1.getOperand(2),
10456 N1.getOperand(0), N1.getOperand(1), N2);
10459 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10460 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10461 (N1.getOperand(0).hasOneUse() &&
10462 N1.getOperand(0).getOpcode() == ISD::SRL))) {
10463 SDNode *Trunc = nullptr;
10464 if (N1.getOpcode() == ISD::TRUNCATE) {
10465 // Look pass the truncate.
10466 Trunc = N1.getNode();
10467 N1 = N1.getOperand(0);
10470 // Match this pattern so that we can generate simpler code:
10473 // %b = and i32 %a, 2
10474 // %c = srl i32 %b, 1
10475 // brcond i32 %c ...
10480 // %b = and i32 %a, 2
10481 // %c = setcc eq %b, 0
10484 // This applies only when the AND constant value has one bit set and the
10485 // SRL constant is equal to the log2 of the AND constant. The back-end is
10486 // smart enough to convert the result into a TEST/JMP sequence.
10487 SDValue Op0 = N1.getOperand(0);
10488 SDValue Op1 = N1.getOperand(1);
10490 if (Op0.getOpcode() == ISD::AND &&
10491 Op1.getOpcode() == ISD::Constant) {
10492 SDValue AndOp1 = Op0.getOperand(1);
10494 if (AndOp1.getOpcode() == ISD::Constant) {
10495 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10497 if (AndConst.isPowerOf2() &&
10498 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10502 getSetCCResultType(Op0.getValueType()),
10503 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10506 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10507 MVT::Other, Chain, SetCC, N2);
10508 // Don't add the new BRCond into the worklist or else SimplifySelectCC
10509 // will convert it back to (X & C1) >> C2.
10510 CombineTo(N, NewBRCond, false);
10511 // Truncate is dead.
10513 deleteAndRecombine(Trunc);
10514 // Replace the uses of SRL with SETCC
10515 WorklistRemover DeadNodes(*this);
10516 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10517 deleteAndRecombine(N1.getNode());
10518 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10524 // Restore N1 if the above transformation doesn't match.
10525 N1 = N->getOperand(1);
10528 // Transform br(xor(x, y)) -> br(x != y)
10529 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10530 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10531 SDNode *TheXor = N1.getNode();
10532 SDValue Op0 = TheXor->getOperand(0);
10533 SDValue Op1 = TheXor->getOperand(1);
10534 if (Op0.getOpcode() == Op1.getOpcode()) {
10535 // Avoid missing important xor optimizations.
10536 if (SDValue Tmp = visitXOR(TheXor)) {
10537 if (Tmp.getNode() != TheXor) {
10538 DEBUG(dbgs() << "\nReplacing.8 ";
10539 TheXor->dump(&DAG);
10540 dbgs() << "\nWith: ";
10541 Tmp.getNode()->dump(&DAG);
10543 WorklistRemover DeadNodes(*this);
10544 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10545 deleteAndRecombine(TheXor);
10546 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10547 MVT::Other, Chain, Tmp, N2);
10550 // visitXOR has changed XOR's operands or replaced the XOR completely,
10552 return SDValue(N, 0);
10556 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10557 bool Equal = false;
10558 if (isOneConstant(Op0) && Op0.hasOneUse() &&
10559 Op0.getOpcode() == ISD::XOR) {
10560 TheXor = Op0.getNode();
10564 EVT SetCCVT = N1.getValueType();
10566 SetCCVT = getSetCCResultType(SetCCVT);
10567 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10570 Equal ? ISD::SETEQ : ISD::SETNE);
10571 // Replace the uses of XOR with SETCC
10572 WorklistRemover DeadNodes(*this);
10573 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10574 deleteAndRecombine(N1.getNode());
10575 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10576 MVT::Other, Chain, SetCC, N2);
10583 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10585 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10586 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10587 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10589 // If N is a constant we could fold this into a fallthrough or unconditional
10590 // branch. However that doesn't happen very often in normal code, because
10591 // Instcombine/SimplifyCFG should have handled the available opportunities.
10592 // If we did this folding here, it would be necessary to update the
10593 // MachineBasicBlock CFG, which is awkward.
10595 // Use SimplifySetCC to simplify SETCC's.
10596 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10597 CondLHS, CondRHS, CC->get(), SDLoc(N),
10599 if (Simp.getNode()) AddToWorklist(Simp.getNode());
10601 // fold to a simpler setcc
10602 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10603 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10604 N->getOperand(0), Simp.getOperand(2),
10605 Simp.getOperand(0), Simp.getOperand(1),
10611 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10612 /// and that N may be folded in the load / store addressing mode.
10613 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10615 const TargetLowering &TLI) {
10619 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
10620 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10622 VT = LD->getMemoryVT();
10623 AS = LD->getAddressSpace();
10624 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
10625 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10627 VT = ST->getMemoryVT();
10628 AS = ST->getAddressSpace();
10632 TargetLowering::AddrMode AM;
10633 if (N->getOpcode() == ISD::ADD) {
10634 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10637 AM.BaseOffs = Offset->getSExtValue();
10641 } else if (N->getOpcode() == ISD::SUB) {
10642 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10645 AM.BaseOffs = -Offset->getSExtValue();
10652 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10653 VT.getTypeForEVT(*DAG.getContext()), AS);
10656 /// Try turning a load/store into a pre-indexed load/store when the base
10657 /// pointer is an add or subtract and it has other uses besides the load/store.
10658 /// After the transformation, the new indexed load/store has effectively folded
10659 /// the add/subtract in and all of its other uses are redirected to the
10660 /// new load/store.
10661 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10662 if (Level < AfterLegalizeDAG)
10665 bool isLoad = true;
10668 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10669 if (LD->isIndexed())
10671 VT = LD->getMemoryVT();
10672 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10673 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10675 Ptr = LD->getBasePtr();
10676 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10677 if (ST->isIndexed())
10679 VT = ST->getMemoryVT();
10680 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10681 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10683 Ptr = ST->getBasePtr();
10689 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10690 // out. There is no reason to make this a preinc/predec.
10691 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10692 Ptr.getNode()->hasOneUse())
10695 // Ask the target to do addressing mode selection.
10698 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10699 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10702 // Backends without true r+i pre-indexed forms may need to pass a
10703 // constant base with a variable offset so that constant coercion
10704 // will work with the patterns in canonical form.
10705 bool Swapped = false;
10706 if (isa<ConstantSDNode>(BasePtr)) {
10707 std::swap(BasePtr, Offset);
10711 // Don't create a indexed load / store with zero offset.
10712 if (isNullConstant(Offset))
10715 // Try turning it into a pre-indexed load / store except when:
10716 // 1) The new base ptr is a frame index.
10717 // 2) If N is a store and the new base ptr is either the same as or is a
10718 // predecessor of the value being stored.
10719 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10720 // that would create a cycle.
10721 // 4) All uses are load / store ops that use it as old base ptr.
10723 // Check #1. Preinc'ing a frame index would require copying the stack pointer
10724 // (plus the implicit offset) to a register to preinc anyway.
10725 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10730 SDValue Val = cast<StoreSDNode>(N)->getValue();
10731 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
10735 // Caches for hasPredecessorHelper.
10736 SmallPtrSet<const SDNode *, 32> Visited;
10737 SmallVector<const SDNode *, 16> Worklist;
10738 Worklist.push_back(N);
10740 // If the offset is a constant, there may be other adds of constants that
10741 // can be folded with this one. We should do this to avoid having to keep
10742 // a copy of the original base pointer.
10743 SmallVector<SDNode *, 16> OtherUses;
10744 if (isa<ConstantSDNode>(Offset))
10745 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
10746 UE = BasePtr.getNode()->use_end();
10748 SDUse &Use = UI.getUse();
10749 // Skip the use that is Ptr and uses of other results from BasePtr's
10750 // node (important for nodes that return multiple results).
10751 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
10754 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
10757 if (Use.getUser()->getOpcode() != ISD::ADD &&
10758 Use.getUser()->getOpcode() != ISD::SUB) {
10763 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
10764 if (!isa<ConstantSDNode>(Op1)) {
10769 // FIXME: In some cases, we can be smarter about this.
10770 if (Op1.getValueType() != Offset.getValueType()) {
10775 OtherUses.push_back(Use.getUser());
10779 std::swap(BasePtr, Offset);
10781 // Now check for #3 and #4.
10782 bool RealUse = false;
10784 for (SDNode *Use : Ptr.getNode()->uses()) {
10787 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
10790 // If Ptr may be folded in addressing mode of other use, then it's
10791 // not profitable to do this transformation.
10792 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
10801 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10802 BasePtr, Offset, AM);
10804 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10805 BasePtr, Offset, AM);
10808 DEBUG(dbgs() << "\nReplacing.4 ";
10810 dbgs() << "\nWith: ";
10811 Result.getNode()->dump(&DAG);
10813 WorklistRemover DeadNodes(*this);
10815 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10816 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10818 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10821 // Finally, since the node is now dead, remove it from the graph.
10822 deleteAndRecombine(N);
10825 std::swap(BasePtr, Offset);
10827 // Replace other uses of BasePtr that can be updated to use Ptr
10828 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
10829 unsigned OffsetIdx = 1;
10830 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
10832 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
10833 BasePtr.getNode() && "Expected BasePtr operand");
10835 // We need to replace ptr0 in the following expression:
10836 // x0 * offset0 + y0 * ptr0 = t0
10838 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
10840 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
10841 // indexed load/store and the expresion that needs to be re-written.
10843 // Therefore, we have:
10844 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
10846 ConstantSDNode *CN =
10847 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
10848 int X0, X1, Y0, Y1;
10849 const APInt &Offset0 = CN->getAPIntValue();
10850 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
10852 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
10853 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
10854 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
10855 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
10857 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
10859 APInt CNV = Offset0;
10860 if (X0 < 0) CNV = -CNV;
10861 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
10862 else CNV = CNV - Offset1;
10864 SDLoc DL(OtherUses[i]);
10866 // We can now generate the new expression.
10867 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
10868 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
10870 SDValue NewUse = DAG.getNode(Opcode,
10872 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
10873 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
10874 deleteAndRecombine(OtherUses[i]);
10877 // Replace the uses of Ptr with uses of the updated base value.
10878 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
10879 deleteAndRecombine(Ptr.getNode());
10884 /// Try to combine a load/store with a add/sub of the base pointer node into a
10885 /// post-indexed load/store. The transformation folded the add/subtract into the
10886 /// new indexed load/store effectively and all of its uses are redirected to the
10887 /// new load/store.
10888 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
10889 if (Level < AfterLegalizeDAG)
10892 bool isLoad = true;
10895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10896 if (LD->isIndexed())
10898 VT = LD->getMemoryVT();
10899 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
10900 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
10902 Ptr = LD->getBasePtr();
10903 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10904 if (ST->isIndexed())
10906 VT = ST->getMemoryVT();
10907 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
10908 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
10910 Ptr = ST->getBasePtr();
10916 if (Ptr.getNode()->hasOneUse())
10919 for (SDNode *Op : Ptr.getNode()->uses()) {
10921 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
10926 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10927 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
10928 // Don't create a indexed load / store with zero offset.
10929 if (isNullConstant(Offset))
10932 // Try turning it into a post-indexed load / store except when
10933 // 1) All uses are load / store ops that use it as base ptr (and
10934 // it may be folded as addressing mmode).
10935 // 2) Op must be independent of N, i.e. Op is neither a predecessor
10936 // nor a successor of N. Otherwise, if Op is folded that would
10939 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
10943 bool TryNext = false;
10944 for (SDNode *Use : BasePtr.getNode()->uses()) {
10945 if (Use == Ptr.getNode())
10948 // If all the uses are load / store addresses, then don't do the
10950 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
10951 bool RealUse = false;
10952 for (SDNode *UseUse : Use->uses()) {
10953 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
10968 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
10969 SDValue Result = isLoad
10970 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
10971 BasePtr, Offset, AM)
10972 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
10973 BasePtr, Offset, AM);
10974 ++PostIndexedNodes;
10976 DEBUG(dbgs() << "\nReplacing.5 ";
10978 dbgs() << "\nWith: ";
10979 Result.getNode()->dump(&DAG);
10981 WorklistRemover DeadNodes(*this);
10983 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
10984 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
10986 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
10989 // Finally, since the node is now dead, remove it from the graph.
10990 deleteAndRecombine(N);
10992 // Replace the uses of Use with uses of the updated base value.
10993 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
10994 Result.getValue(isLoad ? 1 : 0));
10995 deleteAndRecombine(Op);
11004 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11005 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11006 ISD::MemIndexedMode AM = LD->getAddressingMode();
11007 assert(AM != ISD::UNINDEXED);
11008 SDValue BP = LD->getOperand(1);
11009 SDValue Inc = LD->getOperand(2);
11011 // Some backends use TargetConstants for load offsets, but don't expect
11012 // TargetConstants in general ADD nodes. We can convert these constants into
11013 // regular Constants (if the constant is not opaque).
11014 assert((Inc.getOpcode() != ISD::TargetConstant ||
11015 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11016 "Cannot split out indexing using opaque target constants");
11017 if (Inc.getOpcode() == ISD::TargetConstant) {
11018 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11019 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11020 ConstInc->getValueType(0));
11024 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11025 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11028 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11029 LoadSDNode *LD = cast<LoadSDNode>(N);
11030 SDValue Chain = LD->getChain();
11031 SDValue Ptr = LD->getBasePtr();
11033 // If load is not volatile and there are no uses of the loaded value (and
11034 // the updated indexed value in case of indexed loads), change uses of the
11035 // chain value into uses of the chain input (i.e. delete the dead load).
11036 if (!LD->isVolatile()) {
11037 if (N->getValueType(1) == MVT::Other) {
11038 // Unindexed loads.
11039 if (!N->hasAnyUseOfValue(0)) {
11040 // It's not safe to use the two value CombineTo variant here. e.g.
11041 // v1, chain2 = load chain1, loc
11042 // v2, chain3 = load chain2, loc
11044 // Now we replace use of chain2 with chain1. This makes the second load
11045 // isomorphic to the one we are deleting, and thus makes this load live.
11046 DEBUG(dbgs() << "\nReplacing.6 ";
11048 dbgs() << "\nWith chain: ";
11049 Chain.getNode()->dump(&DAG);
11051 WorklistRemover DeadNodes(*this);
11052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11053 AddUsersToWorklist(Chain.getNode());
11054 if (N->use_empty())
11055 deleteAndRecombine(N);
11057 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11061 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11063 // If this load has an opaque TargetConstant offset, then we cannot split
11064 // the indexing into an add/sub directly (that TargetConstant may not be
11065 // valid for a different type of node, and we cannot convert an opaque
11066 // target constant into a regular constant).
11067 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11068 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11070 if (!N->hasAnyUseOfValue(0) &&
11071 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11072 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11074 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11075 Index = SplitIndexingFromLoad(LD);
11076 // Try to fold the base pointer arithmetic into subsequent loads and
11078 AddUsersToWorklist(N);
11080 Index = DAG.getUNDEF(N->getValueType(1));
11081 DEBUG(dbgs() << "\nReplacing.7 ";
11083 dbgs() << "\nWith: ";
11084 Undef.getNode()->dump(&DAG);
11085 dbgs() << " and 2 other values\n");
11086 WorklistRemover DeadNodes(*this);
11087 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11088 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11089 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11090 deleteAndRecombine(N);
11091 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11096 // If this load is directly stored, replace the load value with the stored
11098 // TODO: Handle store large -> read small portion.
11099 // TODO: Handle TRUNCSTORE/LOADEXT
11100 if (OptLevel != CodeGenOpt::None &&
11101 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11102 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11103 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11104 if (PrevST->getBasePtr() == Ptr &&
11105 PrevST->getValue().getValueType() == N->getValueType(0))
11106 return CombineTo(N, PrevST->getOperand(1), Chain);
11110 // Try to infer better alignment information than the load already has.
11111 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11112 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11113 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11114 SDValue NewLoad = DAG.getExtLoad(
11115 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11116 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11117 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11118 if (NewLoad.getNode() != N)
11119 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11124 if (LD->isUnindexed()) {
11125 // Walk up chain skipping non-aliasing memory nodes.
11126 SDValue BetterChain = FindBetterChain(N, Chain);
11128 // If there is a better chain.
11129 if (Chain != BetterChain) {
11132 // Replace the chain to void dependency.
11133 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11134 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11135 BetterChain, Ptr, LD->getMemOperand());
11137 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11138 LD->getValueType(0),
11139 BetterChain, Ptr, LD->getMemoryVT(),
11140 LD->getMemOperand());
11143 // Create token factor to keep old chain connected.
11144 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11145 MVT::Other, Chain, ReplLoad.getValue(1));
11147 // Make sure the new and old chains are cleaned up.
11148 AddToWorklist(Token.getNode());
11150 // Replace uses with load result and token factor. Don't add users
11152 return CombineTo(N, ReplLoad.getValue(0), Token, false);
11156 // Try transforming N to an indexed load.
11157 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11158 return SDValue(N, 0);
11160 // Try to slice up N to more direct loads if the slices are mapped to
11161 // different register banks or pairing can take place.
11162 if (SliceUpLoad(N))
11163 return SDValue(N, 0);
11169 /// \brief Helper structure used to slice a load in smaller loads.
11170 /// Basically a slice is obtained from the following sequence:
11171 /// Origin = load Ty1, Base
11172 /// Shift = srl Ty1 Origin, CstTy Amount
11173 /// Inst = trunc Shift to Ty2
11175 /// Then, it will be rewriten into:
11176 /// Slice = load SliceTy, Base + SliceOffset
11177 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11179 /// SliceTy is deduced from the number of bits that are actually used to
11181 struct LoadedSlice {
11182 /// \brief Helper structure used to compute the cost of a slice.
11184 /// Are we optimizing for code size.
11188 unsigned Truncates;
11189 unsigned CrossRegisterBanksCopies;
11193 Cost(bool ForCodeSize = false)
11194 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11195 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11197 /// \brief Get the cost of one isolated slice.
11198 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11199 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11200 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11201 EVT TruncType = LS.Inst->getValueType(0);
11202 EVT LoadedType = LS.getLoadedType();
11203 if (TruncType != LoadedType &&
11204 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11208 /// \brief Account for slicing gain in the current cost.
11209 /// Slicing provide a few gains like removing a shift or a
11210 /// truncate. This method allows to grow the cost of the original
11211 /// load with the gain from this slice.
11212 void addSliceGain(const LoadedSlice &LS) {
11213 // Each slice saves a truncate.
11214 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11215 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11216 LS.Inst->getValueType(0)))
11218 // If there is a shift amount, this slice gets rid of it.
11221 // If this slice can merge a cross register bank copy, account for it.
11222 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11223 ++CrossRegisterBanksCopies;
11226 Cost &operator+=(const Cost &RHS) {
11227 Loads += RHS.Loads;
11228 Truncates += RHS.Truncates;
11229 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11230 ZExts += RHS.ZExts;
11231 Shift += RHS.Shift;
11235 bool operator==(const Cost &RHS) const {
11236 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11237 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11238 ZExts == RHS.ZExts && Shift == RHS.Shift;
11241 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11243 bool operator<(const Cost &RHS) const {
11244 // Assume cross register banks copies are as expensive as loads.
11245 // FIXME: Do we want some more target hooks?
11246 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11247 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11248 // Unless we are optimizing for code size, consider the
11249 // expensive operation first.
11250 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11251 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11252 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11253 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11256 bool operator>(const Cost &RHS) const { return RHS < *this; }
11258 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11260 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11262 // The last instruction that represent the slice. This should be a
11263 // truncate instruction.
11265 // The original load instruction.
11266 LoadSDNode *Origin;
11267 // The right shift amount in bits from the original load.
11269 // The DAG from which Origin came from.
11270 // This is used to get some contextual information about legal types, etc.
11273 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11274 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11275 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11277 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11278 /// \return Result is \p BitWidth and has used bits set to 1 and
11279 /// not used bits set to 0.
11280 APInt getUsedBits() const {
11281 // Reproduce the trunc(lshr) sequence:
11282 // - Start from the truncated value.
11283 // - Zero extend to the desired bit width.
11285 assert(Origin && "No original load to compare against.");
11286 unsigned BitWidth = Origin->getValueSizeInBits(0);
11287 assert(Inst && "This slice is not bound to an instruction");
11288 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11289 "Extracted slice is bigger than the whole type!");
11290 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11291 UsedBits.setAllBits();
11292 UsedBits = UsedBits.zext(BitWidth);
11293 UsedBits <<= Shift;
11297 /// \brief Get the size of the slice to be loaded in bytes.
11298 unsigned getLoadedSize() const {
11299 unsigned SliceSize = getUsedBits().countPopulation();
11300 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11301 return SliceSize / 8;
11304 /// \brief Get the type that will be loaded for this slice.
11305 /// Note: This may not be the final type for the slice.
11306 EVT getLoadedType() const {
11307 assert(DAG && "Missing context");
11308 LLVMContext &Ctxt = *DAG->getContext();
11309 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11312 /// \brief Get the alignment of the load used for this slice.
11313 unsigned getAlignment() const {
11314 unsigned Alignment = Origin->getAlignment();
11315 unsigned Offset = getOffsetFromBase();
11317 Alignment = MinAlign(Alignment, Alignment + Offset);
11321 /// \brief Check if this slice can be rewritten with legal operations.
11322 bool isLegal() const {
11323 // An invalid slice is not legal.
11324 if (!Origin || !Inst || !DAG)
11327 // Offsets are for indexed load only, we do not handle that.
11328 if (!Origin->getOffset().isUndef())
11331 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11333 // Check that the type is legal.
11334 EVT SliceType = getLoadedType();
11335 if (!TLI.isTypeLegal(SliceType))
11338 // Check that the load is legal for this type.
11339 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11342 // Check that the offset can be computed.
11343 // 1. Check its type.
11344 EVT PtrType = Origin->getBasePtr().getValueType();
11345 if (PtrType == MVT::Untyped || PtrType.isExtended())
11348 // 2. Check that it fits in the immediate.
11349 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11352 // 3. Check that the computation is legal.
11353 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11356 // Check that the zext is legal if it needs one.
11357 EVT TruncateType = Inst->getValueType(0);
11358 if (TruncateType != SliceType &&
11359 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11365 /// \brief Get the offset in bytes of this slice in the original chunk of
11367 /// \pre DAG != nullptr.
11368 uint64_t getOffsetFromBase() const {
11369 assert(DAG && "Missing context.");
11370 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11371 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11372 uint64_t Offset = Shift / 8;
11373 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11374 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11375 "The size of the original loaded type is not a multiple of a"
11377 // If Offset is bigger than TySizeInBytes, it means we are loading all
11378 // zeros. This should have been optimized before in the process.
11379 assert(TySizeInBytes > Offset &&
11380 "Invalid shift amount for given loaded size");
11382 Offset = TySizeInBytes - Offset - getLoadedSize();
11386 /// \brief Generate the sequence of instructions to load the slice
11387 /// represented by this object and redirect the uses of this slice to
11388 /// this new sequence of instructions.
11389 /// \pre this->Inst && this->Origin are valid Instructions and this
11390 /// object passed the legal check: LoadedSlice::isLegal returned true.
11391 /// \return The last instruction of the sequence used to load the slice.
11392 SDValue loadSlice() const {
11393 assert(Inst && Origin && "Unable to replace a non-existing slice.");
11394 const SDValue &OldBaseAddr = Origin->getBasePtr();
11395 SDValue BaseAddr = OldBaseAddr;
11396 // Get the offset in that chunk of bytes w.r.t. the endianness.
11397 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11398 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11400 // BaseAddr = BaseAddr + Offset.
11401 EVT ArithType = BaseAddr.getValueType();
11403 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11404 DAG->getConstant(Offset, DL, ArithType));
11407 // Create the type of the loaded slice according to its size.
11408 EVT SliceType = getLoadedType();
11410 // Create the load for the slice.
11412 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11413 Origin->getPointerInfo().getWithOffset(Offset),
11414 getAlignment(), Origin->getMemOperand()->getFlags());
11415 // If the final type is not the same as the loaded type, this means that
11416 // we have to pad with zero. Create a zero extend for that.
11417 EVT FinalType = Inst->getValueType(0);
11418 if (SliceType != FinalType)
11420 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11424 /// \brief Check if this slice can be merged with an expensive cross register
11425 /// bank copy. E.g.,
11427 /// f = bitcast i32 i to float
11428 bool canMergeExpensiveCrossRegisterBankCopy() const {
11429 if (!Inst || !Inst->hasOneUse())
11431 SDNode *Use = *Inst->use_begin();
11432 if (Use->getOpcode() != ISD::BITCAST)
11434 assert(DAG && "Missing context");
11435 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11436 EVT ResVT = Use->getValueType(0);
11437 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11438 const TargetRegisterClass *ArgRC =
11439 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11440 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11443 // At this point, we know that we perform a cross-register-bank copy.
11444 // Check if it is expensive.
11445 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11446 // Assume bitcasts are cheap, unless both register classes do not
11447 // explicitly share a common sub class.
11448 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11451 // Check if it will be merged with the load.
11452 // 1. Check the alignment constraint.
11453 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11454 ResVT.getTypeForEVT(*DAG->getContext()));
11456 if (RequiredAlignment > getAlignment())
11459 // 2. Check that the load is a legal operation for that type.
11460 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11463 // 3. Check that we do not have a zext in the way.
11464 if (Inst->getValueType(0) != getLoadedType())
11472 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11473 /// \p UsedBits looks like 0..0 1..1 0..0.
11474 static bool areUsedBitsDense(const APInt &UsedBits) {
11475 // If all the bits are one, this is dense!
11476 if (UsedBits.isAllOnesValue())
11479 // Get rid of the unused bits on the right.
11480 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11481 // Get rid of the unused bits on the left.
11482 if (NarrowedUsedBits.countLeadingZeros())
11483 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11484 // Check that the chunk of bits is completely used.
11485 return NarrowedUsedBits.isAllOnesValue();
11488 /// \brief Check whether or not \p First and \p Second are next to each other
11489 /// in memory. This means that there is no hole between the bits loaded
11490 /// by \p First and the bits loaded by \p Second.
11491 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11492 const LoadedSlice &Second) {
11493 assert(First.Origin == Second.Origin && First.Origin &&
11494 "Unable to match different memory origins.");
11495 APInt UsedBits = First.getUsedBits();
11496 assert((UsedBits & Second.getUsedBits()) == 0 &&
11497 "Slices are not supposed to overlap.");
11498 UsedBits |= Second.getUsedBits();
11499 return areUsedBitsDense(UsedBits);
11502 /// \brief Adjust the \p GlobalLSCost according to the target
11503 /// paring capabilities and the layout of the slices.
11504 /// \pre \p GlobalLSCost should account for at least as many loads as
11505 /// there is in the slices in \p LoadedSlices.
11506 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11507 LoadedSlice::Cost &GlobalLSCost) {
11508 unsigned NumberOfSlices = LoadedSlices.size();
11509 // If there is less than 2 elements, no pairing is possible.
11510 if (NumberOfSlices < 2)
11513 // Sort the slices so that elements that are likely to be next to each
11514 // other in memory are next to each other in the list.
11515 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11516 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11517 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11518 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11520 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11521 // First (resp. Second) is the first (resp. Second) potentially candidate
11522 // to be placed in a paired load.
11523 const LoadedSlice *First = nullptr;
11524 const LoadedSlice *Second = nullptr;
11525 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11526 // Set the beginning of the pair.
11529 Second = &LoadedSlices[CurrSlice];
11531 // If First is NULL, it means we start a new pair.
11532 // Get to the next slice.
11536 EVT LoadedType = First->getLoadedType();
11538 // If the types of the slices are different, we cannot pair them.
11539 if (LoadedType != Second->getLoadedType())
11542 // Check if the target supplies paired loads for this type.
11543 unsigned RequiredAlignment = 0;
11544 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11545 // move to the next pair, this type is hopeless.
11549 // Check if we meet the alignment requirement.
11550 if (RequiredAlignment > First->getAlignment())
11553 // Check that both loads are next to each other in memory.
11554 if (!areSlicesNextToEachOther(*First, *Second))
11557 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11558 --GlobalLSCost.Loads;
11559 // Move to the next pair.
11564 /// \brief Check the profitability of all involved LoadedSlice.
11565 /// Currently, it is considered profitable if there is exactly two
11566 /// involved slices (1) which are (2) next to each other in memory, and
11567 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11569 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11570 /// the elements themselves.
11572 /// FIXME: When the cost model will be mature enough, we can relax
11573 /// constraints (1) and (2).
11574 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11575 const APInt &UsedBits, bool ForCodeSize) {
11576 unsigned NumberOfSlices = LoadedSlices.size();
11577 if (StressLoadSlicing)
11578 return NumberOfSlices > 1;
11581 if (NumberOfSlices != 2)
11585 if (!areUsedBitsDense(UsedBits))
11589 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11590 // The original code has one big load.
11591 OrigCost.Loads = 1;
11592 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11593 const LoadedSlice &LS = LoadedSlices[CurrSlice];
11594 // Accumulate the cost of all the slices.
11595 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11596 GlobalSlicingCost += SliceCost;
11598 // Account as cost in the original configuration the gain obtained
11599 // with the current slices.
11600 OrigCost.addSliceGain(LS);
11603 // If the target supports paired load, adjust the cost accordingly.
11604 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11605 return OrigCost > GlobalSlicingCost;
11608 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11609 /// operations, split it in the various pieces being extracted.
11611 /// This sort of thing is introduced by SROA.
11612 /// This slicing takes care not to insert overlapping loads.
11613 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11614 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11615 if (Level < AfterLegalizeDAG)
11618 LoadSDNode *LD = cast<LoadSDNode>(N);
11619 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11620 !LD->getValueType(0).isInteger())
11623 // Keep track of already used bits to detect overlapping values.
11624 // In that case, we will just abort the transformation.
11625 APInt UsedBits(LD->getValueSizeInBits(0), 0);
11627 SmallVector<LoadedSlice, 4> LoadedSlices;
11629 // Check if this load is used as several smaller chunks of bits.
11630 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11631 // of computation for each trunc.
11632 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11633 UI != UIEnd; ++UI) {
11634 // Skip the uses of the chain.
11635 if (UI.getUse().getResNo() != 0)
11638 SDNode *User = *UI;
11639 unsigned Shift = 0;
11641 // Check if this is a trunc(lshr).
11642 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11643 isa<ConstantSDNode>(User->getOperand(1))) {
11644 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
11645 User = *User->use_begin();
11648 // At this point, User is a Truncate, iff we encountered, trunc or
11650 if (User->getOpcode() != ISD::TRUNCATE)
11653 // The width of the type must be a power of 2 and greater than 8-bits.
11654 // Otherwise the load cannot be represented in LLVM IR.
11655 // Moreover, if we shifted with a non-8-bits multiple, the slice
11656 // will be across several bytes. We do not support that.
11657 unsigned Width = User->getValueSizeInBits(0);
11658 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11661 // Build the slice for this chain of computations.
11662 LoadedSlice LS(User, LD, Shift, &DAG);
11663 APInt CurrentUsedBits = LS.getUsedBits();
11665 // Check if this slice overlaps with another.
11666 if ((CurrentUsedBits & UsedBits) != 0)
11668 // Update the bits used globally.
11669 UsedBits |= CurrentUsedBits;
11671 // Check if the new slice would be legal.
11675 // Record the slice.
11676 LoadedSlices.push_back(LS);
11679 // Abort slicing if it does not seem to be profitable.
11680 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11685 // Rewrite each chain to use an independent load.
11686 // By construction, each chain can be represented by a unique load.
11688 // Prepare the argument for the new token factor for all the slices.
11689 SmallVector<SDValue, 8> ArgChains;
11690 for (SmallVectorImpl<LoadedSlice>::const_iterator
11691 LSIt = LoadedSlices.begin(),
11692 LSItEnd = LoadedSlices.end();
11693 LSIt != LSItEnd; ++LSIt) {
11694 SDValue SliceInst = LSIt->loadSlice();
11695 CombineTo(LSIt->Inst, SliceInst, true);
11696 if (SliceInst.getOpcode() != ISD::LOAD)
11697 SliceInst = SliceInst.getOperand(0);
11698 assert(SliceInst->getOpcode() == ISD::LOAD &&
11699 "It takes more than a zext to get to the loaded slice!!");
11700 ArgChains.push_back(SliceInst.getValue(1));
11703 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11705 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11706 AddToWorklist(Chain.getNode());
11710 /// Check to see if V is (and load (ptr), imm), where the load is having
11711 /// specific bytes cleared out. If so, return the byte size being masked out
11712 /// and the shift amount.
11713 static std::pair<unsigned, unsigned>
11714 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11715 std::pair<unsigned, unsigned> Result(0, 0);
11717 // Check for the structure we're looking for.
11718 if (V->getOpcode() != ISD::AND ||
11719 !isa<ConstantSDNode>(V->getOperand(1)) ||
11720 !ISD::isNormalLoad(V->getOperand(0).getNode()))
11723 // Check the chain and pointer.
11724 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11725 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
11727 // The store should be chained directly to the load or be an operand of a
11729 if (LD == Chain.getNode())
11731 else if (Chain->getOpcode() != ISD::TokenFactor)
11732 return Result; // Fail.
11735 for (const SDValue &ChainOp : Chain->op_values())
11736 if (ChainOp.getNode() == LD) {
11740 if (!isOk) return Result;
11743 // This only handles simple types.
11744 if (V.getValueType() != MVT::i16 &&
11745 V.getValueType() != MVT::i32 &&
11746 V.getValueType() != MVT::i64)
11749 // Check the constant mask. Invert it so that the bits being masked out are
11750 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
11751 // follow the sign bit for uniformity.
11752 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
11753 unsigned NotMaskLZ = countLeadingZeros(NotMask);
11754 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
11755 unsigned NotMaskTZ = countTrailingZeros(NotMask);
11756 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
11757 if (NotMaskLZ == 64) return Result; // All zero mask.
11759 // See if we have a continuous run of bits. If so, we have 0*1+0*
11760 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
11763 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
11764 if (V.getValueType() != MVT::i64 && NotMaskLZ)
11765 NotMaskLZ -= 64-V.getValueSizeInBits();
11767 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
11768 switch (MaskedBytes) {
11772 default: return Result; // All one mask, or 5-byte mask.
11775 // Verify that the first bit starts at a multiple of mask so that the access
11776 // is aligned the same as the access width.
11777 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
11779 Result.first = MaskedBytes;
11780 Result.second = NotMaskTZ/8;
11785 /// Check to see if IVal is something that provides a value as specified by
11786 /// MaskInfo. If so, replace the specified store with a narrower store of
11787 /// truncated IVal.
11789 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
11790 SDValue IVal, StoreSDNode *St,
11792 unsigned NumBytes = MaskInfo.first;
11793 unsigned ByteShift = MaskInfo.second;
11794 SelectionDAG &DAG = DC->getDAG();
11796 // Check to see if IVal is all zeros in the part being masked in by the 'or'
11797 // that uses this. If not, this is not a replacement.
11798 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
11799 ByteShift*8, (ByteShift+NumBytes)*8);
11800 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
11802 // Check that it is legal on the target to do this. It is legal if the new
11803 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
11805 MVT VT = MVT::getIntegerVT(NumBytes*8);
11806 if (!DC->isTypeLegal(VT))
11809 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
11810 // shifted by ByteShift and truncated down to NumBytes.
11813 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
11814 DAG.getConstant(ByteShift*8, DL,
11815 DC->getShiftAmountTy(IVal.getValueType())));
11818 // Figure out the offset for the store and the alignment of the access.
11820 unsigned NewAlign = St->getAlignment();
11822 if (DAG.getDataLayout().isLittleEndian())
11823 StOffset = ByteShift;
11825 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
11827 SDValue Ptr = St->getBasePtr();
11830 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
11831 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
11832 NewAlign = MinAlign(NewAlign, StOffset);
11835 // Truncate down to the new size.
11836 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
11840 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
11841 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
11846 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
11847 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
11848 /// narrowing the load and store if it would end up being a win for performance
11850 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
11851 StoreSDNode *ST = cast<StoreSDNode>(N);
11852 if (ST->isVolatile())
11855 SDValue Chain = ST->getChain();
11856 SDValue Value = ST->getValue();
11857 SDValue Ptr = ST->getBasePtr();
11858 EVT VT = Value.getValueType();
11860 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
11863 unsigned Opc = Value.getOpcode();
11865 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
11866 // is a byte mask indicating a consecutive number of bytes, check to see if
11867 // Y is known to provide just those bytes. If so, we try to replace the
11868 // load + replace + store sequence with a single (narrower) store, which makes
11870 if (Opc == ISD::OR) {
11871 std::pair<unsigned, unsigned> MaskedLoad;
11872 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
11873 if (MaskedLoad.first)
11874 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11875 Value.getOperand(1), ST,this))
11876 return SDValue(NewST, 0);
11878 // Or is commutative, so try swapping X and Y.
11879 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
11880 if (MaskedLoad.first)
11881 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
11882 Value.getOperand(0), ST,this))
11883 return SDValue(NewST, 0);
11886 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
11887 Value.getOperand(1).getOpcode() != ISD::Constant)
11890 SDValue N0 = Value.getOperand(0);
11891 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11892 Chain == SDValue(N0.getNode(), 1)) {
11893 LoadSDNode *LD = cast<LoadSDNode>(N0);
11894 if (LD->getBasePtr() != Ptr ||
11895 LD->getPointerInfo().getAddrSpace() !=
11896 ST->getPointerInfo().getAddrSpace())
11899 // Find the type to narrow it the load / op / store to.
11900 SDValue N1 = Value.getOperand(1);
11901 unsigned BitWidth = N1.getValueSizeInBits();
11902 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
11903 if (Opc == ISD::AND)
11904 Imm ^= APInt::getAllOnesValue(BitWidth);
11905 if (Imm == 0 || Imm.isAllOnesValue())
11907 unsigned ShAmt = Imm.countTrailingZeros();
11908 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
11909 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
11910 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11911 // The narrowing should be profitable, the load/store operation should be
11912 // legal (or custom) and the store size should be equal to the NewVT width.
11913 while (NewBW < BitWidth &&
11914 (NewVT.getStoreSizeInBits() != NewBW ||
11915 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
11916 !TLI.isNarrowingProfitable(VT, NewVT))) {
11917 NewBW = NextPowerOf2(NewBW);
11918 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
11920 if (NewBW >= BitWidth)
11923 // If the lsb changed does not start at the type bitwidth boundary,
11924 // start at the previous one.
11926 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
11927 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
11928 std::min(BitWidth, ShAmt + NewBW));
11929 if ((Imm & Mask) == Imm) {
11930 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
11931 if (Opc == ISD::AND)
11932 NewImm ^= APInt::getAllOnesValue(NewBW);
11933 uint64_t PtrOff = ShAmt / 8;
11934 // For big endian targets, we need to adjust the offset to the pointer to
11935 // load the correct bytes.
11936 if (DAG.getDataLayout().isBigEndian())
11937 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
11939 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
11940 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
11941 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
11944 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
11945 Ptr.getValueType(), Ptr,
11946 DAG.getConstant(PtrOff, SDLoc(LD),
11947 Ptr.getValueType()));
11949 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
11950 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
11951 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11952 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
11953 DAG.getConstant(NewImm, SDLoc(Value),
11956 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
11957 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
11959 AddToWorklist(NewPtr.getNode());
11960 AddToWorklist(NewLD.getNode());
11961 AddToWorklist(NewVal.getNode());
11962 WorklistRemover DeadNodes(*this);
11963 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
11972 /// For a given floating point load / store pair, if the load value isn't used
11973 /// by any other operations, then consider transforming the pair to integer
11974 /// load / store operations if the target deems the transformation profitable.
11975 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
11976 StoreSDNode *ST = cast<StoreSDNode>(N);
11977 SDValue Chain = ST->getChain();
11978 SDValue Value = ST->getValue();
11979 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
11980 Value.hasOneUse() &&
11981 Chain == SDValue(Value.getNode(), 1)) {
11982 LoadSDNode *LD = cast<LoadSDNode>(Value);
11983 EVT VT = LD->getMemoryVT();
11984 if (!VT.isFloatingPoint() ||
11985 VT != ST->getMemoryVT() ||
11986 LD->isNonTemporal() ||
11987 ST->isNonTemporal() ||
11988 LD->getPointerInfo().getAddrSpace() != 0 ||
11989 ST->getPointerInfo().getAddrSpace() != 0)
11992 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11993 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
11994 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
11995 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
11996 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
11999 unsigned LDAlign = LD->getAlignment();
12000 unsigned STAlign = ST->getAlignment();
12001 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12002 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12003 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12007 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12008 LD->getPointerInfo(), LDAlign);
12011 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12012 ST->getPointerInfo(), STAlign);
12014 AddToWorklist(NewLD.getNode());
12015 AddToWorklist(NewST.getNode());
12016 WorklistRemover DeadNodes(*this);
12017 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12025 // This is a helper function for visitMUL to check the profitability
12026 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12027 // MulNode is the original multiply, AddNode is (add x, c1),
12028 // and ConstNode is c2.
12030 // If the (add x, c1) has multiple uses, we could increase
12031 // the number of adds if we make this transformation.
12032 // It would only be worth doing this if we can remove a
12033 // multiply in the process. Check for that here.
12037 // We're checking for cases where we have common "c3 * A" expressions.
12038 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12040 SDValue &ConstNode) {
12043 // If the add only has one use, this would be OK to do.
12044 if (AddNode.getNode()->hasOneUse())
12047 // Walk all the users of the constant with which we're multiplying.
12048 for (SDNode *Use : ConstNode->uses()) {
12050 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12053 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12055 SDNode *MulVar = AddNode.getOperand(0).getNode();
12057 // OtherOp is what we're multiplying against the constant.
12058 if (Use->getOperand(0) == ConstNode)
12059 OtherOp = Use->getOperand(1).getNode();
12061 OtherOp = Use->getOperand(0).getNode();
12063 // Check to see if multiply is with the same operand of our "add".
12065 // ConstNode = CONST
12066 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12068 // AddNode = (A + c1) <-- MulVar is A.
12069 // = AddNode * ConstNode <-- current visiting instruction.
12071 // If we make this transformation, we will have a common
12072 // multiply (ConstNode * A) that we can save.
12073 if (OtherOp == MulVar)
12076 // Now check to see if a future expansion will give us a common
12079 // ConstNode = CONST
12080 // AddNode = (A + c1)
12081 // ... = AddNode * ConstNode <-- current visiting instruction.
12083 // OtherOp = (A + c2)
12084 // Use = OtherOp * ConstNode <-- visiting Use.
12086 // If we make this transformation, we will have a common
12087 // multiply (CONST * A) after we also do the same transformation
12088 // to the "t2" instruction.
12089 if (OtherOp->getOpcode() == ISD::ADD &&
12090 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12091 OtherOp->getOperand(0).getNode() == MulVar)
12096 // Didn't find a case where this would be profitable.
12100 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12101 unsigned NumStores) {
12102 SmallVector<SDValue, 8> Chains;
12103 SmallPtrSet<const SDNode *, 8> Visited;
12104 SDLoc StoreDL(StoreNodes[0].MemNode);
12106 for (unsigned i = 0; i < NumStores; ++i) {
12107 Visited.insert(StoreNodes[i].MemNode);
12110 // don't include nodes that are children
12111 for (unsigned i = 0; i < NumStores; ++i) {
12112 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12113 Chains.push_back(StoreNodes[i].MemNode->getChain());
12116 assert(Chains.size() > 0 && "Chain should have generated a chain");
12117 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12120 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12121 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
12122 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
12123 // Make sure we have something to merge.
12127 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12129 // The latest Node in the DAG.
12130 SDLoc DL(StoreNodes[0].MemNode);
12134 bool IsVec = MemVT.isVector();
12135 unsigned Elts = NumStores;
12137 // When merging vector stores, get the total number of elements.
12138 Elts *= MemVT.getVectorNumElements();
12140 // Get the type for the merged vector store.
12141 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12142 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12144 if (IsConstantSrc) {
12145 SmallVector<SDValue, 8> BuildVector;
12146 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12147 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12148 SDValue Val = St->getValue();
12149 if (MemVT.getScalarType().isInteger())
12150 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12151 Val = DAG.getConstant(
12152 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12153 SDLoc(CFP), MemVT);
12154 BuildVector.push_back(Val);
12156 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12158 SmallVector<SDValue, 8> Ops;
12159 for (unsigned i = 0; i < NumStores; ++i) {
12160 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12161 SDValue Val = St->getValue();
12162 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12163 if (Val.getValueType() != MemVT)
12165 Ops.push_back(Val);
12168 // Build the extracted vector elements back into a vector.
12169 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12172 // We should always use a vector store when merging extracted vector
12173 // elements, so this path implies a store of constants.
12174 assert(IsConstantSrc && "Merged vector elements should use vector store");
12176 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12177 APInt StoreInt(SizeInBits, 0);
12179 // Construct a single integer constant which is made of the smaller
12180 // constant inputs.
12181 bool IsLE = DAG.getDataLayout().isLittleEndian();
12182 for (unsigned i = 0; i < NumStores; ++i) {
12183 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12184 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12186 SDValue Val = St->getValue();
12187 StoreInt <<= ElementSizeBytes * 8;
12188 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12189 StoreInt |= C->getAPIntValue().zext(SizeInBits);
12190 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12191 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
12193 llvm_unreachable("Invalid constant element type");
12197 // Create the new Load and Store operations.
12198 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12199 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12202 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12203 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12204 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
12205 FirstInChain->getBasePtr(),
12206 FirstInChain->getPointerInfo(),
12207 FirstInChain->getAlignment());
12209 // Replace all merged stores with the new store.
12210 for (unsigned i = 0; i < NumStores; ++i)
12211 CombineTo(StoreNodes[i].MemNode, NewStore);
12213 AddToWorklist(NewChain.getNode());
12217 void DAGCombiner::getStoreMergeCandidates(
12218 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12219 // This holds the base pointer, index, and the offset in bytes from the base
12221 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12222 EVT MemVT = St->getMemoryVT();
12224 // We must have a base and an offset.
12225 if (!BasePtr.Base.getNode())
12228 // Do not handle stores to undef base pointers.
12229 if (BasePtr.Base.isUndef())
12232 bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12233 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12234 isa<ConstantFPSDNode>(St->getValue());
12235 bool IsExtractVecSrc =
12236 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12237 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12238 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool {
12239 if (Other->isVolatile() || Other->isIndexed())
12241 // We can merge constant floats to equivalent integers
12242 if (Other->getMemoryVT() != MemVT)
12243 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12244 isa<ConstantFPSDNode>(Other->getValue())))
12247 if (!isa<LoadSDNode>(Other->getValue()))
12250 if (!(isa<ConstantSDNode>(Other->getValue()) ||
12251 isa<ConstantFPSDNode>(Other->getValue())))
12253 if (IsExtractVecSrc)
12254 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12255 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12257 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12258 return (Ptr.equalBaseIndex(BasePtr));
12260 // We looking for a root node which is an ancestor to all mergable
12261 // stores. We search up through a load, to our root and then down
12262 // through all children. For instance we will find Store{1,2,3} if
12263 // St is Store1, Store2. or Store3 where the root is not a load
12264 // which always true for nonvolatile ops. TODO: Expand
12265 // the search to find all valid candidates through multiple layers of loads.
12268 // |-------|-------|
12269 // Load Load Store3
12273 // FIXME: We should be able to climb and
12274 // descend TokenFactors to find candidates as well.
12276 SDNode *RootNode = (St->getChain()).getNode();
12278 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12279 RootNode = Ldn->getChain().getNode();
12280 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12281 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12282 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12283 if (I2.getOperandNo() == 0)
12284 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12285 BaseIndexOffset Ptr;
12286 if (CandidateMatch(OtherST, Ptr))
12287 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12290 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12291 if (I.getOperandNo() == 0)
12292 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12293 BaseIndexOffset Ptr;
12294 if (CandidateMatch(OtherST, Ptr))
12295 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
12299 // We need to check that merging these stores does not cause a loop
12300 // in the DAG. Any store candidate may depend on another candidate
12301 // indirectly through its operand (we already consider dependencies
12302 // through the chain). Check in parallel by searching up from
12303 // non-chain operands of candidates.
12304 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12305 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12306 SmallPtrSet<const SDNode *, 16> Visited;
12307 SmallVector<const SDNode *, 8> Worklist;
12308 // search ops of store candidates
12309 for (unsigned i = 0; i < NumStores; ++i) {
12310 SDNode *n = StoreNodes[i].MemNode;
12311 // Potential loops may happen only through non-chain operands
12312 for (unsigned j = 1; j < n->getNumOperands(); ++j)
12313 Worklist.push_back(n->getOperand(j).getNode());
12315 // search through DAG. We can stop early if we find a storenode
12316 for (unsigned i = 0; i < NumStores; ++i) {
12317 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12323 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12324 if (OptLevel == CodeGenOpt::None)
12327 EVT MemVT = St->getMemoryVT();
12328 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12330 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12333 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12334 Attribute::NoImplicitFloat);
12336 // This function cannot currently deal with non-byte-sized memory sizes.
12337 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12340 if (!MemVT.isSimple())
12343 // Perform an early exit check. Do not bother looking at stored values that
12344 // are not constants, loads, or extracted vector elements.
12345 SDValue StoredVal = St->getValue();
12346 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12347 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12348 isa<ConstantFPSDNode>(StoredVal);
12349 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12350 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12352 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12355 // Don't merge vectors into wider vectors if the source data comes from loads.
12356 // TODO: This restriction can be lifted by using logic similar to the
12357 // ExtractVecSrc case.
12358 if (MemVT.isVector() && IsLoadSrc)
12361 SmallVector<MemOpLink, 8> StoreNodes;
12362 // Find potential store merge candidates by searching through chain sub-DAG
12363 getStoreMergeCandidates(St, StoreNodes);
12365 // Check if there is anything to merge.
12366 if (StoreNodes.size() < 2)
12369 // Sort the memory operands according to their distance from the
12371 std::sort(StoreNodes.begin(), StoreNodes.end(),
12372 [](MemOpLink LHS, MemOpLink RHS) {
12373 return LHS.OffsetFromBase < RHS.OffsetFromBase;
12376 // Store Merge attempts to merge the lowest stores. This generally
12377 // works out as if successful, as the remaining stores are checked
12378 // after the first collection of stores is merged. However, in the
12379 // case that a non-mergeable store is found first, e.g., {p[-2],
12380 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12381 // mergeable cases. To prevent this, we prune such stores from the
12382 // front of StoreNodes here.
12384 unsigned StartIdx = 0;
12385 while ((StartIdx + 1 < StoreNodes.size()) &&
12386 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12387 StoreNodes[StartIdx + 1].OffsetFromBase)
12390 // Bail if we don't have enough candidates to merge.
12391 if (StartIdx + 1 >= StoreNodes.size())
12395 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12397 // Scan the memory operations on the chain and find the first non-consecutive
12398 // store memory address.
12399 unsigned NumConsecutiveStores = 0;
12400 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12402 // Check that the addresses are consecutive starting from the second
12403 // element in the list of stores.
12404 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12405 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12406 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12408 NumConsecutiveStores = i + 1;
12411 if (NumConsecutiveStores < 2)
12414 // Check that we can merge these candidates without causing a cycle
12415 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores))
12419 // The node with the lowest store address.
12420 LLVMContext &Context = *DAG.getContext();
12421 const DataLayout &DL = DAG.getDataLayout();
12423 // Store the constants into memory as one consecutive store.
12424 if (IsConstantSrc) {
12426 while (NumConsecutiveStores > 1) {
12427 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12428 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12429 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12430 unsigned LastLegalType = 0;
12431 unsigned LastLegalVectorType = 0;
12432 bool NonZero = false;
12433 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12434 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12435 SDValue StoredVal = ST->getValue();
12437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12438 NonZero |= !C->isNullValue();
12439 } else if (ConstantFPSDNode *C =
12440 dyn_cast<ConstantFPSDNode>(StoredVal)) {
12441 NonZero |= !C->getConstantFPValue()->isNullValue();
12447 // Find a legal type for the constant store.
12448 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12449 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12450 bool IsFast = false;
12451 if (TLI.isTypeLegal(StoreTy) &&
12452 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12453 FirstStoreAlign, &IsFast) &&
12455 LastLegalType = i + 1;
12456 // Or check whether a truncstore is legal.
12457 } else if (TLI.getTypeAction(Context, StoreTy) ==
12458 TargetLowering::TypePromoteInteger) {
12459 EVT LegalizedStoredValueTy =
12460 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12461 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12462 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12463 FirstStoreAS, FirstStoreAlign, &IsFast) &&
12465 LastLegalType = i + 1;
12469 // We only use vectors if the constant is known to be zero or the target
12470 // allows it and the function is not marked with the noimplicitfloat
12473 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12475 // Find a legal type for the vector store.
12476 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
12477 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
12478 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12479 FirstStoreAlign, &IsFast) &&
12481 LastLegalVectorType = i + 1;
12485 // Check if we found a legal integer type that creates a meaningful merge.
12486 if (LastLegalType < 2 && LastLegalVectorType < 2)
12489 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12490 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12492 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
12496 // Remove merged stores for next iteration.
12497 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12499 NumConsecutiveStores -= NumElem;
12504 // When extracting multiple vector elements, try to store them
12505 // in one vector store rather than a sequence of scalar stores.
12506 if (IsExtractVecSrc) {
12508 while (StoreNodes.size() >= 2) {
12509 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12510 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12511 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12512 unsigned NumStoresToMerge = 0;
12513 bool IsVec = MemVT.isVector();
12514 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12515 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12516 unsigned StoreValOpcode = St->getValue().getOpcode();
12517 // This restriction could be loosened.
12518 // Bail out if any stored values are not elements extracted from a
12519 // vector. It should be possible to handle mixed sources, but load
12520 // sources need more careful handling (see the block of code below that
12521 // handles consecutive loads).
12522 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12523 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12526 // Find a legal type for the vector store.
12527 unsigned Elts = i + 1;
12529 // When merging vector stores, get the total number of elements.
12530 Elts *= MemVT.getVectorNumElements();
12533 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12535 if (TLI.isTypeLegal(Ty) &&
12536 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12537 FirstStoreAlign, &IsFast) &&
12539 NumStoresToMerge = i + 1;
12542 bool Merged = MergeStoresOfConstantsOrVecElts(
12543 StoreNodes, MemVT, NumStoresToMerge, false, true);
12546 // Remove merged stores for next iteration.
12547 StoreNodes.erase(StoreNodes.begin(),
12548 StoreNodes.begin() + NumStoresToMerge);
12550 NumConsecutiveStores -= NumStoresToMerge;
12555 // Below we handle the case of multiple consecutive stores that
12556 // come from multiple consecutive loads. We merge them into a single
12557 // wide load and a single wide store.
12559 // Look for load nodes which are used by the stored values.
12560 SmallVector<MemOpLink, 8> LoadNodes;
12562 // Find acceptable loads. Loads need to have the same chain (token factor),
12563 // must not be zext, volatile, indexed, and they must be consecutive.
12564 BaseIndexOffset LdBasePtr;
12565 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12566 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12567 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12570 // Loads must only have one use.
12571 if (!Ld->hasNUsesOfValue(1, 0))
12574 // The memory operands must not be volatile.
12575 if (Ld->isVolatile() || Ld->isIndexed())
12578 // We do not accept ext loads.
12579 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12582 // The stored memory type must be the same.
12583 if (Ld->getMemoryVT() != MemVT)
12586 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12587 // If this is not the first ptr that we check.
12588 if (LdBasePtr.Base.getNode()) {
12589 // The base ptr must be the same.
12590 if (!LdPtr.equalBaseIndex(LdBasePtr))
12593 // Check that all other base pointers are the same as this one.
12597 // We found a potential memory operand to merge.
12598 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
12601 if (LoadNodes.size() < 2)
12604 // If we have load/store pair instructions and we only have two values,
12606 unsigned RequiredAlignment;
12607 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12608 St->getAlignment() >= RequiredAlignment)
12610 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12611 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12612 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12613 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12614 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12615 unsigned FirstLoadAlign = FirstLoad->getAlignment();
12617 // Scan the memory operations on the chain and find the first non-consecutive
12618 // load memory address. These variables hold the index in the store node
12620 unsigned LastConsecutiveLoad = 0;
12621 // This variable refers to the size and not index in the array.
12622 unsigned LastLegalVectorType = 0;
12623 unsigned LastLegalIntegerType = 0;
12624 StartAddress = LoadNodes[0].OffsetFromBase;
12625 SDValue FirstChain = FirstLoad->getChain();
12626 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12627 // All loads must share the same chain.
12628 if (LoadNodes[i].MemNode->getChain() != FirstChain)
12631 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12632 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12634 LastConsecutiveLoad = i;
12635 // Find a legal type for the vector store.
12636 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
12637 bool IsFastSt, IsFastLd;
12638 if (TLI.isTypeLegal(StoreTy) &&
12639 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12640 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12641 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12642 FirstLoadAlign, &IsFastLd) && IsFastLd) {
12643 LastLegalVectorType = i + 1;
12646 // Find a legal type for the integer store.
12647 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
12648 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12649 if (TLI.isTypeLegal(StoreTy) &&
12650 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12651 FirstStoreAlign, &IsFastSt) && IsFastSt &&
12652 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12653 FirstLoadAlign, &IsFastLd) && IsFastLd)
12654 LastLegalIntegerType = i + 1;
12655 // Or check whether a truncstore and extload is legal.
12656 else if (TLI.getTypeAction(Context, StoreTy) ==
12657 TargetLowering::TypePromoteInteger) {
12658 EVT LegalizedStoredValueTy =
12659 TLI.getTypeToTransformTo(Context, StoreTy);
12660 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12661 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12662 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12663 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
12664 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12665 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
12667 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12668 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
12670 LastLegalIntegerType = i+1;
12674 // Only use vector types if the vector type is larger than the integer type.
12675 // If they are the same, use integers.
12676 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
12677 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
12679 // We add +1 here because the LastXXX variables refer to location while
12680 // the NumElem refers to array/index size.
12681 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
12682 NumElem = std::min(LastLegalType, NumElem);
12687 // Find if it is better to use vectors or integers to load and store
12691 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
12693 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
12694 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
12697 SDLoc LoadDL(LoadNodes[0].MemNode);
12698 SDLoc StoreDL(StoreNodes[0].MemNode);
12700 // The merged loads are required to have the same incoming chain, so
12701 // using the first's chain is acceptable.
12702 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
12703 FirstLoad->getBasePtr(),
12704 FirstLoad->getPointerInfo(), FirstLoadAlign);
12706 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
12708 AddToWorklist(NewStoreChain.getNode());
12711 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
12712 FirstInChain->getPointerInfo(), FirstStoreAlign);
12714 // Transfer chain users from old loads to the new load.
12715 for (unsigned i = 0; i < NumElem; ++i) {
12716 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
12717 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
12718 SDValue(NewLoad.getNode(), 1));
12721 // Replace the all stores with the new store.
12722 for (unsigned i = 0; i < NumElem; ++i)
12723 CombineTo(StoreNodes[i].MemNode, NewStore);
12727 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
12731 // Replace the chain to avoid dependency.
12732 if (ST->isTruncatingStore()) {
12733 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
12734 ST->getBasePtr(), ST->getMemoryVT(),
12735 ST->getMemOperand());
12737 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
12738 ST->getMemOperand());
12741 // Create token to keep both nodes around.
12742 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
12743 MVT::Other, ST->getChain(), ReplStore);
12745 // Make sure the new and old chains are cleaned up.
12746 AddToWorklist(Token.getNode());
12748 // Don't add users to work list.
12749 return CombineTo(ST, Token, false);
12752 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
12753 SDValue Value = ST->getValue();
12754 if (Value.getOpcode() == ISD::TargetConstantFP)
12759 SDValue Chain = ST->getChain();
12760 SDValue Ptr = ST->getBasePtr();
12762 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
12764 // NOTE: If the original store is volatile, this transform must not increase
12765 // the number of stores. For example, on x86-32 an f64 can be stored in one
12766 // processor operation but an i64 (which is not legal) requires two. So the
12767 // transform should not be done in this case.
12770 switch (CFP->getSimpleValueType(0).SimpleTy) {
12772 llvm_unreachable("Unknown FP type");
12773 case MVT::f16: // We don't do this for these yet.
12779 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
12780 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12782 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
12783 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
12785 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
12790 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
12791 !ST->isVolatile()) ||
12792 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
12794 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
12795 getZExtValue(), SDLoc(CFP), MVT::i64);
12796 return DAG.getStore(Chain, DL, Tmp,
12797 Ptr, ST->getMemOperand());
12800 if (!ST->isVolatile() &&
12801 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
12802 // Many FP stores are not made apparent until after legalize, e.g. for
12803 // argument passing. Since this is so common, custom legalize the
12804 // 64-bit integer store into two 32-bit stores.
12805 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
12806 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
12807 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
12808 if (DAG.getDataLayout().isBigEndian())
12811 unsigned Alignment = ST->getAlignment();
12812 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
12813 AAMDNodes AAInfo = ST->getAAInfo();
12815 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
12816 ST->getAlignment(), MMOFlags, AAInfo);
12817 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
12818 DAG.getConstant(4, DL, Ptr.getValueType()));
12819 Alignment = MinAlign(Alignment, 4U);
12820 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
12821 ST->getPointerInfo().getWithOffset(4),
12822 Alignment, MMOFlags, AAInfo);
12823 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
12831 SDValue DAGCombiner::visitSTORE(SDNode *N) {
12832 StoreSDNode *ST = cast<StoreSDNode>(N);
12833 SDValue Chain = ST->getChain();
12834 SDValue Value = ST->getValue();
12835 SDValue Ptr = ST->getBasePtr();
12837 // If this is a store of a bit convert, store the input value if the
12838 // resultant store does not need a higher alignment than the original.
12839 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
12840 ST->isUnindexed()) {
12841 EVT SVT = Value.getOperand(0).getValueType();
12842 if (((!LegalOperations && !ST->isVolatile()) ||
12843 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
12844 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
12845 unsigned OrigAlign = ST->getAlignment();
12847 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
12848 ST->getAddressSpace(), OrigAlign, &Fast) &&
12850 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
12851 ST->getPointerInfo(), OrigAlign,
12852 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12857 // Turn 'store undef, Ptr' -> nothing.
12858 if (Value.isUndef() && ST->isUnindexed())
12861 // Try to infer better alignment information than the store already has.
12862 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
12863 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
12864 if (Align > ST->getAlignment()) {
12866 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
12867 ST->getMemoryVT(), Align,
12868 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12869 if (NewStore.getNode() != N)
12870 return CombineTo(ST, NewStore, true);
12875 // Try transforming a pair floating point load / store ops to integer
12876 // load / store ops.
12877 if (SDValue NewST = TransformFPLoadStorePair(N))
12880 if (ST->isUnindexed()) {
12881 // Walk up chain skipping non-aliasing memory nodes, on this store and any
12882 // adjacent stores.
12883 if (findBetterNeighborChains(ST)) {
12884 // replaceStoreChain uses CombineTo, which handled all of the worklist
12885 // manipulation. Return the original node to not do anything else.
12886 return SDValue(ST, 0);
12888 Chain = ST->getChain();
12891 // Try transforming N to an indexed store.
12892 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
12893 return SDValue(N, 0);
12895 // FIXME: is there such a thing as a truncating indexed store?
12896 if (ST->isTruncatingStore() && ST->isUnindexed() &&
12897 Value.getValueType().isInteger()) {
12898 // See if we can simplify the input to this truncstore with knowledge that
12899 // only the low bits are being used. For example:
12900 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
12901 SDValue Shorter = GetDemandedBits(
12902 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12903 ST->getMemoryVT().getScalarSizeInBits()));
12904 AddToWorklist(Value.getNode());
12905 if (Shorter.getNode())
12906 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
12907 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12909 // Otherwise, see if we can simplify the operation with
12910 // SimplifyDemandedBits, which only works if the value has a single use.
12911 if (SimplifyDemandedBits(
12913 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
12914 ST->getMemoryVT().getScalarSizeInBits()))) {
12915 // Re-visit the store if anything changed and the store hasn't been merged
12916 // with another node (N is deleted) SimplifyDemandedBits will add Value's
12917 // node back to the worklist if necessary, but we also need to re-visit
12918 // the Store node itself.
12919 if (N->getOpcode() != ISD::DELETED_NODE)
12921 return SDValue(N, 0);
12925 // If this is a load followed by a store to the same location, then the store
12927 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
12928 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
12929 ST->isUnindexed() && !ST->isVolatile() &&
12930 // There can't be any side effects between the load and store, such as
12931 // a call or store.
12932 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
12933 // The store is dead, remove it.
12938 // If this is a store followed by a store with the same value to the same
12939 // location, then the store is dead/noop.
12940 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
12941 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
12942 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
12943 ST1->isUnindexed() && !ST1->isVolatile()) {
12944 // The store is dead, remove it.
12949 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
12950 // truncating store. We can do this even if this is already a truncstore.
12951 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
12952 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
12953 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
12954 ST->getMemoryVT())) {
12955 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
12956 Ptr, ST->getMemoryVT(), ST->getMemOperand());
12959 // Only perform this optimization before the types are legal, because we
12960 // don't want to perform this optimization on every DAGCombine invocation.
12963 // There can be multiple store sequences on the same chain.
12964 // Keep trying to merge store sequences until we are unable to do so
12965 // or until we merge the last store on the chain.
12966 bool Changed = MergeConsecutiveStores(ST);
12967 if (!Changed) break;
12968 // Return N as merge only uses CombineTo and no worklist clean
12969 // up is necessary.
12970 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
12971 return SDValue(N, 0);
12975 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
12977 // Make sure to do this only after attempting to merge stores in order to
12978 // avoid changing the types of some subset of stores due to visit order,
12979 // preventing their merging.
12980 if (isa<ConstantFPSDNode>(ST->getValue())) {
12981 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
12985 if (SDValue NewSt = splitMergedValStore(ST))
12988 return ReduceLoadOpStoreWidth(N);
12991 /// For the instruction sequence of store below, F and I values
12992 /// are bundled together as an i64 value before being stored into memory.
12993 /// Sometimes it is more efficent to generate separate stores for F and I,
12994 /// which can remove the bitwise instructions or sink them to colder places.
12996 /// (store (or (zext (bitcast F to i32) to i64),
12997 /// (shl (zext I to i64), 32)), addr) -->
12998 /// (store F, addr) and (store I, addr+4)
13000 /// Similarly, splitting for other merged store can also be beneficial, like:
13001 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13002 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13003 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13004 /// For pair of {i16, i8}, i32 store --> two i16 stores.
13005 /// For pair of {i8, i8}, i16 store --> two i8 stores.
13007 /// We allow each target to determine specifically which kind of splitting is
13010 /// The store patterns are commonly seen from the simple code snippet below
13011 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13012 /// void goo(const std::pair<int, float> &);
13015 /// goo(std::make_pair(tmp, ftmp));
13019 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13020 if (OptLevel == CodeGenOpt::None)
13023 SDValue Val = ST->getValue();
13026 // Match OR operand.
13027 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13030 // Match SHL operand and get Lower and Higher parts of Val.
13031 SDValue Op1 = Val.getOperand(0);
13032 SDValue Op2 = Val.getOperand(1);
13034 if (Op1.getOpcode() != ISD::SHL) {
13035 std::swap(Op1, Op2);
13036 if (Op1.getOpcode() != ISD::SHL)
13040 Hi = Op1.getOperand(0);
13041 if (!Op1.hasOneUse())
13044 // Match shift amount to HalfValBitSize.
13045 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13046 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13047 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13050 // Lo and Hi are zero-extended from int with size less equal than 32
13052 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13053 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13054 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13055 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13056 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13057 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13060 // Use the EVT of low and high parts before bitcast as the input
13061 // of target query.
13062 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13063 ? Lo.getOperand(0).getValueType()
13064 : Lo.getValueType();
13065 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13066 ? Hi.getOperand(0).getValueType()
13067 : Hi.getValueType();
13068 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13071 // Start to split store.
13072 unsigned Alignment = ST->getAlignment();
13073 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13074 AAMDNodes AAInfo = ST->getAAInfo();
13076 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13077 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13078 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13079 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13081 SDValue Chain = ST->getChain();
13082 SDValue Ptr = ST->getBasePtr();
13083 // Lower value store.
13084 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13085 ST->getAlignment(), MMOFlags, AAInfo);
13087 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13088 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13089 // Higher value store.
13091 DAG.getStore(St0, DL, Hi, Ptr,
13092 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13093 Alignment / 2, MMOFlags, AAInfo);
13097 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13098 SDValue InVec = N->getOperand(0);
13099 SDValue InVal = N->getOperand(1);
13100 SDValue EltNo = N->getOperand(2);
13103 // If the inserted element is an UNDEF, just use the input vector.
13104 if (InVal.isUndef())
13107 EVT VT = InVec.getValueType();
13109 // Check that we know which element is being inserted
13110 if (!isa<ConstantSDNode>(EltNo))
13112 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13114 // Canonicalize insert_vector_elt dag nodes.
13116 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13117 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13119 // Do this only if the child insert_vector node has one use; also
13120 // do this only if indices are both constants and Idx1 < Idx0.
13121 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13122 && isa<ConstantSDNode>(InVec.getOperand(2))) {
13123 unsigned OtherElt =
13124 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
13125 if (Elt < OtherElt) {
13127 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13128 InVec.getOperand(0), InVal, EltNo);
13129 AddToWorklist(NewOp.getNode());
13130 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13131 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13135 // If we can't generate a legal BUILD_VECTOR, exit
13136 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13139 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13140 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
13141 // vector elements.
13142 SmallVector<SDValue, 8> Ops;
13143 // Do not combine these two vectors if the output vector will not replace
13144 // the input vector.
13145 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13146 Ops.append(InVec.getNode()->op_begin(),
13147 InVec.getNode()->op_end());
13148 } else if (InVec.isUndef()) {
13149 unsigned NElts = VT.getVectorNumElements();
13150 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13155 // Insert the element
13156 if (Elt < Ops.size()) {
13157 // All the operands of BUILD_VECTOR must have the same type;
13158 // we enforce that here.
13159 EVT OpVT = Ops[0].getValueType();
13160 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13163 // Return the new vector
13164 return DAG.getBuildVector(VT, DL, Ops);
13167 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13168 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13169 assert(!OriginalLoad->isVolatile());
13171 EVT ResultVT = EVE->getValueType(0);
13172 EVT VecEltVT = InVecVT.getVectorElementType();
13173 unsigned Align = OriginalLoad->getAlignment();
13174 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13175 VecEltVT.getTypeForEVT(*DAG.getContext()));
13177 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13180 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13181 ISD::NON_EXTLOAD : ISD::EXTLOAD;
13182 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13187 SDValue NewPtr = OriginalLoad->getBasePtr();
13189 EVT PtrType = NewPtr.getValueType();
13190 MachinePointerInfo MPI;
13192 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13193 int Elt = ConstEltNo->getZExtValue();
13194 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13195 Offset = DAG.getConstant(PtrOff, DL, PtrType);
13196 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13198 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13199 Offset = DAG.getNode(
13200 ISD::MUL, DL, PtrType, Offset,
13201 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13202 MPI = OriginalLoad->getPointerInfo();
13204 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13206 // The replacement we need to do here is a little tricky: we need to
13207 // replace an extractelement of a load with a load.
13208 // Use ReplaceAllUsesOfValuesWith to do the replacement.
13209 // Note that this replacement assumes that the extractvalue is the only
13210 // use of the load; that's okay because we don't want to perform this
13211 // transformation in other cases anyway.
13214 if (ResultVT.bitsGT(VecEltVT)) {
13215 // If the result type of vextract is wider than the load, then issue an
13216 // extending load instead.
13217 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13221 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13222 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13223 Align, OriginalLoad->getMemOperand()->getFlags(),
13224 OriginalLoad->getAAInfo());
13225 Chain = Load.getValue(1);
13227 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13228 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13229 OriginalLoad->getAAInfo());
13230 Chain = Load.getValue(1);
13231 if (ResultVT.bitsLT(VecEltVT))
13232 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13234 Load = DAG.getBitcast(ResultVT, Load);
13236 WorklistRemover DeadNodes(*this);
13237 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13238 SDValue To[] = { Load, Chain };
13239 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13240 // Since we're explicitly calling ReplaceAllUses, add the new node to the
13241 // worklist explicitly as well.
13242 AddToWorklist(Load.getNode());
13243 AddUsersToWorklist(Load.getNode()); // Add users too
13244 // Make sure to revisit this node to clean it up; it will usually be dead.
13245 AddToWorklist(EVE);
13247 return SDValue(EVE, 0);
13250 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13251 // (vextract (scalar_to_vector val, 0) -> val
13252 SDValue InVec = N->getOperand(0);
13253 EVT VT = InVec.getValueType();
13254 EVT NVT = N->getValueType(0);
13256 if (InVec.isUndef())
13257 return DAG.getUNDEF(NVT);
13259 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13260 // Check if the result type doesn't match the inserted element type. A
13261 // SCALAR_TO_VECTOR may truncate the inserted element and the
13262 // EXTRACT_VECTOR_ELT may widen the extracted vector.
13263 SDValue InOp = InVec.getOperand(0);
13264 if (InOp.getValueType() != NVT) {
13265 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13266 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13271 SDValue EltNo = N->getOperand(1);
13272 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13274 // extract_vector_elt (build_vector x, y), 1 -> y
13276 InVec.getOpcode() == ISD::BUILD_VECTOR &&
13277 TLI.isTypeLegal(VT) &&
13278 (InVec.hasOneUse() ||
13279 TLI.aggressivelyPreferBuildVectorSources(VT))) {
13280 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13281 EVT InEltVT = Elt.getValueType();
13283 // Sometimes build_vector's scalar input types do not match result type.
13284 if (NVT == InEltVT)
13287 // TODO: It may be useful to truncate if free if the build_vector implicitly
13291 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13292 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13293 ConstEltNo->isNullValue() && VT.isInteger()) {
13294 SDValue BCSrc = InVec.getOperand(0);
13295 if (BCSrc.getValueType().isScalarInteger())
13296 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13299 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13301 // This only really matters if the index is non-constant since other combines
13302 // on the constant elements already work.
13303 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13304 EltNo == InVec.getOperand(2)) {
13305 SDValue Elt = InVec.getOperand(1);
13306 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13309 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13310 // We only perform this optimization before the op legalization phase because
13311 // we may introduce new vector instructions which are not backed by TD
13312 // patterns. For example on AVX, extracting elements from a wide vector
13313 // without using extract_subvector. However, if we can find an underlying
13314 // scalar value, then we can always use that.
13315 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13316 int NumElem = VT.getVectorNumElements();
13317 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13318 // Find the new index to extract from.
13319 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13321 // Extracting an undef index is undef.
13323 return DAG.getUNDEF(NVT);
13325 // Select the right vector half to extract from.
13327 if (OrigElt < NumElem) {
13328 SVInVec = InVec->getOperand(0);
13330 SVInVec = InVec->getOperand(1);
13331 OrigElt -= NumElem;
13334 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13335 SDValue InOp = SVInVec.getOperand(OrigElt);
13336 if (InOp.getValueType() != NVT) {
13337 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13338 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13344 // FIXME: We should handle recursing on other vector shuffles and
13345 // scalar_to_vector here as well.
13347 if (!LegalOperations) {
13348 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13349 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13350 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13354 bool BCNumEltsChanged = false;
13355 EVT ExtVT = VT.getVectorElementType();
13358 // If the result of load has to be truncated, then it's not necessarily
13360 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13363 if (InVec.getOpcode() == ISD::BITCAST) {
13364 // Don't duplicate a load with other uses.
13365 if (!InVec.hasOneUse())
13368 EVT BCVT = InVec.getOperand(0).getValueType();
13369 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13371 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13372 BCNumEltsChanged = true;
13373 InVec = InVec.getOperand(0);
13374 ExtVT = BCVT.getVectorElementType();
13377 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13378 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13379 ISD::isNormalLoad(InVec.getNode()) &&
13380 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13381 SDValue Index = N->getOperand(1);
13382 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13383 if (!OrigLoad->isVolatile()) {
13384 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13390 // Perform only after legalization to ensure build_vector / vector_shuffle
13391 // optimizations have already been done.
13392 if (!LegalOperations) return SDValue();
13394 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13395 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13396 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13399 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13401 LoadSDNode *LN0 = nullptr;
13402 const ShuffleVectorSDNode *SVN = nullptr;
13403 if (ISD::isNormalLoad(InVec.getNode())) {
13404 LN0 = cast<LoadSDNode>(InVec);
13405 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13406 InVec.getOperand(0).getValueType() == ExtVT &&
13407 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13408 // Don't duplicate a load with other uses.
13409 if (!InVec.hasOneUse())
13412 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13413 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13414 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13416 // (load $addr+1*size)
13418 // Don't duplicate a load with other uses.
13419 if (!InVec.hasOneUse())
13422 // If the bit convert changed the number of elements, it is unsafe
13423 // to examine the mask.
13424 if (BCNumEltsChanged)
13427 // Select the input vector, guarding against out of range extract vector.
13428 unsigned NumElems = VT.getVectorNumElements();
13429 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13430 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13432 if (InVec.getOpcode() == ISD::BITCAST) {
13433 // Don't duplicate a load with other uses.
13434 if (!InVec.hasOneUse())
13437 InVec = InVec.getOperand(0);
13439 if (ISD::isNormalLoad(InVec.getNode())) {
13440 LN0 = cast<LoadSDNode>(InVec);
13441 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13442 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13446 // Make sure we found a non-volatile load and the extractelement is
13448 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13451 // If Idx was -1 above, Elt is going to be -1, so just return undef.
13453 return DAG.getUNDEF(LVT);
13455 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13461 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13462 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13463 // We perform this optimization post type-legalization because
13464 // the type-legalizer often scalarizes integer-promoted vectors.
13465 // Performing this optimization before may create bit-casts which
13466 // will be type-legalized to complex code sequences.
13467 // We perform this optimization only before the operation legalizer because we
13468 // may introduce illegal operations.
13469 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13472 unsigned NumInScalars = N->getNumOperands();
13474 EVT VT = N->getValueType(0);
13476 // Check to see if this is a BUILD_VECTOR of a bunch of values
13477 // which come from any_extend or zero_extend nodes. If so, we can create
13478 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13479 // optimizations. We do not handle sign-extend because we can't fill the sign
13481 EVT SourceType = MVT::Other;
13482 bool AllAnyExt = true;
13484 for (unsigned i = 0; i != NumInScalars; ++i) {
13485 SDValue In = N->getOperand(i);
13486 // Ignore undef inputs.
13487 if (In.isUndef()) continue;
13489 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
13490 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13492 // Abort if the element is not an extension.
13493 if (!ZeroExt && !AnyExt) {
13494 SourceType = MVT::Other;
13498 // The input is a ZeroExt or AnyExt. Check the original type.
13499 EVT InTy = In.getOperand(0).getValueType();
13501 // Check that all of the widened source types are the same.
13502 if (SourceType == MVT::Other)
13505 else if (InTy != SourceType) {
13506 // Multiple income types. Abort.
13507 SourceType = MVT::Other;
13511 // Check if all of the extends are ANY_EXTENDs.
13512 AllAnyExt &= AnyExt;
13515 // In order to have valid types, all of the inputs must be extended from the
13516 // same source type and all of the inputs must be any or zero extend.
13517 // Scalar sizes must be a power of two.
13518 EVT OutScalarTy = VT.getScalarType();
13519 bool ValidTypes = SourceType != MVT::Other &&
13520 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13521 isPowerOf2_32(SourceType.getSizeInBits());
13523 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13524 // turn into a single shuffle instruction.
13528 bool isLE = DAG.getDataLayout().isLittleEndian();
13529 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13530 assert(ElemRatio > 1 && "Invalid element size ratio");
13531 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13532 DAG.getConstant(0, DL, SourceType);
13534 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13535 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13537 // Populate the new build_vector
13538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13539 SDValue Cast = N->getOperand(i);
13540 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13541 Cast.getOpcode() == ISD::ZERO_EXTEND ||
13542 Cast.isUndef()) && "Invalid cast opcode");
13544 if (Cast.isUndef())
13545 In = DAG.getUNDEF(SourceType);
13547 In = Cast->getOperand(0);
13548 unsigned Index = isLE ? (i * ElemRatio) :
13549 (i * ElemRatio + (ElemRatio - 1));
13551 assert(Index < Ops.size() && "Invalid index");
13555 // The type of the new BUILD_VECTOR node.
13556 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13557 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13558 "Invalid vector size");
13559 // Check if the new vector type is legal.
13560 if (!isTypeLegal(VecVT)) return SDValue();
13562 // Make the new BUILD_VECTOR.
13563 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13565 // The new BUILD_VECTOR node has the potential to be further optimized.
13566 AddToWorklist(BV.getNode());
13567 // Bitcast to the desired type.
13568 return DAG.getBitcast(VT, BV);
13571 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13572 EVT VT = N->getValueType(0);
13574 unsigned NumInScalars = N->getNumOperands();
13577 EVT SrcVT = MVT::Other;
13578 unsigned Opcode = ISD::DELETED_NODE;
13579 unsigned NumDefs = 0;
13581 for (unsigned i = 0; i != NumInScalars; ++i) {
13582 SDValue In = N->getOperand(i);
13583 unsigned Opc = In.getOpcode();
13585 if (Opc == ISD::UNDEF)
13588 // If all scalar values are floats and converted from integers.
13589 if (Opcode == ISD::DELETED_NODE &&
13590 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13597 EVT InVT = In.getOperand(0).getValueType();
13599 // If all scalar values are typed differently, bail out. It's chosen to
13600 // simplify BUILD_VECTOR of integer types.
13601 if (SrcVT == MVT::Other)
13608 // If the vector has just one element defined, it's not worth to fold it into
13609 // a vectorized one.
13613 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13614 && "Should only handle conversion from integer to float.");
13615 assert(SrcVT != MVT::Other && "Cannot determine source type!");
13617 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
13619 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
13622 // Just because the floating-point vector type is legal does not necessarily
13623 // mean that the corresponding integer vector type is.
13624 if (!isTypeLegal(NVT))
13627 SmallVector<SDValue, 8> Opnds;
13628 for (unsigned i = 0; i != NumInScalars; ++i) {
13629 SDValue In = N->getOperand(i);
13632 Opnds.push_back(DAG.getUNDEF(SrcVT));
13634 Opnds.push_back(In.getOperand(0));
13636 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
13637 AddToWorklist(BV.getNode());
13639 return DAG.getNode(Opcode, DL, VT, BV);
13642 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
13643 ArrayRef<int> VectorMask,
13644 SDValue VecIn1, SDValue VecIn2,
13645 unsigned LeftIdx) {
13646 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13647 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
13649 EVT VT = N->getValueType(0);
13650 EVT InVT1 = VecIn1.getValueType();
13651 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
13653 unsigned Vec2Offset = InVT1.getVectorNumElements();
13654 unsigned NumElems = VT.getVectorNumElements();
13655 unsigned ShuffleNumElems = NumElems;
13657 // We can't generate a shuffle node with mismatched input and output types.
13658 // Try to make the types match the type of the output.
13659 if (InVT1 != VT || InVT2 != VT) {
13660 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
13661 // If the output vector length is a multiple of both input lengths,
13662 // we can concatenate them and pad the rest with undefs.
13663 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
13664 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
13665 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
13666 ConcatOps[0] = VecIn1;
13667 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
13668 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
13669 VecIn2 = SDValue();
13670 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
13671 if (!TLI.isExtractSubvectorCheap(VT, NumElems))
13674 if (!VecIn2.getNode()) {
13675 // If we only have one input vector, and it's twice the size of the
13676 // output, split it in two.
13677 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
13678 DAG.getConstant(NumElems, DL, IdxTy));
13679 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
13680 // Since we now have shorter input vectors, adjust the offset of the
13681 // second vector's start.
13682 Vec2Offset = NumElems;
13683 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
13684 // VecIn1 is wider than the output, and we have another, possibly
13685 // smaller input. Pad the smaller input with undefs, shuffle at the
13686 // input vector width, and extract the output.
13687 // The shuffle type is different than VT, so check legality again.
13688 if (LegalOperations &&
13689 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
13692 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
13693 // lower it back into a BUILD_VECTOR. So if the inserted type is
13694 // illegal, don't even try.
13695 if (InVT1 != InVT2) {
13696 if (!TLI.isTypeLegal(InVT2))
13698 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
13699 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
13701 ShuffleNumElems = NumElems * 2;
13703 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
13704 // than VecIn1. We can't handle this for now - this case will disappear
13705 // when we start sorting the vectors by type.
13709 // TODO: Support cases where the length mismatch isn't exactly by a
13711 // TODO: Move this check upwards, so that if we have bad type
13712 // mismatches, we don't create any DAG nodes.
13717 // Initialize mask to undef.
13718 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
13720 // Only need to run up to the number of elements actually used, not the
13721 // total number of elements in the shuffle - if we are shuffling a wider
13722 // vector, the high lanes should be set to undef.
13723 for (unsigned i = 0; i != NumElems; ++i) {
13724 if (VectorMask[i] <= 0)
13727 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
13728 if (VectorMask[i] == (int)LeftIdx) {
13729 Mask[i] = ExtIndex;
13730 } else if (VectorMask[i] == (int)LeftIdx + 1) {
13731 Mask[i] = Vec2Offset + ExtIndex;
13735 // The type the input vectors may have changed above.
13736 InVT1 = VecIn1.getValueType();
13738 // If we already have a VecIn2, it should have the same type as VecIn1.
13739 // If we don't, get an undef/zero vector of the appropriate type.
13740 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
13741 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
13743 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
13744 if (ShuffleNumElems > NumElems)
13745 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
13750 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
13751 // operations. If the types of the vectors we're extracting from allow it,
13752 // turn this into a vector_shuffle node.
13753 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
13755 EVT VT = N->getValueType(0);
13757 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
13758 if (!isTypeLegal(VT))
13761 // May only combine to shuffle after legalize if shuffle is legal.
13762 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
13765 bool UsesZeroVector = false;
13766 unsigned NumElems = N->getNumOperands();
13768 // Record, for each element of the newly built vector, which input vector
13769 // that element comes from. -1 stands for undef, 0 for the zero vector,
13770 // and positive values for the input vectors.
13771 // VectorMask maps each element to its vector number, and VecIn maps vector
13772 // numbers to their initial SDValues.
13774 SmallVector<int, 8> VectorMask(NumElems, -1);
13775 SmallVector<SDValue, 8> VecIn;
13776 VecIn.push_back(SDValue());
13778 for (unsigned i = 0; i != NumElems; ++i) {
13779 SDValue Op = N->getOperand(i);
13784 // See if we can use a blend with a zero vector.
13785 // TODO: Should we generalize this to a blend with an arbitrary constant
13787 if (isNullConstant(Op) || isNullFPConstant(Op)) {
13788 UsesZeroVector = true;
13793 // Not an undef or zero. If the input is something other than an
13794 // EXTRACT_VECTOR_ELT with a constant index, bail out.
13795 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13796 !isa<ConstantSDNode>(Op.getOperand(1)))
13799 SDValue ExtractedFromVec = Op.getOperand(0);
13801 // All inputs must have the same element type as the output.
13802 if (VT.getVectorElementType() !=
13803 ExtractedFromVec.getValueType().getVectorElementType())
13806 // Have we seen this input vector before?
13807 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
13808 // a map back from SDValues to numbers isn't worth it.
13809 unsigned Idx = std::distance(
13810 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
13811 if (Idx == VecIn.size())
13812 VecIn.push_back(ExtractedFromVec);
13814 VectorMask[i] = Idx;
13817 // If we didn't find at least one input vector, bail out.
13818 if (VecIn.size() < 2)
13821 // TODO: We want to sort the vectors by descending length, so that adjacent
13822 // pairs have similar length, and the longer vector is always first in the
13825 // TODO: Should this fire if some of the input vectors has illegal type (like
13826 // it does now), or should we let legalization run its course first?
13829 // Take pairs of vectors, and shuffle them so that the result has elements
13830 // from these vectors in the correct places.
13831 // For example, given:
13832 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
13833 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
13834 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
13835 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
13836 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
13837 // We will generate:
13838 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
13839 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
13840 SmallVector<SDValue, 4> Shuffles;
13841 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
13842 unsigned LeftIdx = 2 * In + 1;
13843 SDValue VecLeft = VecIn[LeftIdx];
13845 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
13847 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
13848 VecRight, LeftIdx))
13849 Shuffles.push_back(Shuffle);
13854 // If we need the zero vector as an "ingredient" in the blend tree, add it
13855 // to the list of shuffles.
13856 if (UsesZeroVector)
13857 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
13858 : DAG.getConstantFP(0.0, DL, VT));
13860 // If we only have one shuffle, we're done.
13861 if (Shuffles.size() == 1)
13862 return Shuffles[0];
13864 // Update the vector mask to point to the post-shuffle vectors.
13865 for (int &Vec : VectorMask)
13867 Vec = Shuffles.size() - 1;
13869 Vec = (Vec - 1) / 2;
13871 // More than one shuffle. Generate a binary tree of blends, e.g. if from
13872 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
13874 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
13875 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
13876 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
13877 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
13878 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
13879 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
13880 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
13882 // Make sure the initial size of the shuffle list is even.
13883 if (Shuffles.size() % 2)
13884 Shuffles.push_back(DAG.getUNDEF(VT));
13886 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
13888 Shuffles[CurSize] = DAG.getUNDEF(VT);
13891 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
13893 int Right = 2 * In + 1;
13894 SmallVector<int, 8> Mask(NumElems, -1);
13895 for (unsigned i = 0; i != NumElems; ++i) {
13896 if (VectorMask[i] == Left) {
13898 VectorMask[i] = In;
13899 } else if (VectorMask[i] == Right) {
13900 Mask[i] = i + NumElems;
13901 VectorMask[i] = In;
13906 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
13910 return Shuffles[0];
13913 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
13914 EVT VT = N->getValueType(0);
13916 // A vector built entirely of undefs is undef.
13917 if (ISD::allOperandsUndef(N))
13918 return DAG.getUNDEF(VT);
13920 // Check if we can express BUILD VECTOR via subvector extract.
13921 if (!LegalTypes && (N->getNumOperands() > 1)) {
13922 SDValue Op0 = N->getOperand(0);
13923 auto checkElem = [&](SDValue Op) -> uint64_t {
13924 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
13925 (Op0.getOperand(0) == Op.getOperand(0)))
13926 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
13927 return CNode->getZExtValue();
13931 int Offset = checkElem(Op0);
13932 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
13933 if (Offset + i != checkElem(N->getOperand(i))) {
13939 if ((Offset == 0) &&
13940 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
13941 return Op0.getOperand(0);
13942 if ((Offset != -1) &&
13943 ((Offset % N->getValueType(0).getVectorNumElements()) ==
13944 0)) // IDX must be multiple of output size.
13945 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
13946 Op0.getOperand(0), Op0.getOperand(1));
13949 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
13952 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
13955 if (SDValue V = reduceBuildVecToShuffle(N))
13961 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
13962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13963 EVT OpVT = N->getOperand(0).getValueType();
13965 // If the operands are legal vectors, leave them alone.
13966 if (TLI.isTypeLegal(OpVT))
13970 EVT VT = N->getValueType(0);
13971 SmallVector<SDValue, 8> Ops;
13973 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
13974 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
13976 // Keep track of what we encounter.
13977 bool AnyInteger = false;
13978 bool AnyFP = false;
13979 for (const SDValue &Op : N->ops()) {
13980 if (ISD::BITCAST == Op.getOpcode() &&
13981 !Op.getOperand(0).getValueType().isVector())
13982 Ops.push_back(Op.getOperand(0));
13983 else if (ISD::UNDEF == Op.getOpcode())
13984 Ops.push_back(ScalarUndef);
13988 // Note whether we encounter an integer or floating point scalar.
13989 // If it's neither, bail out, it could be something weird like x86mmx.
13990 EVT LastOpVT = Ops.back().getValueType();
13991 if (LastOpVT.isFloatingPoint())
13993 else if (LastOpVT.isInteger())
13999 // If any of the operands is a floating point scalar bitcast to a vector,
14000 // use floating point types throughout, and bitcast everything.
14001 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14003 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14004 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14006 for (SDValue &Op : Ops) {
14007 if (Op.getValueType() == SVT)
14012 Op = DAG.getBitcast(SVT, Op);
14017 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14018 VT.getSizeInBits() / SVT.getSizeInBits());
14019 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14022 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14023 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14024 // most two distinct vectors the same size as the result, attempt to turn this
14025 // into a legal shuffle.
14026 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14027 EVT VT = N->getValueType(0);
14028 EVT OpVT = N->getOperand(0).getValueType();
14029 int NumElts = VT.getVectorNumElements();
14030 int NumOpElts = OpVT.getVectorNumElements();
14032 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14033 SmallVector<int, 8> Mask;
14035 for (SDValue Op : N->ops()) {
14036 // Peek through any bitcast.
14037 while (Op.getOpcode() == ISD::BITCAST)
14038 Op = Op.getOperand(0);
14040 // UNDEF nodes convert to UNDEF shuffle mask values.
14041 if (Op.isUndef()) {
14042 Mask.append((unsigned)NumOpElts, -1);
14046 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14049 // What vector are we extracting the subvector from and at what index?
14050 SDValue ExtVec = Op.getOperand(0);
14052 // We want the EVT of the original extraction to correctly scale the
14053 // extraction index.
14054 EVT ExtVT = ExtVec.getValueType();
14056 // Peek through any bitcast.
14057 while (ExtVec.getOpcode() == ISD::BITCAST)
14058 ExtVec = ExtVec.getOperand(0);
14060 // UNDEF nodes convert to UNDEF shuffle mask values.
14061 if (ExtVec.isUndef()) {
14062 Mask.append((unsigned)NumOpElts, -1);
14066 if (!isa<ConstantSDNode>(Op.getOperand(1)))
14068 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14070 // Ensure that we are extracting a subvector from a vector the same
14071 // size as the result.
14072 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14075 // Scale the subvector index to account for any bitcast.
14076 int NumExtElts = ExtVT.getVectorNumElements();
14077 if (0 == (NumExtElts % NumElts))
14078 ExtIdx /= (NumExtElts / NumElts);
14079 else if (0 == (NumElts % NumExtElts))
14080 ExtIdx *= (NumElts / NumExtElts);
14084 // At most we can reference 2 inputs in the final shuffle.
14085 if (SV0.isUndef() || SV0 == ExtVec) {
14087 for (int i = 0; i != NumOpElts; ++i)
14088 Mask.push_back(i + ExtIdx);
14089 } else if (SV1.isUndef() || SV1 == ExtVec) {
14091 for (int i = 0; i != NumOpElts; ++i)
14092 Mask.push_back(i + ExtIdx + NumElts);
14098 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14101 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14102 DAG.getBitcast(VT, SV1), Mask);
14105 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14106 // If we only have one input vector, we don't need to do any concatenation.
14107 if (N->getNumOperands() == 1)
14108 return N->getOperand(0);
14110 // Check if all of the operands are undefs.
14111 EVT VT = N->getValueType(0);
14112 if (ISD::allOperandsUndef(N))
14113 return DAG.getUNDEF(VT);
14115 // Optimize concat_vectors where all but the first of the vectors are undef.
14116 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14117 return Op.isUndef();
14119 SDValue In = N->getOperand(0);
14120 assert(In.getValueType().isVector() && "Must concat vectors");
14122 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14123 if (In->getOpcode() == ISD::BITCAST &&
14124 !In->getOperand(0)->getValueType(0).isVector()) {
14125 SDValue Scalar = In->getOperand(0);
14127 // If the bitcast type isn't legal, it might be a trunc of a legal type;
14128 // look through the trunc so we can still do the transform:
14129 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14130 if (Scalar->getOpcode() == ISD::TRUNCATE &&
14131 !TLI.isTypeLegal(Scalar.getValueType()) &&
14132 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14133 Scalar = Scalar->getOperand(0);
14135 EVT SclTy = Scalar->getValueType(0);
14137 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14140 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14141 if (VNTNumElms < 2)
14144 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14145 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14148 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14149 return DAG.getBitcast(VT, Res);
14153 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14154 // We have already tested above for an UNDEF only concatenation.
14155 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14156 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14157 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14158 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14160 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14161 SmallVector<SDValue, 8> Opnds;
14162 EVT SVT = VT.getScalarType();
14165 if (!SVT.isFloatingPoint()) {
14166 // If BUILD_VECTOR are from built from integer, they may have different
14167 // operand types. Get the smallest type and truncate all operands to it.
14168 bool FoundMinVT = false;
14169 for (const SDValue &Op : N->ops())
14170 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14171 EVT OpSVT = Op.getOperand(0)->getValueType(0);
14172 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14175 assert(FoundMinVT && "Concat vector type mismatch");
14178 for (const SDValue &Op : N->ops()) {
14179 EVT OpVT = Op.getValueType();
14180 unsigned NumElts = OpVT.getVectorNumElements();
14182 if (ISD::UNDEF == Op.getOpcode())
14183 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14185 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14186 if (SVT.isFloatingPoint()) {
14187 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14188 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14190 for (unsigned i = 0; i != NumElts; ++i)
14192 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14197 assert(VT.getVectorNumElements() == Opnds.size() &&
14198 "Concat vector type mismatch");
14199 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14202 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14203 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14206 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14207 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14208 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14211 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14212 // nodes often generate nop CONCAT_VECTOR nodes.
14213 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14214 // place the incoming vectors at the exact same location.
14215 SDValue SingleSource = SDValue();
14216 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14218 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14219 SDValue Op = N->getOperand(i);
14224 // Check if this is the identity extract:
14225 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14228 // Find the single incoming vector for the extract_subvector.
14229 if (SingleSource.getNode()) {
14230 if (Op.getOperand(0) != SingleSource)
14233 SingleSource = Op.getOperand(0);
14235 // Check the source type is the same as the type of the result.
14236 // If not, this concat may extend the vector, so we can not
14237 // optimize it away.
14238 if (SingleSource.getValueType() != N->getValueType(0))
14242 unsigned IdentityIndex = i * PartNumElem;
14243 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14244 // The extract index must be constant.
14248 // Check that we are reading from the identity index.
14249 if (CS->getZExtValue() != IdentityIndex)
14253 if (SingleSource.getNode())
14254 return SingleSource;
14259 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14260 EVT NVT = N->getValueType(0);
14261 SDValue V = N->getOperand(0);
14263 // Extract from UNDEF is UNDEF.
14265 return DAG.getUNDEF(NVT);
14268 // (extract_subvec (concat V1, V2, ...), i)
14271 // Only operand 0 is checked as 'concat' assumes all inputs of the same
14273 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14274 isa<ConstantSDNode>(N->getOperand(1)) &&
14275 V->getOperand(0).getValueType() == NVT) {
14276 unsigned Idx = N->getConstantOperandVal(1);
14277 unsigned NumElems = NVT.getVectorNumElements();
14278 assert((Idx % NumElems) == 0 &&
14279 "IDX in concat is not a multiple of the result vector length.");
14280 return V->getOperand(Idx / NumElems);
14284 if (V->getOpcode() == ISD::BITCAST)
14285 V = V.getOperand(0);
14287 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14288 // Handle only simple case where vector being inserted and vector
14289 // being extracted are of same size.
14290 EVT SmallVT = V->getOperand(1).getValueType();
14291 if (!NVT.bitsEq(SmallVT))
14294 // Only handle cases where both indexes are constants.
14295 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14296 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14298 if (InsIdx && ExtIdx) {
14300 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14302 // indices are equal or bit offsets are equal => V1
14303 // otherwise => (extract_subvec V1, ExtIdx)
14304 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14305 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14306 return DAG.getBitcast(NVT, V->getOperand(1));
14307 return DAG.getNode(
14308 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14309 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14317 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14318 SDValue V, SelectionDAG &DAG) {
14320 EVT VT = V.getValueType();
14322 switch (V.getOpcode()) {
14326 case ISD::CONCAT_VECTORS: {
14327 EVT OpVT = V->getOperand(0).getValueType();
14328 int OpSize = OpVT.getVectorNumElements();
14329 SmallBitVector OpUsedElements(OpSize, false);
14330 bool FoundSimplification = false;
14331 SmallVector<SDValue, 4> NewOps;
14332 NewOps.reserve(V->getNumOperands());
14333 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14334 SDValue Op = V->getOperand(i);
14335 bool OpUsed = false;
14336 for (int j = 0; j < OpSize; ++j)
14337 if (UsedElements[i * OpSize + j]) {
14338 OpUsedElements[j] = true;
14342 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14343 : DAG.getUNDEF(OpVT));
14344 FoundSimplification |= Op == NewOps.back();
14345 OpUsedElements.reset();
14347 if (FoundSimplification)
14348 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14352 case ISD::INSERT_SUBVECTOR: {
14353 SDValue BaseV = V->getOperand(0);
14354 SDValue SubV = V->getOperand(1);
14355 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14359 int SubSize = SubV.getValueType().getVectorNumElements();
14360 int Idx = IdxN->getZExtValue();
14361 bool SubVectorUsed = false;
14362 SmallBitVector SubUsedElements(SubSize, false);
14363 for (int i = 0; i < SubSize; ++i)
14364 if (UsedElements[i + Idx]) {
14365 SubVectorUsed = true;
14366 SubUsedElements[i] = true;
14367 UsedElements[i + Idx] = false;
14370 // Now recurse on both the base and sub vectors.
14371 SDValue SimplifiedSubV =
14373 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14374 : DAG.getUNDEF(SubV.getValueType());
14375 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14376 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14377 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14378 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14384 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14385 SDValue N1, SelectionDAG &DAG) {
14386 EVT VT = SVN->getValueType(0);
14387 int NumElts = VT.getVectorNumElements();
14388 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14389 for (int M : SVN->getMask())
14390 if (M >= 0 && M < NumElts)
14391 N0UsedElements[M] = true;
14392 else if (M >= NumElts)
14393 N1UsedElements[M - NumElts] = true;
14395 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14396 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14397 if (S0 == N0 && S1 == N1)
14400 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14403 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14404 // or turn a shuffle of a single concat into simpler shuffle then concat.
14405 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14406 EVT VT = N->getValueType(0);
14407 unsigned NumElts = VT.getVectorNumElements();
14409 SDValue N0 = N->getOperand(0);
14410 SDValue N1 = N->getOperand(1);
14411 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14413 SmallVector<SDValue, 4> Ops;
14414 EVT ConcatVT = N0.getOperand(0).getValueType();
14415 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
14416 unsigned NumConcats = NumElts / NumElemsPerConcat;
14418 // Special case: shuffle(concat(A,B)) can be more efficiently represented
14419 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
14420 // half vector elements.
14421 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
14422 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
14423 SVN->getMask().end(), [](int i) { return i == -1; })) {
14424 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
14425 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
14426 N1 = DAG.getUNDEF(ConcatVT);
14427 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
14430 // Look at every vector that's inserted. We're looking for exact
14431 // subvector-sized copies from a concatenated vector
14432 for (unsigned I = 0; I != NumConcats; ++I) {
14433 // Make sure we're dealing with a copy.
14434 unsigned Begin = I * NumElemsPerConcat;
14435 bool AllUndef = true, NoUndef = true;
14436 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
14437 if (SVN->getMaskElt(J) >= 0)
14444 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
14447 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
14448 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
14451 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
14452 if (FirstElt < N0.getNumOperands())
14453 Ops.push_back(N0.getOperand(FirstElt));
14455 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
14457 } else if (AllUndef) {
14458 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
14459 } else { // Mixed with general masks and undefs, can't do optimization.
14464 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
14467 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14468 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14470 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
14471 // a simplification in some sense, but it isn't appropriate in general: some
14472 // BUILD_VECTORs are substantially cheaper than others. The general case
14473 // of a BUILD_VECTOR requires inserting each element individually (or
14474 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
14475 // all constants is a single constant pool load. A BUILD_VECTOR where each
14476 // element is identical is a splat. A BUILD_VECTOR where most of the operands
14477 // are undef lowers to a small number of element insertions.
14479 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
14480 // We don't fold shuffles where one side is a non-zero constant, and we don't
14481 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
14482 // non-constant operands. This seems to work out reasonably well in practice.
14483 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
14485 const TargetLowering &TLI) {
14486 EVT VT = SVN->getValueType(0);
14487 unsigned NumElts = VT.getVectorNumElements();
14488 SDValue N0 = SVN->getOperand(0);
14489 SDValue N1 = SVN->getOperand(1);
14491 if (!N0->hasOneUse() || !N1->hasOneUse())
14493 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
14494 // discussed above.
14495 if (!N1.isUndef()) {
14496 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
14497 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
14498 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
14500 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
14504 SmallVector<SDValue, 8> Ops;
14505 SmallSet<SDValue, 16> DuplicateOps;
14506 for (int M : SVN->getMask()) {
14507 SDValue Op = DAG.getUNDEF(VT.getScalarType());
14509 int Idx = M < (int)NumElts ? M : M - NumElts;
14510 SDValue &S = (M < (int)NumElts ? N0 : N1);
14511 if (S.getOpcode() == ISD::BUILD_VECTOR) {
14512 Op = S.getOperand(Idx);
14513 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
14515 Op = S.getOperand(0);
14517 // Operand can't be combined - bail out.
14522 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
14523 // fine, but it's likely to generate low-quality code if the target can't
14524 // reconstruct an appropriate shuffle.
14525 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
14526 if (!DuplicateOps.insert(Op).second)
14531 // BUILD_VECTOR requires all inputs to be of the same type, find the
14532 // maximum type and extend them all.
14533 EVT SVT = VT.getScalarType();
14534 if (SVT.isInteger())
14535 for (SDValue &Op : Ops)
14536 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
14537 if (SVT != VT.getScalarType())
14538 for (SDValue &Op : Ops)
14539 Op = TLI.isZExtFree(Op.getValueType(), SVT)
14540 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
14541 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
14542 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
14545 // Match shuffles that can be converted to any_vector_extend_in_reg.
14546 // This is often generated during legalization.
14547 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
14548 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
14549 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
14551 const TargetLowering &TLI,
14552 bool LegalOperations) {
14553 EVT VT = SVN->getValueType(0);
14554 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14556 // TODO Add support for big-endian when we have a test case.
14557 if (!VT.isInteger() || IsBigEndian)
14560 unsigned NumElts = VT.getVectorNumElements();
14561 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14562 ArrayRef<int> Mask = SVN->getMask();
14563 SDValue N0 = SVN->getOperand(0);
14565 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
14566 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
14567 for (unsigned i = 0; i != NumElts; ++i) {
14570 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
14577 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
14578 // power-of-2 extensions as they are the most likely.
14579 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
14580 if (!isAnyExtend(Scale))
14583 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
14584 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
14585 if (!LegalOperations ||
14586 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
14587 return DAG.getBitcast(VT,
14588 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
14594 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
14595 // each source element of a large type into the lowest elements of a smaller
14596 // destination type. This is often generated during legalization.
14597 // If the source node itself was a '*_extend_vector_inreg' node then we should
14598 // then be able to remove it.
14599 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
14600 EVT VT = SVN->getValueType(0);
14601 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
14603 // TODO Add support for big-endian when we have a test case.
14604 if (!VT.isInteger() || IsBigEndian)
14607 SDValue N0 = SVN->getOperand(0);
14608 while (N0.getOpcode() == ISD::BITCAST)
14609 N0 = N0.getOperand(0);
14611 unsigned Opcode = N0.getOpcode();
14612 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
14613 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
14614 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
14617 SDValue N00 = N0.getOperand(0);
14618 ArrayRef<int> Mask = SVN->getMask();
14619 unsigned NumElts = VT.getVectorNumElements();
14620 unsigned EltSizeInBits = VT.getScalarSizeInBits();
14621 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
14623 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
14624 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
14625 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
14626 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
14627 for (unsigned i = 0; i != NumElts; ++i) {
14630 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
14637 // At the moment we just handle the case where we've truncated back to the
14638 // same size as before the extension.
14639 // TODO: handle more extension/truncation cases as cases arise.
14640 if (EltSizeInBits != ExtSrcSizeInBits)
14643 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
14644 // power-of-2 truncations as they are the most likely.
14645 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
14646 if (isTruncate(Scale))
14647 return DAG.getBitcast(VT, N00);
14652 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
14653 EVT VT = N->getValueType(0);
14654 unsigned NumElts = VT.getVectorNumElements();
14656 SDValue N0 = N->getOperand(0);
14657 SDValue N1 = N->getOperand(1);
14659 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
14661 // Canonicalize shuffle undef, undef -> undef
14662 if (N0.isUndef() && N1.isUndef())
14663 return DAG.getUNDEF(VT);
14665 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
14667 // Canonicalize shuffle v, v -> v, undef
14669 SmallVector<int, 8> NewMask;
14670 for (unsigned i = 0; i != NumElts; ++i) {
14671 int Idx = SVN->getMaskElt(i);
14672 if (Idx >= (int)NumElts) Idx -= NumElts;
14673 NewMask.push_back(Idx);
14675 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
14678 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
14680 return DAG.getCommutedVectorShuffle(*SVN);
14682 // Remove references to rhs if it is undef
14683 if (N1.isUndef()) {
14684 bool Changed = false;
14685 SmallVector<int, 8> NewMask;
14686 for (unsigned i = 0; i != NumElts; ++i) {
14687 int Idx = SVN->getMaskElt(i);
14688 if (Idx >= (int)NumElts) {
14692 NewMask.push_back(Idx);
14695 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
14698 // If it is a splat, check if the argument vector is another splat or a
14700 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
14701 SDNode *V = N0.getNode();
14703 // If this is a bit convert that changes the element type of the vector but
14704 // not the number of vector elements, look through it. Be careful not to
14705 // look though conversions that change things like v4f32 to v2f64.
14706 if (V->getOpcode() == ISD::BITCAST) {
14707 SDValue ConvInput = V->getOperand(0);
14708 if (ConvInput.getValueType().isVector() &&
14709 ConvInput.getValueType().getVectorNumElements() == NumElts)
14710 V = ConvInput.getNode();
14713 if (V->getOpcode() == ISD::BUILD_VECTOR) {
14714 assert(V->getNumOperands() == NumElts &&
14715 "BUILD_VECTOR has wrong number of operands");
14717 bool AllSame = true;
14718 for (unsigned i = 0; i != NumElts; ++i) {
14719 if (!V->getOperand(i).isUndef()) {
14720 Base = V->getOperand(i);
14724 // Splat of <u, u, u, u>, return <u, u, u, u>
14725 if (!Base.getNode())
14727 for (unsigned i = 0; i != NumElts; ++i) {
14728 if (V->getOperand(i) != Base) {
14733 // Splat of <x, x, x, x>, return <x, x, x, x>
14737 // Canonicalize any other splat as a build_vector.
14738 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
14739 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
14740 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
14742 // We may have jumped through bitcasts, so the type of the
14743 // BUILD_VECTOR may not match the type of the shuffle.
14744 if (V->getValueType(0) != VT)
14745 NewBV = DAG.getBitcast(VT, NewBV);
14750 // There are various patterns used to build up a vector from smaller vectors,
14751 // subvectors, or elements. Scan chains of these and replace unused insertions
14752 // or components with undef.
14753 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
14756 // Match shuffles that can be converted to any_vector_extend_in_reg.
14757 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
14760 // Combine "truncate_vector_in_reg" style shuffles.
14761 if (SDValue V = combineTruncationShuffle(SVN, DAG))
14764 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
14765 Level < AfterLegalizeVectorOps &&
14767 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
14768 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
14769 if (SDValue V = partitionShuffleOfConcats(N, DAG))
14773 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
14774 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
14775 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14776 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
14779 // If this shuffle only has a single input that is a bitcasted shuffle,
14780 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
14781 // back to their original types.
14782 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
14783 N1.isUndef() && Level < AfterLegalizeVectorOps &&
14784 TLI.isTypeLegal(VT)) {
14786 // Peek through the bitcast only if there is one user.
14788 while (BC0.getOpcode() == ISD::BITCAST) {
14789 if (!BC0.hasOneUse())
14791 BC0 = BC0.getOperand(0);
14794 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
14796 return SmallVector<int, 8>(Mask.begin(), Mask.end());
14798 SmallVector<int, 8> NewMask;
14800 for (int s = 0; s != Scale; ++s)
14801 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
14805 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
14806 EVT SVT = VT.getScalarType();
14807 EVT InnerVT = BC0->getValueType(0);
14808 EVT InnerSVT = InnerVT.getScalarType();
14810 // Determine which shuffle works with the smaller scalar type.
14811 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
14812 EVT ScaleSVT = ScaleVT.getScalarType();
14814 if (TLI.isTypeLegal(ScaleVT) &&
14815 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
14816 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
14818 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14819 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
14821 // Scale the shuffle masks to the smaller scalar type.
14822 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
14823 SmallVector<int, 8> InnerMask =
14824 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
14825 SmallVector<int, 8> OuterMask =
14826 ScaleShuffleMask(SVN->getMask(), OuterScale);
14828 // Merge the shuffle masks.
14829 SmallVector<int, 8> NewMask;
14830 for (int M : OuterMask)
14831 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
14833 // Test for shuffle mask legality over both commutations.
14834 SDValue SV0 = BC0->getOperand(0);
14835 SDValue SV1 = BC0->getOperand(1);
14836 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14838 std::swap(SV0, SV1);
14839 ShuffleVectorSDNode::commuteMask(NewMask);
14840 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
14844 SV0 = DAG.getBitcast(ScaleVT, SV0);
14845 SV1 = DAG.getBitcast(ScaleVT, SV1);
14846 return DAG.getBitcast(
14847 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
14853 // Canonicalize shuffles according to rules:
14854 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
14855 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
14856 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
14857 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
14858 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
14859 TLI.isTypeLegal(VT)) {
14860 // The incoming shuffle must be of the same type as the result of the
14861 // current shuffle.
14862 assert(N1->getOperand(0).getValueType() == VT &&
14863 "Shuffle types don't match");
14865 SDValue SV0 = N1->getOperand(0);
14866 SDValue SV1 = N1->getOperand(1);
14867 bool HasSameOp0 = N0 == SV0;
14868 bool IsSV1Undef = SV1.isUndef();
14869 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
14870 // Commute the operands of this shuffle so that next rule
14872 return DAG.getCommutedVectorShuffle(*SVN);
14875 // Try to fold according to rules:
14876 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14877 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14878 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14879 // Don't try to fold shuffles with illegal type.
14880 // Only fold if this shuffle is the only user of the other shuffle.
14881 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
14882 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
14883 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
14885 // Don't try to fold splats; they're likely to simplify somehow, or they
14887 if (OtherSV->isSplat())
14890 // The incoming shuffle must be of the same type as the result of the
14891 // current shuffle.
14892 assert(OtherSV->getOperand(0).getValueType() == VT &&
14893 "Shuffle types don't match");
14896 SmallVector<int, 4> Mask;
14897 // Compute the combined shuffle mask for a shuffle with SV0 as the first
14898 // operand, and SV1 as the second operand.
14899 for (unsigned i = 0; i != NumElts; ++i) {
14900 int Idx = SVN->getMaskElt(i);
14902 // Propagate Undef.
14903 Mask.push_back(Idx);
14907 SDValue CurrentVec;
14908 if (Idx < (int)NumElts) {
14909 // This shuffle index refers to the inner shuffle N0. Lookup the inner
14910 // shuffle mask to identify which vector is actually referenced.
14911 Idx = OtherSV->getMaskElt(Idx);
14913 // Propagate Undef.
14914 Mask.push_back(Idx);
14918 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
14919 : OtherSV->getOperand(1);
14921 // This shuffle index references an element within N1.
14925 // Simple case where 'CurrentVec' is UNDEF.
14926 if (CurrentVec.isUndef()) {
14927 Mask.push_back(-1);
14931 // Canonicalize the shuffle index. We don't know yet if CurrentVec
14932 // will be the first or second operand of the combined shuffle.
14933 Idx = Idx % NumElts;
14934 if (!SV0.getNode() || SV0 == CurrentVec) {
14935 // Ok. CurrentVec is the left hand side.
14936 // Update the mask accordingly.
14938 Mask.push_back(Idx);
14942 // Bail out if we cannot convert the shuffle pair into a single shuffle.
14943 if (SV1.getNode() && SV1 != CurrentVec)
14946 // Ok. CurrentVec is the right hand side.
14947 // Update the mask accordingly.
14949 Mask.push_back(Idx + NumElts);
14952 // Check if all indices in Mask are Undef. In case, propagate Undef.
14953 bool isUndefMask = true;
14954 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
14955 isUndefMask &= Mask[i] < 0;
14958 return DAG.getUNDEF(VT);
14960 if (!SV0.getNode())
14961 SV0 = DAG.getUNDEF(VT);
14962 if (!SV1.getNode())
14963 SV1 = DAG.getUNDEF(VT);
14965 // Avoid introducing shuffles with illegal mask.
14966 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
14967 ShuffleVectorSDNode::commuteMask(Mask);
14969 if (!TLI.isShuffleMaskLegal(Mask, VT))
14972 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
14973 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
14974 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
14975 std::swap(SV0, SV1);
14978 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
14979 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
14980 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
14981 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
14987 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
14988 SDValue InVal = N->getOperand(0);
14989 EVT VT = N->getValueType(0);
14991 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
14992 // with a VECTOR_SHUFFLE.
14993 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14994 SDValue InVec = InVal->getOperand(0);
14995 SDValue EltNo = InVal->getOperand(1);
14997 // FIXME: We could support implicit truncation if the shuffle can be
14998 // scaled to a smaller vector scalar type.
14999 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15000 if (C0 && VT == InVec.getValueType() &&
15001 VT.getScalarType() == InVal.getValueType()) {
15002 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15003 int Elt = C0->getZExtValue();
15006 if (TLI.isShuffleMaskLegal(NewMask, VT))
15007 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15015 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15016 EVT VT = N->getValueType(0);
15017 SDValue N0 = N->getOperand(0);
15018 SDValue N1 = N->getOperand(1);
15019 SDValue N2 = N->getOperand(2);
15021 // If inserting an UNDEF, just return the original vector.
15025 // If this is an insert of an extracted vector into an undef vector, we can
15026 // just use the input to the extract.
15027 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15028 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15029 return N1.getOperand(0);
15031 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15032 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15033 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15034 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15035 N0.getOperand(1).getValueType() == N1.getValueType() &&
15036 N0.getOperand(2) == N2)
15037 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15040 if (!isa<ConstantSDNode>(N2))
15043 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15045 // Canonicalize insert_subvector dag nodes.
15047 // (insert_subvector (insert_subvector A, Idx0), Idx1)
15048 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15049 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15050 N1.getValueType() == N0.getOperand(1).getValueType() &&
15051 isa<ConstantSDNode>(N0.getOperand(2))) {
15052 unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue();
15053 if (InsIdx < OtherIdx) {
15055 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15056 N0.getOperand(0), N1, N2);
15057 AddToWorklist(NewOp.getNode());
15058 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15059 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15063 // If the input vector is a concatenation, and the insert replaces
15064 // one of the pieces, we can optimize into a single concat_vectors.
15065 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15066 N0.getOperand(0).getValueType() == N1.getValueType()) {
15067 unsigned Factor = N1.getValueType().getVectorNumElements();
15069 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15070 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15072 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15078 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15079 SDValue N0 = N->getOperand(0);
15081 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15082 if (N0->getOpcode() == ISD::FP16_TO_FP)
15083 return N0->getOperand(0);
15088 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15089 SDValue N0 = N->getOperand(0);
15091 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15092 if (N0->getOpcode() == ISD::AND) {
15093 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15094 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15095 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15103 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15104 /// with the destination vector and a zero vector.
15105 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15106 /// vector_shuffle V, Zero, <0, 4, 2, 4>
15107 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15108 EVT VT = N->getValueType(0);
15109 SDValue LHS = N->getOperand(0);
15110 SDValue RHS = N->getOperand(1);
15113 // Make sure we're not running after operation legalization where it
15114 // may have custom lowered the vector shuffles.
15115 if (LegalOperations)
15118 if (N->getOpcode() != ISD::AND)
15121 if (RHS.getOpcode() == ISD::BITCAST)
15122 RHS = RHS.getOperand(0);
15124 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15127 EVT RVT = RHS.getValueType();
15128 unsigned NumElts = RHS.getNumOperands();
15130 // Attempt to create a valid clear mask, splitting the mask into
15131 // sub elements and checking to see if each is
15132 // all zeros or all ones - suitable for shuffle masking.
15133 auto BuildClearMask = [&](int Split) {
15134 int NumSubElts = NumElts * Split;
15135 int NumSubBits = RVT.getScalarSizeInBits() / Split;
15137 SmallVector<int, 8> Indices;
15138 for (int i = 0; i != NumSubElts; ++i) {
15139 int EltIdx = i / Split;
15140 int SubIdx = i % Split;
15141 SDValue Elt = RHS.getOperand(EltIdx);
15142 if (Elt.isUndef()) {
15143 Indices.push_back(-1);
15148 if (isa<ConstantSDNode>(Elt))
15149 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15150 else if (isa<ConstantFPSDNode>(Elt))
15151 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15155 // Extract the sub element from the constant bit mask.
15156 if (DAG.getDataLayout().isBigEndian()) {
15157 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15159 Bits.lshrInPlace(SubIdx * NumSubBits);
15163 Bits = Bits.trunc(NumSubBits);
15165 if (Bits.isAllOnesValue())
15166 Indices.push_back(i);
15167 else if (Bits == 0)
15168 Indices.push_back(i + NumSubElts);
15173 // Let's see if the target supports this vector_shuffle.
15174 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15175 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15176 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15179 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15180 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15181 DAG.getBitcast(ClearVT, LHS),
15185 // Determine maximum split level (byte level masking).
15187 if (RVT.getScalarSizeInBits() % 8 == 0)
15188 MaxSplit = RVT.getScalarSizeInBits() / 8;
15190 for (int Split = 1; Split <= MaxSplit; ++Split)
15191 if (RVT.getScalarSizeInBits() % Split == 0)
15192 if (SDValue S = BuildClearMask(Split))
15198 /// Visit a binary vector operation, like ADD.
15199 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15200 assert(N->getValueType(0).isVector() &&
15201 "SimplifyVBinOp only works on vectors!");
15203 SDValue LHS = N->getOperand(0);
15204 SDValue RHS = N->getOperand(1);
15205 SDValue Ops[] = {LHS, RHS};
15207 // See if we can constant fold the vector operation.
15208 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15209 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15212 // Try to convert a constant mask AND into a shuffle clear mask.
15213 if (SDValue Shuffle = XformToShuffleWithZero(N))
15216 // Type legalization might introduce new shuffles in the DAG.
15217 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15218 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
15219 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15220 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15221 LHS.getOperand(1).isUndef() &&
15222 RHS.getOperand(1).isUndef()) {
15223 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15224 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15226 if (SVN0->getMask().equals(SVN1->getMask())) {
15227 EVT VT = N->getValueType(0);
15228 SDValue UndefVector = LHS.getOperand(1);
15229 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15230 LHS.getOperand(0), RHS.getOperand(0),
15232 AddUsersToWorklist(N);
15233 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15241 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15243 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15245 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15246 cast<CondCodeSDNode>(N0.getOperand(2))->get());
15248 // If we got a simplified select_cc node back from SimplifySelectCC, then
15249 // break it down into a new SETCC node, and a new SELECT node, and then return
15250 // the SELECT node, since we were called with a SELECT node.
15251 if (SCC.getNode()) {
15252 // Check to see if we got a select_cc back (to turn into setcc/select).
15253 // Otherwise, just return whatever node we got back, like fabs.
15254 if (SCC.getOpcode() == ISD::SELECT_CC) {
15255 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15257 SCC.getOperand(0), SCC.getOperand(1),
15258 SCC.getOperand(4));
15259 AddToWorklist(SETCC.getNode());
15260 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15261 SCC.getOperand(2), SCC.getOperand(3));
15269 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15270 /// being selected between, see if we can simplify the select. Callers of this
15271 /// should assume that TheSelect is deleted if this returns true. As such, they
15272 /// should return the appropriate thing (e.g. the node) back to the top-level of
15273 /// the DAG combiner loop to avoid it being looked at.
15274 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15277 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15278 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15279 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15280 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15281 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15282 SDValue Sqrt = RHS;
15285 const ConstantFPSDNode *Zero = nullptr;
15287 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15288 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15289 CmpLHS = TheSelect->getOperand(0);
15290 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15292 // SELECT or VSELECT
15293 SDValue Cmp = TheSelect->getOperand(0);
15294 if (Cmp.getOpcode() == ISD::SETCC) {
15295 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15296 CmpLHS = Cmp.getOperand(0);
15297 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15300 if (Zero && Zero->isZero() &&
15301 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15302 CC == ISD::SETULT || CC == ISD::SETLT)) {
15303 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15304 CombineTo(TheSelect, Sqrt);
15309 // Cannot simplify select with vector condition
15310 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15312 // If this is a select from two identical things, try to pull the operation
15313 // through the select.
15314 if (LHS.getOpcode() != RHS.getOpcode() ||
15315 !LHS.hasOneUse() || !RHS.hasOneUse())
15318 // If this is a load and the token chain is identical, replace the select
15319 // of two loads with a load through a select of the address to load from.
15320 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15321 // constants have been dropped into the constant pool.
15322 if (LHS.getOpcode() == ISD::LOAD) {
15323 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15324 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15326 // Token chains must be identical.
15327 if (LHS.getOperand(0) != RHS.getOperand(0) ||
15328 // Do not let this transformation reduce the number of volatile loads.
15329 LLD->isVolatile() || RLD->isVolatile() ||
15330 // FIXME: If either is a pre/post inc/dec load,
15331 // we'd need to split out the address adjustment.
15332 LLD->isIndexed() || RLD->isIndexed() ||
15333 // If this is an EXTLOAD, the VT's must match.
15334 LLD->getMemoryVT() != RLD->getMemoryVT() ||
15335 // If this is an EXTLOAD, the kind of extension must match.
15336 (LLD->getExtensionType() != RLD->getExtensionType() &&
15337 // The only exception is if one of the extensions is anyext.
15338 LLD->getExtensionType() != ISD::EXTLOAD &&
15339 RLD->getExtensionType() != ISD::EXTLOAD) ||
15340 // FIXME: this discards src value information. This is
15341 // over-conservative. It would be beneficial to be able to remember
15342 // both potential memory locations. Since we are discarding
15343 // src value info, don't do the transformation if the memory
15344 // locations are not in the default address space.
15345 LLD->getPointerInfo().getAddrSpace() != 0 ||
15346 RLD->getPointerInfo().getAddrSpace() != 0 ||
15347 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
15348 LLD->getBasePtr().getValueType()))
15351 // Check that the select condition doesn't reach either load. If so,
15352 // folding this will induce a cycle into the DAG. If not, this is safe to
15353 // xform, so create a select of the addresses.
15355 if (TheSelect->getOpcode() == ISD::SELECT) {
15356 SDNode *CondNode = TheSelect->getOperand(0).getNode();
15357 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
15358 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
15360 // The loads must not depend on one another.
15361 if (LLD->isPredecessorOf(RLD) ||
15362 RLD->isPredecessorOf(LLD))
15364 Addr = DAG.getSelect(SDLoc(TheSelect),
15365 LLD->getBasePtr().getValueType(),
15366 TheSelect->getOperand(0), LLD->getBasePtr(),
15367 RLD->getBasePtr());
15368 } else { // Otherwise SELECT_CC
15369 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
15370 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
15372 if ((LLD->hasAnyUseOfValue(1) &&
15373 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
15374 (RLD->hasAnyUseOfValue(1) &&
15375 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
15378 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
15379 LLD->getBasePtr().getValueType(),
15380 TheSelect->getOperand(0),
15381 TheSelect->getOperand(1),
15382 LLD->getBasePtr(), RLD->getBasePtr(),
15383 TheSelect->getOperand(4));
15387 // It is safe to replace the two loads if they have different alignments,
15388 // but the new load must be the minimum (most restrictive) alignment of the
15390 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
15391 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
15392 if (!RLD->isInvariant())
15393 MMOFlags &= ~MachineMemOperand::MOInvariant;
15394 if (!RLD->isDereferenceable())
15395 MMOFlags &= ~MachineMemOperand::MODereferenceable;
15396 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
15397 // FIXME: Discards pointer and AA info.
15398 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
15399 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
15402 // FIXME: Discards pointer and AA info.
15403 Load = DAG.getExtLoad(
15404 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
15405 : LLD->getExtensionType(),
15406 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
15407 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
15410 // Users of the select now use the result of the load.
15411 CombineTo(TheSelect, Load);
15413 // Users of the old loads now use the new load's chain. We know the
15414 // old-load value is dead now.
15415 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
15416 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
15423 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
15425 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
15426 SDValue N1, SDValue N2, SDValue N3,
15427 ISD::CondCode CC) {
15428 // If this is a select where the false operand is zero and the compare is a
15429 // check of the sign bit, see if we can perform the "gzip trick":
15430 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
15431 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
15432 EVT XType = N0.getValueType();
15433 EVT AType = N2.getValueType();
15434 if (!isNullConstant(N3) || !XType.bitsGE(AType))
15437 // If the comparison is testing for a positive value, we have to invert
15438 // the sign bit mask, so only do that transform if the target has a bitwise
15439 // 'and not' instruction (the invert is free).
15440 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
15441 // (X > -1) ? A : 0
15442 // (X > 0) ? X : 0 <-- This is canonical signed max.
15443 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
15445 } else if (CC == ISD::SETLT) {
15447 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
15448 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
15454 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
15456 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
15457 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15458 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
15459 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
15460 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
15461 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
15462 AddToWorklist(Shift.getNode());
15464 if (XType.bitsGT(AType)) {
15465 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15466 AddToWorklist(Shift.getNode());
15469 if (CC == ISD::SETGT)
15470 Shift = DAG.getNOT(DL, Shift, AType);
15472 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15475 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
15476 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
15477 AddToWorklist(Shift.getNode());
15479 if (XType.bitsGT(AType)) {
15480 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
15481 AddToWorklist(Shift.getNode());
15484 if (CC == ISD::SETGT)
15485 Shift = DAG.getNOT(DL, Shift, AType);
15487 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
15490 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
15491 /// where 'cond' is the comparison specified by CC.
15492 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
15493 SDValue N2, SDValue N3, ISD::CondCode CC,
15494 bool NotExtCompare) {
15495 // (x ? y : y) -> y.
15496 if (N2 == N3) return N2;
15498 EVT VT = N2.getValueType();
15499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
15500 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
15502 // Determine if the condition we're dealing with is constant
15503 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
15504 N0, N1, CC, DL, false);
15505 if (SCC.getNode()) AddToWorklist(SCC.getNode());
15507 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
15508 // fold select_cc true, x, y -> x
15509 // fold select_cc false, x, y -> y
15510 return !SCCC->isNullValue() ? N2 : N3;
15513 // Check to see if we can simplify the select into an fabs node
15514 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
15515 // Allow either -0.0 or 0.0
15516 if (CFP->isZero()) {
15517 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
15518 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
15519 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
15520 N2 == N3.getOperand(0))
15521 return DAG.getNode(ISD::FABS, DL, VT, N0);
15523 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
15524 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
15525 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
15526 N2.getOperand(0) == N3)
15527 return DAG.getNode(ISD::FABS, DL, VT, N3);
15531 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
15532 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
15533 // in it. This is a win when the constant is not otherwise available because
15534 // it replaces two constant pool loads with one. We only do this if the FP
15535 // type is known to be legal, because if it isn't, then we are before legalize
15536 // types an we want the other legalization to happen first (e.g. to avoid
15537 // messing with soft float) and if the ConstantFP is not legal, because if
15538 // it is legal, we may not need to store the FP constant in a constant pool.
15539 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
15540 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
15541 if (TLI.isTypeLegal(N2.getValueType()) &&
15542 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
15543 TargetLowering::Legal &&
15544 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
15545 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
15546 // If both constants have multiple uses, then we won't need to do an
15547 // extra load, they are likely around in registers for other users.
15548 (TV->hasOneUse() || FV->hasOneUse())) {
15549 Constant *Elts[] = {
15550 const_cast<ConstantFP*>(FV->getConstantFPValue()),
15551 const_cast<ConstantFP*>(TV->getConstantFPValue())
15553 Type *FPTy = Elts[0]->getType();
15554 const DataLayout &TD = DAG.getDataLayout();
15556 // Create a ConstantArray of the two constants.
15557 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
15559 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
15560 TD.getPrefTypeAlignment(FPTy));
15561 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
15563 // Get the offsets to the 0 and 1 element of the array so that we can
15564 // select between them.
15565 SDValue Zero = DAG.getIntPtrConstant(0, DL);
15566 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
15567 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
15569 SDValue Cond = DAG.getSetCC(DL,
15570 getSetCCResultType(N0.getValueType()),
15572 AddToWorklist(Cond.getNode());
15573 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
15575 AddToWorklist(CstOffset.getNode());
15576 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
15578 AddToWorklist(CPIdx.getNode());
15579 return DAG.getLoad(
15580 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
15581 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
15586 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
15589 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
15590 // where y is has a single bit set.
15591 // A plaintext description would be, we can turn the SELECT_CC into an AND
15592 // when the condition can be materialized as an all-ones register. Any
15593 // single bit-test can be materialized as an all-ones register with
15594 // shift-left and shift-right-arith.
15595 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
15596 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
15597 SDValue AndLHS = N0->getOperand(0);
15598 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15599 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
15600 // Shift the tested bit over the sign bit.
15601 const APInt &AndMask = ConstAndRHS->getAPIntValue();
15603 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
15604 getShiftAmountTy(AndLHS.getValueType()));
15605 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
15607 // Now arithmetic right shift it all the way over, so the result is either
15608 // all-ones, or zero.
15610 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
15611 getShiftAmountTy(Shl.getValueType()));
15612 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
15614 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
15618 // fold select C, 16, 0 -> shl C, 4
15619 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
15620 TLI.getBooleanContents(N0.getValueType()) ==
15621 TargetLowering::ZeroOrOneBooleanContent) {
15623 // If the caller doesn't want us to simplify this into a zext of a compare,
15625 if (NotExtCompare && N2C->isOne())
15628 // Get a SetCC of the condition
15629 // NOTE: Don't create a SETCC if it's not legal on this target.
15630 if (!LegalOperations ||
15631 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
15633 // cast from setcc result type to select result type
15635 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
15637 if (N2.getValueType().bitsLT(SCC.getValueType()))
15638 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
15639 N2.getValueType());
15641 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15642 N2.getValueType(), SCC);
15644 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
15645 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
15646 N2.getValueType(), SCC);
15649 AddToWorklist(SCC.getNode());
15650 AddToWorklist(Temp.getNode());
15655 // shl setcc result by log2 n2c
15656 return DAG.getNode(
15657 ISD::SHL, DL, N2.getValueType(), Temp,
15658 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
15659 getShiftAmountTy(Temp.getValueType())));
15663 // Check to see if this is an integer abs.
15664 // select_cc setg[te] X, 0, X, -X ->
15665 // select_cc setgt X, -1, X, -X ->
15666 // select_cc setl[te] X, 0, -X, X ->
15667 // select_cc setlt X, 1, -X, X ->
15668 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
15670 ConstantSDNode *SubC = nullptr;
15671 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
15672 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
15673 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
15674 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
15675 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
15676 (N1C->isOne() && CC == ISD::SETLT)) &&
15677 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
15678 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
15680 EVT XType = N0.getValueType();
15681 if (SubC && SubC->isNullValue() && XType.isInteger()) {
15683 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
15685 DAG.getConstant(XType.getSizeInBits() - 1, DL,
15686 getShiftAmountTy(N0.getValueType())));
15687 SDValue Add = DAG.getNode(ISD::ADD, DL,
15689 AddToWorklist(Shift.getNode());
15690 AddToWorklist(Add.getNode());
15691 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
15695 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
15696 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
15697 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
15698 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
15699 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
15700 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
15701 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
15702 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
15703 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15704 SDValue ValueOnZero = N2;
15705 SDValue Count = N3;
15706 // If the condition is NE instead of E, swap the operands.
15707 if (CC == ISD::SETNE)
15708 std::swap(ValueOnZero, Count);
15709 // Check if the value on zero is a constant equal to the bits in the type.
15710 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
15711 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
15712 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
15713 // legal, combine to just cttz.
15714 if ((Count.getOpcode() == ISD::CTTZ ||
15715 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
15716 N0 == Count.getOperand(0) &&
15717 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
15718 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
15719 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
15720 // legal, combine to just ctlz.
15721 if ((Count.getOpcode() == ISD::CTLZ ||
15722 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
15723 N0 == Count.getOperand(0) &&
15724 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
15725 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
15733 /// This is a stub for TargetLowering::SimplifySetCC.
15734 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
15735 ISD::CondCode Cond, const SDLoc &DL,
15736 bool foldBooleans) {
15737 TargetLowering::DAGCombinerInfo
15738 DagCombineInfo(DAG, Level, false, this);
15739 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
15742 /// Given an ISD::SDIV node expressing a divide by constant, return
15743 /// a DAG expression to select that will generate the same value by multiplying
15744 /// by a magic number.
15745 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15746 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
15747 // when optimising for minimum size, we don't want to expand a div to a mul
15749 if (DAG.getMachineFunction().getFunction()->optForMinSize())
15752 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15756 // Avoid division by zero.
15757 if (C->isNullValue())
15760 std::vector<SDNode*> Built;
15762 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15764 for (SDNode *N : Built)
15769 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
15770 /// DAG expression that will generate the same value by right shifting.
15771 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
15772 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15776 // Avoid division by zero.
15777 if (C->isNullValue())
15780 std::vector<SDNode *> Built;
15781 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
15783 for (SDNode *N : Built)
15788 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
15789 /// expression that will generate the same value by multiplying by a magic
15791 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
15792 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
15793 // when optimising for minimum size, we don't want to expand a div to a mul
15795 if (DAG.getMachineFunction().getFunction()->optForMinSize())
15798 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
15802 // Avoid division by zero.
15803 if (C->isNullValue())
15806 std::vector<SDNode*> Built;
15808 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
15810 for (SDNode *N : Built)
15815 /// Determines the LogBase2 value for a non-null input value using the
15816 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
15817 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
15818 EVT VT = V.getValueType();
15819 unsigned EltBits = VT.getScalarSizeInBits();
15820 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
15821 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
15822 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
15826 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15827 /// For the reciprocal, we need to find the zero of the function:
15828 /// F(X) = A X - 1 [which has a zero at X = 1/A]
15830 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
15831 /// does not require additional intermediate precision]
15832 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
15833 if (Level >= AfterLegalizeDAG)
15836 // TODO: Handle half and/or extended types?
15837 EVT VT = Op.getValueType();
15838 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15841 // If estimates are explicitly disabled for this function, we're done.
15842 MachineFunction &MF = DAG.getMachineFunction();
15843 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
15844 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15847 // Estimates may be explicitly enabled for this type with a custom number of
15848 // refinement steps.
15849 int Iterations = TLI.getDivRefinementSteps(VT, MF);
15850 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
15851 AddToWorklist(Est.getNode());
15854 EVT VT = Op.getValueType();
15856 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
15858 // Newton iterations: Est = Est + Est (1 - Arg * Est)
15859 for (int i = 0; i < Iterations; ++i) {
15860 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
15861 AddToWorklist(NewEst.getNode());
15863 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
15864 AddToWorklist(NewEst.getNode());
15866 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15867 AddToWorklist(NewEst.getNode());
15869 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
15870 AddToWorklist(Est.getNode());
15879 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15880 /// For the reciprocal sqrt, we need to find the zero of the function:
15881 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15883 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
15884 /// As a result, we precompute A/2 prior to the iteration loop.
15885 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
15886 unsigned Iterations,
15887 SDNodeFlags *Flags, bool Reciprocal) {
15888 EVT VT = Arg.getValueType();
15890 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
15892 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
15893 // this entire sequence requires only one FP constant.
15894 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
15895 AddToWorklist(HalfArg.getNode());
15897 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
15898 AddToWorklist(HalfArg.getNode());
15900 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
15901 for (unsigned i = 0; i < Iterations; ++i) {
15902 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
15903 AddToWorklist(NewEst.getNode());
15905 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
15906 AddToWorklist(NewEst.getNode());
15908 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
15909 AddToWorklist(NewEst.getNode());
15911 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
15912 AddToWorklist(Est.getNode());
15915 // If non-reciprocal square root is requested, multiply the result by Arg.
15917 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
15918 AddToWorklist(Est.getNode());
15924 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
15925 /// For the reciprocal sqrt, we need to find the zero of the function:
15926 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
15928 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
15929 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
15930 unsigned Iterations,
15931 SDNodeFlags *Flags, bool Reciprocal) {
15932 EVT VT = Arg.getValueType();
15934 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
15935 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
15937 // This routine must enter the loop below to work correctly
15938 // when (Reciprocal == false).
15939 assert(Iterations > 0);
15941 // Newton iterations for reciprocal square root:
15942 // E = (E * -0.5) * ((A * E) * E + -3.0)
15943 for (unsigned i = 0; i < Iterations; ++i) {
15944 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
15945 AddToWorklist(AE.getNode());
15947 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
15948 AddToWorklist(AEE.getNode());
15950 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
15951 AddToWorklist(RHS.getNode());
15953 // When calculating a square root at the last iteration build:
15954 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
15955 // (notice a common subexpression)
15957 if (Reciprocal || (i + 1) < Iterations) {
15958 // RSQRT: LHS = (E * -0.5)
15959 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
15961 // SQRT: LHS = (A * E) * -0.5
15962 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
15964 AddToWorklist(LHS.getNode());
15966 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
15967 AddToWorklist(Est.getNode());
15973 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
15974 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
15975 /// Op can be zero.
15976 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
15978 if (Level >= AfterLegalizeDAG)
15981 // TODO: Handle half and/or extended types?
15982 EVT VT = Op.getValueType();
15983 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
15986 // If estimates are explicitly disabled for this function, we're done.
15987 MachineFunction &MF = DAG.getMachineFunction();
15988 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
15989 if (Enabled == TLI.ReciprocalEstimate::Disabled)
15992 // Estimates may be explicitly enabled for this type with a custom number of
15993 // refinement steps.
15994 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
15996 bool UseOneConstNR = false;
15998 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16000 AddToWorklist(Est.getNode());
16003 Est = UseOneConstNR
16004 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16005 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16008 // Unfortunately, Est is now NaN if the input was exactly 0.0.
16009 // Select out this case and force the answer to 0.0.
16010 EVT VT = Op.getValueType();
16013 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16014 EVT CCVT = getSetCCResultType(VT);
16015 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16016 AddToWorklist(ZeroCmp.getNode());
16018 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16019 ZeroCmp, FPZero, Est);
16020 AddToWorklist(Est.getNode());
16029 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16030 return buildSqrtEstimateImpl(Op, Flags, true);
16033 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
16034 return buildSqrtEstimateImpl(Op, Flags, false);
16037 /// Return true if base is a frame index, which is known not to alias with
16038 /// anything but itself. Provides base object and offset as results.
16039 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16040 const GlobalValue *&GV, const void *&CV) {
16041 // Assume it is a primitive operation.
16042 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16044 // If it's an adding a simple constant then integrate the offset.
16045 if (Base.getOpcode() == ISD::ADD) {
16046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16047 Base = Base.getOperand(0);
16048 Offset += C->getSExtValue();
16052 // Return the underlying GlobalValue, and update the Offset. Return false
16053 // for GlobalAddressSDNode since the same GlobalAddress may be represented
16054 // by multiple nodes with different offsets.
16055 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16056 GV = G->getGlobal();
16057 Offset += G->getOffset();
16061 // Return the underlying Constant value, and update the Offset. Return false
16062 // for ConstantSDNodes since the same constant pool entry may be represented
16063 // by multiple nodes with different offsets.
16064 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16065 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16066 : (const void *)C->getConstVal();
16067 Offset += C->getOffset();
16070 // If it's any of the following then it can't alias with anything but itself.
16071 return isa<FrameIndexSDNode>(Base);
16074 /// Return true if there is any possibility that the two addresses overlap.
16075 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16076 // If they are the same then they must be aliases.
16077 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16079 // If they are both volatile then they cannot be reordered.
16080 if (Op0->isVolatile() && Op1->isVolatile()) return true;
16082 // If one operation reads from invariant memory, and the other may store, they
16083 // cannot alias. These should really be checking the equivalent of mayWrite,
16084 // but it only matters for memory nodes other than load /store.
16085 if (Op0->isInvariant() && Op1->writeMem())
16088 if (Op1->isInvariant() && Op0->writeMem())
16091 // Gather base node and offset information.
16092 SDValue Base0, Base1;
16093 int64_t Offset0, Offset1;
16094 const GlobalValue *GV0, *GV1;
16095 const void *CV0, *CV1;
16096 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16097 Base0, Offset0, GV0, CV0);
16098 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16099 Base1, Offset1, GV1, CV1);
16101 // If they have the same base address, then check to see if they overlap.
16102 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16103 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16104 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16105 return !((Offset0 + NumBytes0) <= Offset1 ||
16106 (Offset1 + NumBytes1) <= Offset0);
16108 // It is possible for different frame indices to alias each other, mostly
16109 // when tail call optimization reuses return address slots for arguments.
16110 // To catch this case, look up the actual index of frame indices to compute
16111 // the real alias relationship.
16112 if (IsFrameIndex0 && IsFrameIndex1) {
16113 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16114 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16115 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16116 return !((Offset0 + NumBytes0) <= Offset1 ||
16117 (Offset1 + NumBytes1) <= Offset0);
16120 // Otherwise, if we know what the bases are, and they aren't identical, then
16121 // we know they cannot alias.
16122 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16125 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16126 // compared to the size and offset of the access, we may be able to prove they
16127 // do not alias. This check is conservative for now to catch cases created by
16128 // splitting vector types.
16129 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16130 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16131 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16132 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16133 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16134 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16135 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16136 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16138 // There is no overlap between these relatively aligned accesses of similar
16139 // size. Return no alias.
16140 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16141 (OffAlign1 + NumBytes1) <= OffAlign0)
16145 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16147 : DAG.getSubtarget().useAA();
16149 if (CombinerAAOnlyFunc.getNumOccurrences() &&
16150 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16155 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16156 // Use alias analysis information.
16157 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16158 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16159 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16160 AliasResult AAResult =
16161 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16162 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16163 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16164 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
16165 if (AAResult == NoAlias)
16169 // Otherwise we have to assume they alias.
16173 /// Walk up chain skipping non-aliasing memory nodes,
16174 /// looking for aliasing nodes and adding them to the Aliases vector.
16175 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16176 SmallVectorImpl<SDValue> &Aliases) {
16177 SmallVector<SDValue, 8> Chains; // List of chains to visit.
16178 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
16180 // Get alias information for node.
16181 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16184 Chains.push_back(OriginalChain);
16185 unsigned Depth = 0;
16187 // Look at each chain and determine if it is an alias. If so, add it to the
16188 // aliases list. If not, then continue up the chain looking for the next
16190 while (!Chains.empty()) {
16191 SDValue Chain = Chains.pop_back_val();
16193 // For TokenFactor nodes, look at each operand and only continue up the
16194 // chain until we reach the depth limit.
16196 // FIXME: The depth check could be made to return the last non-aliasing
16197 // chain we found before we hit a tokenfactor rather than the original
16199 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16201 Aliases.push_back(OriginalChain);
16205 // Don't bother if we've been before.
16206 if (!Visited.insert(Chain.getNode()).second)
16209 switch (Chain.getOpcode()) {
16210 case ISD::EntryToken:
16211 // Entry token is ideal chain operand, but handled in FindBetterChain.
16216 // Get alias information for Chain.
16217 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16218 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16220 // If chain is alias then stop here.
16221 if (!(IsLoad && IsOpLoad) &&
16222 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16223 Aliases.push_back(Chain);
16225 // Look further up the chain.
16226 Chains.push_back(Chain.getOperand(0));
16232 case ISD::TokenFactor:
16233 // We have to check each of the operands of the token factor for "small"
16234 // token factors, so we queue them up. Adding the operands to the queue
16235 // (stack) in reverse order maintains the original order and increases the
16236 // likelihood that getNode will find a matching token factor (CSE.)
16237 if (Chain.getNumOperands() > 16) {
16238 Aliases.push_back(Chain);
16241 for (unsigned n = Chain.getNumOperands(); n;)
16242 Chains.push_back(Chain.getOperand(--n));
16246 case ISD::CopyFromReg:
16247 // Forward past CopyFromReg.
16248 Chains.push_back(Chain.getOperand(0));
16253 // For all other instructions we will just have to take what we can get.
16254 Aliases.push_back(Chain);
16260 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16261 /// (aliasing node.)
16262 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16263 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
16265 // Accumulate all the aliases to this node.
16266 GatherAllAliases(N, OldChain, Aliases);
16268 // If no operands then chain to entry token.
16269 if (Aliases.size() == 0)
16270 return DAG.getEntryNode();
16272 // If a single operand then chain to it. We don't need to revisit it.
16273 if (Aliases.size() == 1)
16276 // Construct a custom tailored token factor.
16277 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16280 // This function tries to collect a bunch of potentially interesting
16281 // nodes to improve the chains of, all at once. This might seem
16282 // redundant, as this function gets called when visiting every store
16283 // node, so why not let the work be done on each store as it's visited?
16285 // I believe this is mainly important because MergeConsecutiveStores
16286 // is unable to deal with merging stores of different sizes, so unless
16287 // we improve the chains of all the potential candidates up-front
16288 // before running MergeConsecutiveStores, it might only see some of
16289 // the nodes that will eventually be candidates, and then not be able
16290 // to go from a partially-merged state to the desired final
16291 // fully-merged state.
16292 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16293 // This holds the base pointer, index, and the offset in bytes from the base
16295 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16297 // We must have a base and an offset.
16298 if (!BasePtr.Base.getNode())
16301 // Do not handle stores to undef base pointers.
16302 if (BasePtr.Base.isUndef())
16305 SmallVector<StoreSDNode *, 8> ChainedStores;
16306 ChainedStores.push_back(St);
16308 // Walk up the chain and look for nodes with offsets from the same
16309 // base pointer. Stop when reaching an instruction with a different kind
16310 // or instruction which has a different base pointer.
16311 StoreSDNode *Index = St;
16313 // If the chain has more than one use, then we can't reorder the mem ops.
16314 if (Index != St && !SDValue(Index, 0)->hasOneUse())
16317 if (Index->isVolatile() || Index->isIndexed())
16320 // Find the base pointer and offset for this memory node.
16321 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
16323 // Check that the base pointer is the same as the original one.
16324 if (!Ptr.equalBaseIndex(BasePtr))
16327 // Walk up the chain to find the next store node, ignoring any
16328 // intermediate loads. Any other kind of node will halt the loop.
16329 SDNode *NextInChain = Index->getChain().getNode();
16331 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
16332 // We found a store node. Use it for the next iteration.
16333 if (STn->isVolatile() || STn->isIndexed()) {
16337 ChainedStores.push_back(STn);
16340 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
16341 NextInChain = Ldn->getChain().getNode();
16350 // At this point, ChainedStores lists all of the Store nodes
16351 // reachable by iterating up through chain nodes matching the above
16352 // conditions. For each such store identified, try to find an
16353 // earlier chain to attach the store to which won't violate the
16354 // required ordering.
16355 bool MadeChangeToSt = false;
16356 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
16358 for (StoreSDNode *ChainedStore : ChainedStores) {
16359 SDValue Chain = ChainedStore->getChain();
16360 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
16362 if (Chain != BetterChain) {
16363 if (ChainedStore == St)
16364 MadeChangeToSt = true;
16365 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
16369 // Do all replacements after finding the replacements to make to avoid making
16370 // the chains more complicated by introducing new TokenFactors.
16371 for (auto Replacement : BetterChains)
16372 replaceStoreChain(Replacement.first, Replacement.second);
16374 return MadeChangeToSt;
16377 /// This is the entry point for the file.
16378 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
16379 CodeGenOpt::Level OptLevel) {
16380 /// This is the main entry point to this class.
16381 DAGCombiner(*this, AA, OptLevel).Run(Level);