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/SelectionDAGAddressAnalysis.h"
29 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/KnownBits.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
47 #define DEBUG_TYPE "dagcombine"
49 STATISTIC(NodesCombined , "Number of dag nodes combined");
50 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
51 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
52 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
53 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
54 STATISTIC(SlicedLoads, "Number of load sliced");
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 32> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 assert(N->getOpcode() != ISD::DELETED_NODE &&
135 "Deleted Node added to Worklist");
137 // Skip handle nodes as they can't usefully be combined and confuse the
138 // zero-use deletion strategy.
139 if (N->getOpcode() == ISD::HANDLENODE)
142 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
143 Worklist.push_back(N);
146 /// Remove all instances of N from the worklist.
147 void removeFromWorklist(SDNode *N) {
148 CombinedNodes.erase(N);
150 auto It = WorklistMap.find(N);
151 if (It == WorklistMap.end())
152 return; // Not in the worklist.
154 // Null out the entry rather than erasing it to avoid a linear operation.
155 Worklist[It->second] = nullptr;
156 WorklistMap.erase(It);
159 void deleteAndRecombine(SDNode *N);
160 bool recursivelyDeleteUnusedNodes(SDNode *N);
162 /// Replaces all uses of the results of one DAG node with new values.
163 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
166 /// Replaces all uses of the results of one DAG node with new values.
167 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
168 return CombineTo(N, &Res, 1, AddTo);
171 /// Replaces all uses of the results of one DAG node with new values.
172 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
174 SDValue To[] = { Res0, Res1 };
175 return CombineTo(N, To, 2, AddTo);
178 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
181 unsigned MaximumLegalStoreInBits;
183 /// Check the specified integer node value to see if it can be simplified or
184 /// if things it uses can be simplified by bit propagation.
185 /// If so, return true.
186 bool SimplifyDemandedBits(SDValue Op) {
187 unsigned BitWidth = Op.getScalarValueSizeInBits();
188 APInt Demanded = APInt::getAllOnesValue(BitWidth);
189 return SimplifyDemandedBits(Op, Demanded);
192 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
194 bool CombineToPreIndexedLoadStore(SDNode *N);
195 bool CombineToPostIndexedLoadStore(SDNode *N);
196 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
197 bool SliceUpLoad(SDNode *N);
199 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
202 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
203 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
204 /// \param EltNo index of the vector element to load.
205 /// \param OriginalLoad load that EVE came from to be replaced.
206 /// \returns EVE on success SDValue() on failure.
207 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
208 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
209 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
210 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
211 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
212 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
213 SDValue PromoteIntBinOp(SDValue Op);
214 SDValue PromoteIntShiftOp(SDValue Op);
215 SDValue PromoteExtend(SDValue Op);
216 bool PromoteLoad(SDValue Op);
218 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
219 SDValue ExtLoad, const SDLoc &DL,
220 ISD::NodeType ExtType);
222 /// Call the node-specific routine that knows how to fold each
223 /// particular type of node. If that doesn't do anything, try the
224 /// target-specific DAG combines.
225 SDValue combine(SDNode *N);
227 // Visitation implementation - Implement dag node combining for different
228 // node types. The semantics are as follows:
230 // SDValue.getNode() == 0 - No change was made
231 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
232 // otherwise - N should be replaced by the returned Operand.
234 SDValue visitTokenFactor(SDNode *N);
235 SDValue visitMERGE_VALUES(SDNode *N);
236 SDValue visitADD(SDNode *N);
237 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
238 SDValue visitSUB(SDNode *N);
239 SDValue visitADDC(SDNode *N);
240 SDValue visitUADDO(SDNode *N);
241 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
242 SDValue visitSUBC(SDNode *N);
243 SDValue visitUSUBO(SDNode *N);
244 SDValue visitADDE(SDNode *N);
245 SDValue visitADDCARRY(SDNode *N);
246 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
247 SDValue visitSUBE(SDNode *N);
248 SDValue visitSUBCARRY(SDNode *N);
249 SDValue visitMUL(SDNode *N);
250 SDValue useDivRem(SDNode *N);
251 SDValue visitSDIV(SDNode *N);
252 SDValue visitUDIV(SDNode *N);
253 SDValue visitREM(SDNode *N);
254 SDValue visitMULHU(SDNode *N);
255 SDValue visitMULHS(SDNode *N);
256 SDValue visitSMUL_LOHI(SDNode *N);
257 SDValue visitUMUL_LOHI(SDNode *N);
258 SDValue visitSMULO(SDNode *N);
259 SDValue visitUMULO(SDNode *N);
260 SDValue visitIMINMAX(SDNode *N);
261 SDValue visitAND(SDNode *N);
262 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
263 SDValue visitOR(SDNode *N);
264 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
265 SDValue visitXOR(SDNode *N);
266 SDValue SimplifyVBinOp(SDNode *N);
267 SDValue visitSHL(SDNode *N);
268 SDValue visitSRA(SDNode *N);
269 SDValue visitSRL(SDNode *N);
270 SDValue visitRotate(SDNode *N);
271 SDValue visitABS(SDNode *N);
272 SDValue visitBSWAP(SDNode *N);
273 SDValue visitBITREVERSE(SDNode *N);
274 SDValue visitCTLZ(SDNode *N);
275 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
276 SDValue visitCTTZ(SDNode *N);
277 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
278 SDValue visitCTPOP(SDNode *N);
279 SDValue visitSELECT(SDNode *N);
280 SDValue visitVSELECT(SDNode *N);
281 SDValue visitSELECT_CC(SDNode *N);
282 SDValue visitSETCC(SDNode *N);
283 SDValue visitSETCCE(SDNode *N);
284 SDValue visitSETCCCARRY(SDNode *N);
285 SDValue visitSIGN_EXTEND(SDNode *N);
286 SDValue visitZERO_EXTEND(SDNode *N);
287 SDValue visitANY_EXTEND(SDNode *N);
288 SDValue visitAssertZext(SDNode *N);
289 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
290 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
291 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
292 SDValue visitTRUNCATE(SDNode *N);
293 SDValue visitBITCAST(SDNode *N);
294 SDValue visitBUILD_PAIR(SDNode *N);
295 SDValue visitFADD(SDNode *N);
296 SDValue visitFSUB(SDNode *N);
297 SDValue visitFMUL(SDNode *N);
298 SDValue visitFMA(SDNode *N);
299 SDValue visitFDIV(SDNode *N);
300 SDValue visitFREM(SDNode *N);
301 SDValue visitFSQRT(SDNode *N);
302 SDValue visitFCOPYSIGN(SDNode *N);
303 SDValue visitSINT_TO_FP(SDNode *N);
304 SDValue visitUINT_TO_FP(SDNode *N);
305 SDValue visitFP_TO_SINT(SDNode *N);
306 SDValue visitFP_TO_UINT(SDNode *N);
307 SDValue visitFP_ROUND(SDNode *N);
308 SDValue visitFP_ROUND_INREG(SDNode *N);
309 SDValue visitFP_EXTEND(SDNode *N);
310 SDValue visitFNEG(SDNode *N);
311 SDValue visitFABS(SDNode *N);
312 SDValue visitFCEIL(SDNode *N);
313 SDValue visitFTRUNC(SDNode *N);
314 SDValue visitFFLOOR(SDNode *N);
315 SDValue visitFMINNUM(SDNode *N);
316 SDValue visitFMAXNUM(SDNode *N);
317 SDValue visitBRCOND(SDNode *N);
318 SDValue visitBR_CC(SDNode *N);
319 SDValue visitLOAD(SDNode *N);
321 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
322 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
324 SDValue visitSTORE(SDNode *N);
325 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
326 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
327 SDValue visitBUILD_VECTOR(SDNode *N);
328 SDValue visitCONCAT_VECTORS(SDNode *N);
329 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
330 SDValue visitVECTOR_SHUFFLE(SDNode *N);
331 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
332 SDValue visitINSERT_SUBVECTOR(SDNode *N);
333 SDValue visitMLOAD(SDNode *N);
334 SDValue visitMSTORE(SDNode *N);
335 SDValue visitMGATHER(SDNode *N);
336 SDValue visitMSCATTER(SDNode *N);
337 SDValue visitFP_TO_FP16(SDNode *N);
338 SDValue visitFP16_TO_FP(SDNode *N);
340 SDValue visitFADDForFMACombine(SDNode *N);
341 SDValue visitFSUBForFMACombine(SDNode *N);
342 SDValue visitFMULForFMADistributiveCombine(SDNode *N);
344 SDValue XformToShuffleWithZero(SDNode *N);
345 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
348 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
350 SDValue foldSelectOfConstants(SDNode *N);
351 SDValue foldBinOpIntoSelect(SDNode *BO);
352 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
353 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
354 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
355 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
356 SDValue N2, SDValue N3, ISD::CondCode CC,
357 bool NotExtCompare = false);
358 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
359 SDValue N2, SDValue N3, ISD::CondCode CC);
360 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
362 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
363 const SDLoc &DL, bool foldBooleans = true);
365 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
367 bool isOneUseSetCC(SDValue N) const;
369 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
371 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
372 SDValue CombineExtLoad(SDNode *N);
373 SDValue combineRepeatedFPDivisors(SDNode *N);
374 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
375 SDValue BuildSDIV(SDNode *N);
376 SDValue BuildSDIVPow2(SDNode *N);
377 SDValue BuildUDIV(SDNode *N);
378 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
379 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags);
380 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
381 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
382 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
383 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
384 SDNodeFlags Flags, bool Reciprocal);
385 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
386 SDNodeFlags Flags, bool Reciprocal);
387 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
388 bool DemandHighBits = true);
389 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
390 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
391 SDValue InnerPos, SDValue InnerNeg,
392 unsigned PosOpcode, unsigned NegOpcode,
394 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
395 SDValue MatchLoadCombine(SDNode *N);
396 SDValue ReduceLoadWidth(SDNode *N);
397 SDValue ReduceLoadOpStoreWidth(SDNode *N);
398 SDValue splitMergedValStore(StoreSDNode *ST);
399 SDValue TransformFPLoadStorePair(SDNode *N);
400 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
401 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
402 SDValue reduceBuildVecToShuffle(SDNode *N);
403 SDValue reduceBuildVecToTrunc(SDNode *N);
404 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
405 ArrayRef<int> VectorMask, SDValue VecIn1,
406 SDValue VecIn2, unsigned LeftIdx);
407 SDValue matchVSelectOpSizesWithSetCC(SDNode *N);
409 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
411 /// Walk up chain skipping non-aliasing memory nodes,
412 /// looking for aliasing nodes and adding them to the Aliases vector.
413 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
414 SmallVectorImpl<SDValue> &Aliases);
416 /// Return true if there is any possibility that the two addresses overlap.
417 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
419 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
420 /// chain (aliasing node.)
421 SDValue FindBetterChain(SDNode *N, SDValue Chain);
423 /// Try to replace a store and any possibly adjacent stores on
424 /// consecutive chains with better chains. Return true only if St is
427 /// Notice that other chains may still be replaced even if the function
429 bool findBetterNeighborChains(StoreSDNode *St);
431 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
432 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
434 /// Holds a pointer to an LSBaseSDNode as well as information on where it
435 /// is located in a sequence of memory operations connected by a chain.
437 MemOpLink(LSBaseSDNode *N, int64_t Offset)
438 : MemNode(N), OffsetFromBase(Offset) {}
439 // Ptr to the mem node.
440 LSBaseSDNode *MemNode;
441 // Offset from the base ptr.
442 int64_t OffsetFromBase;
445 /// This is a helper function for visitMUL to check the profitability
446 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
447 /// MulNode is the original multiply, AddNode is (add x, c1),
448 /// and ConstNode is c2.
449 bool isMulAddWithConstProfitable(SDNode *MulNode,
454 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
455 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
456 /// the type of the loaded value to be extended. LoadedVT returns the type
457 /// of the original loaded value. NarrowLoad returns whether the load would
458 /// need to be narrowed in order to match.
459 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
460 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
463 /// Helper function for MergeConsecutiveStores which merges the
464 /// component store chains.
465 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
468 /// This is a helper function for MergeConsecutiveStores. When the source
469 /// elements of the consecutive stores are all constants or all extracted
470 /// vector elements, try to merge them into one larger store.
471 /// \return True if a merged store was created.
472 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
473 EVT MemVT, unsigned NumStores,
474 bool IsConstantSrc, bool UseVector,
477 /// This is a helper function for MergeConsecutiveStores.
478 /// Stores that may be merged are placed in StoreNodes.
479 void getStoreMergeCandidates(StoreSDNode *St,
480 SmallVectorImpl<MemOpLink> &StoreNodes);
482 /// Helper function for MergeConsecutiveStores. Checks if
483 /// Candidate stores have indirect dependency through their
484 /// operands. \return True if safe to merge
485 bool checkMergeStoreCandidatesForDependencies(
486 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores);
488 /// Merge consecutive store operations into a wide store.
489 /// This optimization uses wide integers or vectors when possible.
490 /// \return number of stores that were merged into a merged store (the
491 /// affected nodes are stored as a prefix in \p StoreNodes).
492 bool MergeConsecutiveStores(StoreSDNode *N);
494 /// \brief Try to transform a truncation where C is a constant:
495 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
497 /// \p N needs to be a truncation and its first operand an AND. Other
498 /// requirements are checked by the function (e.g. that trunc is
499 /// single-use) and if missed an empty SDValue is returned.
500 SDValue distributeTruncateThroughAnd(SDNode *N);
503 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
504 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
505 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) {
506 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
508 MaximumLegalStoreInBits = 0;
509 for (MVT VT : MVT::all_valuetypes())
510 if (EVT(VT).isSimple() && VT != MVT::Other &&
511 TLI.isTypeLegal(EVT(VT)) &&
512 VT.getSizeInBits() >= MaximumLegalStoreInBits)
513 MaximumLegalStoreInBits = VT.getSizeInBits();
516 /// Runs the dag combiner on all nodes in the work list
517 void Run(CombineLevel AtLevel);
519 SelectionDAG &getDAG() const { return DAG; }
521 /// Returns a type large enough to hold any valid shift amount - before type
522 /// legalization these can be huge.
523 EVT getShiftAmountTy(EVT LHSTy) {
524 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
525 if (LHSTy.isVector())
527 auto &DL = DAG.getDataLayout();
528 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
529 : TLI.getPointerTy(DL);
532 /// This method returns true if we are running before type legalization or
533 /// if the specified VT is legal.
534 bool isTypeLegal(const EVT &VT) {
535 if (!LegalTypes) return true;
536 return TLI.isTypeLegal(VT);
539 /// Convenience wrapper around TargetLowering::getSetCCResultType
540 EVT getSetCCResultType(EVT VT) const {
541 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
548 /// This class is a DAGUpdateListener that removes any deleted
549 /// nodes from the worklist.
550 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
553 explicit WorklistRemover(DAGCombiner &dc)
554 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
556 void NodeDeleted(SDNode *N, SDNode *E) override {
557 DC.removeFromWorklist(N);
562 //===----------------------------------------------------------------------===//
563 // TargetLowering::DAGCombinerInfo implementation
564 //===----------------------------------------------------------------------===//
566 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
567 ((DAGCombiner*)DC)->AddToWorklist(N);
570 SDValue TargetLowering::DAGCombinerInfo::
571 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
572 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
575 SDValue TargetLowering::DAGCombinerInfo::
576 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
577 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
581 SDValue TargetLowering::DAGCombinerInfo::
582 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
583 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
586 void TargetLowering::DAGCombinerInfo::
587 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
588 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
591 //===----------------------------------------------------------------------===//
593 //===----------------------------------------------------------------------===//
595 void DAGCombiner::deleteAndRecombine(SDNode *N) {
596 removeFromWorklist(N);
598 // If the operands of this node are only used by the node, they will now be
599 // dead. Make sure to re-visit them and recursively delete dead nodes.
600 for (const SDValue &Op : N->ops())
601 // For an operand generating multiple values, one of the values may
602 // become dead allowing further simplification (e.g. split index
603 // arithmetic from an indexed load).
604 if (Op->hasOneUse() || Op->getNumValues() > 1)
605 AddToWorklist(Op.getNode());
610 /// Return 1 if we can compute the negated form of the specified expression for
611 /// the same cost as the expression itself, or 2 if we can compute the negated
612 /// form more cheaply than the expression itself.
613 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
614 const TargetLowering &TLI,
615 const TargetOptions *Options,
616 unsigned Depth = 0) {
617 // fneg is removable even if it has multiple uses.
618 if (Op.getOpcode() == ISD::FNEG) return 2;
620 // Don't allow anything with multiple uses.
621 if (!Op.hasOneUse()) return 0;
623 // Don't recurse exponentially.
624 if (Depth > 6) return 0;
626 switch (Op.getOpcode()) {
627 default: return false;
628 case ISD::ConstantFP: {
629 if (!LegalOperations)
632 // Don't invert constant FP values after legalization unless the target says
633 // the negated constant is legal.
634 EVT VT = Op.getValueType();
635 return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
636 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
639 // FIXME: determine better conditions for this xform.
640 if (!Options->UnsafeFPMath) return 0;
642 // After operation legalization, it might not be legal to create new FSUBs.
643 if (LegalOperations &&
644 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
647 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
648 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
651 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
652 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
655 // We can't turn -(A-B) into B-A when we honor signed zeros.
656 if (!Options->NoSignedZerosFPMath &&
657 !Op.getNode()->getFlags().hasNoSignedZeros())
660 // fold (fneg (fsub A, B)) -> (fsub B, A)
665 if (Options->HonorSignDependentRoundingFPMath()) return 0;
667 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
668 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
672 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
678 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
683 /// If isNegatibleForFree returns true, return the newly negated expression.
684 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
685 bool LegalOperations, unsigned Depth = 0) {
686 const TargetOptions &Options = DAG.getTarget().Options;
687 // fneg is removable even if it has multiple uses.
688 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
690 // Don't allow anything with multiple uses.
691 assert(Op.hasOneUse() && "Unknown reuse!");
693 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
695 const SDNodeFlags Flags = Op.getNode()->getFlags();
697 switch (Op.getOpcode()) {
698 default: llvm_unreachable("Unknown code");
699 case ISD::ConstantFP: {
700 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
702 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
705 // FIXME: determine better conditions for this xform.
706 assert(Options.UnsafeFPMath);
708 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
709 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
710 DAG.getTargetLoweringInfo(), &Options, Depth+1))
711 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
712 GetNegatedExpression(Op.getOperand(0), DAG,
713 LegalOperations, Depth+1),
714 Op.getOperand(1), Flags);
715 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
716 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
717 GetNegatedExpression(Op.getOperand(1), DAG,
718 LegalOperations, Depth+1),
719 Op.getOperand(0), Flags);
721 // fold (fneg (fsub 0, B)) -> B
722 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
724 return Op.getOperand(1);
726 // fold (fneg (fsub A, B)) -> (fsub B, A)
727 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
728 Op.getOperand(1), Op.getOperand(0), Flags);
732 assert(!Options.HonorSignDependentRoundingFPMath());
734 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
735 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
736 DAG.getTargetLoweringInfo(), &Options, Depth+1))
737 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
738 GetNegatedExpression(Op.getOperand(0), DAG,
739 LegalOperations, Depth+1),
740 Op.getOperand(1), Flags);
742 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
743 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
745 GetNegatedExpression(Op.getOperand(1), DAG,
746 LegalOperations, Depth+1), Flags);
750 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
751 GetNegatedExpression(Op.getOperand(0), DAG,
752 LegalOperations, Depth+1));
754 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
755 GetNegatedExpression(Op.getOperand(0), DAG,
756 LegalOperations, Depth+1),
761 // APInts must be the same size for most operations, this helper
762 // function zero extends the shorter of the pair so that they match.
763 // We provide an Offset so that we can create bitwidths that won't overflow.
764 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
765 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
766 LHS = LHS.zextOrSelf(Bits);
767 RHS = RHS.zextOrSelf(Bits);
770 // Return true if this node is a setcc, or is a select_cc
771 // that selects between the target values used for true and false, making it
772 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
773 // the appropriate nodes based on the type of node we are checking. This
774 // simplifies life a bit for the callers.
775 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
777 if (N.getOpcode() == ISD::SETCC) {
778 LHS = N.getOperand(0);
779 RHS = N.getOperand(1);
780 CC = N.getOperand(2);
784 if (N.getOpcode() != ISD::SELECT_CC ||
785 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
786 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
789 if (TLI.getBooleanContents(N.getValueType()) ==
790 TargetLowering::UndefinedBooleanContent)
793 LHS = N.getOperand(0);
794 RHS = N.getOperand(1);
795 CC = N.getOperand(4);
799 /// Return true if this is a SetCC-equivalent operation with only one use.
800 /// If this is true, it allows the users to invert the operation for free when
801 /// it is profitable to do so.
802 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
804 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
809 // \brief Returns the SDNode if it is a constant float BuildVector
810 // or constant float.
811 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
812 if (isa<ConstantFPSDNode>(N))
814 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
819 // Determines if it is a constant integer or a build vector of constant
820 // integers (and undefs).
821 // Do not permit build vector implicit truncation.
822 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
823 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
824 return !(Const->isOpaque() && NoOpaques);
825 if (N.getOpcode() != ISD::BUILD_VECTOR)
827 unsigned BitWidth = N.getScalarValueSizeInBits();
828 for (const SDValue &Op : N->op_values()) {
831 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
832 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
833 (Const->isOpaque() && NoOpaques))
839 // Determines if it is a constant null integer or a splatted vector of a
840 // constant null integer (with no undefs).
841 // Build vector implicit truncation is not an issue for null values.
842 static bool isNullConstantOrNullSplatConstant(SDValue N) {
843 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
844 return Splat->isNullValue();
848 // Determines if it is a constant integer of one or a splatted vector of a
849 // constant integer of one (with no undefs).
850 // Do not permit build vector implicit truncation.
851 static bool isOneConstantOrOneSplatConstant(SDValue N) {
852 unsigned BitWidth = N.getScalarValueSizeInBits();
853 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
854 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
858 // Determines if it is a constant integer of all ones or a splatted vector of a
859 // constant integer of all ones (with no undefs).
860 // Do not permit build vector implicit truncation.
861 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
862 unsigned BitWidth = N.getScalarValueSizeInBits();
863 if (ConstantSDNode *Splat = isConstOrConstSplat(N))
864 return Splat->isAllOnesValue() &&
865 Splat->getAPIntValue().getBitWidth() == BitWidth;
869 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
871 static bool isAnyConstantBuildVector(const SDNode *N) {
872 return ISD::isBuildVectorOfConstantSDNodes(N) ||
873 ISD::isBuildVectorOfConstantFPSDNodes(N);
876 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
878 EVT VT = N0.getValueType();
879 if (N0.getOpcode() == Opc) {
880 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
881 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
882 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
883 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
884 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
887 if (N0.hasOneUse()) {
888 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
890 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
891 if (!OpNode.getNode())
893 AddToWorklist(OpNode.getNode());
894 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
899 if (N1.getOpcode() == Opc) {
900 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
901 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
902 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
903 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
904 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
907 if (N1.hasOneUse()) {
908 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
910 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
911 if (!OpNode.getNode())
913 AddToWorklist(OpNode.getNode());
914 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
922 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
924 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
926 DEBUG(dbgs() << "\nReplacing.1 ";
928 dbgs() << "\nWith: ";
929 To[0].getNode()->dump(&DAG);
930 dbgs() << " and " << NumTo-1 << " other values\n");
931 for (unsigned i = 0, e = NumTo; i != e; ++i)
932 assert((!To[i].getNode() ||
933 N->getValueType(i) == To[i].getValueType()) &&
934 "Cannot combine value to value of different type!");
936 WorklistRemover DeadNodes(*this);
937 DAG.ReplaceAllUsesWith(N, To);
939 // Push the new nodes and any users onto the worklist
940 for (unsigned i = 0, e = NumTo; i != e; ++i) {
941 if (To[i].getNode()) {
942 AddToWorklist(To[i].getNode());
943 AddUsersToWorklist(To[i].getNode());
948 // Finally, if the node is now dead, remove it from the graph. The node
949 // may not be dead if the replacement process recursively simplified to
950 // something else needing this node.
952 deleteAndRecombine(N);
953 return SDValue(N, 0);
957 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
958 // Replace all uses. If any nodes become isomorphic to other nodes and
959 // are deleted, make sure to remove them from our worklist.
960 WorklistRemover DeadNodes(*this);
961 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
963 // Push the new node and any (possibly new) users onto the worklist.
964 AddToWorklist(TLO.New.getNode());
965 AddUsersToWorklist(TLO.New.getNode());
967 // Finally, if the node is now dead, remove it from the graph. The node
968 // may not be dead if the replacement process recursively simplified to
969 // something else needing this node.
970 if (TLO.Old.getNode()->use_empty())
971 deleteAndRecombine(TLO.Old.getNode());
974 /// Check the specified integer node value to see if it can be simplified or if
975 /// things it uses can be simplified by bit propagation. If so, return true.
976 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
977 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
979 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO))
983 AddToWorklist(Op.getNode());
985 // Replace the old value with the new one.
987 DEBUG(dbgs() << "\nReplacing.2 ";
988 TLO.Old.getNode()->dump(&DAG);
989 dbgs() << "\nWith: ";
990 TLO.New.getNode()->dump(&DAG);
993 CommitTargetLoweringOpt(TLO);
997 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
999 EVT VT = Load->getValueType(0);
1000 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
1002 DEBUG(dbgs() << "\nReplacing.9 ";
1004 dbgs() << "\nWith: ";
1005 Trunc.getNode()->dump(&DAG);
1007 WorklistRemover DeadNodes(*this);
1008 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
1009 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
1010 deleteAndRecombine(Load);
1011 AddToWorklist(Trunc.getNode());
1014 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
1017 if (ISD::isUNINDEXEDLoad(Op.getNode())) {
1018 LoadSDNode *LD = cast<LoadSDNode>(Op);
1019 EVT MemVT = LD->getMemoryVT();
1020 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1021 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1023 : LD->getExtensionType();
1025 return DAG.getExtLoad(ExtType, DL, PVT,
1026 LD->getChain(), LD->getBasePtr(),
1027 MemVT, LD->getMemOperand());
1030 unsigned Opc = Op.getOpcode();
1033 case ISD::AssertSext:
1034 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
1035 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
1037 case ISD::AssertZext:
1038 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
1039 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
1041 case ISD::Constant: {
1043 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1044 return DAG.getNode(ExtOpc, DL, PVT, Op);
1048 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
1050 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
1053 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
1054 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
1056 EVT OldVT = Op.getValueType();
1058 bool Replace = false;
1059 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1060 if (!NewOp.getNode())
1062 AddToWorklist(NewOp.getNode());
1065 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1066 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
1067 DAG.getValueType(OldVT));
1070 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1071 EVT OldVT = Op.getValueType();
1073 bool Replace = false;
1074 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1075 if (!NewOp.getNode())
1077 AddToWorklist(NewOp.getNode());
1080 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1081 return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
1084 /// Promote the specified integer binary operation if the target indicates it is
1085 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1086 /// i32 since i16 instructions are longer.
1087 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1088 if (!LegalOperations)
1091 EVT VT = Op.getValueType();
1092 if (VT.isVector() || !VT.isInteger())
1095 // If operation type is 'undesirable', e.g. i16 on x86, consider
1097 unsigned Opc = Op.getOpcode();
1098 if (TLI.isTypeDesirableForOp(Opc, VT))
1102 // Consult target whether it is a good idea to promote this operation and
1103 // what's the right type to promote it to.
1104 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1105 assert(PVT != VT && "Don't know what type to promote to!");
1107 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1109 bool Replace0 = false;
1110 SDValue N0 = Op.getOperand(0);
1111 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1113 bool Replace1 = false;
1114 SDValue N1 = Op.getOperand(1);
1115 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
1119 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
1121 // New replace instances of N0 and N1
1122 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
1123 NN0.getOpcode() != ISD::DELETED_NODE) {
1124 AddToWorklist(NN0.getNode());
1125 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1128 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
1129 NN1.getOpcode() != ISD::DELETED_NODE) {
1130 AddToWorklist(NN1.getNode());
1131 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1134 // Deal with Op being deleted.
1135 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1141 /// Promote the specified integer shift operation if the target indicates it is
1142 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1143 /// i32 since i16 instructions are longer.
1144 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1145 if (!LegalOperations)
1148 EVT VT = Op.getValueType();
1149 if (VT.isVector() || !VT.isInteger())
1152 // If operation type is 'undesirable', e.g. i16 on x86, consider
1154 unsigned Opc = Op.getOpcode();
1155 if (TLI.isTypeDesirableForOp(Opc, VT))
1159 // Consult target whether it is a good idea to promote this operation and
1160 // what's the right type to promote it to.
1161 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1162 assert(PVT != VT && "Don't know what type to promote to!");
1164 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
1166 bool Replace = false;
1167 SDValue N0 = Op.getOperand(0);
1168 SDValue N1 = Op.getOperand(1);
1169 if (Opc == ISD::SRA)
1170 N0 = SExtPromoteOperand(N0, PVT);
1171 else if (Opc == ISD::SRL)
1172 N0 = ZExtPromoteOperand(N0, PVT);
1174 N0 = PromoteOperand(N0, PVT, Replace);
1181 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
1183 AddToWorklist(N0.getNode());
1185 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1187 // Deal with Op being deleted.
1188 if (Op && Op.getOpcode() != ISD::DELETED_NODE)
1194 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1195 if (!LegalOperations)
1198 EVT VT = Op.getValueType();
1199 if (VT.isVector() || !VT.isInteger())
1202 // If operation type is 'undesirable', e.g. i16 on x86, consider
1204 unsigned Opc = Op.getOpcode();
1205 if (TLI.isTypeDesirableForOp(Opc, VT))
1209 // Consult target whether it is a good idea to promote this operation and
1210 // what's the right type to promote it to.
1211 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1212 assert(PVT != VT && "Don't know what type to promote to!");
1213 // fold (aext (aext x)) -> (aext x)
1214 // fold (aext (zext x)) -> (zext x)
1215 // fold (aext (sext x)) -> (sext x)
1216 DEBUG(dbgs() << "\nPromoting ";
1217 Op.getNode()->dump(&DAG));
1218 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1223 bool DAGCombiner::PromoteLoad(SDValue Op) {
1224 if (!LegalOperations)
1227 if (!ISD::isUNINDEXEDLoad(Op.getNode()))
1230 EVT VT = Op.getValueType();
1231 if (VT.isVector() || !VT.isInteger())
1234 // If operation type is 'undesirable', e.g. i16 on x86, consider
1236 unsigned Opc = Op.getOpcode();
1237 if (TLI.isTypeDesirableForOp(Opc, VT))
1241 // Consult target whether it is a good idea to promote this operation and
1242 // what's the right type to promote it to.
1243 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1244 assert(PVT != VT && "Don't know what type to promote to!");
1247 SDNode *N = Op.getNode();
1248 LoadSDNode *LD = cast<LoadSDNode>(N);
1249 EVT MemVT = LD->getMemoryVT();
1250 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1251 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1253 : LD->getExtensionType();
1254 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
1255 LD->getChain(), LD->getBasePtr(),
1256 MemVT, LD->getMemOperand());
1257 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
1259 DEBUG(dbgs() << "\nPromoting ";
1262 Result.getNode()->dump(&DAG);
1264 WorklistRemover DeadNodes(*this);
1265 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1266 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1267 deleteAndRecombine(N);
1268 AddToWorklist(Result.getNode());
1274 /// \brief Recursively delete a node which has no uses and any operands for
1275 /// which it is the only use.
1277 /// Note that this both deletes the nodes and removes them from the worklist.
1278 /// It also adds any nodes who have had a user deleted to the worklist as they
1279 /// may now have only one use and subject to other combines.
1280 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1281 if (!N->use_empty())
1284 SmallSetVector<SDNode *, 16> Nodes;
1287 N = Nodes.pop_back_val();
1291 if (N->use_empty()) {
1292 for (const SDValue &ChildN : N->op_values())
1293 Nodes.insert(ChildN.getNode());
1295 removeFromWorklist(N);
1300 } while (!Nodes.empty());
1304 //===----------------------------------------------------------------------===//
1305 // Main DAG Combiner implementation
1306 //===----------------------------------------------------------------------===//
1308 void DAGCombiner::Run(CombineLevel AtLevel) {
1309 // set the instance variables, so that the various visit routines may use it.
1311 LegalOperations = Level >= AfterLegalizeVectorOps;
1312 LegalTypes = Level >= AfterLegalizeTypes;
1314 // Add all the dag nodes to the worklist.
1315 for (SDNode &Node : DAG.allnodes())
1316 AddToWorklist(&Node);
1318 // Create a dummy node (which is not added to allnodes), that adds a reference
1319 // to the root node, preventing it from being deleted, and tracking any
1320 // changes of the root.
1321 HandleSDNode Dummy(DAG.getRoot());
1323 // While the worklist isn't empty, find a node and try to combine it.
1324 while (!WorklistMap.empty()) {
1326 // The Worklist holds the SDNodes in order, but it may contain null entries.
1328 N = Worklist.pop_back_val();
1331 bool GoodWorklistEntry = WorklistMap.erase(N);
1332 (void)GoodWorklistEntry;
1333 assert(GoodWorklistEntry &&
1334 "Found a worklist entry without a corresponding map entry!");
1336 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1337 // N is deleted from the DAG, since they too may now be dead or may have a
1338 // reduced number of uses, allowing other xforms.
1339 if (recursivelyDeleteUnusedNodes(N))
1342 WorklistRemover DeadNodes(*this);
1344 // If this combine is running after legalizing the DAG, re-legalize any
1345 // nodes pulled off the worklist.
1346 if (Level == AfterLegalizeDAG) {
1347 SmallSetVector<SDNode *, 16> UpdatedNodes;
1348 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1350 for (SDNode *LN : UpdatedNodes) {
1352 AddUsersToWorklist(LN);
1358 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1360 // Add any operands of the new node which have not yet been combined to the
1361 // worklist as well. Because the worklist uniques things already, this
1362 // won't repeatedly process the same operand.
1363 CombinedNodes.insert(N);
1364 for (const SDValue &ChildN : N->op_values())
1365 if (!CombinedNodes.count(ChildN.getNode()))
1366 AddToWorklist(ChildN.getNode());
1368 SDValue RV = combine(N);
1375 // If we get back the same node we passed in, rather than a new node or
1376 // zero, we know that the node must have defined multiple values and
1377 // CombineTo was used. Since CombineTo takes care of the worklist
1378 // mechanics for us, we have no work to do in this case.
1379 if (RV.getNode() == N)
1382 assert(N->getOpcode() != ISD::DELETED_NODE &&
1383 RV.getOpcode() != ISD::DELETED_NODE &&
1384 "Node was deleted but visit returned new node!");
1386 DEBUG(dbgs() << " ... into: ";
1387 RV.getNode()->dump(&DAG));
1389 if (N->getNumValues() == RV.getNode()->getNumValues())
1390 DAG.ReplaceAllUsesWith(N, RV.getNode());
1392 assert(N->getValueType(0) == RV.getValueType() &&
1393 N->getNumValues() == 1 && "Type mismatch");
1394 DAG.ReplaceAllUsesWith(N, &RV);
1397 // Push the new node and any users onto the worklist
1398 AddToWorklist(RV.getNode());
1399 AddUsersToWorklist(RV.getNode());
1401 // Finally, if the node is now dead, remove it from the graph. The node
1402 // may not be dead if the replacement process recursively simplified to
1403 // something else needing this node. This will also take care of adding any
1404 // operands which have lost a user to the worklist.
1405 recursivelyDeleteUnusedNodes(N);
1408 // If the root changed (e.g. it was a dead load, update the root).
1409 DAG.setRoot(Dummy.getValue());
1410 DAG.RemoveDeadNodes();
1413 SDValue DAGCombiner::visit(SDNode *N) {
1414 switch (N->getOpcode()) {
1416 case ISD::TokenFactor: return visitTokenFactor(N);
1417 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1418 case ISD::ADD: return visitADD(N);
1419 case ISD::SUB: return visitSUB(N);
1420 case ISD::ADDC: return visitADDC(N);
1421 case ISD::UADDO: return visitUADDO(N);
1422 case ISD::SUBC: return visitSUBC(N);
1423 case ISD::USUBO: return visitUSUBO(N);
1424 case ISD::ADDE: return visitADDE(N);
1425 case ISD::ADDCARRY: return visitADDCARRY(N);
1426 case ISD::SUBE: return visitSUBE(N);
1427 case ISD::SUBCARRY: return visitSUBCARRY(N);
1428 case ISD::MUL: return visitMUL(N);
1429 case ISD::SDIV: return visitSDIV(N);
1430 case ISD::UDIV: return visitUDIV(N);
1432 case ISD::UREM: return visitREM(N);
1433 case ISD::MULHU: return visitMULHU(N);
1434 case ISD::MULHS: return visitMULHS(N);
1435 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1436 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1437 case ISD::SMULO: return visitSMULO(N);
1438 case ISD::UMULO: return visitUMULO(N);
1442 case ISD::UMAX: return visitIMINMAX(N);
1443 case ISD::AND: return visitAND(N);
1444 case ISD::OR: return visitOR(N);
1445 case ISD::XOR: return visitXOR(N);
1446 case ISD::SHL: return visitSHL(N);
1447 case ISD::SRA: return visitSRA(N);
1448 case ISD::SRL: return visitSRL(N);
1450 case ISD::ROTL: return visitRotate(N);
1451 case ISD::ABS: return visitABS(N);
1452 case ISD::BSWAP: return visitBSWAP(N);
1453 case ISD::BITREVERSE: return visitBITREVERSE(N);
1454 case ISD::CTLZ: return visitCTLZ(N);
1455 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1456 case ISD::CTTZ: return visitCTTZ(N);
1457 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1458 case ISD::CTPOP: return visitCTPOP(N);
1459 case ISD::SELECT: return visitSELECT(N);
1460 case ISD::VSELECT: return visitVSELECT(N);
1461 case ISD::SELECT_CC: return visitSELECT_CC(N);
1462 case ISD::SETCC: return visitSETCC(N);
1463 case ISD::SETCCE: return visitSETCCE(N);
1464 case ISD::SETCCCARRY: return visitSETCCCARRY(N);
1465 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1466 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1467 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1468 case ISD::AssertZext: return visitAssertZext(N);
1469 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1470 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1471 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
1472 case ISD::TRUNCATE: return visitTRUNCATE(N);
1473 case ISD::BITCAST: return visitBITCAST(N);
1474 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1475 case ISD::FADD: return visitFADD(N);
1476 case ISD::FSUB: return visitFSUB(N);
1477 case ISD::FMUL: return visitFMUL(N);
1478 case ISD::FMA: return visitFMA(N);
1479 case ISD::FDIV: return visitFDIV(N);
1480 case ISD::FREM: return visitFREM(N);
1481 case ISD::FSQRT: return visitFSQRT(N);
1482 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1483 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1484 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1485 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1486 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1487 case ISD::FP_ROUND: return visitFP_ROUND(N);
1488 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1489 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1490 case ISD::FNEG: return visitFNEG(N);
1491 case ISD::FABS: return visitFABS(N);
1492 case ISD::FFLOOR: return visitFFLOOR(N);
1493 case ISD::FMINNUM: return visitFMINNUM(N);
1494 case ISD::FMAXNUM: return visitFMAXNUM(N);
1495 case ISD::FCEIL: return visitFCEIL(N);
1496 case ISD::FTRUNC: return visitFTRUNC(N);
1497 case ISD::BRCOND: return visitBRCOND(N);
1498 case ISD::BR_CC: return visitBR_CC(N);
1499 case ISD::LOAD: return visitLOAD(N);
1500 case ISD::STORE: return visitSTORE(N);
1501 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1502 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1503 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1504 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1505 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1506 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1507 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1508 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1509 case ISD::MGATHER: return visitMGATHER(N);
1510 case ISD::MLOAD: return visitMLOAD(N);
1511 case ISD::MSCATTER: return visitMSCATTER(N);
1512 case ISD::MSTORE: return visitMSTORE(N);
1513 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1514 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1519 SDValue DAGCombiner::combine(SDNode *N) {
1520 SDValue RV = visit(N);
1522 // If nothing happened, try a target-specific DAG combine.
1523 if (!RV.getNode()) {
1524 assert(N->getOpcode() != ISD::DELETED_NODE &&
1525 "Node was deleted but visit returned NULL!");
1527 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1528 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1530 // Expose the DAG combiner to the target combiner impls.
1531 TargetLowering::DAGCombinerInfo
1532 DagCombineInfo(DAG, Level, false, this);
1534 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1538 // If nothing happened still, try promoting the operation.
1539 if (!RV.getNode()) {
1540 switch (N->getOpcode()) {
1548 RV = PromoteIntBinOp(SDValue(N, 0));
1553 RV = PromoteIntShiftOp(SDValue(N, 0));
1555 case ISD::SIGN_EXTEND:
1556 case ISD::ZERO_EXTEND:
1557 case ISD::ANY_EXTEND:
1558 RV = PromoteExtend(SDValue(N, 0));
1561 if (PromoteLoad(SDValue(N, 0)))
1567 // If N is a commutative binary node, try commuting it to enable more
1569 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
1570 N->getNumValues() == 1) {
1571 SDValue N0 = N->getOperand(0);
1572 SDValue N1 = N->getOperand(1);
1574 // Constant operands are canonicalized to RHS.
1575 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1576 SDValue Ops[] = {N1, N0};
1577 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1580 return SDValue(CSENode, 0);
1587 /// Given a node, return its input chain if it has one, otherwise return a null
1589 static SDValue getInputChainForNode(SDNode *N) {
1590 if (unsigned NumOps = N->getNumOperands()) {
1591 if (N->getOperand(0).getValueType() == MVT::Other)
1592 return N->getOperand(0);
1593 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1594 return N->getOperand(NumOps-1);
1595 for (unsigned i = 1; i < NumOps-1; ++i)
1596 if (N->getOperand(i).getValueType() == MVT::Other)
1597 return N->getOperand(i);
1602 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1603 // If N has two operands, where one has an input chain equal to the other,
1604 // the 'other' chain is redundant.
1605 if (N->getNumOperands() == 2) {
1606 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1607 return N->getOperand(0);
1608 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1609 return N->getOperand(1);
1612 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1613 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1614 SmallPtrSet<SDNode*, 16> SeenOps;
1615 bool Changed = false; // If we should replace this token factor.
1617 // Start out with this token factor.
1620 // Iterate through token factors. The TFs grows when new token factors are
1622 for (unsigned i = 0; i < TFs.size(); ++i) {
1623 SDNode *TF = TFs[i];
1625 // Check each of the operands.
1626 for (const SDValue &Op : TF->op_values()) {
1628 switch (Op.getOpcode()) {
1629 case ISD::EntryToken:
1630 // Entry tokens don't need to be added to the list. They are
1635 case ISD::TokenFactor:
1636 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
1637 // Queue up for processing.
1638 TFs.push_back(Op.getNode());
1639 // Clean up in case the token factor is removed.
1640 AddToWorklist(Op.getNode());
1647 // Only add if it isn't already in the list.
1648 if (SeenOps.insert(Op.getNode()).second)
1657 // Remove Nodes that are chained to another node in the list. Do so
1658 // by walking up chains breath-first stopping when we've seen
1659 // another operand. In general we must climb to the EntryNode, but we can exit
1660 // early if we find all remaining work is associated with just one operand as
1661 // no further pruning is possible.
1663 // List of nodes to search through and original Ops from which they originate.
1664 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
1665 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
1666 SmallPtrSet<SDNode *, 16> SeenChains;
1667 bool DidPruneOps = false;
1669 unsigned NumLeftToConsider = 0;
1670 for (const SDValue &Op : Ops) {
1671 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
1672 OpWorkCount.push_back(1);
1675 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
1676 // If this is an Op, we can remove the op from the list. Remark any
1677 // search associated with it as from the current OpNumber.
1678 if (SeenOps.count(Op) != 0) {
1681 unsigned OrigOpNumber = 0;
1682 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
1684 assert((OrigOpNumber != Ops.size()) &&
1685 "expected to find TokenFactor Operand");
1686 // Re-mark worklist from OrigOpNumber to OpNumber
1687 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
1688 if (Worklist[i].second == OrigOpNumber) {
1689 Worklist[i].second = OpNumber;
1692 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
1693 OpWorkCount[OrigOpNumber] = 0;
1694 NumLeftToConsider--;
1696 // Add if it's a new chain
1697 if (SeenChains.insert(Op).second) {
1698 OpWorkCount[OpNumber]++;
1699 Worklist.push_back(std::make_pair(Op, OpNumber));
1703 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
1704 // We need at least be consider at least 2 Ops to prune.
1705 if (NumLeftToConsider <= 1)
1707 auto CurNode = Worklist[i].first;
1708 auto CurOpNumber = Worklist[i].second;
1709 assert((OpWorkCount[CurOpNumber] > 0) &&
1710 "Node should not appear in worklist");
1711 switch (CurNode->getOpcode()) {
1712 case ISD::EntryToken:
1713 // Hitting EntryToken is the only way for the search to terminate without
1715 // another operand's search. Prevent us from marking this operand
1717 NumLeftToConsider++;
1719 case ISD::TokenFactor:
1720 for (const SDValue &Op : CurNode->op_values())
1721 AddToWorklist(i, Op.getNode(), CurOpNumber);
1723 case ISD::CopyFromReg:
1724 case ISD::CopyToReg:
1725 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
1728 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
1729 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
1732 OpWorkCount[CurOpNumber]--;
1733 if (OpWorkCount[CurOpNumber] == 0)
1734 NumLeftToConsider--;
1737 // If we've changed things around then replace token factor.
1741 // The entry token is the only possible outcome.
1742 Result = DAG.getEntryNode();
1745 SmallVector<SDValue, 8> PrunedOps;
1747 for (const SDValue &Op : Ops) {
1748 if (SeenChains.count(Op.getNode()) == 0)
1749 PrunedOps.push_back(Op);
1751 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
1753 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1761 /// MERGE_VALUES can always be eliminated.
1762 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1763 WorklistRemover DeadNodes(*this);
1764 // Replacing results may cause a different MERGE_VALUES to suddenly
1765 // be CSE'd with N, and carry its uses with it. Iterate until no
1766 // uses remain, to ensure that the node can be safely deleted.
1767 // First add the users of this node to the work list so that they
1768 // can be tried again once they have new operands.
1769 AddUsersToWorklist(N);
1771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1773 } while (!N->use_empty());
1774 deleteAndRecombine(N);
1775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1778 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
1779 /// ConstantSDNode pointer else nullptr.
1780 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1781 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1782 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1785 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
1786 auto BinOpcode = BO->getOpcode();
1787 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
1788 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
1789 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
1790 BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
1791 BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
1792 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
1793 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
1794 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
1795 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
1796 "Unexpected binary operator");
1798 // Bail out if any constants are opaque because we can't constant fold those.
1799 SDValue C1 = BO->getOperand(1);
1800 if (!isConstantOrConstantVector(C1, true) &&
1801 !isConstantFPBuildVectorOrConstantFP(C1))
1804 // Don't do this unless the old select is going away. We want to eliminate the
1805 // binary operator, not replace a binop with a select.
1806 // TODO: Handle ISD::SELECT_CC.
1807 SDValue Sel = BO->getOperand(0);
1808 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
1811 SDValue CT = Sel.getOperand(1);
1812 if (!isConstantOrConstantVector(CT, true) &&
1813 !isConstantFPBuildVectorOrConstantFP(CT))
1816 SDValue CF = Sel.getOperand(2);
1817 if (!isConstantOrConstantVector(CF, true) &&
1818 !isConstantFPBuildVectorOrConstantFP(CF))
1821 // We have a select-of-constants followed by a binary operator with a
1822 // constant. Eliminate the binop by pulling the constant math into the select.
1823 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
1824 EVT VT = Sel.getValueType();
1826 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
1827 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
1828 isConstantFPBuildVectorOrConstantFP(NewCT)) &&
1829 "Failed to constant fold a binop with constant operands");
1831 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
1832 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
1833 isConstantFPBuildVectorOrConstantFP(NewCF)) &&
1834 "Failed to constant fold a binop with constant operands");
1836 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
1839 SDValue DAGCombiner::visitADD(SDNode *N) {
1840 SDValue N0 = N->getOperand(0);
1841 SDValue N1 = N->getOperand(1);
1842 EVT VT = N0.getValueType();
1846 if (VT.isVector()) {
1847 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1850 // fold (add x, 0) -> x, vector edition
1851 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1853 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1857 // fold (add x, undef) -> undef
1864 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
1865 // canonicalize constant to RHS
1866 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
1867 return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
1868 // fold (add c1, c2) -> c1+c2
1869 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
1873 // fold (add x, 0) -> x
1874 if (isNullConstant(N1))
1877 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
1878 // fold ((c1-A)+c2) -> (c1+c2)-A
1879 if (N0.getOpcode() == ISD::SUB &&
1880 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
1881 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic.
1882 return DAG.getNode(ISD::SUB, DL, VT,
1883 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
1887 // add (sext i1 X), 1 -> zext (not i1 X)
1888 // We don't transform this pattern:
1889 // add (zext i1 X), -1 -> sext (not i1 X)
1890 // because most (?) targets generate better code for the zext form.
1891 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
1892 isOneConstantOrOneSplatConstant(N1)) {
1893 SDValue X = N0.getOperand(0);
1894 if ((!LegalOperations ||
1895 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
1896 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
1897 X.getScalarValueSizeInBits() == 1) {
1898 SDValue Not = DAG.getNOT(DL, X, X.getValueType());
1899 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
1904 if (SDValue NewSel = foldBinOpIntoSelect(N))
1908 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
1911 // fold ((0-A) + B) -> B-A
1912 if (N0.getOpcode() == ISD::SUB &&
1913 isNullConstantOrNullSplatConstant(N0.getOperand(0)))
1914 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
1916 // fold (A + (0-B)) -> A-B
1917 if (N1.getOpcode() == ISD::SUB &&
1918 isNullConstantOrNullSplatConstant(N1.getOperand(0)))
1919 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
1921 // fold (A+(B-A)) -> B
1922 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1923 return N1.getOperand(0);
1925 // fold ((B-A)+A) -> B
1926 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1927 return N0.getOperand(0);
1929 // fold (A+(B-(A+C))) to (B-C)
1930 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1931 N0 == N1.getOperand(1).getOperand(0))
1932 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1933 N1.getOperand(1).getOperand(1));
1935 // fold (A+(B-(C+A))) to (B-C)
1936 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1937 N0 == N1.getOperand(1).getOperand(1))
1938 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
1939 N1.getOperand(1).getOperand(0));
1941 // fold (A+((B-A)+or-C)) to (B+or-C)
1942 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1943 N1.getOperand(0).getOpcode() == ISD::SUB &&
1944 N0 == N1.getOperand(0).getOperand(1))
1945 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
1948 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1949 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1950 SDValue N00 = N0.getOperand(0);
1951 SDValue N01 = N0.getOperand(1);
1952 SDValue N10 = N1.getOperand(0);
1953 SDValue N11 = N1.getOperand(1);
1955 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
1956 return DAG.getNode(ISD::SUB, DL, VT,
1957 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1958 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1961 if (SimplifyDemandedBits(SDValue(N, 0)))
1962 return SDValue(N, 0);
1964 // fold (a+b) -> (a|b) iff a and b share no bits.
1965 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
1966 DAG.haveNoCommonBitsSet(N0, N1))
1967 return DAG.getNode(ISD::OR, DL, VT, N0, N1);
1969 if (SDValue Combined = visitADDLike(N0, N1, N))
1972 if (SDValue Combined = visitADDLike(N1, N0, N))
1978 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
1979 bool Masked = false;
1981 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
1983 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
1984 V = V.getOperand(0);
1988 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
1990 V = V.getOperand(0);
1997 // If this is not a carry, return.
1998 if (V.getResNo() != 1)
2001 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
2002 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
2005 // If the result is masked, then no matter what kind of bool it is we can
2006 // return. If it isn't, then we need to make sure the bool type is either 0 or
2007 // 1 and not other values.
2009 TLI.getBooleanContents(V.getValueType()) ==
2010 TargetLoweringBase::ZeroOrOneBooleanContent)
2016 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
2017 EVT VT = N0.getValueType();
2018 SDLoc DL(LocReference);
2020 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
2021 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
2022 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
2023 return DAG.getNode(ISD::SUB, DL, VT, N0,
2024 DAG.getNode(ISD::SHL, DL, VT,
2025 N1.getOperand(0).getOperand(1),
2028 if (N1.getOpcode() == ISD::AND) {
2029 SDValue AndOp0 = N1.getOperand(0);
2030 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
2031 unsigned DestBits = VT.getScalarSizeInBits();
2033 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
2034 // and similar xforms where the inner op is either ~0 or 0.
2035 if (NumSignBits == DestBits &&
2036 isOneConstantOrOneSplatConstant(N1->getOperand(1)))
2037 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
2040 // add (sext i1), X -> sub X, (zext i1)
2041 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
2042 N0.getOperand(0).getValueType() == MVT::i1 &&
2043 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
2044 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
2045 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
2048 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
2049 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2050 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2051 if (TN->getVT() == MVT::i1) {
2052 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2053 DAG.getConstant(1, DL, VT));
2054 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
2058 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2059 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)))
2060 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
2061 N0, N1.getOperand(0), N1.getOperand(2));
2063 // (add X, Carry) -> (addcarry X, 0, Carry)
2064 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2065 if (SDValue Carry = getAsCarry(TLI, N1))
2066 return DAG.getNode(ISD::ADDCARRY, DL,
2067 DAG.getVTList(VT, Carry.getValueType()), N0,
2068 DAG.getConstant(0, DL, VT), Carry);
2073 SDValue DAGCombiner::visitADDC(SDNode *N) {
2074 SDValue N0 = N->getOperand(0);
2075 SDValue N1 = N->getOperand(1);
2076 EVT VT = N0.getValueType();
2079 // If the flag result is dead, turn this into an ADD.
2080 if (!N->hasAnyUseOfValue(1))
2081 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2082 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2084 // canonicalize constant to RHS.
2085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2088 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
2090 // fold (addc x, 0) -> x + no carry out
2091 if (isNullConstant(N1))
2092 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
2095 // If it cannot overflow, transform into an add.
2096 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2097 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2098 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2103 SDValue DAGCombiner::visitUADDO(SDNode *N) {
2104 SDValue N0 = N->getOperand(0);
2105 SDValue N1 = N->getOperand(1);
2106 EVT VT = N0.getValueType();
2110 EVT CarryVT = N->getValueType(1);
2113 // If the flag result is dead, turn this into an ADD.
2114 if (!N->hasAnyUseOfValue(1))
2115 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2116 DAG.getUNDEF(CarryVT));
2118 // canonicalize constant to RHS.
2119 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2120 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2122 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
2124 // fold (uaddo x, 0) -> x + no carry out
2125 if (isNullConstant(N1))
2126 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2128 // If it cannot overflow, transform into an add.
2129 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
2130 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
2131 DAG.getConstant(0, DL, CarryVT));
2133 if (SDValue Combined = visitUADDOLike(N0, N1, N))
2136 if (SDValue Combined = visitUADDOLike(N1, N0, N))
2142 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
2143 auto VT = N0.getValueType();
2145 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
2146 // If Y + 1 cannot overflow.
2147 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
2148 SDValue Y = N1.getOperand(0);
2149 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
2150 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
2151 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
2155 // (uaddo X, Carry) -> (addcarry X, 0, Carry)
2156 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
2157 if (SDValue Carry = getAsCarry(TLI, N1))
2158 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2159 DAG.getConstant(0, SDLoc(N), VT), Carry);
2164 SDValue DAGCombiner::visitADDE(SDNode *N) {
2165 SDValue N0 = N->getOperand(0);
2166 SDValue N1 = N->getOperand(1);
2167 SDValue CarryIn = N->getOperand(2);
2169 // canonicalize constant to RHS
2170 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2171 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2173 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
2176 // fold (adde x, y, false) -> (addc x, y)
2177 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2178 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
2183 SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
2184 SDValue N0 = N->getOperand(0);
2185 SDValue N1 = N->getOperand(1);
2186 SDValue CarryIn = N->getOperand(2);
2189 // canonicalize constant to RHS
2190 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2191 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2193 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
2195 // fold (addcarry x, y, false) -> (uaddo x, y)
2196 if (isNullConstant(CarryIn))
2197 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
2199 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
2200 if (isNullConstant(N0) && isNullConstant(N1)) {
2201 EVT VT = N0.getValueType();
2202 EVT CarryVT = CarryIn.getValueType();
2203 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
2204 AddToWorklist(CarryExt.getNode());
2205 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
2206 DAG.getConstant(1, DL, VT)),
2207 DAG.getConstant(0, DL, CarryVT));
2210 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
2213 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
2219 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
2221 // Iff the flag result is dead:
2222 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
2223 if ((N0.getOpcode() == ISD::ADD ||
2224 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) &&
2225 isNullConstant(N1) && !N->hasAnyUseOfValue(1))
2226 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
2227 N0.getOperand(0), N0.getOperand(1), CarryIn);
2230 * When one of the addcarry argument is itself a carry, we may be facing
2231 * a diamond carry propagation. In which case we try to transform the DAG
2232 * to ensure linear carry propagation if that is possible.
2234 * We are trying to get:
2235 * (addcarry X, 0, (addcarry A, B, Z):Carry)
2237 if (auto Y = getAsCarry(TLI, N1)) {
2243 * | (addcarry *, 0, Z)
2247 * (addcarry X, *, *)
2249 if (Y.getOpcode() == ISD::UADDO &&
2250 CarryIn.getResNo() == 1 &&
2251 CarryIn.getOpcode() == ISD::ADDCARRY &&
2252 isNullConstant(CarryIn.getOperand(1)) &&
2253 CarryIn.getOperand(0) == Y.getValue(0)) {
2254 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(),
2255 Y.getOperand(0), Y.getOperand(1),
2256 CarryIn.getOperand(2));
2257 AddToWorklist(NewY.getNode());
2258 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
2259 DAG.getConstant(0, SDLoc(N), N0.getValueType()),
2267 // Since it may not be valid to emit a fold to zero for vector initializers
2268 // check if we can before folding.
2269 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
2270 SelectionDAG &DAG, bool LegalOperations,
2273 return DAG.getConstant(0, DL, VT);
2274 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
2275 return DAG.getConstant(0, DL, VT);
2279 SDValue DAGCombiner::visitSUB(SDNode *N) {
2280 SDValue N0 = N->getOperand(0);
2281 SDValue N1 = N->getOperand(1);
2282 EVT VT = N0.getValueType();
2286 if (VT.isVector()) {
2287 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2290 // fold (sub x, 0) -> x, vector edition
2291 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2295 // fold (sub x, x) -> 0
2296 // FIXME: Refactor this and xor and other similar operations together.
2298 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
2299 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2300 DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
2301 // fold (sub c1, c2) -> c1-c2
2302 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
2306 if (SDValue NewSel = foldBinOpIntoSelect(N))
2309 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2311 // fold (sub x, c) -> (add x, -c)
2313 return DAG.getNode(ISD::ADD, DL, VT, N0,
2314 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
2317 if (isNullConstantOrNullSplatConstant(N0)) {
2318 unsigned BitWidth = VT.getScalarSizeInBits();
2319 // Right-shifting everything out but the sign bit followed by negation is
2320 // the same as flipping arithmetic/logical shift type without the negation:
2321 // -(X >>u 31) -> (X >>s 31)
2322 // -(X >>s 31) -> (X >>u 31)
2323 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
2324 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
2325 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
2326 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
2327 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
2328 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
2332 // 0 - X --> 0 if the sub is NUW.
2333 if (N->getFlags().hasNoUnsignedWrap())
2336 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
2337 // N1 is either 0 or the minimum signed value. If the sub is NSW, then
2338 // N1 must be 0 because negating the minimum signed value is undefined.
2339 if (N->getFlags().hasNoSignedWrap())
2342 // 0 - X --> X if X is 0 or the minimum signed value.
2347 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
2348 if (isAllOnesConstantOrAllOnesSplatConstant(N0))
2349 return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
2351 // fold A-(A-B) -> B
2352 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
2353 return N1.getOperand(1);
2355 // fold (A+B)-A -> B
2356 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
2357 return N0.getOperand(1);
2359 // fold (A+B)-B -> A
2360 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
2361 return N0.getOperand(0);
2363 // fold C2-(A+C1) -> (C2-C1)-A
2364 if (N1.getOpcode() == ISD::ADD) {
2365 SDValue N11 = N1.getOperand(1);
2366 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
2367 isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
2368 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
2369 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
2373 // fold ((A+(B+or-C))-B) -> A+or-C
2374 if (N0.getOpcode() == ISD::ADD &&
2375 (N0.getOperand(1).getOpcode() == ISD::SUB ||
2376 N0.getOperand(1).getOpcode() == ISD::ADD) &&
2377 N0.getOperand(1).getOperand(0) == N1)
2378 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
2379 N0.getOperand(1).getOperand(1));
2381 // fold ((A+(C+B))-B) -> A+C
2382 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
2383 N0.getOperand(1).getOperand(1) == N1)
2384 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
2385 N0.getOperand(1).getOperand(0));
2387 // fold ((A-(B-C))-C) -> A-B
2388 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
2389 N0.getOperand(1).getOperand(1) == N1)
2390 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
2391 N0.getOperand(1).getOperand(0));
2393 // If either operand of a sub is undef, the result is undef
2399 // If the relocation model supports it, consider symbol offsets.
2400 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
2401 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
2402 // fold (sub Sym, c) -> Sym-c
2403 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
2404 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
2406 (uint64_t)N1C->getSExtValue());
2407 // fold (sub Sym+c1, Sym+c2) -> c1-c2
2408 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
2409 if (GA->getGlobal() == GB->getGlobal())
2410 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
2414 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
2415 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
2416 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
2417 if (TN->getVT() == MVT::i1) {
2418 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
2419 DAG.getConstant(1, DL, VT));
2420 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
2427 SDValue DAGCombiner::visitSUBC(SDNode *N) {
2428 SDValue N0 = N->getOperand(0);
2429 SDValue N1 = N->getOperand(1);
2430 EVT VT = N0.getValueType();
2433 // If the flag result is dead, turn this into an SUB.
2434 if (!N->hasAnyUseOfValue(1))
2435 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2436 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2438 // fold (subc x, x) -> 0 + no borrow
2440 return CombineTo(N, DAG.getConstant(0, DL, VT),
2441 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2443 // fold (subc x, 0) -> x + no borrow
2444 if (isNullConstant(N1))
2445 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2447 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2448 if (isAllOnesConstant(N0))
2449 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2450 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2455 SDValue DAGCombiner::visitUSUBO(SDNode *N) {
2456 SDValue N0 = N->getOperand(0);
2457 SDValue N1 = N->getOperand(1);
2458 EVT VT = N0.getValueType();
2462 EVT CarryVT = N->getValueType(1);
2465 // If the flag result is dead, turn this into an SUB.
2466 if (!N->hasAnyUseOfValue(1))
2467 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2468 DAG.getUNDEF(CarryVT));
2470 // fold (usubo x, x) -> 0 + no borrow
2472 return CombineTo(N, DAG.getConstant(0, DL, VT),
2473 DAG.getConstant(0, DL, CarryVT));
2475 // fold (usubo x, 0) -> x + no borrow
2476 if (isNullConstant(N1))
2477 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
2479 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2480 if (isAllOnesConstant(N0))
2481 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2482 DAG.getConstant(0, DL, CarryVT));
2487 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2488 SDValue N0 = N->getOperand(0);
2489 SDValue N1 = N->getOperand(1);
2490 SDValue CarryIn = N->getOperand(2);
2492 // fold (sube x, y, false) -> (subc x, y)
2493 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2494 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2499 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
2500 SDValue N0 = N->getOperand(0);
2501 SDValue N1 = N->getOperand(1);
2502 SDValue CarryIn = N->getOperand(2);
2504 // fold (subcarry x, y, false) -> (usubo x, y)
2505 if (isNullConstant(CarryIn))
2506 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
2511 SDValue DAGCombiner::visitMUL(SDNode *N) {
2512 SDValue N0 = N->getOperand(0);
2513 SDValue N1 = N->getOperand(1);
2514 EVT VT = N0.getValueType();
2516 // fold (mul x, undef) -> 0
2517 if (N0.isUndef() || N1.isUndef())
2518 return DAG.getConstant(0, SDLoc(N), VT);
2520 bool N0IsConst = false;
2521 bool N1IsConst = false;
2522 bool N1IsOpaqueConst = false;
2523 bool N0IsOpaqueConst = false;
2524 APInt ConstValue0, ConstValue1;
2526 if (VT.isVector()) {
2527 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2530 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
2531 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
2533 N0IsConst = isa<ConstantSDNode>(N0);
2535 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2536 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2538 N1IsConst = isa<ConstantSDNode>(N1);
2540 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2541 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2545 // fold (mul c1, c2) -> c1*c2
2546 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2547 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2548 N0.getNode(), N1.getNode());
2550 // canonicalize constant to RHS (vector doesn't have to splat)
2551 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
2552 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
2553 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2554 // fold (mul x, 0) -> 0
2555 if (N1IsConst && ConstValue1.isNullValue())
2557 // We require a splat of the entire scalar bit width for non-contiguous
2560 ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
2561 // fold (mul x, 1) -> x
2562 if (N1IsConst && ConstValue1.isOneValue() && IsFullSplat)
2565 if (SDValue NewSel = foldBinOpIntoSelect(N))
2568 // fold (mul x, -1) -> 0-x
2569 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2571 return DAG.getNode(ISD::SUB, DL, VT,
2572 DAG.getConstant(0, DL, VT), N0);
2574 // fold (mul x, (1 << c)) -> x << c
2575 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2578 return DAG.getNode(ISD::SHL, DL, VT, N0,
2579 DAG.getConstant(ConstValue1.logBase2(), DL,
2580 getShiftAmountTy(N0.getValueType())));
2582 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2583 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2585 unsigned Log2Val = (-ConstValue1).logBase2();
2587 // FIXME: If the input is something that is easily negated (e.g. a
2588 // single-use add), we should put the negate there.
2589 return DAG.getNode(ISD::SUB, DL, VT,
2590 DAG.getConstant(0, DL, VT),
2591 DAG.getNode(ISD::SHL, DL, VT, N0,
2592 DAG.getConstant(Log2Val, DL,
2593 getShiftAmountTy(N0.getValueType()))));
2596 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2597 if (N0.getOpcode() == ISD::SHL &&
2598 isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
2599 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
2600 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
2601 if (isConstantOrConstantVector(C3))
2602 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
2605 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2608 SDValue Sh(nullptr, 0), Y(nullptr, 0);
2610 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2611 if (N0.getOpcode() == ISD::SHL &&
2612 isConstantOrConstantVector(N0.getOperand(1)) &&
2613 N0.getNode()->hasOneUse()) {
2615 } else if (N1.getOpcode() == ISD::SHL &&
2616 isConstantOrConstantVector(N1.getOperand(1)) &&
2617 N1.getNode()->hasOneUse()) {
2622 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
2623 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
2627 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2628 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
2629 N0.getOpcode() == ISD::ADD &&
2630 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2631 isMulAddWithConstProfitable(N, N0, N1))
2632 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2633 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2634 N0.getOperand(0), N1),
2635 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2636 N0.getOperand(1), N1));
2639 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2645 /// Return true if divmod libcall is available.
2646 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2647 const TargetLowering &TLI) {
2649 EVT NodeType = Node->getValueType(0);
2650 if (!NodeType.isSimple())
2652 switch (NodeType.getSimpleVT().SimpleTy) {
2653 default: return false; // No libcall for vector types.
2654 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2655 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2656 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2657 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2658 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2661 return TLI.getLibcallName(LC) != nullptr;
2664 /// Issue divrem if both quotient and remainder are needed.
2665 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2666 if (Node->use_empty())
2667 return SDValue(); // This is a dead node, leave it alone.
2669 unsigned Opcode = Node->getOpcode();
2670 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2671 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2673 // DivMod lib calls can still work on non-legal types if using lib-calls.
2674 EVT VT = Node->getValueType(0);
2675 if (VT.isVector() || !VT.isInteger())
2678 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
2681 // If DIVREM is going to get expanded into a libcall,
2682 // but there is no libcall available, then don't combine.
2683 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2684 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2687 // If div is legal, it's better to do the normal expansion
2688 unsigned OtherOpcode = 0;
2689 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2690 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2691 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2694 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2695 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2699 SDValue Op0 = Node->getOperand(0);
2700 SDValue Op1 = Node->getOperand(1);
2702 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2703 UE = Op0.getNode()->use_end(); UI != UE;) {
2704 SDNode *User = *UI++;
2705 if (User == Node || User->use_empty())
2707 // Convert the other matching node(s), too;
2708 // otherwise, the DIVREM may get target-legalized into something
2709 // target-specific that we won't be able to recognize.
2710 unsigned UserOpc = User->getOpcode();
2711 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2712 User->getOperand(0) == Op0 &&
2713 User->getOperand(1) == Op1) {
2715 if (UserOpc == OtherOpcode) {
2716 SDVTList VTs = DAG.getVTList(VT, VT);
2717 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2718 } else if (UserOpc == DivRemOpc) {
2719 combined = SDValue(User, 0);
2721 assert(UserOpc == Opcode);
2725 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2726 CombineTo(User, combined);
2727 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2728 CombineTo(User, combined.getValue(1));
2734 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
2735 SDValue N0 = N->getOperand(0);
2736 SDValue N1 = N->getOperand(1);
2737 EVT VT = N->getValueType(0);
2740 if (DAG.isUndef(N->getOpcode(), {N0, N1}))
2741 return DAG.getUNDEF(VT);
2746 return DAG.getConstant(0, DL, VT);
2751 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2752 SDValue N0 = N->getOperand(0);
2753 SDValue N1 = N->getOperand(1);
2754 EVT VT = N->getValueType(0);
2758 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2763 // fold (sdiv c1, c2) -> c1/c2
2764 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2765 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2766 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2767 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2768 // fold (sdiv X, 1) -> X
2769 if (N1C && N1C->isOne())
2771 // fold (sdiv X, -1) -> 0-X
2772 if (N1C && N1C->isAllOnesValue())
2773 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
2775 if (SDValue V = simplifyDivRem(N, DAG))
2778 if (SDValue NewSel = foldBinOpIntoSelect(N))
2781 // If we know the sign bits of both operands are zero, strength reduce to a
2782 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2783 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2784 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2786 // fold (sdiv X, pow2) -> simple ops after legalize
2787 // FIXME: We check for the exact bit here because the generic lowering gives
2788 // better results in that case. The target-specific lowering should learn how
2789 // to handle exact sdivs efficiently.
2790 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2791 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() ||
2792 (-N1C->getAPIntValue()).isPowerOf2())) {
2793 // Target-specific implementation of sdiv x, pow2.
2794 if (SDValue Res = BuildSDIVPow2(N))
2797 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2799 // Splat the sign bit into the register
2801 DAG.getNode(ISD::SRA, DL, VT, N0,
2802 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2803 getShiftAmountTy(N0.getValueType())));
2804 AddToWorklist(SGN.getNode());
2806 // Add (N0 < 0) ? abs2 - 1 : 0;
2808 DAG.getNode(ISD::SRL, DL, VT, SGN,
2809 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2810 getShiftAmountTy(SGN.getValueType())));
2811 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2812 AddToWorklist(SRL.getNode());
2813 AddToWorklist(ADD.getNode()); // Divide by pow2
2814 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2815 DAG.getConstant(lg2, DL,
2816 getShiftAmountTy(ADD.getValueType())));
2818 // If we're dividing by a positive value, we're done. Otherwise, we must
2819 // negate the result.
2820 if (N1C->getAPIntValue().isNonNegative())
2823 AddToWorklist(SRA.getNode());
2824 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2827 // If integer divide is expensive and we satisfy the requirements, emit an
2828 // alternate sequence. Targets may check function attributes for size/speed
2830 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2831 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2832 if (SDValue Op = BuildSDIV(N))
2835 // sdiv, srem -> sdivrem
2836 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2837 // true. Otherwise, we break the simplification logic in visitREM().
2838 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2839 if (SDValue DivRem = useDivRem(N))
2845 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2846 SDValue N0 = N->getOperand(0);
2847 SDValue N1 = N->getOperand(1);
2848 EVT VT = N->getValueType(0);
2852 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2857 // fold (udiv c1, c2) -> c1/c2
2858 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2859 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2861 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2865 if (SDValue V = simplifyDivRem(N, DAG))
2868 if (SDValue NewSel = foldBinOpIntoSelect(N))
2871 // fold (udiv x, (1 << c)) -> x >>u c
2872 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
2873 DAG.isKnownToBeAPowerOfTwo(N1)) {
2874 SDValue LogBase2 = BuildLogBase2(N1, DL);
2875 AddToWorklist(LogBase2.getNode());
2877 EVT ShiftVT = getShiftAmountTy(N0.getValueType());
2878 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
2879 AddToWorklist(Trunc.getNode());
2880 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
2883 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2884 if (N1.getOpcode() == ISD::SHL) {
2885 SDValue N10 = N1.getOperand(0);
2886 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
2887 DAG.isKnownToBeAPowerOfTwo(N10)) {
2888 SDValue LogBase2 = BuildLogBase2(N10, DL);
2889 AddToWorklist(LogBase2.getNode());
2891 EVT ADDVT = N1.getOperand(1).getValueType();
2892 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
2893 AddToWorklist(Trunc.getNode());
2894 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
2895 AddToWorklist(Add.getNode());
2896 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2900 // fold (udiv x, c) -> alternate
2901 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2902 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2903 if (SDValue Op = BuildUDIV(N))
2906 // sdiv, srem -> sdivrem
2907 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
2908 // true. Otherwise, we break the simplification logic in visitREM().
2909 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2910 if (SDValue DivRem = useDivRem(N))
2916 // handles ISD::SREM and ISD::UREM
2917 SDValue DAGCombiner::visitREM(SDNode *N) {
2918 unsigned Opcode = N->getOpcode();
2919 SDValue N0 = N->getOperand(0);
2920 SDValue N1 = N->getOperand(1);
2921 EVT VT = N->getValueType(0);
2922 bool isSigned = (Opcode == ISD::SREM);
2925 // fold (rem c1, c2) -> c1%c2
2926 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2927 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2929 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2932 if (SDValue V = simplifyDivRem(N, DAG))
2935 if (SDValue NewSel = foldBinOpIntoSelect(N))
2939 // If we know the sign bits of both operands are zero, strength reduce to a
2940 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2941 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2942 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2944 SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
2945 if (DAG.isKnownToBeAPowerOfTwo(N1)) {
2946 // fold (urem x, pow2) -> (and x, pow2-1)
2947 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2948 AddToWorklist(Add.getNode());
2949 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2951 if (N1.getOpcode() == ISD::SHL &&
2952 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
2953 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2954 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
2955 AddToWorklist(Add.getNode());
2956 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2960 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2962 // If X/C can be simplified by the division-by-constant logic, lower
2963 // X%C to the equivalent of X-X/C*C.
2964 // To avoid mangling nodes, this simplification requires that the combine()
2965 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2966 // against this by skipping the simplification if isIntDivCheap(). When
2967 // div is not cheap, combine will not return a DIVREM. Regardless,
2968 // checking cheapness here makes sense since the simplification results in
2970 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2971 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2972 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2973 AddToWorklist(Div.getNode());
2974 SDValue OptimizedDiv = combine(Div.getNode());
2975 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2976 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2977 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2978 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2979 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2980 AddToWorklist(Mul.getNode());
2985 // sdiv, srem -> sdivrem
2986 if (SDValue DivRem = useDivRem(N))
2987 return DivRem.getValue(1);
2992 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2993 SDValue N0 = N->getOperand(0);
2994 SDValue N1 = N->getOperand(1);
2995 EVT VT = N->getValueType(0);
2998 // fold (mulhs x, 0) -> 0
2999 if (isNullConstant(N1))
3001 // fold (mulhs x, 1) -> (sra x, size(x)-1)
3002 if (isOneConstant(N1)) {
3004 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
3005 DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
3006 getShiftAmountTy(N0.getValueType())));
3008 // fold (mulhs x, undef) -> 0
3009 if (N0.isUndef() || N1.isUndef())
3010 return DAG.getConstant(0, SDLoc(N), VT);
3012 // If the type twice as wide is legal, transform the mulhs to a wider multiply
3014 if (VT.isSimple() && !VT.isVector()) {
3015 MVT Simple = VT.getSimpleVT();
3016 unsigned SimpleSize = Simple.getSizeInBits();
3017 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3018 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3019 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
3020 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
3021 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3022 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3023 DAG.getConstant(SimpleSize, DL,
3024 getShiftAmountTy(N1.getValueType())));
3025 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3032 SDValue DAGCombiner::visitMULHU(SDNode *N) {
3033 SDValue N0 = N->getOperand(0);
3034 SDValue N1 = N->getOperand(1);
3035 EVT VT = N->getValueType(0);
3038 // fold (mulhu x, 0) -> 0
3039 if (isNullConstant(N1))
3041 // fold (mulhu x, 1) -> 0
3042 if (isOneConstant(N1))
3043 return DAG.getConstant(0, DL, N0.getValueType());
3044 // fold (mulhu x, undef) -> 0
3045 if (N0.isUndef() || N1.isUndef())
3046 return DAG.getConstant(0, DL, VT);
3048 // If the type twice as wide is legal, transform the mulhu to a wider multiply
3050 if (VT.isSimple() && !VT.isVector()) {
3051 MVT Simple = VT.getSimpleVT();
3052 unsigned SimpleSize = Simple.getSizeInBits();
3053 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3054 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3055 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
3056 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
3057 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
3058 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
3059 DAG.getConstant(SimpleSize, DL,
3060 getShiftAmountTy(N1.getValueType())));
3061 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
3068 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
3069 /// give the opcodes for the two computations that are being performed. Return
3070 /// true if a simplification was made.
3071 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
3073 // If the high half is not needed, just compute the low half.
3074 bool HiExists = N->hasAnyUseOfValue(1);
3076 (!LegalOperations ||
3077 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
3078 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3079 return CombineTo(N, Res, Res);
3082 // If the low half is not needed, just compute the high half.
3083 bool LoExists = N->hasAnyUseOfValue(0);
3085 (!LegalOperations ||
3086 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
3087 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3088 return CombineTo(N, Res, Res);
3091 // If both halves are used, return as it is.
3092 if (LoExists && HiExists)
3095 // If the two computed results can be simplified separately, separate them.
3097 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
3098 AddToWorklist(Lo.getNode());
3099 SDValue LoOpt = combine(Lo.getNode());
3100 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
3101 (!LegalOperations ||
3102 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
3103 return CombineTo(N, LoOpt, LoOpt);
3107 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
3108 AddToWorklist(Hi.getNode());
3109 SDValue HiOpt = combine(Hi.getNode());
3110 if (HiOpt.getNode() && HiOpt != Hi &&
3111 (!LegalOperations ||
3112 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
3113 return CombineTo(N, HiOpt, HiOpt);
3119 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
3120 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
3123 EVT VT = N->getValueType(0);
3126 // If the type is twice as wide is legal, transform the mulhu to a wider
3127 // multiply plus a shift.
3128 if (VT.isSimple() && !VT.isVector()) {
3129 MVT Simple = VT.getSimpleVT();
3130 unsigned SimpleSize = Simple.getSizeInBits();
3131 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3132 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3133 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
3134 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
3135 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3136 // Compute the high part as N1.
3137 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3138 DAG.getConstant(SimpleSize, DL,
3139 getShiftAmountTy(Lo.getValueType())));
3140 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3141 // Compute the low part as N0.
3142 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3143 return CombineTo(N, Lo, Hi);
3150 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
3151 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
3154 EVT VT = N->getValueType(0);
3157 // If the type is twice as wide is legal, transform the mulhu to a wider
3158 // multiply plus a shift.
3159 if (VT.isSimple() && !VT.isVector()) {
3160 MVT Simple = VT.getSimpleVT();
3161 unsigned SimpleSize = Simple.getSizeInBits();
3162 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
3163 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
3164 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
3165 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
3166 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
3167 // Compute the high part as N1.
3168 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
3169 DAG.getConstant(SimpleSize, DL,
3170 getShiftAmountTy(Lo.getValueType())));
3171 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
3172 // Compute the low part as N0.
3173 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
3174 return CombineTo(N, Lo, Hi);
3181 SDValue DAGCombiner::visitSMULO(SDNode *N) {
3182 // (smulo x, 2) -> (saddo x, x)
3183 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3184 if (C2->getAPIntValue() == 2)
3185 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
3186 N->getOperand(0), N->getOperand(0));
3191 SDValue DAGCombiner::visitUMULO(SDNode *N) {
3192 // (umulo x, 2) -> (uaddo x, x)
3193 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3194 if (C2->getAPIntValue() == 2)
3195 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
3196 N->getOperand(0), N->getOperand(0));
3201 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
3202 SDValue N0 = N->getOperand(0);
3203 SDValue N1 = N->getOperand(1);
3204 EVT VT = N0.getValueType();
3208 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3211 // fold (add c1, c2) -> c1+c2
3212 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3213 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3215 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
3217 // canonicalize constant to RHS
3218 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3219 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3220 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
3225 /// If this is a binary operator with two operands of the same opcode, try to
3227 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
3228 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3229 EVT VT = N0.getValueType();
3230 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
3232 // Bail early if none of these transforms apply.
3233 if (N0.getNumOperands() == 0) return SDValue();
3235 // For each of OP in AND/OR/XOR:
3236 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
3237 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
3238 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
3239 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
3240 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
3242 // do not sink logical op inside of a vector extend, since it may combine
3244 EVT Op0VT = N0.getOperand(0).getValueType();
3245 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
3246 N0.getOpcode() == ISD::SIGN_EXTEND ||
3247 N0.getOpcode() == ISD::BSWAP ||
3248 // Avoid infinite looping with PromoteIntBinOp.
3249 (N0.getOpcode() == ISD::ANY_EXTEND &&
3250 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
3251 (N0.getOpcode() == ISD::TRUNCATE &&
3252 (!TLI.isZExtFree(VT, Op0VT) ||
3253 !TLI.isTruncateFree(Op0VT, VT)) &&
3254 TLI.isTypeLegal(Op0VT))) &&
3256 Op0VT == N1.getOperand(0).getValueType() &&
3257 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
3258 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3259 N0.getOperand(0).getValueType(),
3260 N0.getOperand(0), N1.getOperand(0));
3261 AddToWorklist(ORNode.getNode());
3262 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
3265 // For each of OP in SHL/SRL/SRA/AND...
3266 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
3267 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
3268 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
3269 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
3270 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
3271 N0.getOperand(1) == N1.getOperand(1)) {
3272 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
3273 N0.getOperand(0).getValueType(),
3274 N0.getOperand(0), N1.getOperand(0));
3275 AddToWorklist(ORNode.getNode());
3276 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
3277 ORNode, N0.getOperand(1));
3280 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
3281 // Only perform this optimization up until type legalization, before
3282 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
3283 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
3284 // we don't want to undo this promotion.
3285 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
3287 if ((N0.getOpcode() == ISD::BITCAST ||
3288 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
3289 Level <= AfterLegalizeTypes) {
3290 SDValue In0 = N0.getOperand(0);
3291 SDValue In1 = N1.getOperand(0);
3292 EVT In0Ty = In0.getValueType();
3293 EVT In1Ty = In1.getValueType();
3295 // If both incoming values are integers, and the original types are the
3297 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
3298 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
3299 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
3300 AddToWorklist(Op.getNode());
3305 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
3306 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
3307 // If both shuffles use the same mask, and both shuffle within a single
3308 // vector, then it is worthwhile to move the swizzle after the operation.
3309 // The type-legalizer generates this pattern when loading illegal
3310 // vector types from memory. In many cases this allows additional shuffle
3312 // There are other cases where moving the shuffle after the xor/and/or
3313 // is profitable even if shuffles don't perform a swizzle.
3314 // If both shuffles use the same mask, and both shuffles have the same first
3315 // or second operand, then it might still be profitable to move the shuffle
3316 // after the xor/and/or operation.
3317 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
3318 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
3319 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
3321 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
3322 "Inputs to shuffles are not the same type");
3324 // Check that both shuffles use the same mask. The masks are known to be of
3325 // the same length because the result vector type is the same.
3326 // Check also that shuffles have only one use to avoid introducing extra
3328 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
3329 SVN0->getMask().equals(SVN1->getMask())) {
3330 SDValue ShOp = N0->getOperand(1);
3332 // Don't try to fold this node if it requires introducing a
3333 // build vector of all zeros that might be illegal at this stage.
3334 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3336 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3341 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
3342 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
3343 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
3344 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
3345 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3346 N0->getOperand(0), N1->getOperand(0));
3347 AddToWorklist(NewNode.getNode());
3348 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
3352 // Don't try to fold this node if it requires introducing a
3353 // build vector of all zeros that might be illegal at this stage.
3354 ShOp = N0->getOperand(0);
3355 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
3357 ShOp = DAG.getConstant(0, SDLoc(N), VT);
3362 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
3363 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
3364 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
3365 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
3366 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
3367 N0->getOperand(1), N1->getOperand(1));
3368 AddToWorklist(NewNode.getNode());
3369 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
3378 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
3379 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
3381 SDValue LL, LR, RL, RR, N0CC, N1CC;
3382 if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
3383 !isSetCCEquivalent(N1, RL, RR, N1CC))
3386 assert(N0.getValueType() == N1.getValueType() &&
3387 "Unexpected operand types for bitwise logic op");
3388 assert(LL.getValueType() == LR.getValueType() &&
3389 RL.getValueType() == RR.getValueType() &&
3390 "Unexpected operand types for setcc");
3392 // If we're here post-legalization or the logic op type is not i1, the logic
3393 // op type must match a setcc result type. Also, all folds require new
3394 // operations on the left and right operands, so those types must match.
3395 EVT VT = N0.getValueType();
3396 EVT OpVT = LL.getValueType();
3397 if (LegalOperations || VT != MVT::i1)
3398 if (VT != getSetCCResultType(OpVT))
3400 if (OpVT != RL.getValueType())
3403 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
3404 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
3405 bool IsInteger = OpVT.isInteger();
3406 if (LR == RR && CC0 == CC1 && IsInteger) {
3407 bool IsZero = isNullConstantOrNullSplatConstant(LR);
3408 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
3411 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
3412 // All sign bits clear?
3413 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
3415 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
3416 // Any sign bits set?
3417 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
3419 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
3420 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
3421 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
3422 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
3423 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
3424 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
3425 AddToWorklist(Or.getNode());
3426 return DAG.getSetCC(DL, VT, Or, LR, CC1);
3430 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
3431 // All sign bits set?
3432 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
3434 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
3435 // Any sign bits clear?
3436 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
3438 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
3439 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
3440 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
3441 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
3442 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
3443 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
3444 AddToWorklist(And.getNode());
3445 return DAG.getSetCC(DL, VT, And, LR, CC1);
3449 // TODO: What is the 'or' equivalent of this fold?
3450 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
3451 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
3452 ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
3453 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
3454 SDValue One = DAG.getConstant(1, DL, OpVT);
3455 SDValue Two = DAG.getConstant(2, DL, OpVT);
3456 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
3457 AddToWorklist(Add.getNode());
3458 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
3461 // Try more general transforms if the predicates match and the only user of
3462 // the compares is the 'and' or 'or'.
3463 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
3464 N0.hasOneUse() && N1.hasOneUse()) {
3465 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
3466 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
3467 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
3468 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
3469 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
3470 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
3471 SDValue Zero = DAG.getConstant(0, DL, OpVT);
3472 return DAG.getSetCC(DL, VT, Or, Zero, CC1);
3476 // Canonicalize equivalent operands to LL == RL.
3477 if (LL == RR && LR == RL) {
3478 CC1 = ISD::getSetCCSwappedOperands(CC1);
3482 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3483 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
3484 if (LL == RL && LR == RR) {
3485 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
3486 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
3487 if (NewCC != ISD::SETCC_INVALID &&
3488 (!LegalOperations ||
3489 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
3490 TLI.isOperationLegal(ISD::SETCC, OpVT))))
3491 return DAG.getSetCC(DL, VT, LL, LR, NewCC);
3497 /// This contains all DAGCombine rules which reduce two values combined by
3498 /// an And operation to a single value. This makes them reusable in the context
3499 /// of visitSELECT(). Rules involving constants are not included as
3500 /// visitSELECT() already handles those cases.
3501 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
3502 EVT VT = N1.getValueType();
3505 // fold (and x, undef) -> 0
3506 if (N0.isUndef() || N1.isUndef())
3507 return DAG.getConstant(0, DL, VT);
3509 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
3512 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3513 VT.getSizeInBits() <= 64) {
3514 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3515 APInt ADDC = ADDI->getAPIntValue();
3516 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3517 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3518 // immediate for an add, but it is legal if its top c2 bits are set,
3519 // transform the ADD so the immediate doesn't need to be materialized
3521 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3522 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3523 SRLI->getZExtValue());
3524 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3526 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3529 DAG.getNode(ISD::ADD, DL0, VT,
3530 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
3531 CombineTo(N0.getNode(), NewAdd);
3532 // Return N so it doesn't get rechecked!
3533 return SDValue(N, 0);
3541 // Reduce bit extract of low half of an integer to the narrower type.
3542 // (and (srl i64:x, K), KMask) ->
3543 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
3544 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3545 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
3546 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3547 unsigned Size = VT.getSizeInBits();
3548 const APInt &AndMask = CAnd->getAPIntValue();
3549 unsigned ShiftBits = CShift->getZExtValue();
3551 // Bail out, this node will probably disappear anyway.
3555 unsigned MaskBits = AndMask.countTrailingOnes();
3556 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
3558 if (AndMask.isMask() &&
3559 // Required bits must not span the two halves of the integer and
3560 // must fit in the half size type.
3561 (ShiftBits + MaskBits <= Size / 2) &&
3562 TLI.isNarrowingProfitable(VT, HalfVT) &&
3563 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
3564 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
3565 TLI.isTruncateFree(VT, HalfVT) &&
3566 TLI.isZExtFree(HalfVT, VT)) {
3567 // The isNarrowingProfitable is to avoid regressions on PPC and
3568 // AArch64 which match a few 64-bit bit insert / bit extract patterns
3569 // on downstream users of this. Those patterns could probably be
3570 // extended to handle extensions mixed in.
3573 assert(MaskBits <= Size);
3575 // Extracting the highest bit of the low half.
3576 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
3577 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
3580 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
3581 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
3582 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
3583 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
3584 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
3593 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
3594 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
3596 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
3598 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
3601 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3602 LoadedVT = LoadN->getMemoryVT();
3604 if (ExtVT == LoadedVT &&
3605 (!LegalOperations ||
3606 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
3607 // ZEXTLOAD will match without needing to change the size of the value being
3613 // Do not change the width of a volatile load.
3614 if (LoadN->isVolatile())
3617 // Do not generate loads of non-round integer types since these can
3618 // be expensive (and would be wrong if the type is not byte sized).
3619 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
3622 if (LegalOperations &&
3623 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
3626 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
3633 SDValue DAGCombiner::visitAND(SDNode *N) {
3634 SDValue N0 = N->getOperand(0);
3635 SDValue N1 = N->getOperand(1);
3636 EVT VT = N1.getValueType();
3643 if (VT.isVector()) {
3644 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3647 // fold (and x, 0) -> 0, vector edition
3648 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3649 // do not return N0, because undef node may exist in N0
3650 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
3651 SDLoc(N), N0.getValueType());
3652 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3653 // do not return N1, because undef node may exist in N1
3654 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
3655 SDLoc(N), N1.getValueType());
3657 // fold (and x, -1) -> x, vector edition
3658 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3660 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3664 // fold (and c1, c2) -> c1&c2
3665 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3666 ConstantSDNode *N1C = isConstOrConstSplat(N1);
3667 if (N0C && N1C && !N1C->isOpaque())
3668 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3669 // canonicalize constant to RHS
3670 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
3671 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
3672 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3673 // fold (and x, -1) -> x
3674 if (isAllOnesConstant(N1))
3676 // if (and x, c) is known to be zero, return 0
3677 unsigned BitWidth = VT.getScalarSizeInBits();
3678 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3679 APInt::getAllOnesValue(BitWidth)))
3680 return DAG.getConstant(0, SDLoc(N), VT);
3682 if (SDValue NewSel = foldBinOpIntoSelect(N))
3686 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3688 // fold (and (or x, C), D) -> D if (C & D) == D
3689 if (N1C && N0.getOpcode() == ISD::OR)
3690 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
3691 if (N1C->getAPIntValue().isSubsetOf(ORI->getAPIntValue()))
3693 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3694 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3695 SDValue N0Op0 = N0.getOperand(0);
3696 APInt Mask = ~N1C->getAPIntValue();
3697 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
3698 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3699 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3700 N0.getValueType(), N0Op0);
3702 // Replace uses of the AND with uses of the Zero extend node.
3705 // We actually want to replace all uses of the any_extend with the
3706 // zero_extend, to avoid duplicating things. This will later cause this
3707 // AND to be folded.
3708 CombineTo(N0.getNode(), Zext);
3709 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3712 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3713 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3714 // already be zero by virtue of the width of the base type of the load.
3716 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3718 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3719 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
3720 N0.getOperand(0).getOpcode() == ISD::LOAD &&
3721 N0.getOperand(0).getResNo() == 0) ||
3722 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
3723 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3724 N0 : N0.getOperand(0) );
3726 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3727 // This can be a pure constant or a vector splat, in which case we treat the
3728 // vector as a scalar and use the splat value.
3729 APInt Constant = APInt::getNullValue(1);
3730 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3731 Constant = C->getAPIntValue();
3732 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3733 APInt SplatValue, SplatUndef;
3734 unsigned SplatBitSize;
3736 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3737 SplatBitSize, HasAnyUndefs);
3739 // Undef bits can contribute to a possible optimisation if set, so
3741 SplatValue |= SplatUndef;
3743 // The splat value may be something like "0x00FFFFFF", which means 0 for
3744 // the first vector value and FF for the rest, repeating. We need a mask
3745 // that will apply equally to all members of the vector, so AND all the
3746 // lanes of the constant together.
3747 EVT VT = Vector->getValueType(0);
3748 unsigned BitWidth = VT.getScalarSizeInBits();
3750 // If the splat value has been compressed to a bitlength lower
3751 // than the size of the vector lane, we need to re-expand it to
3753 if (BitWidth > SplatBitSize)
3754 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3755 SplatBitSize < BitWidth;
3756 SplatBitSize = SplatBitSize * 2)
3757 SplatValue |= SplatValue.shl(SplatBitSize);
3759 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3760 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3761 if (SplatBitSize % BitWidth == 0) {
3762 Constant = APInt::getAllOnesValue(BitWidth);
3763 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3764 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3769 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3770 // actually legal and isn't going to get expanded, else this is a false
3772 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3773 Load->getValueType(0),
3774 Load->getMemoryVT());
3776 // Resize the constant to the same size as the original memory access before
3777 // extension. If it is still the AllOnesValue then this AND is completely
3779 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
3782 switch (Load->getExtensionType()) {
3783 default: B = false; break;
3784 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3786 case ISD::NON_EXTLOAD: B = true; break;
3789 if (B && Constant.isAllOnesValue()) {
3790 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3791 // preserve semantics once we get rid of the AND.
3792 SDValue NewLoad(Load, 0);
3794 // Fold the AND away. NewLoad may get replaced immediately.
3795 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3797 if (Load->getExtensionType() == ISD::EXTLOAD) {
3798 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3799 Load->getValueType(0), SDLoc(Load),
3800 Load->getChain(), Load->getBasePtr(),
3801 Load->getOffset(), Load->getMemoryVT(),
3802 Load->getMemOperand());
3803 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3804 if (Load->getNumValues() == 3) {
3805 // PRE/POST_INC loads have 3 values.
3806 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3807 NewLoad.getValue(2) };
3808 CombineTo(Load, To, 3, true);
3810 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3814 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3818 // fold (and (load x), 255) -> (zextload x, i8)
3819 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3820 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3821 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
3822 (N0.getOpcode() == ISD::ANY_EXTEND &&
3823 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3824 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3825 LoadSDNode *LN0 = HasAnyExt
3826 ? cast<LoadSDNode>(N0.getOperand(0))
3827 : cast<LoadSDNode>(N0);
3828 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3829 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3830 auto NarrowLoad = false;
3831 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3832 EVT ExtVT, LoadedVT;
3833 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
3837 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3838 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3839 LN0->getMemOperand());
3841 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3844 EVT PtrType = LN0->getOperand(1).getValueType();
3846 unsigned Alignment = LN0->getAlignment();
3847 SDValue NewPtr = LN0->getBasePtr();
3849 // For big endian targets, we need to add an offset to the pointer
3850 // to load the correct bytes. For little endian systems, we merely
3851 // need to read fewer bytes from the same pointer.
3852 if (DAG.getDataLayout().isBigEndian()) {
3853 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3854 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3855 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3857 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3858 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3859 Alignment = MinAlign(Alignment, PtrOff);
3862 AddToWorklist(NewPtr.getNode());
3864 SDValue Load = DAG.getExtLoad(
3865 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
3866 LN0->getPointerInfo(), ExtVT, Alignment,
3867 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
3869 CombineTo(LN0, Load, Load.getValue(1));
3870 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3876 if (SDValue Combined = visitANDLike(N0, N1, N))
3879 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3880 if (N0.getOpcode() == N1.getOpcode())
3881 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3884 // Masking the negated extension of a boolean is just the zero-extended
3886 // and (sub 0, zext(bool X)), 1 --> zext(bool X)
3887 // and (sub 0, sext(bool X)), 1 --> zext(bool X)
3889 // Note: the SimplifyDemandedBits fold below can make an information-losing
3890 // transform, and then we have no way to find this better fold.
3891 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
3892 if (isNullConstantOrNullSplatConstant(N0.getOperand(0))) {
3893 SDValue SubRHS = N0.getOperand(1);
3894 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
3895 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3897 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
3898 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
3899 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
3903 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3904 // fold (and (sra)) -> (and (srl)) when possible.
3905 if (SimplifyDemandedBits(SDValue(N, 0)))
3906 return SDValue(N, 0);
3908 // fold (zext_inreg (extload x)) -> (zextload x)
3909 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3910 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3911 EVT MemVT = LN0->getMemoryVT();
3912 // If we zero all the possible extended bits, then we can turn this into
3913 // a zextload if we are running before legalize or the operation is legal.
3914 unsigned BitWidth = N1.getScalarValueSizeInBits();
3915 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3916 BitWidth - MemVT.getScalarSizeInBits())) &&
3917 ((!LegalOperations && !LN0->isVolatile()) ||
3918 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3919 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3920 LN0->getChain(), LN0->getBasePtr(),
3921 MemVT, LN0->getMemOperand());
3923 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3927 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3928 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3931 EVT MemVT = LN0->getMemoryVT();
3932 // If we zero all the possible extended bits, then we can turn this into
3933 // a zextload if we are running before legalize or the operation is legal.
3934 unsigned BitWidth = N1.getScalarValueSizeInBits();
3935 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3936 BitWidth - MemVT.getScalarSizeInBits())) &&
3937 ((!LegalOperations && !LN0->isVolatile()) ||
3938 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3939 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3940 LN0->getChain(), LN0->getBasePtr(),
3941 MemVT, LN0->getMemOperand());
3943 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3947 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3948 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3949 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3950 N0.getOperand(1), false))
3957 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3958 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3959 bool DemandHighBits) {
3960 if (!LegalOperations)
3963 EVT VT = N->getValueType(0);
3964 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3966 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
3969 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3970 bool LookPassAnd0 = false;
3971 bool LookPassAnd1 = false;
3972 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3974 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3976 if (N0.getOpcode() == ISD::AND) {
3977 if (!N0.getNode()->hasOneUse())
3979 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3980 if (!N01C || N01C->getZExtValue() != 0xFF00)
3982 N0 = N0.getOperand(0);
3983 LookPassAnd0 = true;
3986 if (N1.getOpcode() == ISD::AND) {
3987 if (!N1.getNode()->hasOneUse())
3989 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3990 if (!N11C || N11C->getZExtValue() != 0xFF)
3992 N1 = N1.getOperand(0);
3993 LookPassAnd1 = true;
3996 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3998 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
4000 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
4003 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4004 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
4007 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
4010 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
4011 SDValue N00 = N0->getOperand(0);
4012 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
4013 if (!N00.getNode()->hasOneUse())
4015 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
4016 if (!N001C || N001C->getZExtValue() != 0xFF)
4018 N00 = N00.getOperand(0);
4019 LookPassAnd0 = true;
4022 SDValue N10 = N1->getOperand(0);
4023 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
4024 if (!N10.getNode()->hasOneUse())
4026 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
4027 if (!N101C || N101C->getZExtValue() != 0xFF00)
4029 N10 = N10.getOperand(0);
4030 LookPassAnd1 = true;
4036 // Make sure everything beyond the low halfword gets set to zero since the SRL
4037 // 16 will clear the top bits.
4038 unsigned OpSizeInBits = VT.getSizeInBits();
4039 if (DemandHighBits && OpSizeInBits > 16) {
4040 // If the left-shift isn't masked out then the only way this is a bswap is
4041 // if all bits beyond the low 8 are 0. In that case the entire pattern
4042 // reduces to a left shift anyway: leave it for other parts of the combiner.
4046 // However, if the right shift isn't masked out then it might be because
4047 // it's not needed. See if we can spot that too.
4048 if (!LookPassAnd1 &&
4049 !DAG.MaskedValueIsZero(
4050 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
4054 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
4055 if (OpSizeInBits > 16) {
4057 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
4058 DAG.getConstant(OpSizeInBits - 16, DL,
4059 getShiftAmountTy(VT)));
4064 /// Return true if the specified node is an element that makes up a 32-bit
4065 /// packed halfword byteswap.
4066 /// ((x & 0x000000ff) << 8) |
4067 /// ((x & 0x0000ff00) >> 8) |
4068 /// ((x & 0x00ff0000) << 8) |
4069 /// ((x & 0xff000000) >> 8)
4070 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
4071 if (!N.getNode()->hasOneUse())
4074 unsigned Opc = N.getOpcode();
4075 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
4078 SDValue N0 = N.getOperand(0);
4079 unsigned Opc0 = N0.getOpcode();
4080 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
4083 ConstantSDNode *N1C = nullptr;
4084 // SHL or SRL: look upstream for AND mask operand
4085 if (Opc == ISD::AND)
4086 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4087 else if (Opc0 == ISD::AND)
4088 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4092 unsigned MaskByteOffset;
4093 switch (N1C->getZExtValue()) {
4096 case 0xFF: MaskByteOffset = 0; break;
4097 case 0xFF00: MaskByteOffset = 1; break;
4098 case 0xFF0000: MaskByteOffset = 2; break;
4099 case 0xFF000000: MaskByteOffset = 3; break;
4102 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
4103 if (Opc == ISD::AND) {
4104 if (MaskByteOffset == 0 || MaskByteOffset == 2) {
4106 // (x >> 8) & 0xff0000
4107 if (Opc0 != ISD::SRL)
4109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4110 if (!C || C->getZExtValue() != 8)
4113 // (x << 8) & 0xff00
4114 // (x << 8) & 0xff000000
4115 if (Opc0 != ISD::SHL)
4117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4118 if (!C || C->getZExtValue() != 8)
4121 } else if (Opc == ISD::SHL) {
4123 // (x & 0xff0000) << 8
4124 if (MaskByteOffset != 0 && MaskByteOffset != 2)
4126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4127 if (!C || C->getZExtValue() != 8)
4129 } else { // Opc == ISD::SRL
4130 // (x & 0xff00) >> 8
4131 // (x & 0xff000000) >> 8
4132 if (MaskByteOffset != 1 && MaskByteOffset != 3)
4134 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
4135 if (!C || C->getZExtValue() != 8)
4139 if (Parts[MaskByteOffset])
4142 Parts[MaskByteOffset] = N0.getOperand(0).getNode();
4146 /// Match a 32-bit packed halfword bswap. That is
4147 /// ((x & 0x000000ff) << 8) |
4148 /// ((x & 0x0000ff00) >> 8) |
4149 /// ((x & 0x00ff0000) << 8) |
4150 /// ((x & 0xff000000) >> 8)
4151 /// => (rotl (bswap x), 16)
4152 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
4153 if (!LegalOperations)
4156 EVT VT = N->getValueType(0);
4159 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
4163 // (or (or (and), (and)), (or (and), (and)))
4164 // (or (or (or (and), (and)), (and)), (and))
4165 if (N0.getOpcode() != ISD::OR)
4167 SDValue N00 = N0.getOperand(0);
4168 SDValue N01 = N0.getOperand(1);
4169 SDNode *Parts[4] = {};
4171 if (N1.getOpcode() == ISD::OR &&
4172 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
4173 // (or (or (and), (and)), (or (and), (and)))
4174 if (!isBSwapHWordElement(N00, Parts))
4177 if (!isBSwapHWordElement(N01, Parts))
4179 SDValue N10 = N1.getOperand(0);
4180 if (!isBSwapHWordElement(N10, Parts))
4182 SDValue N11 = N1.getOperand(1);
4183 if (!isBSwapHWordElement(N11, Parts))
4186 // (or (or (or (and), (and)), (and)), (and))
4187 if (!isBSwapHWordElement(N1, Parts))
4189 if (!isBSwapHWordElement(N01, Parts))
4191 if (N00.getOpcode() != ISD::OR)
4193 SDValue N000 = N00.getOperand(0);
4194 if (!isBSwapHWordElement(N000, Parts))
4196 SDValue N001 = N00.getOperand(1);
4197 if (!isBSwapHWordElement(N001, Parts))
4201 // Make sure the parts are all coming from the same node.
4202 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
4206 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
4207 SDValue(Parts[0], 0));
4209 // Result of the bswap should be rotated by 16. If it's not legal, then
4210 // do (x << 16) | (x >> 16).
4211 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
4212 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4213 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
4214 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
4215 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
4216 return DAG.getNode(ISD::OR, DL, VT,
4217 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
4218 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
4221 /// This contains all DAGCombine rules which reduce two values combined by
4222 /// an Or operation to a single value \see visitANDLike().
4223 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
4224 EVT VT = N1.getValueType();
4227 // fold (or x, undef) -> -1
4228 if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
4229 return DAG.getAllOnesConstant(DL, VT);
4231 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
4234 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
4235 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
4236 // Don't increase # computations.
4237 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4238 // We can only do this xform if we know that bits from X that are set in C2
4239 // but not in C1 are already zero. Likewise for Y.
4240 if (const ConstantSDNode *N0O1C =
4241 getAsNonOpaqueConstant(N0.getOperand(1))) {
4242 if (const ConstantSDNode *N1O1C =
4243 getAsNonOpaqueConstant(N1.getOperand(1))) {
4244 // We can only do this xform if we know that bits from X that are set in
4245 // C2 but not in C1 are already zero. Likewise for Y.
4246 const APInt &LHSMask = N0O1C->getAPIntValue();
4247 const APInt &RHSMask = N1O1C->getAPIntValue();
4249 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
4250 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
4251 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4252 N0.getOperand(0), N1.getOperand(0));
4253 return DAG.getNode(ISD::AND, DL, VT, X,
4254 DAG.getConstant(LHSMask | RHSMask, DL, VT));
4260 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
4261 if (N0.getOpcode() == ISD::AND &&
4262 N1.getOpcode() == ISD::AND &&
4263 N0.getOperand(0) == N1.getOperand(0) &&
4264 // Don't increase # computations.
4265 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
4266 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
4267 N0.getOperand(1), N1.getOperand(1));
4268 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
4274 SDValue DAGCombiner::visitOR(SDNode *N) {
4275 SDValue N0 = N->getOperand(0);
4276 SDValue N1 = N->getOperand(1);
4277 EVT VT = N1.getValueType();
4284 if (VT.isVector()) {
4285 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4288 // fold (or x, 0) -> x, vector edition
4289 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4291 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4294 // fold (or x, -1) -> -1, vector edition
4295 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4296 // do not return N0, because undef node may exist in N0
4297 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
4298 if (ISD::isBuildVectorAllOnes(N1.getNode()))
4299 // do not return N1, because undef node may exist in N1
4300 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
4302 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
4303 // Do this only if the resulting shuffle is legal.
4304 if (isa<ShuffleVectorSDNode>(N0) &&
4305 isa<ShuffleVectorSDNode>(N1) &&
4306 // Avoid folding a node with illegal type.
4307 TLI.isTypeLegal(VT)) {
4308 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
4309 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
4310 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4311 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
4312 // Ensure both shuffles have a zero input.
4313 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
4314 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
4315 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
4316 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
4317 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
4318 bool CanFold = true;
4319 int NumElts = VT.getVectorNumElements();
4320 SmallVector<int, 4> Mask(NumElts);
4322 for (int i = 0; i != NumElts; ++i) {
4323 int M0 = SV0->getMaskElt(i);
4324 int M1 = SV1->getMaskElt(i);
4326 // Determine if either index is pointing to a zero vector.
4327 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
4328 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
4330 // If one element is zero and the otherside is undef, keep undef.
4331 // This also handles the case that both are undef.
4332 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
4337 // Make sure only one of the elements is zero.
4338 if (M0Zero == M1Zero) {
4343 assert((M0 >= 0 || M1 >= 0) && "Undef index!");
4345 // We have a zero and non-zero element. If the non-zero came from
4346 // SV0 make the index a LHS index. If it came from SV1, make it
4347 // a RHS index. We need to mod by NumElts because we don't care
4348 // which operand it came from in the original shuffles.
4349 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
4353 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
4354 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
4356 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4358 std::swap(NewLHS, NewRHS);
4359 ShuffleVectorSDNode::commuteMask(Mask);
4360 LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
4364 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
4370 // fold (or c1, c2) -> c1|c2
4371 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4373 if (N0C && N1C && !N1C->isOpaque())
4374 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
4375 // canonicalize constant to RHS
4376 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
4377 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
4378 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
4379 // fold (or x, 0) -> x
4380 if (isNullConstant(N1))
4382 // fold (or x, -1) -> -1
4383 if (isAllOnesConstant(N1))
4386 if (SDValue NewSel = foldBinOpIntoSelect(N))
4389 // fold (or x, c) -> c iff (x & ~c) == 0
4390 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
4393 if (SDValue Combined = visitORLike(N0, N1, N))
4396 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
4397 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
4399 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
4403 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
4406 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
4407 // iff (c1 & c2) != 0.
4408 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) {
4409 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4410 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) {
4412 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1))
4414 ISD::AND, SDLoc(N), VT,
4415 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
4421 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
4422 if (N0.getOpcode() == N1.getOpcode())
4423 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4426 // See if this is some rotate idiom.
4427 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
4428 return SDValue(Rot, 0);
4430 if (SDValue Load = MatchLoadCombine(N))
4433 // Simplify the operands using demanded-bits information.
4434 if (SimplifyDemandedBits(SDValue(N, 0)))
4435 return SDValue(N, 0);
4440 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
4441 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
4442 if (Op.getOpcode() == ISD::AND) {
4443 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
4444 Mask = Op.getOperand(1);
4445 Op = Op.getOperand(0);
4451 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
4459 // Return true if we can prove that, whenever Neg and Pos are both in the
4460 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
4461 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
4463 // (or (shift1 X, Neg), (shift2 X, Pos))
4465 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
4466 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
4467 // to consider shift amounts with defined behavior.
4468 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
4469 // If EltSize is a power of 2 then:
4471 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
4472 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
4474 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
4475 // for the stronger condition:
4477 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
4479 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
4480 // we can just replace Neg with Neg' for the rest of the function.
4482 // In other cases we check for the even stronger condition:
4484 // Neg == EltSize - Pos [B]
4486 // for all Neg and Pos. Note that the (or ...) then invokes undefined
4487 // behavior if Pos == 0 (and consequently Neg == EltSize).
4489 // We could actually use [A] whenever EltSize is a power of 2, but the
4490 // only extra cases that it would match are those uninteresting ones
4491 // where Neg and Pos are never in range at the same time. E.g. for
4492 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
4493 // as well as (sub 32, Pos), but:
4495 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
4497 // always invokes undefined behavior for 32-bit X.
4499 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
4500 unsigned MaskLoBits = 0;
4501 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
4502 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
4503 if (NegC->getAPIntValue() == EltSize - 1) {
4504 Neg = Neg.getOperand(0);
4505 MaskLoBits = Log2_64(EltSize);
4510 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
4511 if (Neg.getOpcode() != ISD::SUB)
4513 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
4516 SDValue NegOp1 = Neg.getOperand(1);
4518 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
4519 // Pos'. The truncation is redundant for the purpose of the equality.
4520 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
4521 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4522 if (PosC->getAPIntValue() == EltSize - 1)
4523 Pos = Pos.getOperand(0);
4525 // The condition we need is now:
4527 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
4529 // If NegOp1 == Pos then we need:
4531 // EltSize & Mask == NegC & Mask
4533 // (because "x & Mask" is a truncation and distributes through subtraction).
4536 Width = NegC->getAPIntValue();
4538 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
4539 // Then the condition we want to prove becomes:
4541 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
4543 // which, again because "x & Mask" is a truncation, becomes:
4545 // NegC & Mask == (EltSize - PosC) & Mask
4546 // EltSize & Mask == (NegC + PosC) & Mask
4547 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
4548 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
4549 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
4555 // Now we just need to check that EltSize & Mask == Width & Mask.
4557 // EltSize & Mask is 0 since Mask is EltSize - 1.
4558 return Width.getLoBits(MaskLoBits) == 0;
4559 return Width == EltSize;
4562 // A subroutine of MatchRotate used once we have found an OR of two opposite
4563 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
4564 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
4565 // former being preferred if supported. InnerPos and InnerNeg are Pos and
4566 // Neg with outer conversions stripped away.
4567 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
4568 SDValue Neg, SDValue InnerPos,
4569 SDValue InnerNeg, unsigned PosOpcode,
4570 unsigned NegOpcode, const SDLoc &DL) {
4571 // fold (or (shl x, (*ext y)),
4572 // (srl x, (*ext (sub 32, y)))) ->
4573 // (rotl x, y) or (rotr x, (sub 32, y))
4575 // fold (or (shl x, (*ext (sub 32, y))),
4576 // (srl x, (*ext y))) ->
4577 // (rotr x, y) or (rotl x, (sub 32, y))
4578 EVT VT = Shifted.getValueType();
4579 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
4580 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
4581 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
4582 HasPos ? Pos : Neg).getNode();
4588 // if Left + Right == Sum (constant or constant splat vector)
4589 static bool sumMatchConstant(SDValue Left, SDValue Right, unsigned Sum,
4590 SelectionDAG &DAG, const SDLoc &DL) {
4591 EVT ShiftVT = Left.getValueType();
4592 if (ShiftVT != Right.getValueType()) return false;
4594 SDValue ShiftSum = DAG.FoldConstantArithmetic(ISD::ADD, DL, ShiftVT,
4595 Left.getNode(), Right.getNode());
4596 if (!ShiftSum) return false;
4598 ConstantSDNode *CSum = isConstOrConstSplat(ShiftSum);
4599 return CSum && CSum->getZExtValue() == Sum;
4602 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
4603 // idioms for rotate, and if the target supports rotation instructions, generate
4605 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
4606 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
4607 EVT VT = LHS.getValueType();
4608 if (!TLI.isTypeLegal(VT)) return nullptr;
4610 // The target must have at least one rotate flavor.
4611 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
4612 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
4613 if (!HasROTL && !HasROTR) return nullptr;
4615 // Match "(X shl/srl V1) & V2" where V2 may not be present.
4616 SDValue LHSShift; // The shift.
4617 SDValue LHSMask; // AND value if any.
4618 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
4619 return nullptr; // Not part of a rotate.
4621 SDValue RHSShift; // The shift.
4622 SDValue RHSMask; // AND value if any.
4623 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
4624 return nullptr; // Not part of a rotate.
4626 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
4627 return nullptr; // Not shifting the same value.
4629 if (LHSShift.getOpcode() == RHSShift.getOpcode())
4630 return nullptr; // Shifts must disagree.
4632 // Canonicalize shl to left side in a shl/srl pair.
4633 if (RHSShift.getOpcode() == ISD::SHL) {
4634 std::swap(LHS, RHS);
4635 std::swap(LHSShift, RHSShift);
4636 std::swap(LHSMask, RHSMask);
4639 unsigned EltSizeInBits = VT.getScalarSizeInBits();
4640 SDValue LHSShiftArg = LHSShift.getOperand(0);
4641 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4642 SDValue RHSShiftArg = RHSShift.getOperand(0);
4643 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4645 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4646 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4647 if (sumMatchConstant(LHSShiftAmt, RHSShiftAmt, EltSizeInBits, DAG, DL)) {
4648 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4649 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4651 // If there is an AND of either shifted operand, apply it to the result.
4652 if (LHSMask.getNode() || RHSMask.getNode()) {
4653 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
4654 SDValue Mask = AllOnes;
4656 if (LHSMask.getNode()) {
4657 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
4658 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4659 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
4661 if (RHSMask.getNode()) {
4662 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
4663 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4664 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
4667 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4670 return Rot.getNode();
4673 // If there is a mask here, and we have a variable shift, we can't be sure
4674 // that we're masking out the right stuff.
4675 if (LHSMask.getNode() || RHSMask.getNode())
4678 // If the shift amount is sign/zext/any-extended just peel it off.
4679 SDValue LExtOp0 = LHSShiftAmt;
4680 SDValue RExtOp0 = RHSShiftAmt;
4681 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4682 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4683 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4684 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4685 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4686 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4687 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4688 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4689 LExtOp0 = LHSShiftAmt.getOperand(0);
4690 RExtOp0 = RHSShiftAmt.getOperand(0);
4693 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4694 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4698 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4699 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4707 /// Represents known origin of an individual byte in load combine pattern. The
4708 /// value of the byte is either constant zero or comes from memory.
4709 struct ByteProvider {
4710 // For constant zero providers Load is set to nullptr. For memory providers
4711 // Load represents the node which loads the byte from memory.
4712 // ByteOffset is the offset of the byte in the value produced by the load.
4714 unsigned ByteOffset;
4716 ByteProvider() : Load(nullptr), ByteOffset(0) {}
4718 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
4719 return ByteProvider(Load, ByteOffset);
4721 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
4723 bool isConstantZero() const { return !Load; }
4724 bool isMemory() const { return Load; }
4726 bool operator==(const ByteProvider &Other) const {
4727 return Other.Load == Load && Other.ByteOffset == ByteOffset;
4731 ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
4732 : Load(Load), ByteOffset(ByteOffset) {}
4735 /// Recursively traverses the expression calculating the origin of the requested
4736 /// byte of the given value. Returns None if the provider can't be calculated.
4738 /// For all the values except the root of the expression verifies that the value
4739 /// has exactly one use and if it's not true return None. This way if the origin
4740 /// of the byte is returned it's guaranteed that the values which contribute to
4741 /// the byte are not used outside of this expression.
4743 /// Because the parts of the expression are not allowed to have more than one
4744 /// use this function iterates over trees, not DAGs. So it never visits the same
4745 /// node more than once.
4746 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
4748 bool Root = false) {
4749 // Typical i64 by i8 pattern requires recursion up to 8 calls depth
4753 if (!Root && !Op.hasOneUse())
4756 assert(Op.getValueType().isScalarInteger() && "can't handle other types");
4757 unsigned BitWidth = Op.getValueSizeInBits();
4758 if (BitWidth % 8 != 0)
4760 unsigned ByteWidth = BitWidth / 8;
4761 assert(Index < ByteWidth && "invalid index requested");
4764 switch (Op.getOpcode()) {
4766 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
4769 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
4773 if (LHS->isConstantZero())
4775 if (RHS->isConstantZero())
4780 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
4784 uint64_t BitShift = ShiftOp->getZExtValue();
4785 if (BitShift % 8 != 0)
4787 uint64_t ByteShift = BitShift / 8;
4789 return Index < ByteShift
4790 ? ByteProvider::getConstantZero()
4791 : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
4794 case ISD::ANY_EXTEND:
4795 case ISD::SIGN_EXTEND:
4796 case ISD::ZERO_EXTEND: {
4797 SDValue NarrowOp = Op->getOperand(0);
4798 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
4799 if (NarrowBitWidth % 8 != 0)
4801 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4803 if (Index >= NarrowByteWidth)
4804 return Op.getOpcode() == ISD::ZERO_EXTEND
4805 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4807 return calculateByteProvider(NarrowOp, Index, Depth + 1);
4810 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
4813 auto L = cast<LoadSDNode>(Op.getNode());
4814 if (L->isVolatile() || L->isIndexed())
4817 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
4818 if (NarrowBitWidth % 8 != 0)
4820 uint64_t NarrowByteWidth = NarrowBitWidth / 8;
4822 if (Index >= NarrowByteWidth)
4823 return L->getExtensionType() == ISD::ZEXTLOAD
4824 ? Optional<ByteProvider>(ByteProvider::getConstantZero())
4826 return ByteProvider::getMemory(L, Index);
4834 /// Match a pattern where a wide type scalar value is loaded by several narrow
4835 /// loads and combined by shifts and ors. Fold it into a single load or a load
4836 /// and a BSWAP if the targets supports it.
4838 /// Assuming little endian target:
4840 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
4842 /// i32 val = *((i32)a)
4845 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
4847 /// i32 val = BSWAP(*((i32)a))
4849 /// TODO: This rule matches complex patterns with OR node roots and doesn't
4850 /// interact well with the worklist mechanism. When a part of the pattern is
4851 /// updated (e.g. one of the loads) its direct users are put into the worklist,
4852 /// but the root node of the pattern which triggers the load combine is not
4853 /// necessarily a direct user of the changed node. For example, once the address
4854 /// of t28 load is reassociated load combine won't be triggered:
4855 /// t25: i32 = add t4, Constant:i32<2>
4856 /// t26: i64 = sign_extend t25
4857 /// t27: i64 = add t2, t26
4858 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
4859 /// t29: i32 = zero_extend t28
4860 /// t32: i32 = shl t29, Constant:i8<8>
4861 /// t33: i32 = or t23, t32
4862 /// As a possible fix visitLoad can check if the load can be a part of a load
4863 /// combine pattern and add corresponding OR roots to the worklist.
4864 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
4865 assert(N->getOpcode() == ISD::OR &&
4866 "Can only match load combining against OR nodes");
4868 // Handles simple types only
4869 EVT VT = N->getValueType(0);
4870 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
4872 unsigned ByteWidth = VT.getSizeInBits() / 8;
4874 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4875 // Before legalize we can introduce too wide illegal loads which will be later
4876 // split into legal sized loads. This enables us to combine i64 load by i8
4877 // patterns to a couple of i32 loads on 32 bit targets.
4878 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
4881 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
4882 unsigned BW, unsigned i) { return i; };
4883 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
4884 unsigned BW, unsigned i) { return BW - i - 1; };
4886 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
4887 auto MemoryByteOffset = [&] (ByteProvider P) {
4888 assert(P.isMemory() && "Must be a memory byte provider");
4889 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
4890 assert(LoadBitWidth % 8 == 0 &&
4891 "can only analyze providers for individual bytes not bit");
4892 unsigned LoadByteWidth = LoadBitWidth / 8;
4893 return IsBigEndianTarget
4894 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
4895 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
4898 Optional<BaseIndexOffset> Base;
4901 SmallSet<LoadSDNode *, 8> Loads;
4902 Optional<ByteProvider> FirstByteProvider;
4903 int64_t FirstOffset = INT64_MAX;
4905 // Check if all the bytes of the OR we are looking at are loaded from the same
4906 // base address. Collect bytes offsets from Base address in ByteOffsets.
4907 SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
4908 for (unsigned i = 0; i < ByteWidth; i++) {
4909 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
4910 if (!P || !P->isMemory()) // All the bytes must be loaded from memory
4913 LoadSDNode *L = P->Load;
4914 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
4915 "Must be enforced by calculateByteProvider");
4916 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
4918 // All loads must share the same chain
4919 SDValue LChain = L->getChain();
4922 else if (Chain != LChain)
4925 // Loads must share the same base address
4926 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
4927 int64_t ByteOffsetFromBase = 0;
4930 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
4933 // Calculate the offset of the current byte from the base address
4934 ByteOffsetFromBase += MemoryByteOffset(*P);
4935 ByteOffsets[i] = ByteOffsetFromBase;
4937 // Remember the first byte load
4938 if (ByteOffsetFromBase < FirstOffset) {
4939 FirstByteProvider = P;
4940 FirstOffset = ByteOffsetFromBase;
4945 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
4946 "memory, so there must be at least one load which produces the value");
4947 assert(Base && "Base address of the accessed memory location must be set");
4948 assert(FirstOffset != INT64_MAX && "First byte offset must be set");
4950 // Check if the bytes of the OR we are looking at match with either big or
4951 // little endian value load
4952 bool BigEndian = true, LittleEndian = true;
4953 for (unsigned i = 0; i < ByteWidth; i++) {
4954 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
4955 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
4956 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
4957 if (!BigEndian && !LittleEndian)
4960 assert((BigEndian != LittleEndian) && "should be either or");
4961 assert(FirstByteProvider && "must be set");
4963 // Ensure that the first byte is loaded from zero offset of the first load.
4964 // So the combined value can be loaded from the first load address.
4965 if (MemoryByteOffset(*FirstByteProvider) != 0)
4967 LoadSDNode *FirstLoad = FirstByteProvider->Load;
4969 // The node we are looking at matches with the pattern, check if we can
4970 // replace it with a single load and bswap if needed.
4972 // If the load needs byte swap check if the target supports it
4973 bool NeedsBswap = IsBigEndianTarget != BigEndian;
4975 // Before legalize we can introduce illegal bswaps which will be later
4976 // converted to an explicit bswap sequence. This way we end up with a single
4977 // load and byte shuffling instead of several loads and byte shuffling.
4978 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
4981 // Check that a load of the wide type is both allowed and fast on the target
4983 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
4984 VT, FirstLoad->getAddressSpace(),
4985 FirstLoad->getAlignment(), &Fast);
4986 if (!Allowed || !Fast)
4990 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
4991 FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
4993 // Transfer chain users from old loads to the new load.
4994 for (LoadSDNode *L : Loads)
4995 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
4997 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
5000 SDValue DAGCombiner::visitXOR(SDNode *N) {
5001 SDValue N0 = N->getOperand(0);
5002 SDValue N1 = N->getOperand(1);
5003 EVT VT = N0.getValueType();
5006 if (VT.isVector()) {
5007 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5010 // fold (xor x, 0) -> x, vector edition
5011 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5013 if (ISD::isBuildVectorAllZeros(N1.getNode()))
5017 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
5018 if (N0.isUndef() && N1.isUndef())
5019 return DAG.getConstant(0, SDLoc(N), VT);
5020 // fold (xor x, undef) -> undef
5025 // fold (xor c1, c2) -> c1^c2
5026 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5027 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
5029 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
5030 // canonicalize constant to RHS
5031 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
5032 !DAG.isConstantIntBuildVectorOrConstantInt(N1))
5033 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
5034 // fold (xor x, 0) -> x
5035 if (isNullConstant(N1))
5038 if (SDValue NewSel = foldBinOpIntoSelect(N))
5042 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
5045 // fold !(x cc y) -> (x !cc y)
5046 SDValue LHS, RHS, CC;
5047 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
5048 bool isInt = LHS.getValueType().isInteger();
5049 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
5052 if (!LegalOperations ||
5053 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
5054 switch (N0.getOpcode()) {
5056 llvm_unreachable("Unhandled SetCC Equivalent!");
5058 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
5059 case ISD::SELECT_CC:
5060 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
5061 N0.getOperand(3), NotCC);
5066 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
5067 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
5068 N0.getNode()->hasOneUse() &&
5069 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
5070 SDValue V = N0.getOperand(0);
5072 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
5073 DAG.getConstant(1, DL, V.getValueType()));
5074 AddToWorklist(V.getNode());
5075 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
5078 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
5079 if (isOneConstant(N1) && VT == MVT::i1 &&
5080 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5081 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5082 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
5083 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5084 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5085 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5086 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5087 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5090 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
5091 if (isAllOnesConstant(N1) &&
5092 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
5093 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5094 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
5095 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
5096 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
5097 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
5098 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
5099 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
5102 // fold (xor (and x, y), y) -> (and (not x), y)
5103 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
5104 N0->getOperand(1) == N1) {
5105 SDValue X = N0->getOperand(0);
5106 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
5107 AddToWorklist(NotX.getNode());
5108 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
5110 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
5111 if (N1C && N0.getOpcode() == ISD::XOR) {
5112 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
5114 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
5115 DAG.getConstant(N1C->getAPIntValue() ^
5116 N00C->getAPIntValue(), DL, VT));
5118 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
5120 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
5121 DAG.getConstant(N1C->getAPIntValue() ^
5122 N01C->getAPIntValue(), DL, VT));
5126 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
5127 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5128 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5129 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
5130 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
5131 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
5132 if (C->getAPIntValue() == (OpSizeInBits - 1))
5133 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
5136 // fold (xor x, x) -> 0
5138 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
5140 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
5141 // Here is a concrete example of this equivalence:
5143 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
5144 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
5148 // i16 ~1 == 0b1111111111111110
5149 // i16 rol(~1, 14) == 0b1011111111111111
5151 // Some additional tips to help conceptualize this transform:
5152 // - Try to see the operation as placing a single zero in a value of all ones.
5153 // - There exists no value for x which would allow the result to contain zero.
5154 // - Values of x larger than the bitwidth are undefined and do not require a
5155 // consistent result.
5156 // - Pushing the zero left requires shifting one bits in from the right.
5157 // A rotate left of ~1 is a nice way of achieving the desired result.
5158 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
5159 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
5161 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
5165 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
5166 if (N0.getOpcode() == N1.getOpcode())
5167 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
5170 // Simplify the expression using non-local knowledge.
5171 if (SimplifyDemandedBits(SDValue(N, 0)))
5172 return SDValue(N, 0);
5177 /// Handle transforms common to the three shifts, when the shift amount is a
5179 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
5180 SDNode *LHS = N->getOperand(0).getNode();
5181 if (!LHS->hasOneUse()) return SDValue();
5183 // We want to pull some binops through shifts, so that we have (and (shift))
5184 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
5185 // thing happens with address calculations, so it's important to canonicalize
5187 bool HighBitSet = false; // Can we transform this if the high bit is set?
5189 switch (LHS->getOpcode()) {
5190 default: return SDValue();
5193 HighBitSet = false; // We can only transform sra if the high bit is clear.
5196 HighBitSet = true; // We can only transform sra if the high bit is set.
5199 if (N->getOpcode() != ISD::SHL)
5200 return SDValue(); // only shl(add) not sr[al](add).
5201 HighBitSet = false; // We can only transform sra if the high bit is clear.
5205 // We require the RHS of the binop to be a constant and not opaque as well.
5206 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
5207 if (!BinOpCst) return SDValue();
5209 // FIXME: disable this unless the input to the binop is a shift by a constant
5210 // or is copy/select.Enable this in other cases when figure out it's exactly profitable.
5211 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
5212 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
5213 BinOpLHSVal->getOpcode() == ISD::SRA ||
5214 BinOpLHSVal->getOpcode() == ISD::SRL;
5215 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
5216 BinOpLHSVal->getOpcode() == ISD::SELECT;
5218 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
5222 if (isCopyOrSelect && N->hasOneUse())
5225 EVT VT = N->getValueType(0);
5227 // If this is a signed shift right, and the high bit is modified by the
5228 // logical operation, do not perform the transformation. The highBitSet
5229 // boolean indicates the value of the high bit of the constant which would
5230 // cause it to be modified for this operation.
5231 if (N->getOpcode() == ISD::SRA) {
5232 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
5233 if (BinOpRHSSignSet != HighBitSet)
5237 if (!TLI.isDesirableToCommuteWithShift(LHS))
5240 // Fold the constants, shifting the binop RHS by the shift amount.
5241 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
5243 LHS->getOperand(1), N->getOperand(1));
5244 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
5246 // Create the new shift.
5247 SDValue NewShift = DAG.getNode(N->getOpcode(),
5248 SDLoc(LHS->getOperand(0)),
5249 VT, LHS->getOperand(0), N->getOperand(1));
5251 // Create the new binop.
5252 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
5255 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
5256 assert(N->getOpcode() == ISD::TRUNCATE);
5257 assert(N->getOperand(0).getOpcode() == ISD::AND);
5259 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
5260 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
5261 SDValue N01 = N->getOperand(0).getOperand(1);
5262 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
5264 EVT TruncVT = N->getValueType(0);
5265 SDValue N00 = N->getOperand(0).getOperand(0);
5266 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
5267 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
5268 AddToWorklist(Trunc00.getNode());
5269 AddToWorklist(Trunc01.getNode());
5270 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
5277 SDValue DAGCombiner::visitRotate(SDNode *N) {
5279 SDValue N0 = N->getOperand(0);
5280 SDValue N1 = N->getOperand(1);
5281 EVT VT = N->getValueType(0);
5282 unsigned Bitsize = VT.getScalarSizeInBits();
5284 // fold (rot x, 0) -> x
5285 if (isNullConstantOrNullSplatConstant(N1))
5288 // fold (rot x, c) -> (rot x, c % BitSize)
5289 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) {
5290 if (Cst->getAPIntValue().uge(Bitsize)) {
5291 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize);
5292 return DAG.getNode(N->getOpcode(), dl, VT, N0,
5293 DAG.getConstant(RotAmt, dl, N1.getValueType()));
5297 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
5298 if (N1.getOpcode() == ISD::TRUNCATE &&
5299 N1.getOperand(0).getOpcode() == ISD::AND) {
5300 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5301 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
5304 unsigned NextOp = N0.getOpcode();
5305 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
5306 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
5307 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
5308 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
5309 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
5310 EVT ShiftVT = C1->getValueType(0);
5311 bool SameSide = (N->getOpcode() == NextOp);
5312 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
5313 if (SDValue CombinedShift =
5314 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) {
5315 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
5316 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
5317 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(),
5318 BitsizeC.getNode());
5319 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
5327 SDValue DAGCombiner::visitSHL(SDNode *N) {
5328 SDValue N0 = N->getOperand(0);
5329 SDValue N1 = N->getOperand(1);
5330 EVT VT = N0.getValueType();
5331 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5334 if (VT.isVector()) {
5335 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5338 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
5339 // If setcc produces all-one true value then:
5340 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
5341 if (N1CV && N1CV->isConstant()) {
5342 if (N0.getOpcode() == ISD::AND) {
5343 SDValue N00 = N0->getOperand(0);
5344 SDValue N01 = N0->getOperand(1);
5345 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
5347 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
5348 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
5349 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5350 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
5352 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
5358 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5360 // fold (shl c1, c2) -> c1<<c2
5361 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5362 if (N0C && N1C && !N1C->isOpaque())
5363 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
5364 // fold (shl 0, x) -> 0
5365 if (isNullConstantOrNullSplatConstant(N0))
5367 // fold (shl x, c >= size(x)) -> undef
5368 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5369 return DAG.getUNDEF(VT);
5370 // fold (shl x, 0) -> x
5371 if (N1C && N1C->isNullValue())
5373 // fold (shl undef, x) -> 0
5375 return DAG.getConstant(0, SDLoc(N), VT);
5377 if (SDValue NewSel = foldBinOpIntoSelect(N))
5380 // if (shl x, c) is known to be zero, return 0
5381 if (DAG.MaskedValueIsZero(SDValue(N, 0),
5382 APInt::getAllOnesValue(OpSizeInBits)))
5383 return DAG.getConstant(0, SDLoc(N), VT);
5384 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
5385 if (N1.getOpcode() == ISD::TRUNCATE &&
5386 N1.getOperand(0).getOpcode() == ISD::AND) {
5387 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5388 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
5391 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5392 return SDValue(N, 0);
5394 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
5395 if (N1C && N0.getOpcode() == ISD::SHL) {
5396 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5398 APInt c1 = N0C1->getAPIntValue();
5399 APInt c2 = N1C->getAPIntValue();
5400 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5402 APInt Sum = c1 + c2;
5403 if (Sum.uge(OpSizeInBits))
5404 return DAG.getConstant(0, DL, VT);
5407 ISD::SHL, DL, VT, N0.getOperand(0),
5408 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5412 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
5413 // For this to be valid, the second form must not preserve any of the bits
5414 // that are shifted out by the inner shift in the first form. This means
5415 // the outer shift size must be >= the number of bits added by the ext.
5416 // As a corollary, we don't care what kind of ext it is.
5417 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
5418 N0.getOpcode() == ISD::ANY_EXTEND ||
5419 N0.getOpcode() == ISD::SIGN_EXTEND) &&
5420 N0.getOperand(0).getOpcode() == ISD::SHL) {
5421 SDValue N0Op0 = N0.getOperand(0);
5422 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5423 APInt c1 = N0Op0C1->getAPIntValue();
5424 APInt c2 = N1C->getAPIntValue();
5425 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5427 EVT InnerShiftVT = N0Op0.getValueType();
5428 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5429 if (c2.uge(OpSizeInBits - InnerShiftSize)) {
5431 APInt Sum = c1 + c2;
5432 if (Sum.uge(OpSizeInBits))
5433 return DAG.getConstant(0, DL, VT);
5437 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
5438 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5443 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
5444 // Only fold this if the inner zext has no other uses to avoid increasing
5445 // the total number of instructions.
5446 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
5447 N0.getOperand(0).getOpcode() == ISD::SRL) {
5448 SDValue N0Op0 = N0.getOperand(0);
5449 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
5450 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
5451 uint64_t c1 = N0Op0C1->getZExtValue();
5452 uint64_t c2 = N1C->getZExtValue();
5454 SDValue NewOp0 = N0.getOperand(0);
5455 EVT CountVT = NewOp0.getOperand(1).getValueType();
5457 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
5459 DAG.getConstant(c2, DL, CountVT));
5460 AddToWorklist(NewSHL.getNode());
5461 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
5467 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
5468 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
5469 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
5470 N0->getFlags().hasExact()) {
5471 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5472 uint64_t C1 = N0C1->getZExtValue();
5473 uint64_t C2 = N1C->getZExtValue();
5476 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5477 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
5478 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
5479 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
5483 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
5484 // (and (srl x, (sub c1, c2), MASK)
5485 // Only fold this if the inner shift has no other uses -- if it does, folding
5486 // this will increase the total number of instructions.
5487 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5488 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5489 uint64_t c1 = N0C1->getZExtValue();
5490 if (c1 < OpSizeInBits) {
5491 uint64_t c2 = N1C->getZExtValue();
5492 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
5497 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
5498 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
5500 Mask.lshrInPlace(c1 - c2);
5502 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
5503 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
5506 return DAG.getNode(ISD::AND, DL, VT, Shift,
5507 DAG.getConstant(Mask, DL, VT));
5512 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
5513 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
5514 isConstantOrConstantVector(N1, /* No Opaques */ true)) {
5516 SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
5517 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
5518 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
5521 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
5522 // Variant of version done on multiply, except mul by a power of 2 is turned
5524 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
5525 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5526 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5527 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
5528 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5529 AddToWorklist(Shl0.getNode());
5530 AddToWorklist(Shl1.getNode());
5531 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
5534 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
5535 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
5536 isConstantOrConstantVector(N1, /* No Opaques */ true) &&
5537 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
5538 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
5539 if (isConstantOrConstantVector(Shl))
5540 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
5543 if (N1C && !N1C->isOpaque())
5544 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
5550 SDValue DAGCombiner::visitSRA(SDNode *N) {
5551 SDValue N0 = N->getOperand(0);
5552 SDValue N1 = N->getOperand(1);
5553 EVT VT = N0.getValueType();
5554 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5556 // Arithmetic shifting an all-sign-bit value is a no-op.
5557 // fold (sra 0, x) -> 0
5558 // fold (sra -1, x) -> -1
5559 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
5564 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5567 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5569 // fold (sra c1, c2) -> (sra c1, c2)
5570 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5571 if (N0C && N1C && !N1C->isOpaque())
5572 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
5573 // fold (sra x, c >= size(x)) -> undef
5574 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5575 return DAG.getUNDEF(VT);
5576 // fold (sra x, 0) -> x
5577 if (N1C && N1C->isNullValue())
5580 if (SDValue NewSel = foldBinOpIntoSelect(N))
5583 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
5585 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
5586 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
5587 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
5589 ExtVT = EVT::getVectorVT(*DAG.getContext(),
5590 ExtVT, VT.getVectorNumElements());
5591 if ((!LegalOperations ||
5592 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
5593 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5594 N0.getOperand(0), DAG.getValueType(ExtVT));
5597 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
5598 if (N1C && N0.getOpcode() == ISD::SRA) {
5599 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5601 APInt c1 = N0C1->getAPIntValue();
5602 APInt c2 = N1C->getAPIntValue();
5603 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5605 APInt Sum = c1 + c2;
5606 if (Sum.uge(OpSizeInBits))
5607 Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
5610 ISD::SRA, DL, VT, N0.getOperand(0),
5611 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5615 // fold (sra (shl X, m), (sub result_size, n))
5616 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
5617 // result_size - n != m.
5618 // If truncate is free for the target sext(shl) is likely to result in better
5620 if (N0.getOpcode() == ISD::SHL && N1C) {
5621 // Get the two constanst of the shifts, CN0 = m, CN = n.
5622 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
5624 LLVMContext &Ctx = *DAG.getContext();
5625 // Determine what the truncate's result bitsize and type would be.
5626 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
5629 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
5631 // Determine the residual right-shift amount.
5632 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
5634 // If the shift is not a no-op (in which case this should be just a sign
5635 // extend already), the truncated to type is legal, sign_extend is legal
5636 // on that type, and the truncate to that type is both legal and free,
5637 // perform the transform.
5638 if ((ShiftAmt > 0) &&
5639 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
5640 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
5641 TLI.isTruncateFree(VT, TruncVT)) {
5644 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
5645 getShiftAmountTy(N0.getOperand(0).getValueType()));
5646 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
5647 N0.getOperand(0), Amt);
5648 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
5650 return DAG.getNode(ISD::SIGN_EXTEND, DL,
5651 N->getValueType(0), Trunc);
5656 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
5657 if (N1.getOpcode() == ISD::TRUNCATE &&
5658 N1.getOperand(0).getOpcode() == ISD::AND) {
5659 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5660 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
5663 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
5664 // if c1 is equal to the number of bits the trunc removes
5665 if (N0.getOpcode() == ISD::TRUNCATE &&
5666 (N0.getOperand(0).getOpcode() == ISD::SRL ||
5667 N0.getOperand(0).getOpcode() == ISD::SRA) &&
5668 N0.getOperand(0).hasOneUse() &&
5669 N0.getOperand(0).getOperand(1).hasOneUse() &&
5671 SDValue N0Op0 = N0.getOperand(0);
5672 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
5673 unsigned LargeShiftVal = LargeShift->getZExtValue();
5674 EVT LargeVT = N0Op0.getValueType();
5676 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
5679 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
5680 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
5681 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
5682 N0Op0.getOperand(0), Amt);
5683 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
5688 // Simplify, based on bits shifted out of the LHS.
5689 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5690 return SDValue(N, 0);
5693 // If the sign bit is known to be zero, switch this to a SRL.
5694 if (DAG.SignBitIsZero(N0))
5695 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
5697 if (N1C && !N1C->isOpaque())
5698 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
5704 SDValue DAGCombiner::visitSRL(SDNode *N) {
5705 SDValue N0 = N->getOperand(0);
5706 SDValue N1 = N->getOperand(1);
5707 EVT VT = N0.getValueType();
5708 unsigned OpSizeInBits = VT.getScalarSizeInBits();
5712 if (SDValue FoldedVOp = SimplifyVBinOp(N))
5715 ConstantSDNode *N1C = isConstOrConstSplat(N1);
5717 // fold (srl c1, c2) -> c1 >>u c2
5718 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
5719 if (N0C && N1C && !N1C->isOpaque())
5720 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
5721 // fold (srl 0, x) -> 0
5722 if (isNullConstantOrNullSplatConstant(N0))
5724 // fold (srl x, c >= size(x)) -> undef
5725 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
5726 return DAG.getUNDEF(VT);
5727 // fold (srl x, 0) -> x
5728 if (N1C && N1C->isNullValue())
5731 if (SDValue NewSel = foldBinOpIntoSelect(N))
5734 // if (srl x, c) is known to be zero, return 0
5735 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
5736 APInt::getAllOnesValue(OpSizeInBits)))
5737 return DAG.getConstant(0, SDLoc(N), VT);
5739 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
5740 if (N1C && N0.getOpcode() == ISD::SRL) {
5741 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
5743 APInt c1 = N0C1->getAPIntValue();
5744 APInt c2 = N1C->getAPIntValue();
5745 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
5747 APInt Sum = c1 + c2;
5748 if (Sum.uge(OpSizeInBits))
5749 return DAG.getConstant(0, DL, VT);
5752 ISD::SRL, DL, VT, N0.getOperand(0),
5753 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
5757 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
5758 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
5759 N0.getOperand(0).getOpcode() == ISD::SRL) {
5760 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) {
5761 uint64_t c1 = N001C->getZExtValue();
5762 uint64_t c2 = N1C->getZExtValue();
5763 EVT InnerShiftVT = N0.getOperand(0).getValueType();
5764 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType();
5765 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
5766 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
5767 if (c1 + OpSizeInBits == InnerShiftSize) {
5769 if (c1 + c2 >= InnerShiftSize)
5770 return DAG.getConstant(0, DL, VT);
5771 return DAG.getNode(ISD::TRUNCATE, DL, VT,
5772 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
5773 N0.getOperand(0).getOperand(0),
5774 DAG.getConstant(c1 + c2, DL,
5780 // fold (srl (shl x, c), c) -> (and x, cst2)
5781 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
5782 isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
5785 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
5786 AddToWorklist(Mask.getNode());
5787 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
5790 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
5791 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
5792 // Shifting in all undef bits?
5793 EVT SmallVT = N0.getOperand(0).getValueType();
5794 unsigned BitSize = SmallVT.getScalarSizeInBits();
5795 if (N1C->getZExtValue() >= BitSize)
5796 return DAG.getUNDEF(VT);
5798 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
5799 uint64_t ShiftAmt = N1C->getZExtValue();
5801 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
5803 DAG.getConstant(ShiftAmt, DL0,
5804 getShiftAmountTy(SmallVT)));
5805 AddToWorklist(SmallShift.getNode());
5806 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
5808 return DAG.getNode(ISD::AND, DL, VT,
5809 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
5810 DAG.getConstant(Mask, DL, VT));
5814 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
5815 // bit, which is unmodified by sra.
5816 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
5817 if (N0.getOpcode() == ISD::SRA)
5818 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
5821 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
5822 if (N1C && N0.getOpcode() == ISD::CTLZ &&
5823 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
5825 DAG.computeKnownBits(N0.getOperand(0), Known);
5827 // If any of the input bits are KnownOne, then the input couldn't be all
5828 // zeros, thus the result of the srl will always be zero.
5829 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
5831 // If all of the bits input the to ctlz node are known to be zero, then
5832 // the result of the ctlz is "32" and the result of the shift is one.
5833 APInt UnknownBits = ~Known.Zero;
5834 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
5836 // Otherwise, check to see if there is exactly one bit input to the ctlz.
5837 if (UnknownBits.isPowerOf2()) {
5838 // Okay, we know that only that the single bit specified by UnknownBits
5839 // could be set on input to the CTLZ node. If this bit is set, the SRL
5840 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
5841 // to an SRL/XOR pair, which is likely to simplify more.
5842 unsigned ShAmt = UnknownBits.countTrailingZeros();
5843 SDValue Op = N0.getOperand(0);
5847 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5848 DAG.getConstant(ShAmt, DL,
5849 getShiftAmountTy(Op.getValueType())));
5850 AddToWorklist(Op.getNode());
5854 return DAG.getNode(ISD::XOR, DL, VT,
5855 Op, DAG.getConstant(1, DL, VT));
5859 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
5860 if (N1.getOpcode() == ISD::TRUNCATE &&
5861 N1.getOperand(0).getOpcode() == ISD::AND) {
5862 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
5863 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
5866 // fold operands of srl based on knowledge that the low bits are not
5868 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
5869 return SDValue(N, 0);
5871 if (N1C && !N1C->isOpaque())
5872 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
5875 // Attempt to convert a srl of a load into a narrower zero-extending load.
5876 if (SDValue NarrowLoad = ReduceLoadWidth(N))
5879 // Here is a common situation. We want to optimize:
5882 // %b = and i32 %a, 2
5883 // %c = srl i32 %b, 1
5884 // brcond i32 %c ...
5890 // %c = setcc eq %b, 0
5893 // However when after the source operand of SRL is optimized into AND, the SRL
5894 // itself may not be optimized further. Look for it and add the BRCOND into
5896 if (N->hasOneUse()) {
5897 SDNode *Use = *N->use_begin();
5898 if (Use->getOpcode() == ISD::BRCOND)
5900 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
5901 // Also look pass the truncate.
5902 Use = *Use->use_begin();
5903 if (Use->getOpcode() == ISD::BRCOND)
5911 SDValue DAGCombiner::visitABS(SDNode *N) {
5912 SDValue N0 = N->getOperand(0);
5913 EVT VT = N->getValueType(0);
5915 // fold (abs c1) -> c2
5916 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5917 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
5918 // fold (abs (abs x)) -> (abs x)
5919 if (N0.getOpcode() == ISD::ABS)
5921 // fold (abs x) -> x iff not-negative
5922 if (DAG.SignBitIsZero(N0))
5927 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
5928 SDValue N0 = N->getOperand(0);
5929 EVT VT = N->getValueType(0);
5931 // fold (bswap c1) -> c2
5932 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5933 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
5934 // fold (bswap (bswap x)) -> x
5935 if (N0.getOpcode() == ISD::BSWAP)
5936 return N0->getOperand(0);
5940 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
5941 SDValue N0 = N->getOperand(0);
5942 EVT VT = N->getValueType(0);
5944 // fold (bitreverse c1) -> c2
5945 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5946 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
5947 // fold (bitreverse (bitreverse x)) -> x
5948 if (N0.getOpcode() == ISD::BITREVERSE)
5949 return N0.getOperand(0);
5953 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
5954 SDValue N0 = N->getOperand(0);
5955 EVT VT = N->getValueType(0);
5957 // fold (ctlz c1) -> c2
5958 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5959 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
5963 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
5964 SDValue N0 = N->getOperand(0);
5965 EVT VT = N->getValueType(0);
5967 // fold (ctlz_zero_undef c1) -> c2
5968 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5969 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5973 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
5974 SDValue N0 = N->getOperand(0);
5975 EVT VT = N->getValueType(0);
5977 // fold (cttz c1) -> c2
5978 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5979 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
5983 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
5984 SDValue N0 = N->getOperand(0);
5985 EVT VT = N->getValueType(0);
5987 // fold (cttz_zero_undef c1) -> c2
5988 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5989 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
5993 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
5994 SDValue N0 = N->getOperand(0);
5995 EVT VT = N->getValueType(0);
5997 // fold (ctpop c1) -> c2
5998 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
5999 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
6004 /// \brief Generate Min/Max node
6005 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
6006 SDValue RHS, SDValue True, SDValue False,
6007 ISD::CondCode CC, const TargetLowering &TLI,
6008 SelectionDAG &DAG) {
6009 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
6019 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
6020 if (TLI.isOperationLegal(Opcode, VT))
6021 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6030 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
6031 if (TLI.isOperationLegal(Opcode, VT))
6032 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6040 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
6041 SDValue Cond = N->getOperand(0);
6042 SDValue N1 = N->getOperand(1);
6043 SDValue N2 = N->getOperand(2);
6044 EVT VT = N->getValueType(0);
6045 EVT CondVT = Cond.getValueType();
6048 if (!VT.isInteger())
6051 auto *C1 = dyn_cast<ConstantSDNode>(N1);
6052 auto *C2 = dyn_cast<ConstantSDNode>(N2);
6056 // Only do this before legalization to avoid conflicting with target-specific
6057 // transforms in the other direction (create a select from a zext/sext). There
6058 // is also a target-independent combine here in DAGCombiner in the other
6059 // direction for (select Cond, -1, 0) when the condition is not i1.
6060 if (CondVT == MVT::i1 && !LegalOperations) {
6061 if (C1->isNullValue() && C2->isOne()) {
6062 // select Cond, 0, 1 --> zext (!Cond)
6063 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6065 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
6068 if (C1->isNullValue() && C2->isAllOnesValue()) {
6069 // select Cond, 0, -1 --> sext (!Cond)
6070 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
6072 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
6075 if (C1->isOne() && C2->isNullValue()) {
6076 // select Cond, 1, 0 --> zext (Cond)
6078 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6081 if (C1->isAllOnesValue() && C2->isNullValue()) {
6082 // select Cond, -1, 0 --> sext (Cond)
6084 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6088 // For any constants that differ by 1, we can transform the select into an
6089 // extend and add. Use a target hook because some targets may prefer to
6090 // transform in the other direction.
6091 if (TLI.convertSelectOfConstantsToMath()) {
6092 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
6093 // select Cond, C1, C1-1 --> add (zext Cond), C1-1
6095 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
6096 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6098 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
6099 // select Cond, C1, C1+1 --> add (sext Cond), C1+1
6101 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
6102 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
6109 // fold (select Cond, 0, 1) -> (xor Cond, 1)
6110 // We can't do this reliably if integer based booleans have different contents
6111 // to floating point based booleans. This is because we can't tell whether we
6112 // have an integer-based boolean or a floating-point-based boolean unless we
6113 // can find the SETCC that produced it and inspect its operands. This is
6114 // fairly easy if C is the SETCC node, but it can potentially be
6115 // undiscoverable (or not reasonably discoverable). For example, it could be
6116 // in another basic block or it could require searching a complicated
6118 if (CondVT.isInteger() &&
6119 TLI.getBooleanContents(false, true) ==
6120 TargetLowering::ZeroOrOneBooleanContent &&
6121 TLI.getBooleanContents(false, false) ==
6122 TargetLowering::ZeroOrOneBooleanContent &&
6123 C1->isNullValue() && C2->isOne()) {
6125 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
6126 if (VT.bitsEq(CondVT))
6128 return DAG.getZExtOrTrunc(NotCond, DL, VT);
6134 SDValue DAGCombiner::visitSELECT(SDNode *N) {
6135 SDValue N0 = N->getOperand(0);
6136 SDValue N1 = N->getOperand(1);
6137 SDValue N2 = N->getOperand(2);
6138 EVT VT = N->getValueType(0);
6139 EVT VT0 = N0.getValueType();
6142 // fold (select C, X, X) -> X
6146 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
6147 // fold (select true, X, Y) -> X
6148 // fold (select false, X, Y) -> Y
6149 return !N0C->isNullValue() ? N1 : N2;
6152 // fold (select X, X, Y) -> (or X, Y)
6153 // fold (select X, 1, Y) -> (or C, Y)
6154 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
6155 return DAG.getNode(ISD::OR, DL, VT, N0, N2);
6157 if (SDValue V = foldSelectOfConstants(N))
6160 // fold (select C, 0, X) -> (and (not C), X)
6161 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
6162 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6163 AddToWorklist(NOTNode.getNode());
6164 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2);
6166 // fold (select C, X, 1) -> (or (not C), X)
6167 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
6168 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
6169 AddToWorklist(NOTNode.getNode());
6170 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1);
6172 // fold (select X, Y, X) -> (and X, Y)
6173 // fold (select X, Y, 0) -> (and X, Y)
6174 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
6175 return DAG.getNode(ISD::AND, DL, VT, N0, N1);
6177 // If we can fold this based on the true/false value, do so.
6178 if (SimplifySelectOps(N, N1, N2))
6179 return SDValue(N, 0); // Don't revisit N.
6181 if (VT0 == MVT::i1) {
6182 // The code in this block deals with the following 2 equivalences:
6183 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
6184 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
6185 // The target can specify its preferred form with the
6186 // shouldNormalizeToSelectSequence() callback. However we always transform
6187 // to the right anyway if we find the inner select exists in the DAG anyway
6188 // and we always transform to the left side if we know that we can further
6189 // optimize the combination of the conditions.
6190 bool normalizeToSequence =
6191 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
6192 // select (and Cond0, Cond1), X, Y
6193 // -> select Cond0, (select Cond1, X, Y), Y
6194 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
6195 SDValue Cond0 = N0->getOperand(0);
6196 SDValue Cond1 = N0->getOperand(1);
6197 SDValue InnerSelect =
6198 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6199 if (normalizeToSequence || !InnerSelect.use_empty())
6200 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
6203 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
6204 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
6205 SDValue Cond0 = N0->getOperand(0);
6206 SDValue Cond1 = N0->getOperand(1);
6207 SDValue InnerSelect =
6208 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2);
6209 if (normalizeToSequence || !InnerSelect.use_empty())
6210 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
6214 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
6215 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
6216 SDValue N1_0 = N1->getOperand(0);
6217 SDValue N1_1 = N1->getOperand(1);
6218 SDValue N1_2 = N1->getOperand(2);
6219 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
6220 // Create the actual and node if we can generate good code for it.
6221 if (!normalizeToSequence) {
6222 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
6223 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2);
6225 // Otherwise see if we can optimize the "and" to a better pattern.
6226 if (SDValue Combined = visitANDLike(N0, N1_0, N))
6227 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
6231 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
6232 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
6233 SDValue N2_0 = N2->getOperand(0);
6234 SDValue N2_1 = N2->getOperand(1);
6235 SDValue N2_2 = N2->getOperand(2);
6236 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
6237 // Create the actual or node if we can generate good code for it.
6238 if (!normalizeToSequence) {
6239 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
6240 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2);
6242 // Otherwise see if we can optimize to a better pattern.
6243 if (SDValue Combined = visitORLike(N0, N2_0, N))
6244 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
6250 // select (xor Cond, 1), X, Y -> select Cond, Y, X
6251 if (VT0 == MVT::i1) {
6252 if (N0->getOpcode() == ISD::XOR) {
6253 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
6254 SDValue Cond0 = N0->getOperand(0);
6256 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N2, N1);
6261 // fold selects based on a setcc into other things, such as min/max/abs
6262 if (N0.getOpcode() == ISD::SETCC) {
6263 // select x, y (fcmp lt x, y) -> fminnum x, y
6264 // select x, y (fcmp gt x, y) -> fmaxnum x, y
6266 // This is OK if we don't care about what happens if either operand is a
6270 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
6271 // no signed zeros as well as no nans.
6272 const TargetOptions &Options = DAG.getTarget().Options;
6273 if (Options.UnsafeFPMath && VT.isFloatingPoint() && N0.hasOneUse() &&
6274 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
6275 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6277 if (SDValue FMinMax = combineMinNumMaxNum(
6278 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG))
6282 if ((!LegalOperations &&
6283 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
6284 TLI.isOperationLegal(ISD::SELECT_CC, VT))
6285 return DAG.getNode(ISD::SELECT_CC, DL, VT, N0.getOperand(0),
6286 N0.getOperand(1), N1, N2, N0.getOperand(2));
6287 return SimplifySelect(DL, N0, N1, N2);
6294 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
6297 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
6299 // Split the inputs.
6300 SDValue Lo, Hi, LL, LH, RL, RH;
6301 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
6302 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
6304 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
6305 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
6307 return std::make_pair(Lo, Hi);
6310 // This function assumes all the vselect's arguments are CONCAT_VECTOR
6311 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
6312 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
6314 SDValue Cond = N->getOperand(0);
6315 SDValue LHS = N->getOperand(1);
6316 SDValue RHS = N->getOperand(2);
6317 EVT VT = N->getValueType(0);
6318 int NumElems = VT.getVectorNumElements();
6319 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
6320 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
6321 Cond.getOpcode() == ISD::BUILD_VECTOR);
6323 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
6324 // binary ones here.
6325 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
6328 // We're sure we have an even number of elements due to the
6329 // concat_vectors we have as arguments to vselect.
6330 // Skip BV elements until we find one that's not an UNDEF
6331 // After we find an UNDEF element, keep looping until we get to half the
6332 // length of the BV and see if all the non-undef nodes are the same.
6333 ConstantSDNode *BottomHalf = nullptr;
6334 for (int i = 0; i < NumElems / 2; ++i) {
6335 if (Cond->getOperand(i)->isUndef())
6338 if (BottomHalf == nullptr)
6339 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6340 else if (Cond->getOperand(i).getNode() != BottomHalf)
6344 // Do the same for the second half of the BuildVector
6345 ConstantSDNode *TopHalf = nullptr;
6346 for (int i = NumElems / 2; i < NumElems; ++i) {
6347 if (Cond->getOperand(i)->isUndef())
6350 if (TopHalf == nullptr)
6351 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
6352 else if (Cond->getOperand(i).getNode() != TopHalf)
6356 assert(TopHalf && BottomHalf &&
6357 "One half of the selector was all UNDEFs and the other was all the "
6358 "same value. This should have been addressed before this function.");
6360 ISD::CONCAT_VECTORS, DL, VT,
6361 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
6362 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
6365 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
6367 if (Level >= AfterLegalizeTypes)
6370 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
6371 SDValue Mask = MSC->getMask();
6372 SDValue Data = MSC->getValue();
6375 // If the MSCATTER data type requires splitting and the mask is provided by a
6376 // SETCC, then split both nodes and its operands before legalization. This
6377 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6378 // and enables future optimizations (e.g. min/max pattern matching on X86).
6379 if (Mask.getOpcode() != ISD::SETCC)
6382 // Check if any splitting is required.
6383 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
6384 TargetLowering::TypeSplitVector)
6386 SDValue MaskLo, MaskHi, Lo, Hi;
6387 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
6392 SDValue Chain = MSC->getChain();
6394 EVT MemoryVT = MSC->getMemoryVT();
6395 unsigned Alignment = MSC->getOriginalAlignment();
6397 EVT LoMemVT, HiMemVT;
6398 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6400 SDValue DataLo, DataHi;
6401 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6403 SDValue BasePtr = MSC->getBasePtr();
6404 SDValue IndexLo, IndexHi;
6405 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
6407 MachineMemOperand *MMO = DAG.getMachineFunction().
6408 getMachineMemOperand(MSC->getPointerInfo(),
6409 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6410 Alignment, MSC->getAAInfo(), MSC->getRanges());
6412 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
6413 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
6416 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
6417 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
6420 AddToWorklist(Lo.getNode());
6421 AddToWorklist(Hi.getNode());
6423 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6426 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
6428 if (Level >= AfterLegalizeTypes)
6431 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
6432 SDValue Mask = MST->getMask();
6433 SDValue Data = MST->getValue();
6434 EVT VT = Data.getValueType();
6437 // If the MSTORE data type requires splitting and the mask is provided by a
6438 // SETCC, then split both nodes and its operands before legalization. This
6439 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6440 // and enables future optimizations (e.g. min/max pattern matching on X86).
6441 if (Mask.getOpcode() == ISD::SETCC) {
6443 // Check if any splitting is required.
6444 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6445 TargetLowering::TypeSplitVector)
6448 SDValue MaskLo, MaskHi, Lo, Hi;
6449 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6451 SDValue Chain = MST->getChain();
6452 SDValue Ptr = MST->getBasePtr();
6454 EVT MemoryVT = MST->getMemoryVT();
6455 unsigned Alignment = MST->getOriginalAlignment();
6457 // if Alignment is equal to the vector size,
6458 // take the half of it for the second part
6459 unsigned SecondHalfAlignment =
6460 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
6462 EVT LoMemVT, HiMemVT;
6463 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6465 SDValue DataLo, DataHi;
6466 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
6468 MachineMemOperand *MMO = DAG.getMachineFunction().
6469 getMachineMemOperand(MST->getPointerInfo(),
6470 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
6471 Alignment, MST->getAAInfo(), MST->getRanges());
6473 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
6474 MST->isTruncatingStore(),
6475 MST->isCompressingStore());
6477 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6478 MST->isCompressingStore());
6480 MMO = DAG.getMachineFunction().
6481 getMachineMemOperand(MST->getPointerInfo(),
6482 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
6483 SecondHalfAlignment, MST->getAAInfo(),
6486 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
6487 MST->isTruncatingStore(),
6488 MST->isCompressingStore());
6490 AddToWorklist(Lo.getNode());
6491 AddToWorklist(Hi.getNode());
6493 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
6498 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
6500 if (Level >= AfterLegalizeTypes)
6503 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
6504 SDValue Mask = MGT->getMask();
6507 // If the MGATHER result requires splitting and the mask is provided by a
6508 // SETCC, then split both nodes and its operands before legalization. This
6509 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6510 // and enables future optimizations (e.g. min/max pattern matching on X86).
6512 if (Mask.getOpcode() != ISD::SETCC)
6515 EVT VT = N->getValueType(0);
6517 // Check if any splitting is required.
6518 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6519 TargetLowering::TypeSplitVector)
6522 SDValue MaskLo, MaskHi, Lo, Hi;
6523 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6525 SDValue Src0 = MGT->getValue();
6526 SDValue Src0Lo, Src0Hi;
6527 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6530 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6532 SDValue Chain = MGT->getChain();
6533 EVT MemoryVT = MGT->getMemoryVT();
6534 unsigned Alignment = MGT->getOriginalAlignment();
6536 EVT LoMemVT, HiMemVT;
6537 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6539 SDValue BasePtr = MGT->getBasePtr();
6540 SDValue Index = MGT->getIndex();
6541 SDValue IndexLo, IndexHi;
6542 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
6544 MachineMemOperand *MMO = DAG.getMachineFunction().
6545 getMachineMemOperand(MGT->getPointerInfo(),
6546 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6547 Alignment, MGT->getAAInfo(), MGT->getRanges());
6549 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
6550 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
6553 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
6554 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
6557 AddToWorklist(Lo.getNode());
6558 AddToWorklist(Hi.getNode());
6560 // Build a factor node to remember that this load is independent of the
6562 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6565 // Legalized the chain result - switch anything that used the old chain to
6567 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
6569 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6571 SDValue RetOps[] = { GatherRes, Chain };
6572 return DAG.getMergeValues(RetOps, DL);
6575 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
6577 if (Level >= AfterLegalizeTypes)
6580 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
6581 SDValue Mask = MLD->getMask();
6584 // If the MLOAD result requires splitting and the mask is provided by a
6585 // SETCC, then split both nodes and its operands before legalization. This
6586 // prevents the type legalizer from unrolling SETCC into scalar comparisons
6587 // and enables future optimizations (e.g. min/max pattern matching on X86).
6589 if (Mask.getOpcode() == ISD::SETCC) {
6590 EVT VT = N->getValueType(0);
6592 // Check if any splitting is required.
6593 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
6594 TargetLowering::TypeSplitVector)
6597 SDValue MaskLo, MaskHi, Lo, Hi;
6598 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
6600 SDValue Src0 = MLD->getSrc0();
6601 SDValue Src0Lo, Src0Hi;
6602 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
6605 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
6607 SDValue Chain = MLD->getChain();
6608 SDValue Ptr = MLD->getBasePtr();
6609 EVT MemoryVT = MLD->getMemoryVT();
6610 unsigned Alignment = MLD->getOriginalAlignment();
6612 // if Alignment is equal to the vector size,
6613 // take the half of it for the second part
6614 unsigned SecondHalfAlignment =
6615 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
6616 Alignment/2 : Alignment;
6618 EVT LoMemVT, HiMemVT;
6619 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
6621 MachineMemOperand *MMO = DAG.getMachineFunction().
6622 getMachineMemOperand(MLD->getPointerInfo(),
6623 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
6624 Alignment, MLD->getAAInfo(), MLD->getRanges());
6626 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
6627 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6629 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
6630 MLD->isExpandingLoad());
6632 MMO = DAG.getMachineFunction().
6633 getMachineMemOperand(MLD->getPointerInfo(),
6634 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
6635 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
6637 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
6638 ISD::NON_EXTLOAD, MLD->isExpandingLoad());
6640 AddToWorklist(Lo.getNode());
6641 AddToWorklist(Hi.getNode());
6643 // Build a factor node to remember that this load is independent of the
6645 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
6648 // Legalized the chain result - switch anything that used the old chain to
6650 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
6652 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
6654 SDValue RetOps[] = { LoadRes, Chain };
6655 return DAG.getMergeValues(RetOps, DL);
6660 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 SDValue N1 = N->getOperand(1);
6663 SDValue N2 = N->getOperand(2);
6666 // fold (vselect C, X, X) -> X
6670 // Canonicalize integer abs.
6671 // vselect (setg[te] X, 0), X, -X ->
6672 // vselect (setgt X, -1), X, -X ->
6673 // vselect (setl[te] X, 0), -X, X ->
6674 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6675 if (N0.getOpcode() == ISD::SETCC) {
6676 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
6677 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6679 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
6681 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6682 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
6683 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
6684 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
6685 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
6686 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
6687 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
6690 EVT VT = LHS.getValueType();
6691 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
6692 return DAG.getNode(ISD::ABS, DL, VT, LHS);
6694 SDValue Shift = DAG.getNode(
6695 ISD::SRA, DL, VT, LHS,
6696 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
6697 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
6698 AddToWorklist(Shift.getNode());
6699 AddToWorklist(Add.getNode());
6700 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
6704 if (SimplifySelectOps(N, N1, N2))
6705 return SDValue(N, 0); // Don't revisit N.
6707 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
6708 if (ISD::isBuildVectorAllOnes(N0.getNode()))
6710 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
6711 if (ISD::isBuildVectorAllZeros(N0.getNode()))
6714 // The ConvertSelectToConcatVector function is assuming both the above
6715 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
6717 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
6718 N2.getOpcode() == ISD::CONCAT_VECTORS &&
6719 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6720 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
6727 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
6728 SDValue N0 = N->getOperand(0);
6729 SDValue N1 = N->getOperand(1);
6730 SDValue N2 = N->getOperand(2);
6731 SDValue N3 = N->getOperand(3);
6732 SDValue N4 = N->getOperand(4);
6733 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
6735 // fold select_cc lhs, rhs, x, x, cc -> x
6739 // Determine if the condition we're dealing with is constant
6740 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
6741 CC, SDLoc(N), false)) {
6742 AddToWorklist(SCC.getNode());
6744 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
6745 if (!SCCC->isNullValue())
6746 return N2; // cond always true -> true val
6748 return N3; // cond always false -> false val
6749 } else if (SCC->isUndef()) {
6750 // When the condition is UNDEF, just return the first operand. This is
6751 // coherent the DAG creation, no setcc node is created in this case
6753 } else if (SCC.getOpcode() == ISD::SETCC) {
6754 // Fold to a simpler select_cc
6755 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
6756 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
6761 // If we can fold this based on the true/false value, do so.
6762 if (SimplifySelectOps(N, N2, N3))
6763 return SDValue(N, 0); // Don't revisit N.
6765 // fold select_cc into other things, such as min/max/abs
6766 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
6769 SDValue DAGCombiner::visitSETCC(SDNode *N) {
6770 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
6771 cast<CondCodeSDNode>(N->getOperand(2))->get(),
6775 SDValue DAGCombiner::visitSETCCE(SDNode *N) {
6776 SDValue LHS = N->getOperand(0);
6777 SDValue RHS = N->getOperand(1);
6778 SDValue Carry = N->getOperand(2);
6779 SDValue Cond = N->getOperand(3);
6781 // If Carry is false, fold to a regular SETCC.
6782 if (Carry.getOpcode() == ISD::CARRY_FALSE)
6783 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6788 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
6789 SDValue LHS = N->getOperand(0);
6790 SDValue RHS = N->getOperand(1);
6791 SDValue Carry = N->getOperand(2);
6792 SDValue Cond = N->getOperand(3);
6794 // If Carry is false, fold to a regular SETCC.
6795 if (isNullConstant(Carry))
6796 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
6801 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
6802 /// a build_vector of constants.
6803 /// This function is called by the DAGCombiner when visiting sext/zext/aext
6804 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
6805 /// Vector extends are not folded if operations are legal; this is to
6806 /// avoid introducing illegal build_vector dag nodes.
6807 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
6808 SelectionDAG &DAG, bool LegalTypes,
6809 bool LegalOperations) {
6810 unsigned Opcode = N->getOpcode();
6811 SDValue N0 = N->getOperand(0);
6812 EVT VT = N->getValueType(0);
6814 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
6815 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
6816 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
6817 && "Expected EXTEND dag node in input!");
6819 // fold (sext c1) -> c1
6820 // fold (zext c1) -> c1
6821 // fold (aext c1) -> c1
6822 if (isa<ConstantSDNode>(N0))
6823 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
6825 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
6826 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
6827 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
6828 EVT SVT = VT.getScalarType();
6829 if (!(VT.isVector() &&
6830 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
6831 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
6834 // We can fold this node into a build_vector.
6835 unsigned VTBits = SVT.getSizeInBits();
6836 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
6837 SmallVector<SDValue, 8> Elts;
6838 unsigned NumElts = VT.getVectorNumElements();
6841 for (unsigned i=0; i != NumElts; ++i) {
6842 SDValue Op = N0->getOperand(i);
6843 if (Op->isUndef()) {
6844 Elts.push_back(DAG.getUNDEF(SVT));
6849 // Get the constant value and if needed trunc it to the size of the type.
6850 // Nodes like build_vector might have constants wider than the scalar type.
6851 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
6852 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
6853 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
6855 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
6858 return DAG.getBuildVector(VT, DL, Elts).getNode();
6861 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
6862 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
6863 // transformation. Returns true if extension are possible and the above
6864 // mentioned transformation is profitable.
6865 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
6867 SmallVectorImpl<SDNode *> &ExtendNodes,
6868 const TargetLowering &TLI) {
6869 bool HasCopyToRegUses = false;
6870 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
6871 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
6872 UE = N0.getNode()->use_end();
6877 if (UI.getUse().getResNo() != N0.getResNo())
6879 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
6880 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
6881 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
6882 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
6883 // Sign bits will be lost after a zext.
6886 for (unsigned i = 0; i != 2; ++i) {
6887 SDValue UseOp = User->getOperand(i);
6890 if (!isa<ConstantSDNode>(UseOp))
6895 ExtendNodes.push_back(User);
6898 // If truncates aren't free and there are users we can't
6899 // extend, it isn't worthwhile.
6902 // Remember if this value is live-out.
6903 if (User->getOpcode() == ISD::CopyToReg)
6904 HasCopyToRegUses = true;
6907 if (HasCopyToRegUses) {
6908 bool BothLiveOut = false;
6909 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6911 SDUse &Use = UI.getUse();
6912 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
6918 // Both unextended and extended values are live out. There had better be
6919 // a good reason for the transformation.
6920 return ExtendNodes.size();
6925 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
6926 SDValue Trunc, SDValue ExtLoad,
6927 const SDLoc &DL, ISD::NodeType ExtType) {
6928 // Extend SetCC uses if necessary.
6929 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
6930 SDNode *SetCC = SetCCs[i];
6931 SmallVector<SDValue, 4> Ops;
6933 for (unsigned j = 0; j != 2; ++j) {
6934 SDValue SOp = SetCC->getOperand(j);
6936 Ops.push_back(ExtLoad);
6938 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
6941 Ops.push_back(SetCC->getOperand(2));
6942 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
6946 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
6947 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
6948 SDValue N0 = N->getOperand(0);
6949 EVT DstVT = N->getValueType(0);
6950 EVT SrcVT = N0.getValueType();
6952 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
6953 N->getOpcode() == ISD::ZERO_EXTEND) &&
6954 "Unexpected node type (not an extend)!");
6956 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
6957 // For example, on a target with legal v4i32, but illegal v8i32, turn:
6958 // (v8i32 (sext (v8i16 (load x))))
6960 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6961 // (v4i32 (sextload (x + 16)))))
6962 // Where uses of the original load, i.e.:
6964 // are replaced with:
6966 // (v8i32 (concat_vectors (v4i32 (sextload x)),
6967 // (v4i32 (sextload (x + 16)))))))
6969 // This combine is only applicable to illegal, but splittable, vectors.
6970 // All legal types, and illegal non-vector types, are handled elsewhere.
6971 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
6973 if (N0->getOpcode() != ISD::LOAD)
6976 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6978 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
6979 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
6980 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
6983 SmallVector<SDNode *, 4> SetCCs;
6984 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
6987 ISD::LoadExtType ExtType =
6988 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
6990 // Try to split the vector types to get down to legal types.
6991 EVT SplitSrcVT = SrcVT;
6992 EVT SplitDstVT = DstVT;
6993 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
6994 SplitSrcVT.getVectorNumElements() > 1) {
6995 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
6996 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
6999 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
7003 const unsigned NumSplits =
7004 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
7005 const unsigned Stride = SplitSrcVT.getStoreSize();
7006 SmallVector<SDValue, 4> Loads;
7007 SmallVector<SDValue, 4> Chains;
7009 SDValue BasePtr = LN0->getBasePtr();
7010 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
7011 const unsigned Offset = Idx * Stride;
7012 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
7014 SDValue SplitLoad = DAG.getExtLoad(
7015 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
7016 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
7017 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
7019 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7020 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
7022 Loads.push_back(SplitLoad.getValue(0));
7023 Chains.push_back(SplitLoad.getValue(1));
7026 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
7027 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
7030 AddToWorklist(NewChain.getNode());
7032 CombineTo(N, NewValue);
7034 // Replace uses of the original load (before extension)
7035 // with a truncate of the concatenated sextloaded vectors.
7037 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
7038 CombineTo(N0.getNode(), Trunc, NewChain);
7039 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
7040 (ISD::NodeType)N->getOpcode());
7041 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7044 /// If we're narrowing or widening the result of a vector select and the final
7045 /// size is the same size as a setcc (compare) feeding the select, then try to
7046 /// apply the cast operation to the select's operands because matching vector
7047 /// sizes for a select condition and other operands should be more efficient.
7048 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
7049 unsigned CastOpcode = Cast->getOpcode();
7050 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
7051 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
7052 CastOpcode == ISD::FP_ROUND) &&
7053 "Unexpected opcode for vector select narrowing/widening");
7055 // We only do this transform before legal ops because the pattern may be
7056 // obfuscated by target-specific operations after legalization. Do not create
7057 // an illegal select op, however, because that may be difficult to lower.
7058 EVT VT = Cast->getValueType(0);
7059 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
7062 SDValue VSel = Cast->getOperand(0);
7063 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
7064 VSel.getOperand(0).getOpcode() != ISD::SETCC)
7067 // Does the setcc have the same vector size as the casted select?
7068 SDValue SetCC = VSel.getOperand(0);
7069 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
7070 if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
7073 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
7074 SDValue A = VSel.getOperand(1);
7075 SDValue B = VSel.getOperand(2);
7076 SDValue CastA, CastB;
7078 if (CastOpcode == ISD::FP_ROUND) {
7079 // FP_ROUND (fptrunc) has an extra flag operand to pass along.
7080 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
7081 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
7083 CastA = DAG.getNode(CastOpcode, DL, VT, A);
7084 CastB = DAG.getNode(CastOpcode, DL, VT, B);
7086 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
7089 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
7090 SDValue N0 = N->getOperand(0);
7091 EVT VT = N->getValueType(0);
7094 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7096 return SDValue(Res, 0);
7098 // fold (sext (sext x)) -> (sext x)
7099 // fold (sext (aext x)) -> (sext x)
7100 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7101 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
7103 if (N0.getOpcode() == ISD::TRUNCATE) {
7104 // fold (sext (truncate (load x))) -> (sext (smaller load x))
7105 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
7106 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7107 SDNode *oye = N0.getOperand(0).getNode();
7108 if (NarrowLoad.getNode() != N0.getNode()) {
7109 CombineTo(N0.getNode(), NarrowLoad);
7110 // CombineTo deleted the truncate, if needed, but not what's under it.
7113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7116 // See if the value being truncated is already sign extended. If so, just
7117 // eliminate the trunc/sext pair.
7118 SDValue Op = N0.getOperand(0);
7119 unsigned OpBits = Op.getScalarValueSizeInBits();
7120 unsigned MidBits = N0.getScalarValueSizeInBits();
7121 unsigned DestBits = VT.getScalarSizeInBits();
7122 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
7124 if (OpBits == DestBits) {
7125 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7126 // bits, it is already ready.
7127 if (NumSignBits > DestBits-MidBits)
7129 } else if (OpBits < DestBits) {
7130 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7131 // bits, just sext from i32.
7132 if (NumSignBits > OpBits-MidBits)
7133 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
7135 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7136 // bits, just truncate to i32.
7137 if (NumSignBits > OpBits-MidBits)
7138 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
7141 // fold (sext (truncate x)) -> (sextinreg x).
7142 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
7143 N0.getValueType())) {
7144 if (OpBits < DestBits)
7145 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
7146 else if (OpBits > DestBits)
7147 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
7148 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
7149 DAG.getValueType(N0.getValueType()));
7153 // fold (sext (load x)) -> (sext (truncate (sextload x)))
7154 // Only generate vector extloads when 1) they're legal, and 2) they are
7155 // deemed desirable by the target.
7156 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7157 ((!LegalOperations && !VT.isVector() &&
7158 !cast<LoadSDNode>(N0)->isVolatile()) ||
7159 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
7160 bool DoXform = true;
7161 SmallVector<SDNode*, 4> SetCCs;
7162 if (!N0.hasOneUse())
7163 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
7165 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7167 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7168 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7169 LN0->getBasePtr(), N0.getValueType(),
7170 LN0->getMemOperand());
7171 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7172 N0.getValueType(), ExtLoad);
7173 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7174 // If the load value is used only by N, replace it via CombineTo N.
7175 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7176 CombineTo(N, ExtLoad);
7178 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7180 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7181 return SDValue(N, 0);
7185 // fold (sext (load x)) to multiple smaller sextloads.
7186 // Only on illegal but splittable vectors.
7187 if (SDValue ExtLoad = CombineExtLoad(N))
7190 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
7191 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
7192 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7193 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7194 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7195 EVT MemVT = LN0->getMemoryVT();
7196 if ((!LegalOperations && !LN0->isVolatile()) ||
7197 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
7198 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
7199 LN0->getBasePtr(), MemVT,
7200 LN0->getMemOperand());
7201 CombineTo(N, ExtLoad);
7202 CombineTo(N0.getNode(),
7203 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7204 N0.getValueType(), ExtLoad),
7205 ExtLoad.getValue(1));
7206 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7210 // fold (sext (and/or/xor (load x), cst)) ->
7211 // (and/or/xor (sextload x), (sext cst))
7212 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7213 N0.getOpcode() == ISD::XOR) &&
7214 isa<LoadSDNode>(N0.getOperand(0)) &&
7215 N0.getOperand(1).getOpcode() == ISD::Constant &&
7216 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
7217 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7218 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7219 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
7220 bool DoXform = true;
7221 SmallVector<SDNode*, 4> SetCCs;
7222 if (!N0.hasOneUse())
7223 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
7226 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
7227 LN0->getChain(), LN0->getBasePtr(),
7229 LN0->getMemOperand());
7230 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7231 Mask = Mask.sext(VT.getSizeInBits());
7232 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7233 ExtLoad, DAG.getConstant(Mask, DL, VT));
7234 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7235 SDLoc(N0.getOperand(0)),
7236 N0.getOperand(0).getValueType(), ExtLoad);
7237 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
7238 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7241 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7243 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7244 return SDValue(N,0); // Return N so it doesn't get rechecked!
7249 if (N0.getOpcode() == ISD::SETCC) {
7250 SDValue N00 = N0.getOperand(0);
7251 SDValue N01 = N0.getOperand(1);
7252 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7253 EVT N00VT = N0.getOperand(0).getValueType();
7255 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
7256 // Only do this before legalize for now.
7257 if (VT.isVector() && !LegalOperations &&
7258 TLI.getBooleanContents(N00VT) ==
7259 TargetLowering::ZeroOrNegativeOneBooleanContent) {
7260 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
7261 // of the same size as the compared operands. Only optimize sext(setcc())
7262 // if this is the case.
7263 EVT SVT = getSetCCResultType(N00VT);
7265 // We know that the # elements of the results is the same as the
7266 // # elements of the compare (and the # elements of the compare result
7267 // for that matter). Check to see that they are the same size. If so,
7268 // we know that the element size of the sext'd result matches the
7269 // element size of the compare operands.
7270 if (VT.getSizeInBits() == SVT.getSizeInBits())
7271 return DAG.getSetCC(DL, VT, N00, N01, CC);
7273 // If the desired elements are smaller or larger than the source
7274 // elements, we can use a matching integer vector type and then
7275 // truncate/sign extend.
7276 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
7277 if (SVT == MatchingVecType) {
7278 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
7279 return DAG.getSExtOrTrunc(VsetCC, DL, VT);
7283 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
7284 // Here, T can be 1 or -1, depending on the type of the setcc and
7285 // getBooleanContents().
7286 unsigned SetCCWidth = N0.getScalarValueSizeInBits();
7288 // To determine the "true" side of the select, we need to know the high bit
7289 // of the value returned by the setcc if it evaluates to true.
7290 // If the type of the setcc is i1, then the true case of the select is just
7291 // sext(i1 1), that is, -1.
7292 // If the type of the setcc is larger (say, i8) then the value of the high
7293 // bit depends on getBooleanContents(), so ask TLI for a real "true" value
7294 // of the appropriate width.
7295 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
7296 : TLI.getConstTrueVal(DAG, VT, DL);
7297 SDValue Zero = DAG.getConstant(0, DL, VT);
7299 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
7302 if (!VT.isVector()) {
7303 EVT SetCCVT = getSetCCResultType(N00VT);
7304 // Don't do this transform for i1 because there's a select transform
7305 // that would reverse it.
7306 // TODO: We should not do this transform at all without a target hook
7307 // because a sext is likely cheaper than a select?
7308 if (SetCCVT.getScalarSizeInBits() != 1 &&
7309 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
7310 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
7311 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
7316 // fold (sext x) -> (zext x) if the sign bit is known zero.
7317 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
7318 DAG.SignBitIsZero(N0))
7319 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
7321 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7327 // isTruncateOf - If N is a truncate of some other value, return true, record
7328 // the value being truncated in Op and which of Op's bits are zero/one in Known.
7329 // This function computes KnownBits to avoid a duplicated call to
7330 // computeKnownBits in the caller.
7331 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
7333 if (N->getOpcode() == ISD::TRUNCATE) {
7334 Op = N->getOperand(0);
7335 DAG.computeKnownBits(Op, Known);
7339 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
7340 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
7343 SDValue Op0 = N->getOperand(0);
7344 SDValue Op1 = N->getOperand(1);
7345 assert(Op0.getValueType() == Op1.getValueType());
7347 if (isNullConstant(Op0))
7349 else if (isNullConstant(Op1))
7354 DAG.computeKnownBits(Op, Known);
7356 if (!(Known.Zero | 1).isAllOnesValue())
7362 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
7363 SDValue N0 = N->getOperand(0);
7364 EVT VT = N->getValueType(0);
7366 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7368 return SDValue(Res, 0);
7370 // fold (zext (zext x)) -> (zext x)
7371 // fold (zext (aext x)) -> (zext x)
7372 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
7373 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
7376 // fold (zext (truncate x)) -> (zext x) or
7377 // (zext (truncate x)) -> (truncate x)
7378 // This is valid when the truncated bits of x are already zero.
7379 // FIXME: We should extend this to work for vectors too.
7382 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) {
7383 APInt TruncatedBits =
7384 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
7385 APInt(Op.getValueSizeInBits(), 0) :
7386 APInt::getBitsSet(Op.getValueSizeInBits(),
7387 N0.getValueSizeInBits(),
7388 std::min(Op.getValueSizeInBits(),
7389 VT.getSizeInBits()));
7390 if (TruncatedBits.isSubsetOf(Known.Zero))
7391 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7394 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7395 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
7396 if (N0.getOpcode() == ISD::TRUNCATE) {
7397 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7398 SDNode *oye = N0.getOperand(0).getNode();
7399 if (NarrowLoad.getNode() != N0.getNode()) {
7400 CombineTo(N0.getNode(), NarrowLoad);
7401 // CombineTo deleted the truncate, if needed, but not what's under it.
7404 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7408 // fold (zext (truncate x)) -> (and x, mask)
7409 if (N0.getOpcode() == ISD::TRUNCATE) {
7410 // fold (zext (truncate (load x))) -> (zext (smaller load x))
7411 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
7412 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7413 SDNode *oye = N0.getOperand(0).getNode();
7414 if (NarrowLoad.getNode() != N0.getNode()) {
7415 CombineTo(N0.getNode(), NarrowLoad);
7416 // CombineTo deleted the truncate, if needed, but not what's under it.
7419 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7422 EVT SrcVT = N0.getOperand(0).getValueType();
7423 EVT MinVT = N0.getValueType();
7425 // Try to mask before the extension to avoid having to generate a larger mask,
7426 // possibly over several sub-vectors.
7427 if (SrcVT.bitsLT(VT)) {
7428 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
7429 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
7430 SDValue Op = N0.getOperand(0);
7431 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7432 AddToWorklist(Op.getNode());
7433 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
7437 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
7438 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7439 AddToWorklist(Op.getNode());
7440 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
7444 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
7445 // if either of the casts is not free.
7446 if (N0.getOpcode() == ISD::AND &&
7447 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7448 N0.getOperand(1).getOpcode() == ISD::Constant &&
7449 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7450 N0.getValueType()) ||
7451 !TLI.isZExtFree(N0.getValueType(), VT))) {
7452 SDValue X = N0.getOperand(0).getOperand(0);
7453 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
7454 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7455 Mask = Mask.zext(VT.getSizeInBits());
7457 return DAG.getNode(ISD::AND, DL, VT,
7458 X, DAG.getConstant(Mask, DL, VT));
7461 // fold (zext (load x)) -> (zext (truncate (zextload x)))
7462 // Only generate vector extloads when 1) they're legal, and 2) they are
7463 // deemed desirable by the target.
7464 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7465 ((!LegalOperations && !VT.isVector() &&
7466 !cast<LoadSDNode>(N0)->isVolatile()) ||
7467 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
7468 bool DoXform = true;
7469 SmallVector<SDNode*, 4> SetCCs;
7470 if (!N0.hasOneUse())
7471 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
7473 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
7475 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7476 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7478 LN0->getBasePtr(), N0.getValueType(),
7479 LN0->getMemOperand());
7481 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7482 N0.getValueType(), ExtLoad);
7483 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), ISD::ZERO_EXTEND);
7484 // If the load value is used only by N, replace it via CombineTo N.
7485 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7486 CombineTo(N, ExtLoad);
7488 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7490 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7491 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7495 // fold (zext (load x)) to multiple smaller zextloads.
7496 // Only on illegal but splittable vectors.
7497 if (SDValue ExtLoad = CombineExtLoad(N))
7500 // fold (zext (and/or/xor (load x), cst)) ->
7501 // (and/or/xor (zextload x), (zext cst))
7502 // Unless (and (load x) cst) will match as a zextload already and has
7503 // additional users.
7504 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
7505 N0.getOpcode() == ISD::XOR) &&
7506 isa<LoadSDNode>(N0.getOperand(0)) &&
7507 N0.getOperand(1).getOpcode() == ISD::Constant &&
7508 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
7509 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
7510 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
7511 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
7512 bool DoXform = true;
7513 SmallVector<SDNode*, 4> SetCCs;
7514 if (!N0.hasOneUse()) {
7515 if (N0.getOpcode() == ISD::AND) {
7516 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
7517 auto NarrowLoad = false;
7518 EVT LoadResultTy = AndC->getValueType(0);
7519 EVT ExtVT, LoadedVT;
7520 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
7525 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
7526 ISD::ZERO_EXTEND, SetCCs, TLI);
7529 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
7530 LN0->getChain(), LN0->getBasePtr(),
7532 LN0->getMemOperand());
7533 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7534 Mask = Mask.zext(VT.getSizeInBits());
7536 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
7537 ExtLoad, DAG.getConstant(Mask, DL, VT));
7538 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
7539 SDLoc(N0.getOperand(0)),
7540 N0.getOperand(0).getValueType(), ExtLoad);
7541 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::ZERO_EXTEND);
7542 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
7545 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7547 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7548 return SDValue(N,0); // Return N so it doesn't get rechecked!
7553 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
7554 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
7555 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
7556 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
7557 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7558 EVT MemVT = LN0->getMemoryVT();
7559 if ((!LegalOperations && !LN0->isVolatile()) ||
7560 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
7561 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
7563 LN0->getBasePtr(), MemVT,
7564 LN0->getMemOperand());
7565 CombineTo(N, ExtLoad);
7566 CombineTo(N0.getNode(),
7567 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
7569 ExtLoad.getValue(1));
7570 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7574 if (N0.getOpcode() == ISD::SETCC) {
7575 // Only do this before legalize for now.
7576 if (!LegalOperations && VT.isVector() &&
7577 N0.getValueType().getVectorElementType() == MVT::i1) {
7578 EVT N00VT = N0.getOperand(0).getValueType();
7579 if (getSetCCResultType(N00VT) == N0.getValueType())
7582 // We know that the # elements of the results is the same as the #
7583 // elements of the compare (and the # elements of the compare result for
7584 // that matter). Check to see that they are the same size. If so, we know
7585 // that the element size of the sext'd result matches the element size of
7586 // the compare operands.
7588 SDValue VecOnes = DAG.getConstant(1, DL, VT);
7589 if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
7590 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
7591 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
7592 N0.getOperand(1), N0.getOperand(2));
7593 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
7596 // If the desired elements are smaller or larger than the source
7597 // elements we can use a matching integer vector type and then
7598 // truncate/sign extend.
7599 EVT MatchingElementType = EVT::getIntegerVT(
7600 *DAG.getContext(), N00VT.getScalarSizeInBits());
7601 EVT MatchingVectorType = EVT::getVectorVT(
7602 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
7604 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
7605 N0.getOperand(1), N0.getOperand(2));
7606 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
7610 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7612 if (SDValue SCC = SimplifySelectCC(
7613 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7614 DAG.getConstant(0, DL, VT),
7615 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7619 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
7620 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
7621 isa<ConstantSDNode>(N0.getOperand(1)) &&
7622 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
7624 SDValue ShAmt = N0.getOperand(1);
7625 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7626 if (N0.getOpcode() == ISD::SHL) {
7627 SDValue InnerZExt = N0.getOperand(0);
7628 // If the original shl may be shifting out bits, do not perform this
7630 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
7631 InnerZExt.getOperand(0).getValueSizeInBits();
7632 if (ShAmtVal > KnownZeroBits)
7638 // Ensure that the shift amount is wide enough for the shifted value.
7639 if (VT.getSizeInBits() >= 256)
7640 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
7642 return DAG.getNode(N0.getOpcode(), DL, VT,
7643 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
7647 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
7653 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
7654 SDValue N0 = N->getOperand(0);
7655 EVT VT = N->getValueType(0);
7657 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
7659 return SDValue(Res, 0);
7661 // fold (aext (aext x)) -> (aext x)
7662 // fold (aext (zext x)) -> (zext x)
7663 // fold (aext (sext x)) -> (sext x)
7664 if (N0.getOpcode() == ISD::ANY_EXTEND ||
7665 N0.getOpcode() == ISD::ZERO_EXTEND ||
7666 N0.getOpcode() == ISD::SIGN_EXTEND)
7667 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
7669 // fold (aext (truncate (load x))) -> (aext (smaller load x))
7670 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
7671 if (N0.getOpcode() == ISD::TRUNCATE) {
7672 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
7673 SDNode *oye = N0.getOperand(0).getNode();
7674 if (NarrowLoad.getNode() != N0.getNode()) {
7675 CombineTo(N0.getNode(), NarrowLoad);
7676 // CombineTo deleted the truncate, if needed, but not what's under it.
7679 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7683 // fold (aext (truncate x))
7684 if (N0.getOpcode() == ISD::TRUNCATE)
7685 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
7687 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
7688 // if the trunc is not free.
7689 if (N0.getOpcode() == ISD::AND &&
7690 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7691 N0.getOperand(1).getOpcode() == ISD::Constant &&
7692 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
7693 N0.getValueType())) {
7695 SDValue X = N0.getOperand(0).getOperand(0);
7696 X = DAG.getAnyExtOrTrunc(X, DL, VT);
7697 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
7698 Mask = Mask.zext(VT.getSizeInBits());
7699 return DAG.getNode(ISD::AND, DL, VT,
7700 X, DAG.getConstant(Mask, DL, VT));
7703 // fold (aext (load x)) -> (aext (truncate (extload x)))
7704 // None of the supported targets knows how to perform load and any_ext
7705 // on vectors in one instruction. We only perform this transformation on
7707 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
7708 ISD::isUNINDEXEDLoad(N0.getNode()) &&
7709 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7710 bool DoXform = true;
7711 SmallVector<SDNode*, 4> SetCCs;
7712 if (!N0.hasOneUse())
7713 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
7715 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7716 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7718 LN0->getBasePtr(), N0.getValueType(),
7719 LN0->getMemOperand());
7720 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7721 N0.getValueType(), ExtLoad);
7722 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
7724 // If the load value is used only by N, replace it via CombineTo N.
7725 bool NoReplaceTrunc = N0.hasOneUse();
7726 CombineTo(N, ExtLoad);
7728 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
7730 CombineTo(LN0, Trunc, ExtLoad.getValue(1));
7731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7735 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
7736 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
7737 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
7738 if (N0.getOpcode() == ISD::LOAD &&
7739 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
7741 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7742 ISD::LoadExtType ExtType = LN0->getExtensionType();
7743 EVT MemVT = LN0->getMemoryVT();
7744 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
7745 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
7746 VT, LN0->getChain(), LN0->getBasePtr(),
7747 MemVT, LN0->getMemOperand());
7748 CombineTo(N, ExtLoad);
7749 CombineTo(N0.getNode(),
7750 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
7751 N0.getValueType(), ExtLoad),
7752 ExtLoad.getValue(1));
7753 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7757 if (N0.getOpcode() == ISD::SETCC) {
7759 // aext(setcc) -> vsetcc
7760 // aext(setcc) -> truncate(vsetcc)
7761 // aext(setcc) -> aext(vsetcc)
7762 // Only do this before legalize for now.
7763 if (VT.isVector() && !LegalOperations) {
7764 EVT N0VT = N0.getOperand(0).getValueType();
7765 // We know that the # elements of the results is the same as the
7766 // # elements of the compare (and the # elements of the compare result
7767 // for that matter). Check to see that they are the same size. If so,
7768 // we know that the element size of the sext'd result matches the
7769 // element size of the compare operands.
7770 if (VT.getSizeInBits() == N0VT.getSizeInBits())
7771 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
7773 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7774 // If the desired elements are smaller or larger than the source
7775 // elements we can use a matching integer vector type and then
7776 // truncate/any extend
7778 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
7780 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
7782 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7783 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
7787 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
7789 if (SDValue SCC = SimplifySelectCC(
7790 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
7791 DAG.getConstant(0, DL, VT),
7792 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
7799 SDValue DAGCombiner::visitAssertZext(SDNode *N) {
7800 SDValue N0 = N->getOperand(0);
7801 SDValue N1 = N->getOperand(1);
7802 EVT EVT = cast<VTSDNode>(N1)->getVT();
7804 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
7805 if (N0.getOpcode() == ISD::AssertZext &&
7806 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
7812 /// See if the specified operand can be simplified with the knowledge that only
7813 /// the bits specified by Mask are used. If so, return the simpler operand,
7814 /// otherwise return a null SDValue.
7816 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
7817 /// simplify nodes with multiple uses more aggressively.)
7818 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
7819 switch (V.getOpcode()) {
7821 case ISD::Constant: {
7822 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
7823 assert(CV && "Const value should be ConstSDNode.");
7824 const APInt &CVal = CV->getAPIntValue();
7825 APInt NewVal = CVal & Mask;
7827 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
7832 // If the LHS or RHS don't contribute bits to the or, drop them.
7833 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
7834 return V.getOperand(1);
7835 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
7836 return V.getOperand(0);
7839 // Only look at single-use SRLs.
7840 if (!V.getNode()->hasOneUse())
7842 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
7843 // See if we can recursively simplify the LHS.
7844 unsigned Amt = RHSC->getZExtValue();
7846 // Watch out for shift count overflow though.
7847 if (Amt >= Mask.getBitWidth()) break;
7848 APInt NewMask = Mask << Amt;
7849 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
7850 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
7851 SimplifyLHS, V.getOperand(1));
7855 // X & -1 -> X (ignoring bits which aren't demanded).
7856 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
7857 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
7858 return V.getOperand(0);
7865 /// If the result of a wider load is shifted to right of N bits and then
7866 /// truncated to a narrower type and where N is a multiple of number of bits of
7867 /// the narrower type, transform it to a narrower load from address + N / num of
7868 /// bits of new type. If the result is to be extended, also fold the extension
7869 /// to form a extending load.
7870 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
7871 unsigned Opc = N->getOpcode();
7873 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
7874 SDValue N0 = N->getOperand(0);
7875 EVT VT = N->getValueType(0);
7878 // This transformation isn't valid for vector loads.
7882 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
7884 if (Opc == ISD::SIGN_EXTEND_INREG) {
7885 ExtType = ISD::SEXTLOAD;
7886 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7887 } else if (Opc == ISD::SRL) {
7888 // Another special-case: SRL is basically zero-extending a narrower value.
7889 ExtType = ISD::ZEXTLOAD;
7891 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7892 if (!N01) return SDValue();
7893 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
7894 VT.getSizeInBits() - N01->getZExtValue());
7896 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
7899 unsigned EVTBits = ExtVT.getSizeInBits();
7901 // Do not generate loads of non-round integer types since these can
7902 // be expensive (and would be wrong if the type is not byte sized).
7903 if (!ExtVT.isRound())
7907 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
7908 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7909 ShAmt = N01->getZExtValue();
7910 // Is the shift amount a multiple of size of VT?
7911 if ((ShAmt & (EVTBits-1)) == 0) {
7912 N0 = N0.getOperand(0);
7913 // Is the load width a multiple of size of VT?
7914 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
7918 // At this point, we must have a load or else we can't do the transform.
7919 if (!isa<LoadSDNode>(N0)) return SDValue();
7921 // Because a SRL must be assumed to *need* to zero-extend the high bits
7922 // (as opposed to anyext the high bits), we can't combine the zextload
7923 // lowering of SRL and an sextload.
7924 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
7927 // If the shift amount is larger than the input type then we're not
7928 // accessing any of the loaded bytes. If the load was a zextload/extload
7929 // then the result of the shift+trunc is zero/undef (handled elsewhere).
7930 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
7935 // If the load is shifted left (and the result isn't shifted back right),
7936 // we can fold the truncate through the shift.
7937 unsigned ShLeftAmt = 0;
7938 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
7939 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
7940 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
7941 ShLeftAmt = N01->getZExtValue();
7942 N0 = N0.getOperand(0);
7946 // If we haven't found a load, we can't narrow it. Don't transform one with
7947 // multiple uses, this would require adding a new load.
7948 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
7951 // Don't change the width of a volatile load.
7952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7953 if (LN0->isVolatile())
7956 // Verify that we are actually reducing a load width here.
7957 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
7960 // For the transform to be legal, the load must produce only two values
7961 // (the value loaded and the chain). Don't transform a pre-increment
7962 // load, for example, which produces an extra value. Otherwise the
7963 // transformation is not equivalent, and the downstream logic to replace
7964 // uses gets things wrong.
7965 if (LN0->getNumValues() > 2)
7968 // If the load that we're shrinking is an extload and we're not just
7969 // discarding the extension we can't simply shrink the load. Bail.
7970 // TODO: It would be possible to merge the extensions in some cases.
7971 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
7972 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
7975 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
7978 EVT PtrType = N0.getOperand(1).getValueType();
7980 if (PtrType == MVT::Untyped || PtrType.isExtended())
7981 // It's not possible to generate a constant of extended or untyped type.
7984 // For big endian targets, we need to adjust the offset to the pointer to
7985 // load the correct bytes.
7986 if (DAG.getDataLayout().isBigEndian()) {
7987 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
7988 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
7989 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
7992 uint64_t PtrOff = ShAmt / 8;
7993 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
7995 // The original load itself didn't wrap, so an offset within it doesn't.
7997 Flags.setNoUnsignedWrap(true);
7998 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
7999 PtrType, LN0->getBasePtr(),
8000 DAG.getConstant(PtrOff, DL, PtrType),
8002 AddToWorklist(NewPtr.getNode());
8005 if (ExtType == ISD::NON_EXTLOAD)
8006 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
8007 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
8008 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8010 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
8011 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
8012 NewAlign, LN0->getMemOperand()->getFlags(),
8015 // Replace the old load's chain with the new load's chain.
8016 WorklistRemover DeadNodes(*this);
8017 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8019 // Shift the result left, if we've swallowed a left shift.
8020 SDValue Result = Load;
8021 if (ShLeftAmt != 0) {
8022 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
8023 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
8025 // If the shift amount is as large as the result size (but, presumably,
8026 // no larger than the source) then the useful bits of the result are
8027 // zero; we can't simply return the shortened shift, because the result
8028 // of that operation is undefined.
8030 if (ShLeftAmt >= VT.getSizeInBits())
8031 Result = DAG.getConstant(0, DL, VT);
8033 Result = DAG.getNode(ISD::SHL, DL, VT,
8034 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
8037 // Return the new loaded value.
8041 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
8042 SDValue N0 = N->getOperand(0);
8043 SDValue N1 = N->getOperand(1);
8044 EVT VT = N->getValueType(0);
8045 EVT EVT = cast<VTSDNode>(N1)->getVT();
8046 unsigned VTBits = VT.getScalarSizeInBits();
8047 unsigned EVTBits = EVT.getScalarSizeInBits();
8050 return DAG.getUNDEF(VT);
8052 // fold (sext_in_reg c1) -> c1
8053 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8054 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
8056 // If the input is already sign extended, just drop the extension.
8057 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
8060 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
8061 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8062 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
8063 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8064 N0.getOperand(0), N1);
8066 // fold (sext_in_reg (sext x)) -> (sext x)
8067 // fold (sext_in_reg (aext x)) -> (sext x)
8068 // if x is small enough.
8069 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
8070 SDValue N00 = N0.getOperand(0);
8071 if (N00.getScalarValueSizeInBits() <= EVTBits &&
8072 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8073 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8076 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
8077 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
8078 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
8079 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
8080 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
8081 if (!LegalOperations ||
8082 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
8083 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
8086 // fold (sext_in_reg (zext x)) -> (sext x)
8087 // iff we are extending the source sign bit.
8088 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
8089 SDValue N00 = N0.getOperand(0);
8090 if (N00.getScalarValueSizeInBits() == EVTBits &&
8091 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
8092 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
8095 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
8096 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
8097 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
8099 // fold operands of sext_in_reg based on knowledge that the top bits are not
8101 if (SimplifyDemandedBits(SDValue(N, 0)))
8102 return SDValue(N, 0);
8104 // fold (sext_in_reg (load x)) -> (smaller sextload x)
8105 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
8106 if (SDValue NarrowLoad = ReduceLoadWidth(N))
8109 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
8110 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
8111 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
8112 if (N0.getOpcode() == ISD::SRL) {
8113 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
8114 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
8115 // We can turn this into an SRA iff the input to the SRL is already sign
8117 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
8118 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
8119 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
8120 N0.getOperand(0), N0.getOperand(1));
8124 // fold (sext_inreg (extload x)) -> (sextload x)
8125 if (ISD::isEXTLoad(N0.getNode()) &&
8126 ISD::isUNINDEXEDLoad(N0.getNode()) &&
8127 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8128 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8129 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8130 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8131 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8133 LN0->getBasePtr(), EVT,
8134 LN0->getMemOperand());
8135 CombineTo(N, ExtLoad);
8136 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8137 AddToWorklist(ExtLoad.getNode());
8138 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8140 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
8141 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
8143 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
8144 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
8145 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
8146 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8147 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
8149 LN0->getBasePtr(), EVT,
8150 LN0->getMemOperand());
8151 CombineTo(N, ExtLoad);
8152 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
8153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8156 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
8157 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
8158 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
8159 N0.getOperand(1), false))
8160 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
8167 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
8168 SDValue N0 = N->getOperand(0);
8169 EVT VT = N->getValueType(0);
8172 return DAG.getUNDEF(VT);
8174 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8176 return SDValue(Res, 0);
8181 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
8182 SDValue N0 = N->getOperand(0);
8183 EVT VT = N->getValueType(0);
8186 return DAG.getUNDEF(VT);
8188 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
8190 return SDValue(Res, 0);
8195 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
8196 SDValue N0 = N->getOperand(0);
8197 EVT VT = N->getValueType(0);
8198 bool isLE = DAG.getDataLayout().isLittleEndian();
8201 if (N0.getValueType() == N->getValueType(0))
8203 // fold (truncate c1) -> c1
8204 if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
8205 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
8206 // fold (truncate (truncate x)) -> (truncate x)
8207 if (N0.getOpcode() == ISD::TRUNCATE)
8208 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8209 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
8210 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
8211 N0.getOpcode() == ISD::SIGN_EXTEND ||
8212 N0.getOpcode() == ISD::ANY_EXTEND) {
8213 // if the source is smaller than the dest, we still need an extend.
8214 if (N0.getOperand(0).getValueType().bitsLT(VT))
8215 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
8216 // if the source is larger than the dest, than we just need the truncate.
8217 if (N0.getOperand(0).getValueType().bitsGT(VT))
8218 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
8219 // if the source and dest are the same type, we can drop both the extend
8220 // and the truncate.
8221 return N0.getOperand(0);
8224 // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
8225 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
8228 // Fold extract-and-trunc into a narrow extract. For example:
8229 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
8230 // i32 y = TRUNCATE(i64 x)
8232 // v16i8 b = BITCAST (v2i64 val)
8233 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
8235 // Note: We only run this optimization after type legalization (which often
8236 // creates this pattern) and before operation legalization after which
8237 // we need to be more careful about the vector instructions that we generate.
8238 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8239 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
8241 EVT VecTy = N0.getOperand(0).getValueType();
8242 EVT ExTy = N0.getValueType();
8243 EVT TrTy = N->getValueType(0);
8245 unsigned NumElem = VecTy.getVectorNumElements();
8246 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
8248 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
8249 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
8251 SDValue EltNo = N0->getOperand(1);
8252 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
8253 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8254 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8255 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
8258 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
8259 DAG.getBitcast(NVT, N0.getOperand(0)),
8260 DAG.getConstant(Index, DL, IndexTy));
8264 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
8265 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
8266 EVT SrcVT = N0.getValueType();
8267 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
8268 TLI.isTruncateFree(SrcVT, VT)) {
8270 SDValue Cond = N0.getOperand(0);
8271 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8272 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
8273 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
8277 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
8278 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
8279 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
8280 TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
8281 SDValue Amt = N0.getOperand(1);
8283 DAG.computeKnownBits(Amt, Known);
8284 unsigned Size = VT.getScalarSizeInBits();
8285 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
8287 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
8289 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8290 if (AmtVT != Amt.getValueType()) {
8291 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
8292 AddToWorklist(Amt.getNode());
8294 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
8298 // Fold a series of buildvector, bitcast, and truncate if possible.
8300 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
8301 // (2xi32 (buildvector x, y)).
8302 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
8303 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
8304 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
8305 N0.getOperand(0).hasOneUse()) {
8307 SDValue BuildVect = N0.getOperand(0);
8308 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
8309 EVT TruncVecEltTy = VT.getVectorElementType();
8311 // Check that the element types match.
8312 if (BuildVectEltTy == TruncVecEltTy) {
8313 // Now we only need to compute the offset of the truncated elements.
8314 unsigned BuildVecNumElts = BuildVect.getNumOperands();
8315 unsigned TruncVecNumElts = VT.getVectorNumElements();
8316 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
8318 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
8319 "Invalid number of elements");
8321 SmallVector<SDValue, 8> Opnds;
8322 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
8323 Opnds.push_back(BuildVect.getOperand(i));
8325 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
8329 // See if we can simplify the input to this truncate through knowledge that
8330 // only the low bits are being used.
8331 // For example "trunc (or (shl x, 8), y)" // -> trunc y
8332 // Currently we only perform this optimization on scalars because vectors
8333 // may have different active low bits.
8334 if (!VT.isVector()) {
8335 if (SDValue Shorter =
8336 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
8337 VT.getSizeInBits())))
8338 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
8341 // fold (truncate (load x)) -> (smaller load x)
8342 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
8343 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
8344 if (SDValue Reduced = ReduceLoadWidth(N))
8347 // Handle the case where the load remains an extending load even
8348 // after truncation.
8349 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
8350 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8351 if (!LN0->isVolatile() &&
8352 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
8353 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
8354 VT, LN0->getChain(), LN0->getBasePtr(),
8356 LN0->getMemOperand());
8357 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
8363 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
8364 // where ... are all 'undef'.
8365 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
8366 SmallVector<EVT, 8> VTs;
8369 unsigned NumDefs = 0;
8371 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
8372 SDValue X = N0.getOperand(i);
8378 // Stop if more than one members are non-undef.
8381 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
8382 VT.getVectorElementType(),
8383 X.getValueType().getVectorNumElements()));
8387 return DAG.getUNDEF(VT);
8390 assert(V.getNode() && "The single defined operand is empty!");
8391 SmallVector<SDValue, 8> Opnds;
8392 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
8394 Opnds.push_back(DAG.getUNDEF(VTs[i]));
8397 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
8398 AddToWorklist(NV.getNode());
8399 Opnds.push_back(NV);
8401 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
8405 // Fold truncate of a bitcast of a vector to an extract of the low vector
8408 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
8409 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
8410 SDValue VecSrc = N0.getOperand(0);
8411 EVT SrcVT = VecSrc.getValueType();
8412 if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
8413 (!LegalOperations ||
8414 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
8417 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
8418 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
8419 VecSrc, DAG.getConstant(0, SL, IdxVT));
8423 // Simplify the operands using demanded-bits information.
8424 if (!VT.isVector() &&
8425 SimplifyDemandedBits(SDValue(N, 0)))
8426 return SDValue(N, 0);
8428 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
8429 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
8430 // When the adde's carry is not used.
8431 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
8432 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
8433 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) {
8435 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
8436 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
8437 auto VTs = DAG.getVTList(VT, N0->getValueType(1));
8438 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
8441 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
8447 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
8448 SDValue Elt = N->getOperand(i);
8449 if (Elt.getOpcode() != ISD::MERGE_VALUES)
8450 return Elt.getNode();
8451 return Elt.getOperand(Elt.getResNo()).getNode();
8454 /// build_pair (load, load) -> load
8455 /// if load locations are consecutive.
8456 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
8457 assert(N->getOpcode() == ISD::BUILD_PAIR);
8459 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
8460 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
8461 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
8462 LD1->getAddressSpace() != LD2->getAddressSpace())
8464 EVT LD1VT = LD1->getValueType(0);
8465 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
8466 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
8467 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
8468 unsigned Align = LD1->getAlignment();
8469 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
8470 VT.getTypeForEVT(*DAG.getContext()));
8472 if (NewAlign <= Align &&
8473 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
8474 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
8475 LD1->getPointerInfo(), Align);
8481 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
8482 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
8483 // and Lo parts; on big-endian machines it doesn't.
8484 return DAG.getDataLayout().isBigEndian() ? 1 : 0;
8487 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
8488 const TargetLowering &TLI) {
8489 // If this is not a bitcast to an FP type or if the target doesn't have
8490 // IEEE754-compliant FP logic, we're done.
8491 EVT VT = N->getValueType(0);
8492 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
8495 // TODO: Use splat values for the constant-checking below and remove this
8497 SDValue N0 = N->getOperand(0);
8498 EVT SourceVT = N0.getValueType();
8499 if (SourceVT.isVector())
8504 switch (N0.getOpcode()) {
8506 FPOpcode = ISD::FABS;
8507 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits());
8510 FPOpcode = ISD::FNEG;
8511 SignMask = APInt::getSignMask(SourceVT.getSizeInBits());
8513 // TODO: ISD::OR --> ISD::FNABS?
8518 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
8519 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
8520 SDValue LogicOp0 = N0.getOperand(0);
8521 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8522 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
8523 LogicOp0.getOpcode() == ISD::BITCAST &&
8524 LogicOp0->getOperand(0).getValueType() == VT)
8525 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
8530 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
8531 SDValue N0 = N->getOperand(0);
8532 EVT VT = N->getValueType(0);
8535 return DAG.getUNDEF(VT);
8537 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
8538 // Only do this before legalize, since afterward the target may be depending
8539 // on the bitconvert.
8540 // First check to see if this is all constant.
8542 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
8544 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
8546 EVT DestEltVT = N->getValueType(0).getVectorElementType();
8547 assert(!DestEltVT.isVector() &&
8548 "Element type of vector ValueType must not be vector!");
8550 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
8553 // If the input is a constant, let getNode fold it.
8554 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
8555 // If we can't allow illegal operations, we need to check that this is just
8556 // a fp -> int or int -> conversion and that the resulting operation will
8558 if (!LegalOperations ||
8559 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
8560 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
8561 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
8562 TLI.isOperationLegal(ISD::Constant, VT)))
8563 return DAG.getBitcast(VT, N0);
8566 // (conv (conv x, t1), t2) -> (conv x, t2)
8567 if (N0.getOpcode() == ISD::BITCAST)
8568 return DAG.getBitcast(VT, N0.getOperand(0));
8570 // fold (conv (load x)) -> (load (conv*)x)
8571 // If the resultant load doesn't need a higher alignment than the original!
8572 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8573 // Do not change the width of a volatile load.
8574 !cast<LoadSDNode>(N0)->isVolatile() &&
8575 // Do not remove the cast if the types differ in endian layout.
8576 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
8577 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
8578 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
8579 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
8580 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8581 unsigned OrigAlign = LN0->getAlignment();
8584 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
8585 LN0->getAddressSpace(), OrigAlign, &Fast) &&
8588 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8589 LN0->getPointerInfo(), OrigAlign,
8590 LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
8591 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
8596 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
8599 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8600 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8603 // fold (bitcast (fneg x)) ->
8604 // flipbit = signbit
8605 // (xor (bitcast x) (build_pair flipbit, flipbit))
8607 // fold (bitcast (fabs x)) ->
8608 // flipbit = (and (extract_element (bitcast x), 0), signbit)
8609 // (xor (bitcast x) (build_pair flipbit, flipbit))
8610 // This often reduces constant pool loads.
8611 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
8612 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
8613 N0.getNode()->hasOneUse() && VT.isInteger() &&
8614 !VT.isVector() && !N0.getValueType().isVector()) {
8615 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
8616 AddToWorklist(NewConv.getNode());
8619 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8620 assert(VT.getSizeInBits() == 128);
8621 SDValue SignBit = DAG.getConstant(
8622 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
8624 if (N0.getOpcode() == ISD::FNEG) {
8626 AddToWorklist(FlipBit.getNode());
8628 assert(N0.getOpcode() == ISD::FABS);
8630 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
8631 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8633 AddToWorklist(Hi.getNode());
8634 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
8635 AddToWorklist(FlipBit.getNode());
8638 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8639 AddToWorklist(FlipBits.getNode());
8640 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
8642 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8643 if (N0.getOpcode() == ISD::FNEG)
8644 return DAG.getNode(ISD::XOR, DL, VT,
8645 NewConv, DAG.getConstant(SignBit, DL, VT));
8646 assert(N0.getOpcode() == ISD::FABS);
8647 return DAG.getNode(ISD::AND, DL, VT,
8648 NewConv, DAG.getConstant(~SignBit, DL, VT));
8651 // fold (bitconvert (fcopysign cst, x)) ->
8652 // (or (and (bitconvert x), sign), (and cst, (not sign)))
8653 // Note that we don't handle (copysign x, cst) because this can always be
8654 // folded to an fneg or fabs.
8657 // fold (bitcast (fcopysign cst, x)) ->
8658 // flipbit = (and (extract_element
8659 // (xor (bitcast cst), (bitcast x)), 0),
8661 // (xor (bitcast cst) (build_pair flipbit, flipbit))
8662 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
8663 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
8664 VT.isInteger() && !VT.isVector()) {
8665 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
8666 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
8667 if (isTypeLegal(IntXVT)) {
8668 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
8669 AddToWorklist(X.getNode());
8671 // If X has a different width than the result/lhs, sext it or truncate it.
8672 unsigned VTWidth = VT.getSizeInBits();
8673 if (OrigXWidth < VTWidth) {
8674 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
8675 AddToWorklist(X.getNode());
8676 } else if (OrigXWidth > VTWidth) {
8677 // To get the sign bit in the right place, we have to shift it right
8678 // before truncating.
8680 X = DAG.getNode(ISD::SRL, DL,
8681 X.getValueType(), X,
8682 DAG.getConstant(OrigXWidth-VTWidth, DL,
8684 AddToWorklist(X.getNode());
8685 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
8686 AddToWorklist(X.getNode());
8689 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
8690 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
8691 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8692 AddToWorklist(Cst.getNode());
8693 SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
8694 AddToWorklist(X.getNode());
8695 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
8696 AddToWorklist(XorResult.getNode());
8697 SDValue XorResult64 = DAG.getNode(
8698 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
8699 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
8701 AddToWorklist(XorResult64.getNode());
8703 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
8704 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
8705 AddToWorklist(FlipBit.getNode());
8707 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
8708 AddToWorklist(FlipBits.getNode());
8709 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
8711 APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
8712 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
8713 X, DAG.getConstant(SignBit, SDLoc(X), VT));
8714 AddToWorklist(X.getNode());
8716 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
8717 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
8718 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
8719 AddToWorklist(Cst.getNode());
8721 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
8725 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
8726 if (N0.getOpcode() == ISD::BUILD_PAIR)
8727 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
8730 // Remove double bitcasts from shuffles - this is often a legacy of
8731 // XformToShuffleWithZero being used to combine bitmaskings (of
8732 // float vectors bitcast to integer vectors) into shuffles.
8733 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
8734 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
8735 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
8736 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
8737 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
8738 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
8740 // If operands are a bitcast, peek through if it casts the original VT.
8741 // If operands are a constant, just bitcast back to original VT.
8742 auto PeekThroughBitcast = [&](SDValue Op) {
8743 if (Op.getOpcode() == ISD::BITCAST &&
8744 Op.getOperand(0).getValueType() == VT)
8745 return SDValue(Op.getOperand(0));
8746 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
8747 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
8748 return DAG.getBitcast(VT, Op);
8752 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
8753 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
8758 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
8759 SmallVector<int, 8> NewMask;
8760 for (int M : SVN->getMask())
8761 for (int i = 0; i != MaskScale; ++i)
8762 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
8764 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8766 std::swap(SV0, SV1);
8767 ShuffleVectorSDNode::commuteMask(NewMask);
8768 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
8772 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
8778 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
8779 EVT VT = N->getValueType(0);
8780 return CombineConsecutiveLoads(N, VT);
8783 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
8784 /// operands. DstEltVT indicates the destination element value type.
8785 SDValue DAGCombiner::
8786 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
8787 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8789 // If this is already the right type, we're done.
8790 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
8792 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8793 unsigned DstBitSize = DstEltVT.getSizeInBits();
8795 // If this is a conversion of N elements of one type to N elements of another
8796 // type, convert each element. This handles FP<->INT cases.
8797 if (SrcBitSize == DstBitSize) {
8798 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8799 BV->getValueType(0).getVectorNumElements());
8801 // Due to the FP element handling below calling this routine recursively,
8802 // we can end up with a scalar-to-vector node here.
8803 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
8804 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
8805 DAG.getBitcast(DstEltVT, BV->getOperand(0)));
8807 SmallVector<SDValue, 8> Ops;
8808 for (SDValue Op : BV->op_values()) {
8809 // If the vector element type is not legal, the BUILD_VECTOR operands
8810 // are promoted and implicitly truncated. Make that explicit here.
8811 if (Op.getValueType() != SrcEltVT)
8812 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
8813 Ops.push_back(DAG.getBitcast(DstEltVT, Op));
8814 AddToWorklist(Ops.back().getNode());
8816 return DAG.getBuildVector(VT, SDLoc(BV), Ops);
8819 // Otherwise, we're growing or shrinking the elements. To avoid having to
8820 // handle annoying details of growing/shrinking FP values, we convert them to
8822 if (SrcEltVT.isFloatingPoint()) {
8823 // Convert the input float vector to a int vector where the elements are the
8825 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
8826 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
8830 // Now we know the input is an integer vector. If the output is a FP type,
8831 // convert to integer first, then to FP of the right size.
8832 if (DstEltVT.isFloatingPoint()) {
8833 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
8834 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
8836 // Next, convert to FP elements of the same size.
8837 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
8842 // Okay, we know the src/dst types are both integers of differing types.
8843 // Handling growing first.
8844 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8845 if (SrcBitSize < DstBitSize) {
8846 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
8848 SmallVector<SDValue, 8> Ops;
8849 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
8850 i += NumInputsPerOutput) {
8851 bool isLE = DAG.getDataLayout().isLittleEndian();
8852 APInt NewBits = APInt(DstBitSize, 0);
8853 bool EltIsUndef = true;
8854 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
8855 // Shift the previously computed bits over.
8856 NewBits <<= SrcBitSize;
8857 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
8858 if (Op.isUndef()) continue;
8861 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
8862 zextOrTrunc(SrcBitSize).zext(DstBitSize);
8866 Ops.push_back(DAG.getUNDEF(DstEltVT));
8868 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
8871 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
8872 return DAG.getBuildVector(VT, DL, Ops);
8875 // Finally, this must be the case where we are shrinking elements: each input
8876 // turns into multiple outputs.
8877 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
8878 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
8879 NumOutputsPerInput*BV->getNumOperands());
8880 SmallVector<SDValue, 8> Ops;
8882 for (const SDValue &Op : BV->op_values()) {
8884 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
8888 APInt OpVal = cast<ConstantSDNode>(Op)->
8889 getAPIntValue().zextOrTrunc(SrcBitSize);
8891 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
8892 APInt ThisVal = OpVal.trunc(DstBitSize);
8893 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
8894 OpVal.lshrInPlace(DstBitSize);
8897 // For big endian targets, swap the order of the pieces of each element.
8898 if (DAG.getDataLayout().isBigEndian())
8899 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
8902 return DAG.getBuildVector(VT, DL, Ops);
8905 static bool isContractable(SDNode *N) {
8906 SDNodeFlags F = N->getFlags();
8907 return F.hasAllowContract() || F.hasUnsafeAlgebra();
8910 /// Try to perform FMA combining on a given FADD node.
8911 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
8912 SDValue N0 = N->getOperand(0);
8913 SDValue N1 = N->getOperand(1);
8914 EVT VT = N->getValueType(0);
8917 const TargetOptions &Options = DAG.getTarget().Options;
8919 // Floating-point multiply-add with intermediate rounding.
8920 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
8922 // Floating-point multiply-add without intermediate rounding.
8924 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
8925 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
8927 // No valid opcode, do not combine.
8928 if (!HasFMAD && !HasFMA)
8931 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8932 Options.UnsafeFPMath || HasFMAD);
8933 // If the addition is not contractable, do not combine.
8934 if (!AllowFusionGlobally && !isContractable(N))
8937 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
8938 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
8941 // Always prefer FMAD to FMA for precision.
8942 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8943 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8944 bool LookThroughFPExt = TLI.isFPExtFree(VT);
8946 // Is the node an FMUL and contractable either due to global flags or
8948 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
8949 if (N.getOpcode() != ISD::FMUL)
8951 return AllowFusionGlobally || isContractable(N.getNode());
8953 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
8954 // prefer to fold the multiply with fewer uses.
8955 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
8956 if (N0.getNode()->use_size() > N1.getNode()->use_size())
8960 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
8961 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
8962 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8963 N0.getOperand(0), N0.getOperand(1), N1);
8966 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
8967 // Note: Commutes FADD operands.
8968 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
8969 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8970 N1.getOperand(0), N1.getOperand(1), N0);
8973 // Look through FP_EXTEND nodes to do more combining.
8974 if (LookThroughFPExt) {
8975 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
8976 if (N0.getOpcode() == ISD::FP_EXTEND) {
8977 SDValue N00 = N0.getOperand(0);
8978 if (isContractableFMUL(N00))
8979 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8980 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8982 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8983 N00.getOperand(1)), N1);
8986 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
8987 // Note: Commutes FADD operands.
8988 if (N1.getOpcode() == ISD::FP_EXTEND) {
8989 SDValue N10 = N1.getOperand(0);
8990 if (isContractableFMUL(N10))
8991 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8992 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8994 DAG.getNode(ISD::FP_EXTEND, SL, VT,
8995 N10.getOperand(1)), N0);
8999 // More folding opportunities when target permits.
9001 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
9002 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9003 // are currently only supported on binary nodes.
9004 if (Options.UnsafeFPMath &&
9005 N0.getOpcode() == PreferredFusedOpcode &&
9006 N0.getOperand(2).getOpcode() == ISD::FMUL &&
9007 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
9008 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9009 N0.getOperand(0), N0.getOperand(1),
9010 DAG.getNode(PreferredFusedOpcode, SL, VT,
9011 N0.getOperand(2).getOperand(0),
9012 N0.getOperand(2).getOperand(1),
9016 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
9017 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9018 // are currently only supported on binary nodes.
9019 if (Options.UnsafeFPMath &&
9020 N1->getOpcode() == PreferredFusedOpcode &&
9021 N1.getOperand(2).getOpcode() == ISD::FMUL &&
9022 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
9023 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9024 N1.getOperand(0), N1.getOperand(1),
9025 DAG.getNode(PreferredFusedOpcode, SL, VT,
9026 N1.getOperand(2).getOperand(0),
9027 N1.getOperand(2).getOperand(1),
9031 if (LookThroughFPExt) {
9032 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
9033 // -> (fma x, y, (fma (fpext u), (fpext v), z))
9034 auto FoldFAddFMAFPExtFMul = [&] (
9035 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9036 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
9037 DAG.getNode(PreferredFusedOpcode, SL, VT,
9038 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9039 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9042 if (N0.getOpcode() == PreferredFusedOpcode) {
9043 SDValue N02 = N0.getOperand(2);
9044 if (N02.getOpcode() == ISD::FP_EXTEND) {
9045 SDValue N020 = N02.getOperand(0);
9046 if (isContractableFMUL(N020))
9047 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
9048 N020.getOperand(0), N020.getOperand(1),
9053 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
9054 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
9055 // FIXME: This turns two single-precision and one double-precision
9056 // operation into two double-precision operations, which might not be
9057 // interesting for all targets, especially GPUs.
9058 auto FoldFAddFPExtFMAFMul = [&] (
9059 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
9060 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9061 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
9062 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
9063 DAG.getNode(PreferredFusedOpcode, SL, VT,
9064 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
9065 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
9068 if (N0.getOpcode() == ISD::FP_EXTEND) {
9069 SDValue N00 = N0.getOperand(0);
9070 if (N00.getOpcode() == PreferredFusedOpcode) {
9071 SDValue N002 = N00.getOperand(2);
9072 if (isContractableFMUL(N002))
9073 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
9074 N002.getOperand(0), N002.getOperand(1),
9079 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
9080 // -> (fma y, z, (fma (fpext u), (fpext v), x))
9081 if (N1.getOpcode() == PreferredFusedOpcode) {
9082 SDValue N12 = N1.getOperand(2);
9083 if (N12.getOpcode() == ISD::FP_EXTEND) {
9084 SDValue N120 = N12.getOperand(0);
9085 if (isContractableFMUL(N120))
9086 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
9087 N120.getOperand(0), N120.getOperand(1),
9092 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
9093 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
9094 // FIXME: This turns two single-precision and one double-precision
9095 // operation into two double-precision operations, which might not be
9096 // interesting for all targets, especially GPUs.
9097 if (N1.getOpcode() == ISD::FP_EXTEND) {
9098 SDValue N10 = N1.getOperand(0);
9099 if (N10.getOpcode() == PreferredFusedOpcode) {
9100 SDValue N102 = N10.getOperand(2);
9101 if (isContractableFMUL(N102))
9102 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
9103 N102.getOperand(0), N102.getOperand(1),
9113 /// Try to perform FMA combining on a given FSUB node.
9114 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
9115 SDValue N0 = N->getOperand(0);
9116 SDValue N1 = N->getOperand(1);
9117 EVT VT = N->getValueType(0);
9120 const TargetOptions &Options = DAG.getTarget().Options;
9121 // Floating-point multiply-add with intermediate rounding.
9122 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9124 // Floating-point multiply-add without intermediate rounding.
9126 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9127 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9129 // No valid opcode, do not combine.
9130 if (!HasFMAD && !HasFMA)
9133 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9134 Options.UnsafeFPMath || HasFMAD);
9135 // If the subtraction is not contractable, do not combine.
9136 if (!AllowFusionGlobally && !isContractable(N))
9139 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
9140 if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
9143 // Always prefer FMAD to FMA for precision.
9144 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9145 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9146 bool LookThroughFPExt = TLI.isFPExtFree(VT);
9148 // Is the node an FMUL and contractable either due to global flags or
9150 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
9151 if (N.getOpcode() != ISD::FMUL)
9153 return AllowFusionGlobally || isContractable(N.getNode());
9156 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
9157 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
9158 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9159 N0.getOperand(0), N0.getOperand(1),
9160 DAG.getNode(ISD::FNEG, SL, VT, N1));
9163 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
9164 // Note: Commutes FSUB operands.
9165 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
9166 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9167 DAG.getNode(ISD::FNEG, SL, VT,
9169 N1.getOperand(1), N0);
9171 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
9172 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
9173 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
9174 SDValue N00 = N0.getOperand(0).getOperand(0);
9175 SDValue N01 = N0.getOperand(0).getOperand(1);
9176 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9177 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
9178 DAG.getNode(ISD::FNEG, SL, VT, N1));
9181 // Look through FP_EXTEND nodes to do more combining.
9182 if (LookThroughFPExt) {
9183 // fold (fsub (fpext (fmul x, y)), z)
9184 // -> (fma (fpext x), (fpext y), (fneg z))
9185 if (N0.getOpcode() == ISD::FP_EXTEND) {
9186 SDValue N00 = N0.getOperand(0);
9187 if (isContractableFMUL(N00))
9188 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9189 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9191 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9193 DAG.getNode(ISD::FNEG, SL, VT, N1));
9196 // fold (fsub x, (fpext (fmul y, z)))
9197 // -> (fma (fneg (fpext y)), (fpext z), x)
9198 // Note: Commutes FSUB operands.
9199 if (N1.getOpcode() == ISD::FP_EXTEND) {
9200 SDValue N10 = N1.getOperand(0);
9201 if (isContractableFMUL(N10))
9202 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9203 DAG.getNode(ISD::FNEG, SL, VT,
9204 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9205 N10.getOperand(0))),
9206 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9211 // fold (fsub (fpext (fneg (fmul, x, y))), z)
9212 // -> (fneg (fma (fpext x), (fpext y), z))
9213 // Note: This could be removed with appropriate canonicalization of the
9214 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9215 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9216 // from implementing the canonicalization in visitFSUB.
9217 if (N0.getOpcode() == ISD::FP_EXTEND) {
9218 SDValue N00 = N0.getOperand(0);
9219 if (N00.getOpcode() == ISD::FNEG) {
9220 SDValue N000 = N00.getOperand(0);
9221 if (isContractableFMUL(N000)) {
9222 return DAG.getNode(ISD::FNEG, SL, VT,
9223 DAG.getNode(PreferredFusedOpcode, SL, VT,
9224 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9225 N000.getOperand(0)),
9226 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9227 N000.getOperand(1)),
9233 // fold (fsub (fneg (fpext (fmul, x, y))), z)
9234 // -> (fneg (fma (fpext x)), (fpext y), z)
9235 // Note: This could be removed with appropriate canonicalization of the
9236 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
9237 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
9238 // from implementing the canonicalization in visitFSUB.
9239 if (N0.getOpcode() == ISD::FNEG) {
9240 SDValue N00 = N0.getOperand(0);
9241 if (N00.getOpcode() == ISD::FP_EXTEND) {
9242 SDValue N000 = N00.getOperand(0);
9243 if (isContractableFMUL(N000)) {
9244 return DAG.getNode(ISD::FNEG, SL, VT,
9245 DAG.getNode(PreferredFusedOpcode, SL, VT,
9246 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9247 N000.getOperand(0)),
9248 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9249 N000.getOperand(1)),
9257 // More folding opportunities when target permits.
9259 // fold (fsub (fma x, y, (fmul u, v)), z)
9260 // -> (fma x, y (fma u, v, (fneg z)))
9261 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9262 // are currently only supported on binary nodes.
9263 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
9264 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
9265 N0.getOperand(2)->hasOneUse()) {
9266 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9267 N0.getOperand(0), N0.getOperand(1),
9268 DAG.getNode(PreferredFusedOpcode, SL, VT,
9269 N0.getOperand(2).getOperand(0),
9270 N0.getOperand(2).getOperand(1),
9271 DAG.getNode(ISD::FNEG, SL, VT,
9275 // fold (fsub x, (fma y, z, (fmul u, v)))
9276 // -> (fma (fneg y), z, (fma (fneg u), v, x))
9277 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
9278 // are currently only supported on binary nodes.
9279 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
9280 isContractableFMUL(N1.getOperand(2))) {
9281 SDValue N20 = N1.getOperand(2).getOperand(0);
9282 SDValue N21 = N1.getOperand(2).getOperand(1);
9283 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9284 DAG.getNode(ISD::FNEG, SL, VT,
9287 DAG.getNode(PreferredFusedOpcode, SL, VT,
9288 DAG.getNode(ISD::FNEG, SL, VT, N20),
9293 if (LookThroughFPExt) {
9294 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
9295 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
9296 if (N0.getOpcode() == PreferredFusedOpcode) {
9297 SDValue N02 = N0.getOperand(2);
9298 if (N02.getOpcode() == ISD::FP_EXTEND) {
9299 SDValue N020 = N02.getOperand(0);
9300 if (isContractableFMUL(N020))
9301 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9302 N0.getOperand(0), N0.getOperand(1),
9303 DAG.getNode(PreferredFusedOpcode, SL, VT,
9304 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9305 N020.getOperand(0)),
9306 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9307 N020.getOperand(1)),
9308 DAG.getNode(ISD::FNEG, SL, VT,
9313 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
9314 // -> (fma (fpext x), (fpext y),
9315 // (fma (fpext u), (fpext v), (fneg z)))
9316 // FIXME: This turns two single-precision and one double-precision
9317 // operation into two double-precision operations, which might not be
9318 // interesting for all targets, especially GPUs.
9319 if (N0.getOpcode() == ISD::FP_EXTEND) {
9320 SDValue N00 = N0.getOperand(0);
9321 if (N00.getOpcode() == PreferredFusedOpcode) {
9322 SDValue N002 = N00.getOperand(2);
9323 if (isContractableFMUL(N002))
9324 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9325 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9327 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9329 DAG.getNode(PreferredFusedOpcode, SL, VT,
9330 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9331 N002.getOperand(0)),
9332 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9333 N002.getOperand(1)),
9334 DAG.getNode(ISD::FNEG, SL, VT,
9339 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
9340 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
9341 if (N1.getOpcode() == PreferredFusedOpcode &&
9342 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
9343 SDValue N120 = N1.getOperand(2).getOperand(0);
9344 if (isContractableFMUL(N120)) {
9345 SDValue N1200 = N120.getOperand(0);
9346 SDValue N1201 = N120.getOperand(1);
9347 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9348 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
9350 DAG.getNode(PreferredFusedOpcode, SL, VT,
9351 DAG.getNode(ISD::FNEG, SL, VT,
9352 DAG.getNode(ISD::FP_EXTEND, SL,
9354 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9360 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
9361 // -> (fma (fneg (fpext y)), (fpext z),
9362 // (fma (fneg (fpext u)), (fpext v), x))
9363 // FIXME: This turns two single-precision and one double-precision
9364 // operation into two double-precision operations, which might not be
9365 // interesting for all targets, especially GPUs.
9366 if (N1.getOpcode() == ISD::FP_EXTEND &&
9367 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
9368 SDValue N100 = N1.getOperand(0).getOperand(0);
9369 SDValue N101 = N1.getOperand(0).getOperand(1);
9370 SDValue N102 = N1.getOperand(0).getOperand(2);
9371 if (isContractableFMUL(N102)) {
9372 SDValue N1020 = N102.getOperand(0);
9373 SDValue N1021 = N102.getOperand(1);
9374 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9375 DAG.getNode(ISD::FNEG, SL, VT,
9376 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9378 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
9379 DAG.getNode(PreferredFusedOpcode, SL, VT,
9380 DAG.getNode(ISD::FNEG, SL, VT,
9381 DAG.getNode(ISD::FP_EXTEND, SL,
9383 DAG.getNode(ISD::FP_EXTEND, SL, VT,
9394 /// Try to perform FMA combining on a given FMUL node based on the distributive
9395 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
9396 /// subtraction instead of addition).
9397 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
9398 SDValue N0 = N->getOperand(0);
9399 SDValue N1 = N->getOperand(1);
9400 EVT VT = N->getValueType(0);
9403 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
9405 const TargetOptions &Options = DAG.getTarget().Options;
9407 // The transforms below are incorrect when x == 0 and y == inf, because the
9408 // intermediate multiplication produces a nan.
9409 if (!Options.NoInfsFPMath)
9412 // Floating-point multiply-add without intermediate rounding.
9414 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
9415 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
9416 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
9418 // Floating-point multiply-add with intermediate rounding. This can result
9419 // in a less precise result due to the changed rounding order.
9420 bool HasFMAD = Options.UnsafeFPMath &&
9421 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
9423 // No valid opcode, do not combine.
9424 if (!HasFMAD && !HasFMA)
9427 // Always prefer FMAD to FMA for precision.
9428 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
9429 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
9431 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
9432 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
9433 auto FuseFADD = [&](SDValue X, SDValue Y) {
9434 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
9435 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9436 if (XC1 && XC1->isExactlyValue(+1.0))
9437 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9438 if (XC1 && XC1->isExactlyValue(-1.0))
9439 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9440 DAG.getNode(ISD::FNEG, SL, VT, Y));
9445 if (SDValue FMA = FuseFADD(N0, N1))
9447 if (SDValue FMA = FuseFADD(N1, N0))
9450 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
9451 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
9452 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
9453 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
9454 auto FuseFSUB = [&](SDValue X, SDValue Y) {
9455 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
9456 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
9457 if (XC0 && XC0->isExactlyValue(+1.0))
9458 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9459 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9461 if (XC0 && XC0->isExactlyValue(-1.0))
9462 return DAG.getNode(PreferredFusedOpcode, SL, VT,
9463 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
9464 DAG.getNode(ISD::FNEG, SL, VT, Y));
9466 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
9467 if (XC1 && XC1->isExactlyValue(+1.0))
9468 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
9469 DAG.getNode(ISD::FNEG, SL, VT, Y));
9470 if (XC1 && XC1->isExactlyValue(-1.0))
9471 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
9476 if (SDValue FMA = FuseFSUB(N0, N1))
9478 if (SDValue FMA = FuseFSUB(N1, N0))
9484 static bool isFMulNegTwo(SDValue &N) {
9485 if (N.getOpcode() != ISD::FMUL)
9487 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1)))
9488 return CFP->isExactlyValue(-2.0);
9492 SDValue DAGCombiner::visitFADD(SDNode *N) {
9493 SDValue N0 = N->getOperand(0);
9494 SDValue N1 = N->getOperand(1);
9495 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
9496 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
9497 EVT VT = N->getValueType(0);
9499 const TargetOptions &Options = DAG.getTarget().Options;
9500 const SDNodeFlags Flags = N->getFlags();
9504 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9507 // fold (fadd c1, c2) -> c1 + c2
9509 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
9511 // canonicalize constant to RHS
9512 if (N0CFP && !N1CFP)
9513 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
9515 if (SDValue NewSel = foldBinOpIntoSelect(N))
9518 // fold (fadd A, (fneg B)) -> (fsub A, B)
9519 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9520 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
9521 return DAG.getNode(ISD::FSUB, DL, VT, N0,
9522 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9524 // fold (fadd (fneg A), B) -> (fsub B, A)
9525 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
9526 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
9527 return DAG.getNode(ISD::FSUB, DL, VT, N1,
9528 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
9530 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B))
9531 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B))
9532 if ((isFMulNegTwo(N0) && N0.hasOneUse()) ||
9533 (isFMulNegTwo(N1) && N1.hasOneUse())) {
9534 bool N1IsFMul = isFMulNegTwo(N1);
9535 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0);
9536 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags);
9537 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags);
9540 // FIXME: Auto-upgrade the target/function-level option.
9541 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9542 // fold (fadd A, 0) -> A
9543 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
9548 // If 'unsafe math' is enabled, fold lots of things.
9549 if (Options.UnsafeFPMath) {
9550 // No FP constant should be created after legalization as Instruction
9551 // Selection pass has a hard time dealing with FP constants.
9552 bool AllowNewConst = (Level < AfterLegalizeDAG);
9554 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
9555 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
9556 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
9557 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
9558 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
9562 // If allowed, fold (fadd (fneg x), x) -> 0.0
9563 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
9564 return DAG.getConstantFP(0.0, DL, VT);
9566 // If allowed, fold (fadd x, (fneg x)) -> 0.0
9567 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
9568 return DAG.getConstantFP(0.0, DL, VT);
9570 // We can fold chains of FADD's of the same value into multiplications.
9571 // This transform is not safe in general because we are reducing the number
9572 // of rounding steps.
9573 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
9574 if (N0.getOpcode() == ISD::FMUL) {
9575 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9576 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
9578 // (fadd (fmul x, c), x) -> (fmul x, c+1)
9579 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
9580 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9581 DAG.getConstantFP(1.0, DL, VT), Flags);
9582 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
9585 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
9586 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
9587 N1.getOperand(0) == N1.getOperand(1) &&
9588 N0.getOperand(0) == N1.getOperand(0)) {
9589 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
9590 DAG.getConstantFP(2.0, DL, VT), Flags);
9591 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
9595 if (N1.getOpcode() == ISD::FMUL) {
9596 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9597 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
9599 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
9600 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
9601 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9602 DAG.getConstantFP(1.0, DL, VT), Flags);
9603 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
9606 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
9607 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
9608 N0.getOperand(0) == N0.getOperand(1) &&
9609 N1.getOperand(0) == N0.getOperand(0)) {
9610 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
9611 DAG.getConstantFP(2.0, DL, VT), Flags);
9612 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
9616 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
9617 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
9618 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
9619 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
9620 (N0.getOperand(0) == N1)) {
9621 return DAG.getNode(ISD::FMUL, DL, VT,
9622 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
9626 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
9627 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
9628 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
9629 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
9630 N1.getOperand(0) == N0) {
9631 return DAG.getNode(ISD::FMUL, DL, VT,
9632 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
9636 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
9637 if (AllowNewConst &&
9638 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
9639 N0.getOperand(0) == N0.getOperand(1) &&
9640 N1.getOperand(0) == N1.getOperand(1) &&
9641 N0.getOperand(0) == N1.getOperand(0)) {
9642 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
9643 DAG.getConstantFP(4.0, DL, VT), Flags);
9646 } // enable-unsafe-fp-math
9648 // FADD -> FMA combines:
9649 if (SDValue Fused = visitFADDForFMACombine(N)) {
9650 AddToWorklist(Fused.getNode());
9656 SDValue DAGCombiner::visitFSUB(SDNode *N) {
9657 SDValue N0 = N->getOperand(0);
9658 SDValue N1 = N->getOperand(1);
9659 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9660 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9661 EVT VT = N->getValueType(0);
9663 const TargetOptions &Options = DAG.getTarget().Options;
9664 const SDNodeFlags Flags = N->getFlags();
9668 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9671 // fold (fsub c1, c2) -> c1-c2
9673 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
9675 if (SDValue NewSel = foldBinOpIntoSelect(N))
9678 // fold (fsub A, (fneg B)) -> (fadd A, B)
9679 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9680 return DAG.getNode(ISD::FADD, DL, VT, N0,
9681 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
9683 // FIXME: Auto-upgrade the target/function-level option.
9684 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) {
9685 // (fsub 0, B) -> -B
9686 if (N0CFP && N0CFP->isZero()) {
9687 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
9688 return GetNegatedExpression(N1, DAG, LegalOperations);
9689 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9690 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
9694 // If 'unsafe math' is enabled, fold lots of things.
9695 if (Options.UnsafeFPMath) {
9697 if (N1CFP && N1CFP->isZero())
9700 // (fsub x, x) -> 0.0
9702 return DAG.getConstantFP(0.0f, DL, VT);
9704 // (fsub x, (fadd x, y)) -> (fneg y)
9705 // (fsub x, (fadd y, x)) -> (fneg y)
9706 if (N1.getOpcode() == ISD::FADD) {
9707 SDValue N10 = N1->getOperand(0);
9708 SDValue N11 = N1->getOperand(1);
9710 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
9711 return GetNegatedExpression(N11, DAG, LegalOperations);
9713 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
9714 return GetNegatedExpression(N10, DAG, LegalOperations);
9718 // FSUB -> FMA combines:
9719 if (SDValue Fused = visitFSUBForFMACombine(N)) {
9720 AddToWorklist(Fused.getNode());
9727 SDValue DAGCombiner::visitFMUL(SDNode *N) {
9728 SDValue N0 = N->getOperand(0);
9729 SDValue N1 = N->getOperand(1);
9730 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9731 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9732 EVT VT = N->getValueType(0);
9734 const TargetOptions &Options = DAG.getTarget().Options;
9735 const SDNodeFlags Flags = N->getFlags();
9738 if (VT.isVector()) {
9739 // This just handles C1 * C2 for vectors. Other vector folds are below.
9740 if (SDValue FoldedVOp = SimplifyVBinOp(N))
9744 // fold (fmul c1, c2) -> c1*c2
9746 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
9748 // canonicalize constant to RHS
9749 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9750 !isConstantFPBuildVectorOrConstantFP(N1))
9751 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
9753 // fold (fmul A, 1.0) -> A
9754 if (N1CFP && N1CFP->isExactlyValue(1.0))
9757 if (SDValue NewSel = foldBinOpIntoSelect(N))
9760 if (Options.UnsafeFPMath) {
9761 // fold (fmul A, 0) -> 0
9762 if (N1CFP && N1CFP->isZero())
9765 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
9766 if (N0.getOpcode() == ISD::FMUL) {
9767 // Fold scalars or any vector constants (not just splats).
9768 // This fold is done in general by InstCombine, but extra fmul insts
9769 // may have been generated during lowering.
9770 SDValue N00 = N0.getOperand(0);
9771 SDValue N01 = N0.getOperand(1);
9772 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
9773 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
9774 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
9776 // Check 1: Make sure that the first operand of the inner multiply is NOT
9777 // a constant. Otherwise, we may induce infinite looping.
9778 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
9779 // Check 2: Make sure that the second operand of the inner multiply and
9780 // the second operand of the outer multiply are constants.
9781 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
9782 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
9783 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
9784 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
9789 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
9790 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
9791 // during an early run of DAGCombiner can prevent folding with fmuls
9792 // inserted during lowering.
9793 if (N0.getOpcode() == ISD::FADD &&
9794 (N0.getOperand(0) == N0.getOperand(1)) &&
9796 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
9797 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
9798 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
9802 // fold (fmul X, 2.0) -> (fadd X, X)
9803 if (N1CFP && N1CFP->isExactlyValue(+2.0))
9804 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
9806 // fold (fmul X, -1.0) -> (fneg X)
9807 if (N1CFP && N1CFP->isExactlyValue(-1.0))
9808 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
9809 return DAG.getNode(ISD::FNEG, DL, VT, N0);
9811 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
9812 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
9813 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
9814 // Both can be negated for free, check to see if at least one is cheaper
9816 if (LHSNeg == 2 || RHSNeg == 2)
9817 return DAG.getNode(ISD::FMUL, DL, VT,
9818 GetNegatedExpression(N0, DAG, LegalOperations),
9819 GetNegatedExpression(N1, DAG, LegalOperations),
9824 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
9825 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
9826 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
9827 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
9828 TLI.isOperationLegal(ISD::FABS, VT)) {
9829 SDValue Select = N0, X = N1;
9830 if (Select.getOpcode() != ISD::SELECT)
9831 std::swap(Select, X);
9833 SDValue Cond = Select.getOperand(0);
9834 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
9835 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
9837 if (TrueOpnd && FalseOpnd &&
9838 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
9839 isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
9840 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
9841 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9850 std::swap(TrueOpnd, FalseOpnd);
9858 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
9859 TLI.isOperationLegal(ISD::FNEG, VT))
9860 return DAG.getNode(ISD::FNEG, DL, VT,
9861 DAG.getNode(ISD::FABS, DL, VT, X));
9862 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
9863 return DAG.getNode(ISD::FABS, DL, VT, X);
9870 // FMUL -> FMA combines:
9871 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
9872 AddToWorklist(Fused.getNode());
9879 SDValue DAGCombiner::visitFMA(SDNode *N) {
9880 SDValue N0 = N->getOperand(0);
9881 SDValue N1 = N->getOperand(1);
9882 SDValue N2 = N->getOperand(2);
9883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9884 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
9885 EVT VT = N->getValueType(0);
9887 const TargetOptions &Options = DAG.getTarget().Options;
9889 // Constant fold FMA.
9890 if (isa<ConstantFPSDNode>(N0) &&
9891 isa<ConstantFPSDNode>(N1) &&
9892 isa<ConstantFPSDNode>(N2)) {
9893 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
9896 if (Options.UnsafeFPMath) {
9897 if (N0CFP && N0CFP->isZero())
9899 if (N1CFP && N1CFP->isZero())
9902 // TODO: The FMA node should have flags that propagate to these nodes.
9903 if (N0CFP && N0CFP->isExactlyValue(1.0))
9904 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
9905 if (N1CFP && N1CFP->isExactlyValue(1.0))
9906 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
9908 // Canonicalize (fma c, x, y) -> (fma x, c, y)
9909 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9910 !isConstantFPBuildVectorOrConstantFP(N1))
9911 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
9913 // TODO: FMA nodes should have flags that propagate to the created nodes.
9914 // For now, create a Flags object for use with all unsafe math transforms.
9916 Flags.setUnsafeAlgebra(true);
9918 if (Options.UnsafeFPMath) {
9919 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
9920 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
9921 isConstantFPBuildVectorOrConstantFP(N1) &&
9922 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
9923 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9924 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
9928 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
9929 if (N0.getOpcode() == ISD::FMUL &&
9930 isConstantFPBuildVectorOrConstantFP(N1) &&
9931 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
9932 return DAG.getNode(ISD::FMA, DL, VT,
9934 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
9940 // (fma x, 1, y) -> (fadd x, y)
9941 // (fma x, -1, y) -> (fadd (fneg x), y)
9943 if (N1CFP->isExactlyValue(1.0))
9944 // TODO: The FMA node should have flags that propagate to this node.
9945 return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
9947 if (N1CFP->isExactlyValue(-1.0) &&
9948 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
9949 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
9950 AddToWorklist(RHSNeg.getNode());
9951 // TODO: The FMA node should have flags that propagate to this node.
9952 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
9956 if (Options.UnsafeFPMath) {
9957 // (fma x, c, x) -> (fmul x, (c+1))
9958 if (N1CFP && N0 == N2) {
9959 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9960 DAG.getNode(ISD::FADD, DL, VT, N1,
9961 DAG.getConstantFP(1.0, DL, VT), Flags),
9965 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
9966 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
9967 return DAG.getNode(ISD::FMUL, DL, VT, N0,
9968 DAG.getNode(ISD::FADD, DL, VT, N1,
9969 DAG.getConstantFP(-1.0, DL, VT), Flags),
9977 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9979 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
9980 // Notice that this is not always beneficial. One reason is different targets
9981 // may have different costs for FDIV and FMUL, so sometimes the cost of two
9982 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
9983 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
9984 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
9985 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
9986 const SDNodeFlags Flags = N->getFlags();
9987 if (!UnsafeMath && !Flags.hasAllowReciprocal())
9990 // Skip if current node is a reciprocal.
9991 SDValue N0 = N->getOperand(0);
9992 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
9993 if (N0CFP && N0CFP->isExactlyValue(1.0))
9996 // Exit early if the target does not want this transform or if there can't
9997 // possibly be enough uses of the divisor to make the transform worthwhile.
9998 SDValue N1 = N->getOperand(1);
9999 unsigned MinUses = TLI.combineRepeatedFPDivisors();
10000 if (!MinUses || N1->use_size() < MinUses)
10003 // Find all FDIV users of the same divisor.
10004 // Use a set because duplicates may be present in the user list.
10005 SetVector<SDNode *> Users;
10006 for (auto *U : N1->uses()) {
10007 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
10008 // This division is eligible for optimization only if global unsafe math
10009 // is enabled or if this division allows reciprocal formation.
10010 if (UnsafeMath || U->getFlags().hasAllowReciprocal())
10015 // Now that we have the actual number of divisor uses, make sure it meets
10016 // the minimum threshold specified by the target.
10017 if (Users.size() < MinUses)
10020 EVT VT = N->getValueType(0);
10022 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
10023 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
10025 // Dividend / Divisor -> Dividend * Reciprocal
10026 for (auto *U : Users) {
10027 SDValue Dividend = U->getOperand(0);
10028 if (Dividend != FPOne) {
10029 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
10030 Reciprocal, Flags);
10031 CombineTo(U, NewNode);
10032 } else if (U != Reciprocal.getNode()) {
10033 // In the absence of fast-math-flags, this user node is always the
10034 // same node as Reciprocal, but with FMF they may be different nodes.
10035 CombineTo(U, Reciprocal);
10038 return SDValue(N, 0); // N was replaced.
10041 SDValue DAGCombiner::visitFDIV(SDNode *N) {
10042 SDValue N0 = N->getOperand(0);
10043 SDValue N1 = N->getOperand(1);
10044 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10045 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10046 EVT VT = N->getValueType(0);
10048 const TargetOptions &Options = DAG.getTarget().Options;
10049 SDNodeFlags Flags = N->getFlags();
10053 if (SDValue FoldedVOp = SimplifyVBinOp(N))
10056 // fold (fdiv c1, c2) -> c1/c2
10057 if (N0CFP && N1CFP)
10058 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
10060 if (SDValue NewSel = foldBinOpIntoSelect(N))
10063 if (Options.UnsafeFPMath) {
10064 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
10066 // Compute the reciprocal 1.0 / c2.
10067 const APFloat &N1APF = N1CFP->getValueAPF();
10068 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
10069 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
10070 // Only do the transform if the reciprocal is a legal fp immediate that
10071 // isn't too nasty (eg NaN, denormal, ...).
10072 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
10073 (!LegalOperations ||
10074 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
10075 // backend)... we should handle this gracefully after Legalize.
10076 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
10077 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
10078 TLI.isFPImmLegal(Recip, VT)))
10079 return DAG.getNode(ISD::FMUL, DL, VT, N0,
10080 DAG.getConstantFP(Recip, DL, VT), Flags);
10083 // If this FDIV is part of a reciprocal square root, it may be folded
10084 // into a target-specific square root estimate instruction.
10085 if (N1.getOpcode() == ISD::FSQRT) {
10086 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
10087 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10089 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
10090 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10091 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10093 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
10094 AddToWorklist(RV.getNode());
10095 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10097 } else if (N1.getOpcode() == ISD::FP_ROUND &&
10098 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10099 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
10101 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
10102 AddToWorklist(RV.getNode());
10103 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10105 } else if (N1.getOpcode() == ISD::FMUL) {
10106 // Look through an FMUL. Even though this won't remove the FDIV directly,
10107 // it's still worthwhile to get rid of the FSQRT if possible.
10110 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
10111 SqrtOp = N1.getOperand(0);
10112 OtherOp = N1.getOperand(1);
10113 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
10114 SqrtOp = N1.getOperand(1);
10115 OtherOp = N1.getOperand(0);
10117 if (SqrtOp.getNode()) {
10118 // We found a FSQRT, so try to make this fold:
10119 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
10120 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
10121 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
10122 AddToWorklist(RV.getNode());
10123 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10128 // Fold into a reciprocal estimate and multiply instead of a real divide.
10129 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
10130 AddToWorklist(RV.getNode());
10131 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
10135 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
10136 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
10137 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
10138 // Both can be negated for free, check to see if at least one is cheaper
10140 if (LHSNeg == 2 || RHSNeg == 2)
10141 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
10142 GetNegatedExpression(N0, DAG, LegalOperations),
10143 GetNegatedExpression(N1, DAG, LegalOperations),
10148 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
10149 return CombineRepeatedDivisors;
10154 SDValue DAGCombiner::visitFREM(SDNode *N) {
10155 SDValue N0 = N->getOperand(0);
10156 SDValue N1 = N->getOperand(1);
10157 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10158 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10159 EVT VT = N->getValueType(0);
10161 // fold (frem c1, c2) -> fmod(c1,c2)
10162 if (N0CFP && N1CFP)
10163 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags());
10165 if (SDValue NewSel = foldBinOpIntoSelect(N))
10171 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
10172 if (!DAG.getTarget().Options.UnsafeFPMath)
10175 SDValue N0 = N->getOperand(0);
10176 if (TLI.isFsqrtCheap(N0, DAG))
10179 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
10180 // For now, create a Flags object for use with all unsafe math transforms.
10182 Flags.setUnsafeAlgebra(true);
10183 return buildSqrtEstimate(N0, Flags);
10186 /// copysign(x, fp_extend(y)) -> copysign(x, y)
10187 /// copysign(x, fp_round(y)) -> copysign(x, y)
10188 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
10189 SDValue N1 = N->getOperand(1);
10190 if ((N1.getOpcode() == ISD::FP_EXTEND ||
10191 N1.getOpcode() == ISD::FP_ROUND)) {
10192 // Do not optimize out type conversion of f128 type yet.
10193 // For some targets like x86_64, configuration is changed to keep one f128
10194 // value in one SSE register, but instruction selection cannot handle
10195 // FCOPYSIGN on SSE registers yet.
10196 EVT N1VT = N1->getValueType(0);
10197 EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
10198 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
10203 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
10204 SDValue N0 = N->getOperand(0);
10205 SDValue N1 = N->getOperand(1);
10206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10207 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
10208 EVT VT = N->getValueType(0);
10210 if (N0CFP && N1CFP) // Constant fold
10211 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
10214 const APFloat &V = N1CFP->getValueAPF();
10215 // copysign(x, c1) -> fabs(x) iff ispos(c1)
10216 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
10217 if (!V.isNegative()) {
10218 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
10219 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10221 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
10222 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
10223 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
10227 // copysign(fabs(x), y) -> copysign(x, y)
10228 // copysign(fneg(x), y) -> copysign(x, y)
10229 // copysign(copysign(x,z), y) -> copysign(x, y)
10230 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
10231 N0.getOpcode() == ISD::FCOPYSIGN)
10232 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
10234 // copysign(x, abs(y)) -> abs(x)
10235 if (N1.getOpcode() == ISD::FABS)
10236 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10238 // copysign(x, copysign(y,z)) -> copysign(x, z)
10239 if (N1.getOpcode() == ISD::FCOPYSIGN)
10240 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
10242 // copysign(x, fp_extend(y)) -> copysign(x, y)
10243 // copysign(x, fp_round(y)) -> copysign(x, y)
10244 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
10245 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
10250 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
10251 SDValue N0 = N->getOperand(0);
10252 EVT VT = N->getValueType(0);
10253 EVT OpVT = N0.getValueType();
10255 // fold (sint_to_fp c1) -> c1fp
10256 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10257 // ...but only if the target supports immediate floating-point values
10258 (!LegalOperations ||
10259 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10260 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10262 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
10263 // but UINT_TO_FP is legal on this target, try to convert.
10264 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
10265 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
10266 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
10267 if (DAG.SignBitIsZero(N0))
10268 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10271 // The next optimizations are desirable only if SELECT_CC can be lowered.
10272 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10273 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10274 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
10276 (!LegalOperations ||
10277 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10280 { N0.getOperand(0), N0.getOperand(1),
10281 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10282 N0.getOperand(2) };
10283 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10286 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
10287 // (select_cc x, y, 1.0, 0.0,, cc)
10288 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
10289 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
10290 (!LegalOperations ||
10291 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10294 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
10295 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10296 N0.getOperand(0).getOperand(2) };
10297 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10304 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
10305 SDValue N0 = N->getOperand(0);
10306 EVT VT = N->getValueType(0);
10307 EVT OpVT = N0.getValueType();
10309 // fold (uint_to_fp c1) -> c1fp
10310 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
10311 // ...but only if the target supports immediate floating-point values
10312 (!LegalOperations ||
10313 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
10314 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
10316 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
10317 // but SINT_TO_FP is legal on this target, try to convert.
10318 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
10319 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
10320 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
10321 if (DAG.SignBitIsZero(N0))
10322 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
10325 // The next optimizations are desirable only if SELECT_CC can be lowered.
10326 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
10327 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
10329 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
10330 (!LegalOperations ||
10331 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
10334 { N0.getOperand(0), N0.getOperand(1),
10335 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
10336 N0.getOperand(2) };
10337 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
10344 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
10345 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
10346 SDValue N0 = N->getOperand(0);
10347 EVT VT = N->getValueType(0);
10349 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
10352 SDValue Src = N0.getOperand(0);
10353 EVT SrcVT = Src.getValueType();
10354 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
10355 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
10357 // We can safely assume the conversion won't overflow the output range,
10358 // because (for example) (uint8_t)18293.f is undefined behavior.
10360 // Since we can assume the conversion won't overflow, our decision as to
10361 // whether the input will fit in the float should depend on the minimum
10362 // of the input range and output range.
10364 // This means this is also safe for a signed input and unsigned output, since
10365 // a negative input would lead to undefined behavior.
10366 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
10367 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
10368 unsigned ActualSize = std::min(InputSize, OutputSize);
10369 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
10371 // We can only fold away the float conversion if the input range can be
10372 // represented exactly in the float range.
10373 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
10374 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
10375 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
10376 : ISD::ZERO_EXTEND;
10377 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
10379 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
10380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
10381 return DAG.getBitcast(VT, Src);
10386 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
10387 SDValue N0 = N->getOperand(0);
10388 EVT VT = N->getValueType(0);
10390 // fold (fp_to_sint c1fp) -> c1
10391 if (isConstantFPBuildVectorOrConstantFP(N0))
10392 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
10394 return FoldIntToFPToInt(N, DAG);
10397 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
10398 SDValue N0 = N->getOperand(0);
10399 EVT VT = N->getValueType(0);
10401 // fold (fp_to_uint c1fp) -> c1
10402 if (isConstantFPBuildVectorOrConstantFP(N0))
10403 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
10405 return FoldIntToFPToInt(N, DAG);
10408 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
10409 SDValue N0 = N->getOperand(0);
10410 SDValue N1 = N->getOperand(1);
10411 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10412 EVT VT = N->getValueType(0);
10414 // fold (fp_round c1fp) -> c1fp
10416 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
10418 // fold (fp_round (fp_extend x)) -> x
10419 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
10420 return N0.getOperand(0);
10422 // fold (fp_round (fp_round x)) -> (fp_round x)
10423 if (N0.getOpcode() == ISD::FP_ROUND) {
10424 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
10425 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
10427 // Skip this folding if it results in an fp_round from f80 to f16.
10429 // f80 to f16 always generates an expensive (and as yet, unimplemented)
10430 // libcall to __truncxfhf2 instead of selecting native f16 conversion
10431 // instructions from f32 or f64. Moreover, the first (value-preserving)
10432 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
10434 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
10437 // If the first fp_round isn't a value preserving truncation, it might
10438 // introduce a tie in the second fp_round, that wouldn't occur in the
10439 // single-step fp_round we want to fold to.
10440 // In other words, double rounding isn't the same as rounding.
10441 // Also, this is a value preserving truncation iff both fp_round's are.
10442 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
10444 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
10445 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
10449 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
10450 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
10451 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
10452 N0.getOperand(0), N1);
10453 AddToWorklist(Tmp.getNode());
10454 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
10455 Tmp, N0.getOperand(1));
10458 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10464 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
10465 SDValue N0 = N->getOperand(0);
10466 EVT VT = N->getValueType(0);
10467 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
10468 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
10470 // fold (fp_round_inreg c1fp) -> c1fp
10471 if (N0CFP && isTypeLegal(EVT)) {
10473 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
10474 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
10480 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
10481 SDValue N0 = N->getOperand(0);
10482 EVT VT = N->getValueType(0);
10484 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
10485 if (N->hasOneUse() &&
10486 N->use_begin()->getOpcode() == ISD::FP_ROUND)
10489 // fold (fp_extend c1fp) -> c1fp
10490 if (isConstantFPBuildVectorOrConstantFP(N0))
10491 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
10493 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
10494 if (N0.getOpcode() == ISD::FP16_TO_FP &&
10495 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
10496 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
10498 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
10500 if (N0.getOpcode() == ISD::FP_ROUND
10501 && N0.getConstantOperandVal(1) == 1) {
10502 SDValue In = N0.getOperand(0);
10503 if (In.getValueType() == VT) return In;
10504 if (VT.bitsLT(In.getValueType()))
10505 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
10506 In, N0.getOperand(1));
10507 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
10510 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
10511 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10512 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
10513 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10514 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
10516 LN0->getBasePtr(), N0.getValueType(),
10517 LN0->getMemOperand());
10518 CombineTo(N, ExtLoad);
10519 CombineTo(N0.getNode(),
10520 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
10521 N0.getValueType(), ExtLoad,
10522 DAG.getIntPtrConstant(1, SDLoc(N0))),
10523 ExtLoad.getValue(1));
10524 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10527 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
10533 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
10534 SDValue N0 = N->getOperand(0);
10535 EVT VT = N->getValueType(0);
10537 // fold (fceil c1) -> fceil(c1)
10538 if (isConstantFPBuildVectorOrConstantFP(N0))
10539 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
10544 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
10545 SDValue N0 = N->getOperand(0);
10546 EVT VT = N->getValueType(0);
10548 // fold (ftrunc c1) -> ftrunc(c1)
10549 if (isConstantFPBuildVectorOrConstantFP(N0))
10550 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
10555 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
10556 SDValue N0 = N->getOperand(0);
10557 EVT VT = N->getValueType(0);
10559 // fold (ffloor c1) -> ffloor(c1)
10560 if (isConstantFPBuildVectorOrConstantFP(N0))
10561 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
10566 // FIXME: FNEG and FABS have a lot in common; refactor.
10567 SDValue DAGCombiner::visitFNEG(SDNode *N) {
10568 SDValue N0 = N->getOperand(0);
10569 EVT VT = N->getValueType(0);
10571 // Constant fold FNEG.
10572 if (isConstantFPBuildVectorOrConstantFP(N0))
10573 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
10575 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
10576 &DAG.getTarget().Options))
10577 return GetNegatedExpression(N0, DAG, LegalOperations);
10579 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
10580 // constant pool values.
10581 if (!TLI.isFNegFree(VT) &&
10582 N0.getOpcode() == ISD::BITCAST &&
10583 N0.getNode()->hasOneUse()) {
10584 SDValue Int = N0.getOperand(0);
10585 EVT IntVT = Int.getValueType();
10586 if (IntVT.isInteger() && !IntVT.isVector()) {
10588 if (N0.getValueType().isVector()) {
10589 // For a vector, get a mask such as 0x80... per scalar element
10591 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
10592 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10594 // For a scalar, just generate 0x80...
10595 SignMask = APInt::getSignMask(IntVT.getSizeInBits());
10598 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
10599 DAG.getConstant(SignMask, DL0, IntVT));
10600 AddToWorklist(Int.getNode());
10601 return DAG.getBitcast(VT, Int);
10605 // (fneg (fmul c, x)) -> (fmul -c, x)
10606 if (N0.getOpcode() == ISD::FMUL &&
10607 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
10608 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10610 APFloat CVal = CFP1->getValueAPF();
10612 if (Level >= AfterLegalizeDAG &&
10613 (TLI.isFPImmLegal(CVal, VT) ||
10614 TLI.isOperationLegal(ISD::ConstantFP, VT)))
10615 return DAG.getNode(
10616 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
10617 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)),
10625 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
10626 SDValue N0 = N->getOperand(0);
10627 SDValue N1 = N->getOperand(1);
10628 EVT VT = N->getValueType(0);
10629 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10630 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10632 if (N0CFP && N1CFP) {
10633 const APFloat &C0 = N0CFP->getValueAPF();
10634 const APFloat &C1 = N1CFP->getValueAPF();
10635 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
10638 // Canonicalize to constant on RHS.
10639 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10640 !isConstantFPBuildVectorOrConstantFP(N1))
10641 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
10646 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
10647 SDValue N0 = N->getOperand(0);
10648 SDValue N1 = N->getOperand(1);
10649 EVT VT = N->getValueType(0);
10650 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
10651 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
10653 if (N0CFP && N1CFP) {
10654 const APFloat &C0 = N0CFP->getValueAPF();
10655 const APFloat &C1 = N1CFP->getValueAPF();
10656 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
10659 // Canonicalize to constant on RHS.
10660 if (isConstantFPBuildVectorOrConstantFP(N0) &&
10661 !isConstantFPBuildVectorOrConstantFP(N1))
10662 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
10667 SDValue DAGCombiner::visitFABS(SDNode *N) {
10668 SDValue N0 = N->getOperand(0);
10669 EVT VT = N->getValueType(0);
10671 // fold (fabs c1) -> fabs(c1)
10672 if (isConstantFPBuildVectorOrConstantFP(N0))
10673 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
10675 // fold (fabs (fabs x)) -> (fabs x)
10676 if (N0.getOpcode() == ISD::FABS)
10677 return N->getOperand(0);
10679 // fold (fabs (fneg x)) -> (fabs x)
10680 // fold (fabs (fcopysign x, y)) -> (fabs x)
10681 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
10682 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
10684 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
10685 // constant pool values.
10686 if (!TLI.isFAbsFree(VT) &&
10687 N0.getOpcode() == ISD::BITCAST &&
10688 N0.getNode()->hasOneUse()) {
10689 SDValue Int = N0.getOperand(0);
10690 EVT IntVT = Int.getValueType();
10691 if (IntVT.isInteger() && !IntVT.isVector()) {
10693 if (N0.getValueType().isVector()) {
10694 // For a vector, get a mask such as 0x7f... per scalar element
10696 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits());
10697 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
10699 // For a scalar, just generate 0x7f...
10700 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits());
10703 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
10704 DAG.getConstant(SignMask, DL, IntVT));
10705 AddToWorklist(Int.getNode());
10706 return DAG.getBitcast(N->getValueType(0), Int);
10713 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
10714 SDValue Chain = N->getOperand(0);
10715 SDValue N1 = N->getOperand(1);
10716 SDValue N2 = N->getOperand(2);
10718 // If N is a constant we could fold this into a fallthrough or unconditional
10719 // branch. However that doesn't happen very often in normal code, because
10720 // Instcombine/SimplifyCFG should have handled the available opportunities.
10721 // If we did this folding here, it would be necessary to update the
10722 // MachineBasicBlock CFG, which is awkward.
10724 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
10726 if (N1.getOpcode() == ISD::SETCC &&
10727 TLI.isOperationLegalOrCustom(ISD::BR_CC,
10728 N1.getOperand(0).getValueType())) {
10729 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10730 Chain, N1.getOperand(2),
10731 N1.getOperand(0), N1.getOperand(1), N2);
10734 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
10735 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
10736 (N1.getOperand(0).hasOneUse() &&
10737 N1.getOperand(0).getOpcode() == ISD::SRL))) {
10738 SDNode *Trunc = nullptr;
10739 if (N1.getOpcode() == ISD::TRUNCATE) {
10740 // Look pass the truncate.
10741 Trunc = N1.getNode();
10742 N1 = N1.getOperand(0);
10745 // Match this pattern so that we can generate simpler code:
10748 // %b = and i32 %a, 2
10749 // %c = srl i32 %b, 1
10750 // brcond i32 %c ...
10755 // %b = and i32 %a, 2
10756 // %c = setcc eq %b, 0
10759 // This applies only when the AND constant value has one bit set and the
10760 // SRL constant is equal to the log2 of the AND constant. The back-end is
10761 // smart enough to convert the result into a TEST/JMP sequence.
10762 SDValue Op0 = N1.getOperand(0);
10763 SDValue Op1 = N1.getOperand(1);
10765 if (Op0.getOpcode() == ISD::AND &&
10766 Op1.getOpcode() == ISD::Constant) {
10767 SDValue AndOp1 = Op0.getOperand(1);
10769 if (AndOp1.getOpcode() == ISD::Constant) {
10770 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
10772 if (AndConst.isPowerOf2() &&
10773 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
10777 getSetCCResultType(Op0.getValueType()),
10778 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
10781 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
10782 MVT::Other, Chain, SetCC, N2);
10783 // Don't add the new BRCond into the worklist or else SimplifySelectCC
10784 // will convert it back to (X & C1) >> C2.
10785 CombineTo(N, NewBRCond, false);
10786 // Truncate is dead.
10788 deleteAndRecombine(Trunc);
10789 // Replace the uses of SRL with SETCC
10790 WorklistRemover DeadNodes(*this);
10791 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10792 deleteAndRecombine(N1.getNode());
10793 return SDValue(N, 0); // Return N so it doesn't get rechecked!
10799 // Restore N1 if the above transformation doesn't match.
10800 N1 = N->getOperand(1);
10803 // Transform br(xor(x, y)) -> br(x != y)
10804 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
10805 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
10806 SDNode *TheXor = N1.getNode();
10807 SDValue Op0 = TheXor->getOperand(0);
10808 SDValue Op1 = TheXor->getOperand(1);
10809 if (Op0.getOpcode() == Op1.getOpcode()) {
10810 // Avoid missing important xor optimizations.
10811 if (SDValue Tmp = visitXOR(TheXor)) {
10812 if (Tmp.getNode() != TheXor) {
10813 DEBUG(dbgs() << "\nReplacing.8 ";
10814 TheXor->dump(&DAG);
10815 dbgs() << "\nWith: ";
10816 Tmp.getNode()->dump(&DAG);
10818 WorklistRemover DeadNodes(*this);
10819 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
10820 deleteAndRecombine(TheXor);
10821 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10822 MVT::Other, Chain, Tmp, N2);
10825 // visitXOR has changed XOR's operands or replaced the XOR completely,
10827 return SDValue(N, 0);
10831 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
10832 bool Equal = false;
10833 if (isOneConstant(Op0) && Op0.hasOneUse() &&
10834 Op0.getOpcode() == ISD::XOR) {
10835 TheXor = Op0.getNode();
10839 EVT SetCCVT = N1.getValueType();
10841 SetCCVT = getSetCCResultType(SetCCVT);
10842 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
10845 Equal ? ISD::SETEQ : ISD::SETNE);
10846 // Replace the uses of XOR with SETCC
10847 WorklistRemover DeadNodes(*this);
10848 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
10849 deleteAndRecombine(N1.getNode());
10850 return DAG.getNode(ISD::BRCOND, SDLoc(N),
10851 MVT::Other, Chain, SetCC, N2);
10858 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
10860 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
10861 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
10862 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
10864 // If N is a constant we could fold this into a fallthrough or unconditional
10865 // branch. However that doesn't happen very often in normal code, because
10866 // Instcombine/SimplifyCFG should have handled the available opportunities.
10867 // If we did this folding here, it would be necessary to update the
10868 // MachineBasicBlock CFG, which is awkward.
10870 // Use SimplifySetCC to simplify SETCC's.
10871 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
10872 CondLHS, CondRHS, CC->get(), SDLoc(N),
10874 if (Simp.getNode()) AddToWorklist(Simp.getNode());
10876 // fold to a simpler setcc
10877 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
10878 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
10879 N->getOperand(0), Simp.getOperand(2),
10880 Simp.getOperand(0), Simp.getOperand(1),
10886 /// Return true if 'Use' is a load or a store that uses N as its base pointer
10887 /// and that N may be folded in the load / store addressing mode.
10888 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
10890 const TargetLowering &TLI) {
10894 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
10895 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
10897 VT = LD->getMemoryVT();
10898 AS = LD->getAddressSpace();
10899 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
10900 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
10902 VT = ST->getMemoryVT();
10903 AS = ST->getAddressSpace();
10907 TargetLowering::AddrMode AM;
10908 if (N->getOpcode() == ISD::ADD) {
10909 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10912 AM.BaseOffs = Offset->getSExtValue();
10916 } else if (N->getOpcode() == ISD::SUB) {
10917 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
10920 AM.BaseOffs = -Offset->getSExtValue();
10927 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
10928 VT.getTypeForEVT(*DAG.getContext()), AS);
10931 /// Try turning a load/store into a pre-indexed load/store when the base
10932 /// pointer is an add or subtract and it has other uses besides the load/store.
10933 /// After the transformation, the new indexed load/store has effectively folded
10934 /// the add/subtract in and all of its other uses are redirected to the
10935 /// new load/store.
10936 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
10937 if (Level < AfterLegalizeDAG)
10940 bool isLoad = true;
10943 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10944 if (LD->isIndexed())
10946 VT = LD->getMemoryVT();
10947 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
10948 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
10950 Ptr = LD->getBasePtr();
10951 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10952 if (ST->isIndexed())
10954 VT = ST->getMemoryVT();
10955 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
10956 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
10958 Ptr = ST->getBasePtr();
10964 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
10965 // out. There is no reason to make this a preinc/predec.
10966 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
10967 Ptr.getNode()->hasOneUse())
10970 // Ask the target to do addressing mode selection.
10973 ISD::MemIndexedMode AM = ISD::UNINDEXED;
10974 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
10977 // Backends without true r+i pre-indexed forms may need to pass a
10978 // constant base with a variable offset so that constant coercion
10979 // will work with the patterns in canonical form.
10980 bool Swapped = false;
10981 if (isa<ConstantSDNode>(BasePtr)) {
10982 std::swap(BasePtr, Offset);
10986 // Don't create a indexed load / store with zero offset.
10987 if (isNullConstant(Offset))
10990 // Try turning it into a pre-indexed load / store except when:
10991 // 1) The new base ptr is a frame index.
10992 // 2) If N is a store and the new base ptr is either the same as or is a
10993 // predecessor of the value being stored.
10994 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
10995 // that would create a cycle.
10996 // 4) All uses are load / store ops that use it as old base ptr.
10998 // Check #1. Preinc'ing a frame index would require copying the stack pointer
10999 // (plus the implicit offset) to a register to preinc anyway.
11000 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11005 SDValue Val = cast<StoreSDNode>(N)->getValue();
11006 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
11010 // Caches for hasPredecessorHelper.
11011 SmallPtrSet<const SDNode *, 32> Visited;
11012 SmallVector<const SDNode *, 16> Worklist;
11013 Worklist.push_back(N);
11015 // If the offset is a constant, there may be other adds of constants that
11016 // can be folded with this one. We should do this to avoid having to keep
11017 // a copy of the original base pointer.
11018 SmallVector<SDNode *, 16> OtherUses;
11019 if (isa<ConstantSDNode>(Offset))
11020 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
11021 UE = BasePtr.getNode()->use_end();
11023 SDUse &Use = UI.getUse();
11024 // Skip the use that is Ptr and uses of other results from BasePtr's
11025 // node (important for nodes that return multiple results).
11026 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
11029 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
11032 if (Use.getUser()->getOpcode() != ISD::ADD &&
11033 Use.getUser()->getOpcode() != ISD::SUB) {
11038 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
11039 if (!isa<ConstantSDNode>(Op1)) {
11044 // FIXME: In some cases, we can be smarter about this.
11045 if (Op1.getValueType() != Offset.getValueType()) {
11050 OtherUses.push_back(Use.getUser());
11054 std::swap(BasePtr, Offset);
11056 // Now check for #3 and #4.
11057 bool RealUse = false;
11059 for (SDNode *Use : Ptr.getNode()->uses()) {
11062 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
11065 // If Ptr may be folded in addressing mode of other use, then it's
11066 // not profitable to do this transformation.
11067 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
11076 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11077 BasePtr, Offset, AM);
11079 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11080 BasePtr, Offset, AM);
11083 DEBUG(dbgs() << "\nReplacing.4 ";
11085 dbgs() << "\nWith: ";
11086 Result.getNode()->dump(&DAG);
11088 WorklistRemover DeadNodes(*this);
11090 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11091 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11093 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11096 // Finally, since the node is now dead, remove it from the graph.
11097 deleteAndRecombine(N);
11100 std::swap(BasePtr, Offset);
11102 // Replace other uses of BasePtr that can be updated to use Ptr
11103 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
11104 unsigned OffsetIdx = 1;
11105 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
11107 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
11108 BasePtr.getNode() && "Expected BasePtr operand");
11110 // We need to replace ptr0 in the following expression:
11111 // x0 * offset0 + y0 * ptr0 = t0
11113 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
11115 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
11116 // indexed load/store and the expression that needs to be re-written.
11118 // Therefore, we have:
11119 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
11121 ConstantSDNode *CN =
11122 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
11123 int X0, X1, Y0, Y1;
11124 const APInt &Offset0 = CN->getAPIntValue();
11125 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
11127 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
11128 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
11129 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
11130 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
11132 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
11134 APInt CNV = Offset0;
11135 if (X0 < 0) CNV = -CNV;
11136 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
11137 else CNV = CNV - Offset1;
11139 SDLoc DL(OtherUses[i]);
11141 // We can now generate the new expression.
11142 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
11143 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
11145 SDValue NewUse = DAG.getNode(Opcode,
11147 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
11148 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
11149 deleteAndRecombine(OtherUses[i]);
11152 // Replace the uses of Ptr with uses of the updated base value.
11153 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
11154 deleteAndRecombine(Ptr.getNode());
11159 /// Try to combine a load/store with a add/sub of the base pointer node into a
11160 /// post-indexed load/store. The transformation folded the add/subtract into the
11161 /// new indexed load/store effectively and all of its uses are redirected to the
11162 /// new load/store.
11163 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
11164 if (Level < AfterLegalizeDAG)
11167 bool isLoad = true;
11170 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11171 if (LD->isIndexed())
11173 VT = LD->getMemoryVT();
11174 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
11175 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
11177 Ptr = LD->getBasePtr();
11178 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11179 if (ST->isIndexed())
11181 VT = ST->getMemoryVT();
11182 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
11183 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
11185 Ptr = ST->getBasePtr();
11191 if (Ptr.getNode()->hasOneUse())
11194 for (SDNode *Op : Ptr.getNode()->uses()) {
11196 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
11201 ISD::MemIndexedMode AM = ISD::UNINDEXED;
11202 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
11203 // Don't create a indexed load / store with zero offset.
11204 if (isNullConstant(Offset))
11207 // Try turning it into a post-indexed load / store except when
11208 // 1) All uses are load / store ops that use it as base ptr (and
11209 // it may be folded as addressing mmode).
11210 // 2) Op must be independent of N, i.e. Op is neither a predecessor
11211 // nor a successor of N. Otherwise, if Op is folded that would
11214 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
11218 bool TryNext = false;
11219 for (SDNode *Use : BasePtr.getNode()->uses()) {
11220 if (Use == Ptr.getNode())
11223 // If all the uses are load / store addresses, then don't do the
11225 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
11226 bool RealUse = false;
11227 for (SDNode *UseUse : Use->uses()) {
11228 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
11243 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
11244 SDValue Result = isLoad
11245 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
11246 BasePtr, Offset, AM)
11247 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
11248 BasePtr, Offset, AM);
11249 ++PostIndexedNodes;
11251 DEBUG(dbgs() << "\nReplacing.5 ";
11253 dbgs() << "\nWith: ";
11254 Result.getNode()->dump(&DAG);
11256 WorklistRemover DeadNodes(*this);
11258 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
11259 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
11261 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
11264 // Finally, since the node is now dead, remove it from the graph.
11265 deleteAndRecombine(N);
11267 // Replace the uses of Use with uses of the updated base value.
11268 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
11269 Result.getValue(isLoad ? 1 : 0));
11270 deleteAndRecombine(Op);
11279 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
11280 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
11281 ISD::MemIndexedMode AM = LD->getAddressingMode();
11282 assert(AM != ISD::UNINDEXED);
11283 SDValue BP = LD->getOperand(1);
11284 SDValue Inc = LD->getOperand(2);
11286 // Some backends use TargetConstants for load offsets, but don't expect
11287 // TargetConstants in general ADD nodes. We can convert these constants into
11288 // regular Constants (if the constant is not opaque).
11289 assert((Inc.getOpcode() != ISD::TargetConstant ||
11290 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
11291 "Cannot split out indexing using opaque target constants");
11292 if (Inc.getOpcode() == ISD::TargetConstant) {
11293 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
11294 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
11295 ConstInc->getValueType(0));
11299 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
11300 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
11303 SDValue DAGCombiner::visitLOAD(SDNode *N) {
11304 LoadSDNode *LD = cast<LoadSDNode>(N);
11305 SDValue Chain = LD->getChain();
11306 SDValue Ptr = LD->getBasePtr();
11308 // If load is not volatile and there are no uses of the loaded value (and
11309 // the updated indexed value in case of indexed loads), change uses of the
11310 // chain value into uses of the chain input (i.e. delete the dead load).
11311 if (!LD->isVolatile()) {
11312 if (N->getValueType(1) == MVT::Other) {
11313 // Unindexed loads.
11314 if (!N->hasAnyUseOfValue(0)) {
11315 // It's not safe to use the two value CombineTo variant here. e.g.
11316 // v1, chain2 = load chain1, loc
11317 // v2, chain3 = load chain2, loc
11319 // Now we replace use of chain2 with chain1. This makes the second load
11320 // isomorphic to the one we are deleting, and thus makes this load live.
11321 DEBUG(dbgs() << "\nReplacing.6 ";
11323 dbgs() << "\nWith chain: ";
11324 Chain.getNode()->dump(&DAG);
11326 WorklistRemover DeadNodes(*this);
11327 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11328 AddUsersToWorklist(Chain.getNode());
11329 if (N->use_empty())
11330 deleteAndRecombine(N);
11332 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11336 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
11338 // If this load has an opaque TargetConstant offset, then we cannot split
11339 // the indexing into an add/sub directly (that TargetConstant may not be
11340 // valid for a different type of node, and we cannot convert an opaque
11341 // target constant into a regular constant).
11342 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
11343 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
11345 if (!N->hasAnyUseOfValue(0) &&
11346 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
11347 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
11349 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
11350 Index = SplitIndexingFromLoad(LD);
11351 // Try to fold the base pointer arithmetic into subsequent loads and
11353 AddUsersToWorklist(N);
11355 Index = DAG.getUNDEF(N->getValueType(1));
11356 DEBUG(dbgs() << "\nReplacing.7 ";
11358 dbgs() << "\nWith: ";
11359 Undef.getNode()->dump(&DAG);
11360 dbgs() << " and 2 other values\n");
11361 WorklistRemover DeadNodes(*this);
11362 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
11363 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
11364 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
11365 deleteAndRecombine(N);
11366 return SDValue(N, 0); // Return N so it doesn't get rechecked!
11371 // If this load is directly stored, replace the load value with the stored
11373 // TODO: Handle store large -> read small portion.
11374 // TODO: Handle TRUNCSTORE/LOADEXT
11375 if (OptLevel != CodeGenOpt::None &&
11376 ISD::isNormalLoad(N) && !LD->isVolatile()) {
11377 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
11378 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
11379 if (PrevST->getBasePtr() == Ptr &&
11380 PrevST->getValue().getValueType() == N->getValueType(0))
11381 return CombineTo(N, PrevST->getOperand(1), Chain);
11385 // Try to infer better alignment information than the load already has.
11386 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
11387 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11388 if (Align > LD->getMemOperand()->getBaseAlignment()) {
11389 SDValue NewLoad = DAG.getExtLoad(
11390 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
11391 LD->getPointerInfo(), LD->getMemoryVT(), Align,
11392 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11393 if (NewLoad.getNode() != N)
11394 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
11399 if (LD->isUnindexed()) {
11400 // Walk up chain skipping non-aliasing memory nodes.
11401 SDValue BetterChain = FindBetterChain(N, Chain);
11403 // If there is a better chain.
11404 if (Chain != BetterChain) {
11407 // Replace the chain to void dependency.
11408 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
11409 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
11410 BetterChain, Ptr, LD->getMemOperand());
11412 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
11413 LD->getValueType(0),
11414 BetterChain, Ptr, LD->getMemoryVT(),
11415 LD->getMemOperand());
11418 // Create token factor to keep old chain connected.
11419 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11420 MVT::Other, Chain, ReplLoad.getValue(1));
11422 // Replace uses with load result and token factor
11423 return CombineTo(N, ReplLoad.getValue(0), Token);
11427 // Try transforming N to an indexed load.
11428 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11429 return SDValue(N, 0);
11431 // Try to slice up N to more direct loads if the slices are mapped to
11432 // different register banks or pairing can take place.
11433 if (SliceUpLoad(N))
11434 return SDValue(N, 0);
11440 /// \brief Helper structure used to slice a load in smaller loads.
11441 /// Basically a slice is obtained from the following sequence:
11442 /// Origin = load Ty1, Base
11443 /// Shift = srl Ty1 Origin, CstTy Amount
11444 /// Inst = trunc Shift to Ty2
11446 /// Then, it will be rewritten into:
11447 /// Slice = load SliceTy, Base + SliceOffset
11448 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
11450 /// SliceTy is deduced from the number of bits that are actually used to
11452 struct LoadedSlice {
11453 /// \brief Helper structure used to compute the cost of a slice.
11455 /// Are we optimizing for code size.
11459 unsigned Truncates;
11460 unsigned CrossRegisterBanksCopies;
11464 Cost(bool ForCodeSize = false)
11465 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
11466 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
11468 /// \brief Get the cost of one isolated slice.
11469 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
11470 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
11471 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
11472 EVT TruncType = LS.Inst->getValueType(0);
11473 EVT LoadedType = LS.getLoadedType();
11474 if (TruncType != LoadedType &&
11475 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
11479 /// \brief Account for slicing gain in the current cost.
11480 /// Slicing provide a few gains like removing a shift or a
11481 /// truncate. This method allows to grow the cost of the original
11482 /// load with the gain from this slice.
11483 void addSliceGain(const LoadedSlice &LS) {
11484 // Each slice saves a truncate.
11485 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
11486 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
11487 LS.Inst->getValueType(0)))
11489 // If there is a shift amount, this slice gets rid of it.
11492 // If this slice can merge a cross register bank copy, account for it.
11493 if (LS.canMergeExpensiveCrossRegisterBankCopy())
11494 ++CrossRegisterBanksCopies;
11497 Cost &operator+=(const Cost &RHS) {
11498 Loads += RHS.Loads;
11499 Truncates += RHS.Truncates;
11500 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
11501 ZExts += RHS.ZExts;
11502 Shift += RHS.Shift;
11506 bool operator==(const Cost &RHS) const {
11507 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
11508 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
11509 ZExts == RHS.ZExts && Shift == RHS.Shift;
11512 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
11514 bool operator<(const Cost &RHS) const {
11515 // Assume cross register banks copies are as expensive as loads.
11516 // FIXME: Do we want some more target hooks?
11517 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
11518 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
11519 // Unless we are optimizing for code size, consider the
11520 // expensive operation first.
11521 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
11522 return ExpensiveOpsLHS < ExpensiveOpsRHS;
11523 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
11524 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
11527 bool operator>(const Cost &RHS) const { return RHS < *this; }
11529 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
11531 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
11533 // The last instruction that represent the slice. This should be a
11534 // truncate instruction.
11536 // The original load instruction.
11537 LoadSDNode *Origin;
11538 // The right shift amount in bits from the original load.
11540 // The DAG from which Origin came from.
11541 // This is used to get some contextual information about legal types, etc.
11544 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
11545 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
11546 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
11548 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
11549 /// \return Result is \p BitWidth and has used bits set to 1 and
11550 /// not used bits set to 0.
11551 APInt getUsedBits() const {
11552 // Reproduce the trunc(lshr) sequence:
11553 // - Start from the truncated value.
11554 // - Zero extend to the desired bit width.
11556 assert(Origin && "No original load to compare against.");
11557 unsigned BitWidth = Origin->getValueSizeInBits(0);
11558 assert(Inst && "This slice is not bound to an instruction");
11559 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
11560 "Extracted slice is bigger than the whole type!");
11561 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
11562 UsedBits.setAllBits();
11563 UsedBits = UsedBits.zext(BitWidth);
11564 UsedBits <<= Shift;
11568 /// \brief Get the size of the slice to be loaded in bytes.
11569 unsigned getLoadedSize() const {
11570 unsigned SliceSize = getUsedBits().countPopulation();
11571 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
11572 return SliceSize / 8;
11575 /// \brief Get the type that will be loaded for this slice.
11576 /// Note: This may not be the final type for the slice.
11577 EVT getLoadedType() const {
11578 assert(DAG && "Missing context");
11579 LLVMContext &Ctxt = *DAG->getContext();
11580 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
11583 /// \brief Get the alignment of the load used for this slice.
11584 unsigned getAlignment() const {
11585 unsigned Alignment = Origin->getAlignment();
11586 unsigned Offset = getOffsetFromBase();
11588 Alignment = MinAlign(Alignment, Alignment + Offset);
11592 /// \brief Check if this slice can be rewritten with legal operations.
11593 bool isLegal() const {
11594 // An invalid slice is not legal.
11595 if (!Origin || !Inst || !DAG)
11598 // Offsets are for indexed load only, we do not handle that.
11599 if (!Origin->getOffset().isUndef())
11602 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11604 // Check that the type is legal.
11605 EVT SliceType = getLoadedType();
11606 if (!TLI.isTypeLegal(SliceType))
11609 // Check that the load is legal for this type.
11610 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
11613 // Check that the offset can be computed.
11614 // 1. Check its type.
11615 EVT PtrType = Origin->getBasePtr().getValueType();
11616 if (PtrType == MVT::Untyped || PtrType.isExtended())
11619 // 2. Check that it fits in the immediate.
11620 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
11623 // 3. Check that the computation is legal.
11624 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
11627 // Check that the zext is legal if it needs one.
11628 EVT TruncateType = Inst->getValueType(0);
11629 if (TruncateType != SliceType &&
11630 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
11636 /// \brief Get the offset in bytes of this slice in the original chunk of
11638 /// \pre DAG != nullptr.
11639 uint64_t getOffsetFromBase() const {
11640 assert(DAG && "Missing context.");
11641 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
11642 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
11643 uint64_t Offset = Shift / 8;
11644 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
11645 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
11646 "The size of the original loaded type is not a multiple of a"
11648 // If Offset is bigger than TySizeInBytes, it means we are loading all
11649 // zeros. This should have been optimized before in the process.
11650 assert(TySizeInBytes > Offset &&
11651 "Invalid shift amount for given loaded size");
11653 Offset = TySizeInBytes - Offset - getLoadedSize();
11657 /// \brief Generate the sequence of instructions to load the slice
11658 /// represented by this object and redirect the uses of this slice to
11659 /// this new sequence of instructions.
11660 /// \pre this->Inst && this->Origin are valid Instructions and this
11661 /// object passed the legal check: LoadedSlice::isLegal returned true.
11662 /// \return The last instruction of the sequence used to load the slice.
11663 SDValue loadSlice() const {
11664 assert(Inst && Origin && "Unable to replace a non-existing slice.");
11665 const SDValue &OldBaseAddr = Origin->getBasePtr();
11666 SDValue BaseAddr = OldBaseAddr;
11667 // Get the offset in that chunk of bytes w.r.t. the endianness.
11668 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
11669 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
11671 // BaseAddr = BaseAddr + Offset.
11672 EVT ArithType = BaseAddr.getValueType();
11674 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
11675 DAG->getConstant(Offset, DL, ArithType));
11678 // Create the type of the loaded slice according to its size.
11679 EVT SliceType = getLoadedType();
11681 // Create the load for the slice.
11683 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
11684 Origin->getPointerInfo().getWithOffset(Offset),
11685 getAlignment(), Origin->getMemOperand()->getFlags());
11686 // If the final type is not the same as the loaded type, this means that
11687 // we have to pad with zero. Create a zero extend for that.
11688 EVT FinalType = Inst->getValueType(0);
11689 if (SliceType != FinalType)
11691 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
11695 /// \brief Check if this slice can be merged with an expensive cross register
11696 /// bank copy. E.g.,
11698 /// f = bitcast i32 i to float
11699 bool canMergeExpensiveCrossRegisterBankCopy() const {
11700 if (!Inst || !Inst->hasOneUse())
11702 SDNode *Use = *Inst->use_begin();
11703 if (Use->getOpcode() != ISD::BITCAST)
11705 assert(DAG && "Missing context");
11706 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
11707 EVT ResVT = Use->getValueType(0);
11708 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
11709 const TargetRegisterClass *ArgRC =
11710 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
11711 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
11714 // At this point, we know that we perform a cross-register-bank copy.
11715 // Check if it is expensive.
11716 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
11717 // Assume bitcasts are cheap, unless both register classes do not
11718 // explicitly share a common sub class.
11719 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
11722 // Check if it will be merged with the load.
11723 // 1. Check the alignment constraint.
11724 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
11725 ResVT.getTypeForEVT(*DAG->getContext()));
11727 if (RequiredAlignment > getAlignment())
11730 // 2. Check that the load is a legal operation for that type.
11731 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
11734 // 3. Check that we do not have a zext in the way.
11735 if (Inst->getValueType(0) != getLoadedType())
11743 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
11744 /// \p UsedBits looks like 0..0 1..1 0..0.
11745 static bool areUsedBitsDense(const APInt &UsedBits) {
11746 // If all the bits are one, this is dense!
11747 if (UsedBits.isAllOnesValue())
11750 // Get rid of the unused bits on the right.
11751 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
11752 // Get rid of the unused bits on the left.
11753 if (NarrowedUsedBits.countLeadingZeros())
11754 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
11755 // Check that the chunk of bits is completely used.
11756 return NarrowedUsedBits.isAllOnesValue();
11759 /// \brief Check whether or not \p First and \p Second are next to each other
11760 /// in memory. This means that there is no hole between the bits loaded
11761 /// by \p First and the bits loaded by \p Second.
11762 static bool areSlicesNextToEachOther(const LoadedSlice &First,
11763 const LoadedSlice &Second) {
11764 assert(First.Origin == Second.Origin && First.Origin &&
11765 "Unable to match different memory origins.");
11766 APInt UsedBits = First.getUsedBits();
11767 assert((UsedBits & Second.getUsedBits()) == 0 &&
11768 "Slices are not supposed to overlap.");
11769 UsedBits |= Second.getUsedBits();
11770 return areUsedBitsDense(UsedBits);
11773 /// \brief Adjust the \p GlobalLSCost according to the target
11774 /// paring capabilities and the layout of the slices.
11775 /// \pre \p GlobalLSCost should account for at least as many loads as
11776 /// there is in the slices in \p LoadedSlices.
11777 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11778 LoadedSlice::Cost &GlobalLSCost) {
11779 unsigned NumberOfSlices = LoadedSlices.size();
11780 // If there is less than 2 elements, no pairing is possible.
11781 if (NumberOfSlices < 2)
11784 // Sort the slices so that elements that are likely to be next to each
11785 // other in memory are next to each other in the list.
11786 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
11787 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
11788 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
11789 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
11791 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
11792 // First (resp. Second) is the first (resp. Second) potentially candidate
11793 // to be placed in a paired load.
11794 const LoadedSlice *First = nullptr;
11795 const LoadedSlice *Second = nullptr;
11796 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
11797 // Set the beginning of the pair.
11800 Second = &LoadedSlices[CurrSlice];
11802 // If First is NULL, it means we start a new pair.
11803 // Get to the next slice.
11807 EVT LoadedType = First->getLoadedType();
11809 // If the types of the slices are different, we cannot pair them.
11810 if (LoadedType != Second->getLoadedType())
11813 // Check if the target supplies paired loads for this type.
11814 unsigned RequiredAlignment = 0;
11815 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
11816 // move to the next pair, this type is hopeless.
11820 // Check if we meet the alignment requirement.
11821 if (RequiredAlignment > First->getAlignment())
11824 // Check that both loads are next to each other in memory.
11825 if (!areSlicesNextToEachOther(*First, *Second))
11828 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
11829 --GlobalLSCost.Loads;
11830 // Move to the next pair.
11835 /// \brief Check the profitability of all involved LoadedSlice.
11836 /// Currently, it is considered profitable if there is exactly two
11837 /// involved slices (1) which are (2) next to each other in memory, and
11838 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
11840 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
11841 /// the elements themselves.
11843 /// FIXME: When the cost model will be mature enough, we can relax
11844 /// constraints (1) and (2).
11845 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
11846 const APInt &UsedBits, bool ForCodeSize) {
11847 unsigned NumberOfSlices = LoadedSlices.size();
11848 if (StressLoadSlicing)
11849 return NumberOfSlices > 1;
11852 if (NumberOfSlices != 2)
11856 if (!areUsedBitsDense(UsedBits))
11860 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
11861 // The original code has one big load.
11862 OrigCost.Loads = 1;
11863 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
11864 const LoadedSlice &LS = LoadedSlices[CurrSlice];
11865 // Accumulate the cost of all the slices.
11866 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
11867 GlobalSlicingCost += SliceCost;
11869 // Account as cost in the original configuration the gain obtained
11870 // with the current slices.
11871 OrigCost.addSliceGain(LS);
11874 // If the target supports paired load, adjust the cost accordingly.
11875 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
11876 return OrigCost > GlobalSlicingCost;
11879 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
11880 /// operations, split it in the various pieces being extracted.
11882 /// This sort of thing is introduced by SROA.
11883 /// This slicing takes care not to insert overlapping loads.
11884 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
11885 bool DAGCombiner::SliceUpLoad(SDNode *N) {
11886 if (Level < AfterLegalizeDAG)
11889 LoadSDNode *LD = cast<LoadSDNode>(N);
11890 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
11891 !LD->getValueType(0).isInteger())
11894 // Keep track of already used bits to detect overlapping values.
11895 // In that case, we will just abort the transformation.
11896 APInt UsedBits(LD->getValueSizeInBits(0), 0);
11898 SmallVector<LoadedSlice, 4> LoadedSlices;
11900 // Check if this load is used as several smaller chunks of bits.
11901 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
11902 // of computation for each trunc.
11903 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
11904 UI != UIEnd; ++UI) {
11905 // Skip the uses of the chain.
11906 if (UI.getUse().getResNo() != 0)
11909 SDNode *User = *UI;
11910 unsigned Shift = 0;
11912 // Check if this is a trunc(lshr).
11913 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
11914 isa<ConstantSDNode>(User->getOperand(1))) {
11915 Shift = User->getConstantOperandVal(1);
11916 User = *User->use_begin();
11919 // At this point, User is a Truncate, iff we encountered, trunc or
11921 if (User->getOpcode() != ISD::TRUNCATE)
11924 // The width of the type must be a power of 2 and greater than 8-bits.
11925 // Otherwise the load cannot be represented in LLVM IR.
11926 // Moreover, if we shifted with a non-8-bits multiple, the slice
11927 // will be across several bytes. We do not support that.
11928 unsigned Width = User->getValueSizeInBits(0);
11929 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
11932 // Build the slice for this chain of computations.
11933 LoadedSlice LS(User, LD, Shift, &DAG);
11934 APInt CurrentUsedBits = LS.getUsedBits();
11936 // Check if this slice overlaps with another.
11937 if ((CurrentUsedBits & UsedBits) != 0)
11939 // Update the bits used globally.
11940 UsedBits |= CurrentUsedBits;
11942 // Check if the new slice would be legal.
11946 // Record the slice.
11947 LoadedSlices.push_back(LS);
11950 // Abort slicing if it does not seem to be profitable.
11951 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
11956 // Rewrite each chain to use an independent load.
11957 // By construction, each chain can be represented by a unique load.
11959 // Prepare the argument for the new token factor for all the slices.
11960 SmallVector<SDValue, 8> ArgChains;
11961 for (SmallVectorImpl<LoadedSlice>::const_iterator
11962 LSIt = LoadedSlices.begin(),
11963 LSItEnd = LoadedSlices.end();
11964 LSIt != LSItEnd; ++LSIt) {
11965 SDValue SliceInst = LSIt->loadSlice();
11966 CombineTo(LSIt->Inst, SliceInst, true);
11967 if (SliceInst.getOpcode() != ISD::LOAD)
11968 SliceInst = SliceInst.getOperand(0);
11969 assert(SliceInst->getOpcode() == ISD::LOAD &&
11970 "It takes more than a zext to get to the loaded slice!!");
11971 ArgChains.push_back(SliceInst.getValue(1));
11974 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
11976 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
11977 AddToWorklist(Chain.getNode());
11981 /// Check to see if V is (and load (ptr), imm), where the load is having
11982 /// specific bytes cleared out. If so, return the byte size being masked out
11983 /// and the shift amount.
11984 static std::pair<unsigned, unsigned>
11985 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
11986 std::pair<unsigned, unsigned> Result(0, 0);
11988 // Check for the structure we're looking for.
11989 if (V->getOpcode() != ISD::AND ||
11990 !isa<ConstantSDNode>(V->getOperand(1)) ||
11991 !ISD::isNormalLoad(V->getOperand(0).getNode()))
11994 // Check the chain and pointer.
11995 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
11996 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
11998 // The store should be chained directly to the load or be an operand of a
12000 if (LD == Chain.getNode())
12002 else if (Chain->getOpcode() != ISD::TokenFactor)
12003 return Result; // Fail.
12006 for (const SDValue &ChainOp : Chain->op_values())
12007 if (ChainOp.getNode() == LD) {
12011 if (!isOk) return Result;
12014 // This only handles simple types.
12015 if (V.getValueType() != MVT::i16 &&
12016 V.getValueType() != MVT::i32 &&
12017 V.getValueType() != MVT::i64)
12020 // Check the constant mask. Invert it so that the bits being masked out are
12021 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
12022 // follow the sign bit for uniformity.
12023 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
12024 unsigned NotMaskLZ = countLeadingZeros(NotMask);
12025 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
12026 unsigned NotMaskTZ = countTrailingZeros(NotMask);
12027 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
12028 if (NotMaskLZ == 64) return Result; // All zero mask.
12030 // See if we have a continuous run of bits. If so, we have 0*1+0*
12031 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
12034 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
12035 if (V.getValueType() != MVT::i64 && NotMaskLZ)
12036 NotMaskLZ -= 64-V.getValueSizeInBits();
12038 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
12039 switch (MaskedBytes) {
12043 default: return Result; // All one mask, or 5-byte mask.
12046 // Verify that the first bit starts at a multiple of mask so that the access
12047 // is aligned the same as the access width.
12048 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
12050 Result.first = MaskedBytes;
12051 Result.second = NotMaskTZ/8;
12056 /// Check to see if IVal is something that provides a value as specified by
12057 /// MaskInfo. If so, replace the specified store with a narrower store of
12058 /// truncated IVal.
12060 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
12061 SDValue IVal, StoreSDNode *St,
12063 unsigned NumBytes = MaskInfo.first;
12064 unsigned ByteShift = MaskInfo.second;
12065 SelectionDAG &DAG = DC->getDAG();
12067 // Check to see if IVal is all zeros in the part being masked in by the 'or'
12068 // that uses this. If not, this is not a replacement.
12069 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
12070 ByteShift*8, (ByteShift+NumBytes)*8);
12071 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
12073 // Check that it is legal on the target to do this. It is legal if the new
12074 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
12076 MVT VT = MVT::getIntegerVT(NumBytes*8);
12077 if (!DC->isTypeLegal(VT))
12080 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
12081 // shifted by ByteShift and truncated down to NumBytes.
12084 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
12085 DAG.getConstant(ByteShift*8, DL,
12086 DC->getShiftAmountTy(IVal.getValueType())));
12089 // Figure out the offset for the store and the alignment of the access.
12091 unsigned NewAlign = St->getAlignment();
12093 if (DAG.getDataLayout().isLittleEndian())
12094 StOffset = ByteShift;
12096 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
12098 SDValue Ptr = St->getBasePtr();
12101 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
12102 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
12103 NewAlign = MinAlign(NewAlign, StOffset);
12106 // Truncate down to the new size.
12107 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
12111 .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
12112 St->getPointerInfo().getWithOffset(StOffset), NewAlign)
12117 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
12118 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
12119 /// narrowing the load and store if it would end up being a win for performance
12121 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
12122 StoreSDNode *ST = cast<StoreSDNode>(N);
12123 if (ST->isVolatile())
12126 SDValue Chain = ST->getChain();
12127 SDValue Value = ST->getValue();
12128 SDValue Ptr = ST->getBasePtr();
12129 EVT VT = Value.getValueType();
12131 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
12134 unsigned Opc = Value.getOpcode();
12136 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
12137 // is a byte mask indicating a consecutive number of bytes, check to see if
12138 // Y is known to provide just those bytes. If so, we try to replace the
12139 // load + replace + store sequence with a single (narrower) store, which makes
12141 if (Opc == ISD::OR) {
12142 std::pair<unsigned, unsigned> MaskedLoad;
12143 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
12144 if (MaskedLoad.first)
12145 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12146 Value.getOperand(1), ST,this))
12147 return SDValue(NewST, 0);
12149 // Or is commutative, so try swapping X and Y.
12150 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
12151 if (MaskedLoad.first)
12152 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
12153 Value.getOperand(0), ST,this))
12154 return SDValue(NewST, 0);
12157 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
12158 Value.getOperand(1).getOpcode() != ISD::Constant)
12161 SDValue N0 = Value.getOperand(0);
12162 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
12163 Chain == SDValue(N0.getNode(), 1)) {
12164 LoadSDNode *LD = cast<LoadSDNode>(N0);
12165 if (LD->getBasePtr() != Ptr ||
12166 LD->getPointerInfo().getAddrSpace() !=
12167 ST->getPointerInfo().getAddrSpace())
12170 // Find the type to narrow it the load / op / store to.
12171 SDValue N1 = Value.getOperand(1);
12172 unsigned BitWidth = N1.getValueSizeInBits();
12173 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
12174 if (Opc == ISD::AND)
12175 Imm ^= APInt::getAllOnesValue(BitWidth);
12176 if (Imm == 0 || Imm.isAllOnesValue())
12178 unsigned ShAmt = Imm.countTrailingZeros();
12179 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
12180 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
12181 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12182 // The narrowing should be profitable, the load/store operation should be
12183 // legal (or custom) and the store size should be equal to the NewVT width.
12184 while (NewBW < BitWidth &&
12185 (NewVT.getStoreSizeInBits() != NewBW ||
12186 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
12187 !TLI.isNarrowingProfitable(VT, NewVT))) {
12188 NewBW = NextPowerOf2(NewBW);
12189 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
12191 if (NewBW >= BitWidth)
12194 // If the lsb changed does not start at the type bitwidth boundary,
12195 // start at the previous one.
12197 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
12198 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
12199 std::min(BitWidth, ShAmt + NewBW));
12200 if ((Imm & Mask) == Imm) {
12201 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
12202 if (Opc == ISD::AND)
12203 NewImm ^= APInt::getAllOnesValue(NewBW);
12204 uint64_t PtrOff = ShAmt / 8;
12205 // For big endian targets, we need to adjust the offset to the pointer to
12206 // load the correct bytes.
12207 if (DAG.getDataLayout().isBigEndian())
12208 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
12210 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
12211 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
12212 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
12215 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
12216 Ptr.getValueType(), Ptr,
12217 DAG.getConstant(PtrOff, SDLoc(LD),
12218 Ptr.getValueType()));
12220 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
12221 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
12222 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12223 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
12224 DAG.getConstant(NewImm, SDLoc(Value),
12227 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
12228 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
12230 AddToWorklist(NewPtr.getNode());
12231 AddToWorklist(NewLD.getNode());
12232 AddToWorklist(NewVal.getNode());
12233 WorklistRemover DeadNodes(*this);
12234 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
12243 /// For a given floating point load / store pair, if the load value isn't used
12244 /// by any other operations, then consider transforming the pair to integer
12245 /// load / store operations if the target deems the transformation profitable.
12246 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
12247 StoreSDNode *ST = cast<StoreSDNode>(N);
12248 SDValue Chain = ST->getChain();
12249 SDValue Value = ST->getValue();
12250 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
12251 Value.hasOneUse() &&
12252 Chain == SDValue(Value.getNode(), 1)) {
12253 LoadSDNode *LD = cast<LoadSDNode>(Value);
12254 EVT VT = LD->getMemoryVT();
12255 if (!VT.isFloatingPoint() ||
12256 VT != ST->getMemoryVT() ||
12257 LD->isNonTemporal() ||
12258 ST->isNonTemporal() ||
12259 LD->getPointerInfo().getAddrSpace() != 0 ||
12260 ST->getPointerInfo().getAddrSpace() != 0)
12263 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12264 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
12265 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
12266 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
12267 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
12270 unsigned LDAlign = LD->getAlignment();
12271 unsigned STAlign = ST->getAlignment();
12272 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
12273 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
12274 if (LDAlign < ABIAlign || STAlign < ABIAlign)
12278 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
12279 LD->getPointerInfo(), LDAlign);
12282 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
12283 ST->getPointerInfo(), STAlign);
12285 AddToWorklist(NewLD.getNode());
12286 AddToWorklist(NewST.getNode());
12287 WorklistRemover DeadNodes(*this);
12288 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
12296 // This is a helper function for visitMUL to check the profitability
12297 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
12298 // MulNode is the original multiply, AddNode is (add x, c1),
12299 // and ConstNode is c2.
12301 // If the (add x, c1) has multiple uses, we could increase
12302 // the number of adds if we make this transformation.
12303 // It would only be worth doing this if we can remove a
12304 // multiply in the process. Check for that here.
12308 // We're checking for cases where we have common "c3 * A" expressions.
12309 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
12311 SDValue &ConstNode) {
12314 // If the add only has one use, this would be OK to do.
12315 if (AddNode.getNode()->hasOneUse())
12318 // Walk all the users of the constant with which we're multiplying.
12319 for (SDNode *Use : ConstNode->uses()) {
12321 if (Use == MulNode) // This use is the one we're on right now. Skip it.
12324 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
12326 SDNode *MulVar = AddNode.getOperand(0).getNode();
12328 // OtherOp is what we're multiplying against the constant.
12329 if (Use->getOperand(0) == ConstNode)
12330 OtherOp = Use->getOperand(1).getNode();
12332 OtherOp = Use->getOperand(0).getNode();
12334 // Check to see if multiply is with the same operand of our "add".
12336 // ConstNode = CONST
12337 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
12339 // AddNode = (A + c1) <-- MulVar is A.
12340 // = AddNode * ConstNode <-- current visiting instruction.
12342 // If we make this transformation, we will have a common
12343 // multiply (ConstNode * A) that we can save.
12344 if (OtherOp == MulVar)
12347 // Now check to see if a future expansion will give us a common
12350 // ConstNode = CONST
12351 // AddNode = (A + c1)
12352 // ... = AddNode * ConstNode <-- current visiting instruction.
12354 // OtherOp = (A + c2)
12355 // Use = OtherOp * ConstNode <-- visiting Use.
12357 // If we make this transformation, we will have a common
12358 // multiply (CONST * A) after we also do the same transformation
12359 // to the "t2" instruction.
12360 if (OtherOp->getOpcode() == ISD::ADD &&
12361 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
12362 OtherOp->getOperand(0).getNode() == MulVar)
12367 // Didn't find a case where this would be profitable.
12371 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
12372 unsigned NumStores) {
12373 SmallVector<SDValue, 8> Chains;
12374 SmallPtrSet<const SDNode *, 8> Visited;
12375 SDLoc StoreDL(StoreNodes[0].MemNode);
12377 for (unsigned i = 0; i < NumStores; ++i) {
12378 Visited.insert(StoreNodes[i].MemNode);
12381 // don't include nodes that are children
12382 for (unsigned i = 0; i < NumStores; ++i) {
12383 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0)
12384 Chains.push_back(StoreNodes[i].MemNode->getChain());
12387 assert(Chains.size() > 0 && "Chain should have generated a chain");
12388 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains);
12391 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
12392 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
12393 bool IsConstantSrc, bool UseVector, bool UseTrunc) {
12394 // Make sure we have something to merge.
12398 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12400 // The latest Node in the DAG.
12401 SDLoc DL(StoreNodes[0].MemNode);
12405 bool IsVec = MemVT.isVector();
12406 unsigned Elts = NumStores;
12408 // When merging vector stores, get the total number of elements.
12409 Elts *= MemVT.getVectorNumElements();
12411 // Get the type for the merged vector store.
12412 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12413 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
12415 if (IsConstantSrc) {
12416 SmallVector<SDValue, 8> BuildVector;
12417 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
12418 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
12419 SDValue Val = St->getValue();
12420 if (MemVT.getScalarType().isInteger())
12421 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
12422 Val = DAG.getConstant(
12423 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
12424 SDLoc(CFP), MemVT);
12425 BuildVector.push_back(Val);
12427 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
12429 SmallVector<SDValue, 8> Ops;
12430 for (unsigned i = 0; i < NumStores; ++i) {
12431 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12432 SDValue Val = St->getValue();
12433 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
12434 if (Val.getValueType() != MemVT)
12436 Ops.push_back(Val);
12439 // Build the extracted vector elements back into a vector.
12440 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
12443 // We should always use a vector store when merging extracted vector
12444 // elements, so this path implies a store of constants.
12445 assert(IsConstantSrc && "Merged vector elements should use vector store");
12447 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
12448 APInt StoreInt(SizeInBits, 0);
12450 // Construct a single integer constant which is made of the smaller
12451 // constant inputs.
12452 bool IsLE = DAG.getDataLayout().isLittleEndian();
12453 for (unsigned i = 0; i < NumStores; ++i) {
12454 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
12455 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
12457 SDValue Val = St->getValue();
12458 StoreInt <<= ElementSizeBytes * 8;
12459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
12460 StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits);
12461 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
12462 StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits);
12464 llvm_unreachable("Invalid constant element type");
12468 // Create the new Load and Store operations.
12469 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
12470 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
12473 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12474 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
12476 // make sure we use trunc store if it's necessary to be legal.
12478 if (UseVector || !UseTrunc) {
12479 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
12480 FirstInChain->getPointerInfo(),
12481 FirstInChain->getAlignment());
12482 } else { // Must be realized as a trunc store
12483 EVT LegalizedStoredValueTy =
12484 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
12485 unsigned LegalizedStoreSize = LegalizedStoredValueTy.getSizeInBits();
12486 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
12487 SDValue ExtendedStoreVal =
12488 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
12489 LegalizedStoredValueTy);
12490 NewStore = DAG.getTruncStore(
12491 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
12492 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
12493 FirstInChain->getAlignment(),
12494 FirstInChain->getMemOperand()->getFlags());
12497 // Replace all merged stores with the new store.
12498 for (unsigned i = 0; i < NumStores; ++i)
12499 CombineTo(StoreNodes[i].MemNode, NewStore);
12501 AddToWorklist(NewChain.getNode());
12505 void DAGCombiner::getStoreMergeCandidates(
12506 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
12507 // This holds the base pointer, index, and the offset in bytes from the base
12509 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
12510 EVT MemVT = St->getMemoryVT();
12512 // We must have a base and an offset.
12513 if (!BasePtr.getBase().getNode())
12516 // Do not handle stores to undef base pointers.
12517 if (BasePtr.getBase().isUndef())
12520 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
12521 isa<ConstantFPSDNode>(St->getValue());
12522 bool IsExtractVecSrc =
12523 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12524 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
12525 bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
12526 BaseIndexOffset LBasePtr;
12527 // Match on loadbaseptr if relevant.
12529 LBasePtr = BaseIndexOffset::match(
12530 cast<LoadSDNode>(St->getValue())->getBasePtr(), DAG);
12532 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
12533 int64_t &Offset) -> bool {
12534 if (Other->isVolatile() || Other->isIndexed())
12536 // We can merge constant floats to equivalent integers
12537 if (Other->getMemoryVT() != MemVT)
12538 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) &&
12539 isa<ConstantFPSDNode>(Other->getValue())))
12542 // The Load's Base Ptr must also match
12543 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Other->getValue())) {
12544 auto LPtr = BaseIndexOffset::match(OtherLd->getBasePtr(), DAG);
12545 if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
12551 if (!(isa<ConstantSDNode>(Other->getValue()) ||
12552 isa<ConstantFPSDNode>(Other->getValue())))
12554 if (IsExtractVecSrc)
12555 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12556 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR))
12558 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG);
12559 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
12561 // We looking for a root node which is an ancestor to all mergable
12562 // stores. We search up through a load, to our root and then down
12563 // through all children. For instance we will find Store{1,2,3} if
12564 // St is Store1, Store2. or Store3 where the root is not a load
12565 // which always true for nonvolatile ops. TODO: Expand
12566 // the search to find all valid candidates through multiple layers of loads.
12569 // |-------|-------|
12570 // Load Load Store3
12574 // FIXME: We should be able to climb and
12575 // descend TokenFactors to find candidates as well.
12577 SDNode *RootNode = (St->getChain()).getNode();
12579 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
12580 RootNode = Ldn->getChain().getNode();
12581 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12582 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
12583 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
12584 if (I2.getOperandNo() == 0)
12585 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) {
12586 BaseIndexOffset Ptr;
12588 if (CandidateMatch(OtherST, Ptr, PtrDiff))
12589 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12592 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
12593 if (I.getOperandNo() == 0)
12594 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
12595 BaseIndexOffset Ptr;
12597 if (CandidateMatch(OtherST, Ptr, PtrDiff))
12598 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff));
12602 // We need to check that merging these stores does not cause a loop
12603 // in the DAG. Any store candidate may depend on another candidate
12604 // indirectly through its operand (we already consider dependencies
12605 // through the chain). Check in parallel by searching up from
12606 // non-chain operands of candidates.
12607 bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
12608 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) {
12609 SmallPtrSet<const SDNode *, 16> Visited;
12610 SmallVector<const SDNode *, 8> Worklist;
12611 // search ops of store candidates
12612 for (unsigned i = 0; i < NumStores; ++i) {
12613 SDNode *n = StoreNodes[i].MemNode;
12614 // Potential loops may happen only through non-chain operands
12615 for (unsigned j = 1; j < n->getNumOperands(); ++j)
12616 Worklist.push_back(n->getOperand(j).getNode());
12618 // search through DAG. We can stop early if we find a storenode
12619 for (unsigned i = 0; i < NumStores; ++i) {
12620 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
12626 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
12627 if (OptLevel == CodeGenOpt::None)
12630 EVT MemVT = St->getMemoryVT();
12631 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
12633 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
12636 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
12637 Attribute::NoImplicitFloat);
12639 // This function cannot currently deal with non-byte-sized memory sizes.
12640 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
12643 if (!MemVT.isSimple())
12646 // Perform an early exit check. Do not bother looking at stored values that
12647 // are not constants, loads, or extracted vector elements.
12648 SDValue StoredVal = St->getValue();
12649 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
12650 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
12651 isa<ConstantFPSDNode>(StoredVal);
12652 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
12653 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
12655 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
12658 // Don't merge vectors into wider vectors if the source data comes from loads.
12659 // TODO: This restriction can be lifted by using logic similar to the
12660 // ExtractVecSrc case.
12661 if (MemVT.isVector() && IsLoadSrc)
12664 SmallVector<MemOpLink, 8> StoreNodes;
12665 // Find potential store merge candidates by searching through chain sub-DAG
12666 getStoreMergeCandidates(St, StoreNodes);
12668 // Check if there is anything to merge.
12669 if (StoreNodes.size() < 2)
12672 // Sort the memory operands according to their distance from the
12674 std::sort(StoreNodes.begin(), StoreNodes.end(),
12675 [](MemOpLink LHS, MemOpLink RHS) {
12676 return LHS.OffsetFromBase < RHS.OffsetFromBase;
12679 // Store Merge attempts to merge the lowest stores. This generally
12680 // works out as if successful, as the remaining stores are checked
12681 // after the first collection of stores is merged. However, in the
12682 // case that a non-mergeable store is found first, e.g., {p[-2],
12683 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
12684 // mergeable cases. To prevent this, we prune such stores from the
12685 // front of StoreNodes here.
12688 while (StoreNodes.size() > 1) {
12689 unsigned StartIdx = 0;
12690 while ((StartIdx + 1 < StoreNodes.size()) &&
12691 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
12692 StoreNodes[StartIdx + 1].OffsetFromBase)
12695 // Bail if we don't have enough candidates to merge.
12696 if (StartIdx + 1 >= StoreNodes.size())
12700 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
12702 // Scan the memory operations on the chain and find the first
12703 // non-consecutive store memory address.
12704 unsigned NumConsecutiveStores = 1;
12705 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
12706 // Check that the addresses are consecutive starting from the second
12707 // element in the list of stores.
12708 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
12709 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
12710 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12712 NumConsecutiveStores = i + 1;
12715 if (NumConsecutiveStores < 2) {
12716 StoreNodes.erase(StoreNodes.begin(),
12717 StoreNodes.begin() + NumConsecutiveStores);
12721 // Check that we can merge these candidates without causing a cycle
12722 if (!checkMergeStoreCandidatesForDependencies(StoreNodes,
12723 NumConsecutiveStores)) {
12724 StoreNodes.erase(StoreNodes.begin(),
12725 StoreNodes.begin() + NumConsecutiveStores);
12729 // The node with the lowest store address.
12730 LLVMContext &Context = *DAG.getContext();
12731 const DataLayout &DL = DAG.getDataLayout();
12733 // Store the constants into memory as one consecutive store.
12734 if (IsConstantSrc) {
12735 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12736 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12737 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12738 unsigned LastLegalType = 1;
12739 unsigned LastLegalVectorType = 1;
12740 bool LastIntegerTrunc = false;
12741 bool NonZero = false;
12742 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12743 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
12744 SDValue StoredVal = ST->getValue();
12746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
12747 NonZero |= !C->isNullValue();
12748 } else if (ConstantFPSDNode *C =
12749 dyn_cast<ConstantFPSDNode>(StoredVal)) {
12750 NonZero |= !C->getConstantFPValue()->isNullValue();
12756 // Find a legal type for the constant store.
12757 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12758 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12759 bool IsFast = false;
12760 if (TLI.isTypeLegal(StoreTy) &&
12761 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12762 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12763 FirstStoreAlign, &IsFast) &&
12765 LastIntegerTrunc = false;
12766 LastLegalType = i + 1;
12767 // Or check whether a truncstore is legal.
12768 } else if (TLI.getTypeAction(Context, StoreTy) ==
12769 TargetLowering::TypePromoteInteger) {
12770 EVT LegalizedStoredValueTy =
12771 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
12772 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
12773 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
12774 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
12775 FirstStoreAS, FirstStoreAlign, &IsFast) &&
12777 LastIntegerTrunc = true;
12778 LastLegalType = i + 1;
12782 // We only use vectors if the constant is known to be zero or the target
12783 // allows it and the function is not marked with the noimplicitfloat
12786 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
12788 // Find a legal type for the vector store.
12789 unsigned Elts = i + 1;
12790 if (MemVT.isVector()) {
12791 // When merging vector stores, get the total number of elements.
12792 Elts *= MemVT.getVectorNumElements();
12794 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
12795 if (TLI.isTypeLegal(Ty) &&
12796 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12797 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12798 FirstStoreAlign, &IsFast) &&
12800 LastLegalVectorType = i + 1;
12804 // Check if we found a legal integer type that creates a meaningful merge.
12805 if (LastLegalType < 2 && LastLegalVectorType < 2) {
12806 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12810 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
12811 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
12813 bool Merged = MergeStoresOfConstantsOrVecElts(
12814 StoreNodes, MemVT, NumElem, true, UseVector, LastIntegerTrunc);
12816 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12819 // Remove merged stores for next iteration.
12821 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
12825 // When extracting multiple vector elements, try to store them
12826 // in one vector store rather than a sequence of scalar stores.
12827 if (IsExtractVecSrc) {
12828 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12829 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12830 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12831 unsigned NumStoresToMerge = 1;
12832 bool IsVec = MemVT.isVector();
12833 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12834 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12835 unsigned StoreValOpcode = St->getValue().getOpcode();
12836 // This restriction could be loosened.
12837 // Bail out if any stored values are not elements extracted from a
12838 // vector. It should be possible to handle mixed sources, but load
12839 // sources need more careful handling (see the block of code below that
12840 // handles consecutive loads).
12841 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
12842 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
12845 // Find a legal type for the vector store.
12846 unsigned Elts = i + 1;
12848 // When merging vector stores, get the total number of elements.
12849 Elts *= MemVT.getVectorNumElements();
12852 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
12854 if (TLI.isTypeLegal(Ty) &&
12855 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) &&
12856 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
12857 FirstStoreAlign, &IsFast) &&
12859 NumStoresToMerge = i + 1;
12862 bool Merged = MergeStoresOfConstantsOrVecElts(
12863 StoreNodes, MemVT, NumStoresToMerge, false, true, false);
12865 StoreNodes.erase(StoreNodes.begin(),
12866 StoreNodes.begin() + NumStoresToMerge);
12869 // Remove merged stores for next iteration.
12870 StoreNodes.erase(StoreNodes.begin(),
12871 StoreNodes.begin() + NumStoresToMerge);
12876 // Below we handle the case of multiple consecutive stores that
12877 // come from multiple consecutive loads. We merge them into a single
12878 // wide load and a single wide store.
12880 // Look for load nodes which are used by the stored values.
12881 SmallVector<MemOpLink, 8> LoadNodes;
12883 // Find acceptable loads. Loads need to have the same chain (token factor),
12884 // must not be zext, volatile, indexed, and they must be consecutive.
12885 BaseIndexOffset LdBasePtr;
12886 for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
12887 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
12888 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
12892 // Loads must only have one use.
12893 if (!Ld->hasNUsesOfValue(1, 0))
12896 // The memory operands must not be volatile.
12897 if (Ld->isVolatile() || Ld->isIndexed())
12900 // We do not accept ext loads.
12901 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
12904 // The stored memory type must be the same.
12905 if (Ld->getMemoryVT() != MemVT)
12908 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
12909 // If this is not the first ptr that we check.
12910 int64_t LdOffset = 0;
12911 if (LdBasePtr.getBase().getNode()) {
12912 // The base ptr must be the same.
12913 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
12916 // Check that all other base pointers are the same as this one.
12920 // We found a potential memory operand to merge.
12921 LoadNodes.push_back(MemOpLink(Ld, LdOffset));
12924 if (LoadNodes.size() < 2) {
12925 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
12929 // If we have load/store pair instructions and we only have two values,
12930 // don't bother merging.
12931 unsigned RequiredAlignment;
12932 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
12933 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) {
12934 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
12937 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
12938 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
12939 unsigned FirstStoreAlign = FirstInChain->getAlignment();
12940 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
12941 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
12942 unsigned FirstLoadAlign = FirstLoad->getAlignment();
12944 // Scan the memory operations on the chain and find the first
12945 // non-consecutive load memory address. These variables hold the index in
12946 // the store node array.
12947 unsigned LastConsecutiveLoad = 1;
12948 // This variable refers to the size and not index in the array.
12949 unsigned LastLegalVectorType = 1;
12950 unsigned LastLegalIntegerType = 1;
12951 bool isDereferenceable = true;
12952 bool DoIntegerTruncate = false;
12953 StartAddress = LoadNodes[0].OffsetFromBase;
12954 SDValue FirstChain = FirstLoad->getChain();
12955 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
12956 // All loads must share the same chain.
12957 if (LoadNodes[i].MemNode->getChain() != FirstChain)
12960 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
12961 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
12963 LastConsecutiveLoad = i;
12965 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
12966 isDereferenceable = false;
12968 // Find a legal type for the vector store.
12969 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1);
12970 bool IsFastSt, IsFastLd;
12971 if (TLI.isTypeLegal(StoreTy) &&
12972 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12973 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12974 FirstStoreAlign, &IsFastSt) &&
12976 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12977 FirstLoadAlign, &IsFastLd) &&
12979 LastLegalVectorType = i + 1;
12982 // Find a legal type for the integer store.
12983 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
12984 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
12985 if (TLI.isTypeLegal(StoreTy) &&
12986 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) &&
12987 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
12988 FirstStoreAlign, &IsFastSt) &&
12990 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
12991 FirstLoadAlign, &IsFastLd) &&
12993 LastLegalIntegerType = i + 1;
12994 DoIntegerTruncate = false;
12995 // Or check whether a truncstore and extload is legal.
12996 } else if (TLI.getTypeAction(Context, StoreTy) ==
12997 TargetLowering::TypePromoteInteger) {
12998 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy);
12999 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
13000 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy, DAG) &&
13001 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy,
13003 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy,
13005 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
13006 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
13007 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
13009 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
13010 FirstLoadAlign, &IsFastLd) &&
13012 LastLegalIntegerType = i + 1;
13013 DoIntegerTruncate = true;
13018 // Only use vector types if the vector type is larger than the integer type.
13019 // If they are the same, use integers.
13020 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
13021 unsigned LastLegalType =
13022 std::max(LastLegalVectorType, LastLegalIntegerType);
13024 // We add +1 here because the LastXXX variables refer to location while
13025 // the NumElem refers to array/index size.
13026 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
13027 NumElem = std::min(LastLegalType, NumElem);
13030 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
13034 // Find if it is better to use vectors or integers to load and store
13038 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
13040 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
13041 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
13044 SDLoc LoadDL(LoadNodes[0].MemNode);
13045 SDLoc StoreDL(StoreNodes[0].MemNode);
13047 // The merged loads are required to have the same incoming chain, so
13048 // using the first's chain is acceptable.
13050 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
13051 AddToWorklist(NewStoreChain.getNode());
13053 MachineMemOperand::Flags MMOFlags = isDereferenceable ?
13054 MachineMemOperand::MODereferenceable:
13055 MachineMemOperand::MONone;
13057 SDValue NewLoad, NewStore;
13058 if (UseVectorTy || !DoIntegerTruncate) {
13059 NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
13060 FirstLoad->getBasePtr(),
13061 FirstLoad->getPointerInfo(), FirstLoadAlign,
13063 NewStore = DAG.getStore(NewStoreChain, StoreDL, NewLoad,
13064 FirstInChain->getBasePtr(),
13065 FirstInChain->getPointerInfo(), FirstStoreAlign);
13066 } else { // This must be the truncstore/extload case
13068 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
13070 DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, FirstLoad->getChain(),
13071 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
13072 JointMemOpVT, FirstLoadAlign, MMOFlags);
13073 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad,
13074 FirstInChain->getBasePtr(),
13075 FirstInChain->getPointerInfo(), JointMemOpVT,
13076 FirstInChain->getAlignment(),
13077 FirstInChain->getMemOperand()->getFlags());
13080 // Transfer chain users from old loads to the new load.
13081 for (unsigned i = 0; i < NumElem; ++i) {
13082 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
13083 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
13084 SDValue(NewLoad.getNode(), 1));
13087 // Replace the all stores with the new store.
13088 for (unsigned i = 0; i < NumElem; ++i)
13089 CombineTo(StoreNodes[i].MemNode, NewStore);
13091 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
13097 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
13101 // Replace the chain to avoid dependency.
13102 if (ST->isTruncatingStore()) {
13103 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
13104 ST->getBasePtr(), ST->getMemoryVT(),
13105 ST->getMemOperand());
13107 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
13108 ST->getMemOperand());
13111 // Create token to keep both nodes around.
13112 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
13113 MVT::Other, ST->getChain(), ReplStore);
13115 // Make sure the new and old chains are cleaned up.
13116 AddToWorklist(Token.getNode());
13118 // Don't add users to work list.
13119 return CombineTo(ST, Token, false);
13122 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
13123 SDValue Value = ST->getValue();
13124 if (Value.getOpcode() == ISD::TargetConstantFP)
13129 SDValue Chain = ST->getChain();
13130 SDValue Ptr = ST->getBasePtr();
13132 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
13134 // NOTE: If the original store is volatile, this transform must not increase
13135 // the number of stores. For example, on x86-32 an f64 can be stored in one
13136 // processor operation but an i64 (which is not legal) requires two. So the
13137 // transform should not be done in this case.
13140 switch (CFP->getSimpleValueType(0).SimpleTy) {
13142 llvm_unreachable("Unknown FP type");
13143 case MVT::f16: // We don't do this for these yet.
13149 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
13150 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13152 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
13153 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
13155 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
13160 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
13161 !ST->isVolatile()) ||
13162 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
13164 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
13165 getZExtValue(), SDLoc(CFP), MVT::i64);
13166 return DAG.getStore(Chain, DL, Tmp,
13167 Ptr, ST->getMemOperand());
13170 if (!ST->isVolatile() &&
13171 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
13172 // Many FP stores are not made apparent until after legalize, e.g. for
13173 // argument passing. Since this is so common, custom legalize the
13174 // 64-bit integer store into two 32-bit stores.
13175 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
13176 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
13177 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
13178 if (DAG.getDataLayout().isBigEndian())
13181 unsigned Alignment = ST->getAlignment();
13182 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13183 AAMDNodes AAInfo = ST->getAAInfo();
13185 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13186 ST->getAlignment(), MMOFlags, AAInfo);
13187 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13188 DAG.getConstant(4, DL, Ptr.getValueType()));
13189 Alignment = MinAlign(Alignment, 4U);
13190 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
13191 ST->getPointerInfo().getWithOffset(4),
13192 Alignment, MMOFlags, AAInfo);
13193 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13201 SDValue DAGCombiner::visitSTORE(SDNode *N) {
13202 StoreSDNode *ST = cast<StoreSDNode>(N);
13203 SDValue Chain = ST->getChain();
13204 SDValue Value = ST->getValue();
13205 SDValue Ptr = ST->getBasePtr();
13207 // If this is a store of a bit convert, store the input value if the
13208 // resultant store does not need a higher alignment than the original.
13209 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
13210 ST->isUnindexed()) {
13211 EVT SVT = Value.getOperand(0).getValueType();
13212 if (((!LegalOperations && !ST->isVolatile()) ||
13213 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
13214 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
13215 unsigned OrigAlign = ST->getAlignment();
13217 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
13218 ST->getAddressSpace(), OrigAlign, &Fast) &&
13220 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
13221 ST->getPointerInfo(), OrigAlign,
13222 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13227 // Turn 'store undef, Ptr' -> nothing.
13228 if (Value.isUndef() && ST->isUnindexed())
13231 // Try to infer better alignment information than the store already has.
13232 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
13233 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
13234 if (Align > ST->getAlignment()) {
13236 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
13237 ST->getMemoryVT(), Align,
13238 ST->getMemOperand()->getFlags(), ST->getAAInfo());
13239 if (NewStore.getNode() != N)
13240 return CombineTo(ST, NewStore, true);
13245 // Try transforming a pair floating point load / store ops to integer
13246 // load / store ops.
13247 if (SDValue NewST = TransformFPLoadStorePair(N))
13250 if (ST->isUnindexed()) {
13251 // Walk up chain skipping non-aliasing memory nodes, on this store and any
13252 // adjacent stores.
13253 if (findBetterNeighborChains(ST)) {
13254 // replaceStoreChain uses CombineTo, which handled all of the worklist
13255 // manipulation. Return the original node to not do anything else.
13256 return SDValue(ST, 0);
13258 Chain = ST->getChain();
13261 // FIXME: is there such a thing as a truncating indexed store?
13262 if (ST->isTruncatingStore() && ST->isUnindexed() &&
13263 Value.getValueType().isInteger()) {
13264 // See if we can simplify the input to this truncstore with knowledge that
13265 // only the low bits are being used. For example:
13266 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
13267 SDValue Shorter = GetDemandedBits(
13268 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13269 ST->getMemoryVT().getScalarSizeInBits()));
13270 AddToWorklist(Value.getNode());
13271 if (Shorter.getNode())
13272 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
13273 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13275 // Otherwise, see if we can simplify the operation with
13276 // SimplifyDemandedBits, which only works if the value has a single use.
13277 if (SimplifyDemandedBits(
13279 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
13280 ST->getMemoryVT().getScalarSizeInBits()))) {
13281 // Re-visit the store if anything changed and the store hasn't been merged
13282 // with another node (N is deleted) SimplifyDemandedBits will add Value's
13283 // node back to the worklist if necessary, but we also need to re-visit
13284 // the Store node itself.
13285 if (N->getOpcode() != ISD::DELETED_NODE)
13287 return SDValue(N, 0);
13291 // If this is a load followed by a store to the same location, then the store
13293 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
13294 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
13295 ST->isUnindexed() && !ST->isVolatile() &&
13296 // There can't be any side effects between the load and store, such as
13297 // a call or store.
13298 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
13299 // The store is dead, remove it.
13304 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
13305 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() &&
13306 !ST1->isVolatile() && ST1->getBasePtr() == Ptr &&
13307 ST->getMemoryVT() == ST1->getMemoryVT()) {
13308 // If this is a store followed by a store with the same value to the same
13309 // location, then the store is dead/noop.
13310 if (ST1->getValue() == Value) {
13311 // The store is dead, remove it.
13315 // If this is a store who's preceeding store to the same location
13316 // and no one other node is chained to that store we can effectively
13317 // drop the store. Do not remove stores to undef as they may be used as
13319 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
13320 !ST1->getBasePtr().isUndef()) {
13321 // ST1 is fully overwritten and can be elided. Combine with it's chain
13323 CombineTo(ST1, ST1->getChain());
13329 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
13330 // truncating store. We can do this even if this is already a truncstore.
13331 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
13332 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
13333 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
13334 ST->getMemoryVT())) {
13335 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
13336 Ptr, ST->getMemoryVT(), ST->getMemOperand());
13339 // Only perform this optimization before the types are legal, because we
13340 // don't want to perform this optimization on every DAGCombine invocation.
13341 if ((TLI.mergeStoresAfterLegalization()) ? Level == AfterLegalizeDAG
13344 // There can be multiple store sequences on the same chain.
13345 // Keep trying to merge store sequences until we are unable to do so
13346 // or until we merge the last store on the chain.
13347 bool Changed = MergeConsecutiveStores(ST);
13348 if (!Changed) break;
13349 // Return N as merge only uses CombineTo and no worklist clean
13350 // up is necessary.
13351 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
13352 return SDValue(N, 0);
13356 // Try transforming N to an indexed store.
13357 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
13358 return SDValue(N, 0);
13360 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
13362 // Make sure to do this only after attempting to merge stores in order to
13363 // avoid changing the types of some subset of stores due to visit order,
13364 // preventing their merging.
13365 if (isa<ConstantFPSDNode>(ST->getValue())) {
13366 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
13370 if (SDValue NewSt = splitMergedValStore(ST))
13373 return ReduceLoadOpStoreWidth(N);
13376 /// For the instruction sequence of store below, F and I values
13377 /// are bundled together as an i64 value before being stored into memory.
13378 /// Sometimes it is more efficent to generate separate stores for F and I,
13379 /// which can remove the bitwise instructions or sink them to colder places.
13381 /// (store (or (zext (bitcast F to i32) to i64),
13382 /// (shl (zext I to i64), 32)), addr) -->
13383 /// (store F, addr) and (store I, addr+4)
13385 /// Similarly, splitting for other merged store can also be beneficial, like:
13386 /// For pair of {i32, i32}, i64 store --> two i32 stores.
13387 /// For pair of {i32, i16}, i64 store --> two i32 stores.
13388 /// For pair of {i16, i16}, i32 store --> two i16 stores.
13389 /// For pair of {i16, i8}, i32 store --> two i16 stores.
13390 /// For pair of {i8, i8}, i16 store --> two i8 stores.
13392 /// We allow each target to determine specifically which kind of splitting is
13395 /// The store patterns are commonly seen from the simple code snippet below
13396 /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
13397 /// void goo(const std::pair<int, float> &);
13400 /// goo(std::make_pair(tmp, ftmp));
13404 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
13405 if (OptLevel == CodeGenOpt::None)
13408 SDValue Val = ST->getValue();
13411 // Match OR operand.
13412 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
13415 // Match SHL operand and get Lower and Higher parts of Val.
13416 SDValue Op1 = Val.getOperand(0);
13417 SDValue Op2 = Val.getOperand(1);
13419 if (Op1.getOpcode() != ISD::SHL) {
13420 std::swap(Op1, Op2);
13421 if (Op1.getOpcode() != ISD::SHL)
13425 Hi = Op1.getOperand(0);
13426 if (!Op1.hasOneUse())
13429 // Match shift amount to HalfValBitSize.
13430 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
13431 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
13432 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
13435 // Lo and Hi are zero-extended from int with size less equal than 32
13437 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
13438 !Lo.getOperand(0).getValueType().isScalarInteger() ||
13439 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
13440 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
13441 !Hi.getOperand(0).getValueType().isScalarInteger() ||
13442 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
13445 // Use the EVT of low and high parts before bitcast as the input
13446 // of target query.
13447 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
13448 ? Lo.getOperand(0).getValueType()
13449 : Lo.getValueType();
13450 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
13451 ? Hi.getOperand(0).getValueType()
13452 : Hi.getValueType();
13453 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
13456 // Start to split store.
13457 unsigned Alignment = ST->getAlignment();
13458 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
13459 AAMDNodes AAInfo = ST->getAAInfo();
13461 // Change the sizes of Lo and Hi's value types to HalfValBitSize.
13462 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
13463 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
13464 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
13466 SDValue Chain = ST->getChain();
13467 SDValue Ptr = ST->getBasePtr();
13468 // Lower value store.
13469 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
13470 ST->getAlignment(), MMOFlags, AAInfo);
13472 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
13473 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
13474 // Higher value store.
13476 DAG.getStore(St0, DL, Hi, Ptr,
13477 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
13478 Alignment / 2, MMOFlags, AAInfo);
13482 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
13483 SDValue InVec = N->getOperand(0);
13484 SDValue InVal = N->getOperand(1);
13485 SDValue EltNo = N->getOperand(2);
13488 // If the inserted element is an UNDEF, just use the input vector.
13489 if (InVal.isUndef())
13492 EVT VT = InVec.getValueType();
13494 // Check that we know which element is being inserted
13495 if (!isa<ConstantSDNode>(EltNo))
13497 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13499 // Canonicalize insert_vector_elt dag nodes.
13501 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
13502 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
13504 // Do this only if the child insert_vector node has one use; also
13505 // do this only if indices are both constants and Idx1 < Idx0.
13506 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
13507 && isa<ConstantSDNode>(InVec.getOperand(2))) {
13508 unsigned OtherElt = InVec.getConstantOperandVal(2);
13509 if (Elt < OtherElt) {
13511 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
13512 InVec.getOperand(0), InVal, EltNo);
13513 AddToWorklist(NewOp.getNode());
13514 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
13515 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
13519 // If we can't generate a legal BUILD_VECTOR, exit
13520 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
13523 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
13524 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
13525 // vector elements.
13526 SmallVector<SDValue, 8> Ops;
13527 // Do not combine these two vectors if the output vector will not replace
13528 // the input vector.
13529 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
13530 Ops.append(InVec.getNode()->op_begin(),
13531 InVec.getNode()->op_end());
13532 } else if (InVec.isUndef()) {
13533 unsigned NElts = VT.getVectorNumElements();
13534 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
13539 // Insert the element
13540 if (Elt < Ops.size()) {
13541 // All the operands of BUILD_VECTOR must have the same type;
13542 // we enforce that here.
13543 EVT OpVT = Ops[0].getValueType();
13544 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
13547 // Return the new vector
13548 return DAG.getBuildVector(VT, DL, Ops);
13551 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
13552 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
13553 assert(!OriginalLoad->isVolatile());
13555 EVT ResultVT = EVE->getValueType(0);
13556 EVT VecEltVT = InVecVT.getVectorElementType();
13557 unsigned Align = OriginalLoad->getAlignment();
13558 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
13559 VecEltVT.getTypeForEVT(*DAG.getContext()));
13561 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
13564 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
13565 ISD::NON_EXTLOAD : ISD::EXTLOAD;
13566 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
13571 SDValue NewPtr = OriginalLoad->getBasePtr();
13573 EVT PtrType = NewPtr.getValueType();
13574 MachinePointerInfo MPI;
13576 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
13577 int Elt = ConstEltNo->getZExtValue();
13578 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
13579 Offset = DAG.getConstant(PtrOff, DL, PtrType);
13580 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
13582 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
13583 Offset = DAG.getNode(
13584 ISD::MUL, DL, PtrType, Offset,
13585 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
13586 MPI = OriginalLoad->getPointerInfo();
13588 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
13590 // The replacement we need to do here is a little tricky: we need to
13591 // replace an extractelement of a load with a load.
13592 // Use ReplaceAllUsesOfValuesWith to do the replacement.
13593 // Note that this replacement assumes that the extractvalue is the only
13594 // use of the load; that's okay because we don't want to perform this
13595 // transformation in other cases anyway.
13598 if (ResultVT.bitsGT(VecEltVT)) {
13599 // If the result type of vextract is wider than the load, then issue an
13600 // extending load instead.
13601 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
13605 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
13606 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
13607 Align, OriginalLoad->getMemOperand()->getFlags(),
13608 OriginalLoad->getAAInfo());
13609 Chain = Load.getValue(1);
13611 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
13612 MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
13613 OriginalLoad->getAAInfo());
13614 Chain = Load.getValue(1);
13615 if (ResultVT.bitsLT(VecEltVT))
13616 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
13618 Load = DAG.getBitcast(ResultVT, Load);
13620 WorklistRemover DeadNodes(*this);
13621 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
13622 SDValue To[] = { Load, Chain };
13623 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
13624 // Since we're explicitly calling ReplaceAllUses, add the new node to the
13625 // worklist explicitly as well.
13626 AddToWorklist(Load.getNode());
13627 AddUsersToWorklist(Load.getNode()); // Add users too
13628 // Make sure to revisit this node to clean it up; it will usually be dead.
13629 AddToWorklist(EVE);
13631 return SDValue(EVE, 0);
13634 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
13635 // (vextract (scalar_to_vector val, 0) -> val
13636 SDValue InVec = N->getOperand(0);
13637 EVT VT = InVec.getValueType();
13638 EVT NVT = N->getValueType(0);
13640 if (InVec.isUndef())
13641 return DAG.getUNDEF(NVT);
13643 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
13644 // Check if the result type doesn't match the inserted element type. A
13645 // SCALAR_TO_VECTOR may truncate the inserted element and the
13646 // EXTRACT_VECTOR_ELT may widen the extracted vector.
13647 SDValue InOp = InVec.getOperand(0);
13648 if (InOp.getValueType() != NVT) {
13649 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13650 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
13655 SDValue EltNo = N->getOperand(1);
13656 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
13658 // extract_vector_elt (build_vector x, y), 1 -> y
13660 InVec.getOpcode() == ISD::BUILD_VECTOR &&
13661 TLI.isTypeLegal(VT) &&
13662 (InVec.hasOneUse() ||
13663 TLI.aggressivelyPreferBuildVectorSources(VT))) {
13664 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
13665 EVT InEltVT = Elt.getValueType();
13667 // Sometimes build_vector's scalar input types do not match result type.
13668 if (NVT == InEltVT)
13671 // TODO: It may be useful to truncate if free if the build_vector implicitly
13675 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
13676 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
13677 ConstEltNo->isNullValue() && VT.isInteger()) {
13678 SDValue BCSrc = InVec.getOperand(0);
13679 if (BCSrc.getValueType().isScalarInteger())
13680 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
13683 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
13685 // This only really matters if the index is non-constant since other combines
13686 // on the constant elements already work.
13687 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
13688 EltNo == InVec.getOperand(2)) {
13689 SDValue Elt = InVec.getOperand(1);
13690 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
13693 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
13694 // We only perform this optimization before the op legalization phase because
13695 // we may introduce new vector instructions which are not backed by TD
13696 // patterns. For example on AVX, extracting elements from a wide vector
13697 // without using extract_subvector. However, if we can find an underlying
13698 // scalar value, then we can always use that.
13699 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
13700 int NumElem = VT.getVectorNumElements();
13701 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
13702 // Find the new index to extract from.
13703 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
13705 // Extracting an undef index is undef.
13707 return DAG.getUNDEF(NVT);
13709 // Select the right vector half to extract from.
13711 if (OrigElt < NumElem) {
13712 SVInVec = InVec->getOperand(0);
13714 SVInVec = InVec->getOperand(1);
13715 OrigElt -= NumElem;
13718 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
13719 SDValue InOp = SVInVec.getOperand(OrigElt);
13720 if (InOp.getValueType() != NVT) {
13721 assert(InOp.getValueType().isInteger() && NVT.isInteger());
13722 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
13728 // FIXME: We should handle recursing on other vector shuffles and
13729 // scalar_to_vector here as well.
13731 if (!LegalOperations) {
13732 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
13733 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
13734 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
13738 bool BCNumEltsChanged = false;
13739 EVT ExtVT = VT.getVectorElementType();
13742 // If the result of load has to be truncated, then it's not necessarily
13744 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
13747 if (InVec.getOpcode() == ISD::BITCAST) {
13748 // Don't duplicate a load with other uses.
13749 if (!InVec.hasOneUse())
13752 EVT BCVT = InVec.getOperand(0).getValueType();
13753 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
13755 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
13756 BCNumEltsChanged = true;
13757 InVec = InVec.getOperand(0);
13758 ExtVT = BCVT.getVectorElementType();
13761 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
13762 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
13763 ISD::isNormalLoad(InVec.getNode()) &&
13764 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
13765 SDValue Index = N->getOperand(1);
13766 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
13767 if (!OrigLoad->isVolatile()) {
13768 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
13774 // Perform only after legalization to ensure build_vector / vector_shuffle
13775 // optimizations have already been done.
13776 if (!LegalOperations) return SDValue();
13778 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
13779 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
13780 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
13783 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13785 LoadSDNode *LN0 = nullptr;
13786 const ShuffleVectorSDNode *SVN = nullptr;
13787 if (ISD::isNormalLoad(InVec.getNode())) {
13788 LN0 = cast<LoadSDNode>(InVec);
13789 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13790 InVec.getOperand(0).getValueType() == ExtVT &&
13791 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
13792 // Don't duplicate a load with other uses.
13793 if (!InVec.hasOneUse())
13796 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
13797 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
13798 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
13800 // (load $addr+1*size)
13802 // Don't duplicate a load with other uses.
13803 if (!InVec.hasOneUse())
13806 // If the bit convert changed the number of elements, it is unsafe
13807 // to examine the mask.
13808 if (BCNumEltsChanged)
13811 // Select the input vector, guarding against out of range extract vector.
13812 unsigned NumElems = VT.getVectorNumElements();
13813 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
13814 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
13816 if (InVec.getOpcode() == ISD::BITCAST) {
13817 // Don't duplicate a load with other uses.
13818 if (!InVec.hasOneUse())
13821 InVec = InVec.getOperand(0);
13823 if (ISD::isNormalLoad(InVec.getNode())) {
13824 LN0 = cast<LoadSDNode>(InVec);
13825 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
13826 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
13830 // Make sure we found a non-volatile load and the extractelement is
13832 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
13835 // If Idx was -1 above, Elt is going to be -1, so just return undef.
13837 return DAG.getUNDEF(LVT);
13839 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
13845 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
13846 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
13847 // We perform this optimization post type-legalization because
13848 // the type-legalizer often scalarizes integer-promoted vectors.
13849 // Performing this optimization before may create bit-casts which
13850 // will be type-legalized to complex code sequences.
13851 // We perform this optimization only before the operation legalizer because we
13852 // may introduce illegal operations.
13853 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
13856 unsigned NumInScalars = N->getNumOperands();
13858 EVT VT = N->getValueType(0);
13860 // Check to see if this is a BUILD_VECTOR of a bunch of values
13861 // which come from any_extend or zero_extend nodes. If so, we can create
13862 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
13863 // optimizations. We do not handle sign-extend because we can't fill the sign
13865 EVT SourceType = MVT::Other;
13866 bool AllAnyExt = true;
13868 for (unsigned i = 0; i != NumInScalars; ++i) {
13869 SDValue In = N->getOperand(i);
13870 // Ignore undef inputs.
13871 if (In.isUndef()) continue;
13873 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
13874 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
13876 // Abort if the element is not an extension.
13877 if (!ZeroExt && !AnyExt) {
13878 SourceType = MVT::Other;
13882 // The input is a ZeroExt or AnyExt. Check the original type.
13883 EVT InTy = In.getOperand(0).getValueType();
13885 // Check that all of the widened source types are the same.
13886 if (SourceType == MVT::Other)
13889 else if (InTy != SourceType) {
13890 // Multiple income types. Abort.
13891 SourceType = MVT::Other;
13895 // Check if all of the extends are ANY_EXTENDs.
13896 AllAnyExt &= AnyExt;
13899 // In order to have valid types, all of the inputs must be extended from the
13900 // same source type and all of the inputs must be any or zero extend.
13901 // Scalar sizes must be a power of two.
13902 EVT OutScalarTy = VT.getScalarType();
13903 bool ValidTypes = SourceType != MVT::Other &&
13904 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
13905 isPowerOf2_32(SourceType.getSizeInBits());
13907 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
13908 // turn into a single shuffle instruction.
13912 bool isLE = DAG.getDataLayout().isLittleEndian();
13913 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
13914 assert(ElemRatio > 1 && "Invalid element size ratio");
13915 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
13916 DAG.getConstant(0, DL, SourceType);
13918 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
13919 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
13921 // Populate the new build_vector
13922 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13923 SDValue Cast = N->getOperand(i);
13924 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
13925 Cast.getOpcode() == ISD::ZERO_EXTEND ||
13926 Cast.isUndef()) && "Invalid cast opcode");
13928 if (Cast.isUndef())
13929 In = DAG.getUNDEF(SourceType);
13931 In = Cast->getOperand(0);
13932 unsigned Index = isLE ? (i * ElemRatio) :
13933 (i * ElemRatio + (ElemRatio - 1));
13935 assert(Index < Ops.size() && "Invalid index");
13939 // The type of the new BUILD_VECTOR node.
13940 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
13941 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
13942 "Invalid vector size");
13943 // Check if the new vector type is legal.
13944 if (!isTypeLegal(VecVT)) return SDValue();
13946 // Make the new BUILD_VECTOR.
13947 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
13949 // The new BUILD_VECTOR node has the potential to be further optimized.
13950 AddToWorklist(BV.getNode());
13951 // Bitcast to the desired type.
13952 return DAG.getBitcast(VT, BV);
13955 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
13956 EVT VT = N->getValueType(0);
13958 unsigned NumInScalars = N->getNumOperands();
13961 EVT SrcVT = MVT::Other;
13962 unsigned Opcode = ISD::DELETED_NODE;
13963 unsigned NumDefs = 0;
13965 for (unsigned i = 0; i != NumInScalars; ++i) {
13966 SDValue In = N->getOperand(i);
13967 unsigned Opc = In.getOpcode();
13969 if (Opc == ISD::UNDEF)
13972 // If all scalar values are floats and converted from integers.
13973 if (Opcode == ISD::DELETED_NODE &&
13974 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
13981 EVT InVT = In.getOperand(0).getValueType();
13983 // If all scalar values are typed differently, bail out. It's chosen to
13984 // simplify BUILD_VECTOR of integer types.
13985 if (SrcVT == MVT::Other)
13992 // If the vector has just one element defined, it's not worth to fold it into
13993 // a vectorized one.
13997 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
13998 && "Should only handle conversion from integer to float.");
13999 assert(SrcVT != MVT::Other && "Cannot determine source type!");
14001 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
14003 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
14006 // Just because the floating-point vector type is legal does not necessarily
14007 // mean that the corresponding integer vector type is.
14008 if (!isTypeLegal(NVT))
14011 SmallVector<SDValue, 8> Opnds;
14012 for (unsigned i = 0; i != NumInScalars; ++i) {
14013 SDValue In = N->getOperand(i);
14016 Opnds.push_back(DAG.getUNDEF(SrcVT));
14018 Opnds.push_back(In.getOperand(0));
14020 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
14021 AddToWorklist(BV.getNode());
14023 return DAG.getNode(Opcode, DL, VT, BV);
14026 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
14027 ArrayRef<int> VectorMask,
14028 SDValue VecIn1, SDValue VecIn2,
14029 unsigned LeftIdx) {
14030 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
14031 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
14033 EVT VT = N->getValueType(0);
14034 EVT InVT1 = VecIn1.getValueType();
14035 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
14037 unsigned Vec2Offset = InVT1.getVectorNumElements();
14038 unsigned NumElems = VT.getVectorNumElements();
14039 unsigned ShuffleNumElems = NumElems;
14041 // We can't generate a shuffle node with mismatched input and output types.
14042 // Try to make the types match the type of the output.
14043 if (InVT1 != VT || InVT2 != VT) {
14044 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
14045 // If the output vector length is a multiple of both input lengths,
14046 // we can concatenate them and pad the rest with undefs.
14047 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
14048 assert(NumConcats >= 2 && "Concat needs at least two inputs!");
14049 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
14050 ConcatOps[0] = VecIn1;
14051 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
14052 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14053 VecIn2 = SDValue();
14054 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
14055 if (!TLI.isExtractSubvectorCheap(VT, NumElems))
14058 if (!VecIn2.getNode()) {
14059 // If we only have one input vector, and it's twice the size of the
14060 // output, split it in two.
14061 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
14062 DAG.getConstant(NumElems, DL, IdxTy));
14063 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
14064 // Since we now have shorter input vectors, adjust the offset of the
14065 // second vector's start.
14066 Vec2Offset = NumElems;
14067 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
14068 // VecIn1 is wider than the output, and we have another, possibly
14069 // smaller input. Pad the smaller input with undefs, shuffle at the
14070 // input vector width, and extract the output.
14071 // The shuffle type is different than VT, so check legality again.
14072 if (LegalOperations &&
14073 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
14076 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
14077 // lower it back into a BUILD_VECTOR. So if the inserted type is
14078 // illegal, don't even try.
14079 if (InVT1 != InVT2) {
14080 if (!TLI.isTypeLegal(InVT2))
14082 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
14083 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
14085 ShuffleNumElems = NumElems * 2;
14087 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
14088 // than VecIn1. We can't handle this for now - this case will disappear
14089 // when we start sorting the vectors by type.
14092 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() &&
14093 InVT1.getSizeInBits() == VT.getSizeInBits()) {
14094 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
14095 ConcatOps[0] = VecIn2;
14096 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
14098 // TODO: Support cases where the length mismatch isn't exactly by a
14100 // TODO: Move this check upwards, so that if we have bad type
14101 // mismatches, we don't create any DAG nodes.
14106 // Initialize mask to undef.
14107 SmallVector<int, 8> Mask(ShuffleNumElems, -1);
14109 // Only need to run up to the number of elements actually used, not the
14110 // total number of elements in the shuffle - if we are shuffling a wider
14111 // vector, the high lanes should be set to undef.
14112 for (unsigned i = 0; i != NumElems; ++i) {
14113 if (VectorMask[i] <= 0)
14116 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
14117 if (VectorMask[i] == (int)LeftIdx) {
14118 Mask[i] = ExtIndex;
14119 } else if (VectorMask[i] == (int)LeftIdx + 1) {
14120 Mask[i] = Vec2Offset + ExtIndex;
14124 // The type the input vectors may have changed above.
14125 InVT1 = VecIn1.getValueType();
14127 // If we already have a VecIn2, it should have the same type as VecIn1.
14128 // If we don't, get an undef/zero vector of the appropriate type.
14129 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
14130 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
14132 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
14133 if (ShuffleNumElems > NumElems)
14134 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
14139 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14140 // operations. If the types of the vectors we're extracting from allow it,
14141 // turn this into a vector_shuffle node.
14142 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
14144 EVT VT = N->getValueType(0);
14146 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
14147 if (!isTypeLegal(VT))
14150 // May only combine to shuffle after legalize if shuffle is legal.
14151 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
14154 bool UsesZeroVector = false;
14155 unsigned NumElems = N->getNumOperands();
14157 // Record, for each element of the newly built vector, which input vector
14158 // that element comes from. -1 stands for undef, 0 for the zero vector,
14159 // and positive values for the input vectors.
14160 // VectorMask maps each element to its vector number, and VecIn maps vector
14161 // numbers to their initial SDValues.
14163 SmallVector<int, 8> VectorMask(NumElems, -1);
14164 SmallVector<SDValue, 8> VecIn;
14165 VecIn.push_back(SDValue());
14167 for (unsigned i = 0; i != NumElems; ++i) {
14168 SDValue Op = N->getOperand(i);
14173 // See if we can use a blend with a zero vector.
14174 // TODO: Should we generalize this to a blend with an arbitrary constant
14176 if (isNullConstant(Op) || isNullFPConstant(Op)) {
14177 UsesZeroVector = true;
14182 // Not an undef or zero. If the input is something other than an
14183 // EXTRACT_VECTOR_ELT with a constant index, bail out.
14184 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14185 !isa<ConstantSDNode>(Op.getOperand(1)))
14188 SDValue ExtractedFromVec = Op.getOperand(0);
14190 // All inputs must have the same element type as the output.
14191 if (VT.getVectorElementType() !=
14192 ExtractedFromVec.getValueType().getVectorElementType())
14195 // Have we seen this input vector before?
14196 // The vectors are expected to be tiny (usually 1 or 2 elements), so using
14197 // a map back from SDValues to numbers isn't worth it.
14198 unsigned Idx = std::distance(
14199 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
14200 if (Idx == VecIn.size())
14201 VecIn.push_back(ExtractedFromVec);
14203 VectorMask[i] = Idx;
14206 // If we didn't find at least one input vector, bail out.
14207 if (VecIn.size() < 2)
14210 // TODO: We want to sort the vectors by descending length, so that adjacent
14211 // pairs have similar length, and the longer vector is always first in the
14214 // TODO: Should this fire if some of the input vectors has illegal type (like
14215 // it does now), or should we let legalization run its course first?
14218 // Take pairs of vectors, and shuffle them so that the result has elements
14219 // from these vectors in the correct places.
14220 // For example, given:
14221 // t10: i32 = extract_vector_elt t1, Constant:i64<0>
14222 // t11: i32 = extract_vector_elt t2, Constant:i64<0>
14223 // t12: i32 = extract_vector_elt t3, Constant:i64<0>
14224 // t13: i32 = extract_vector_elt t1, Constant:i64<1>
14225 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
14226 // We will generate:
14227 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
14228 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
14229 SmallVector<SDValue, 4> Shuffles;
14230 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
14231 unsigned LeftIdx = 2 * In + 1;
14232 SDValue VecLeft = VecIn[LeftIdx];
14234 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
14236 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
14237 VecRight, LeftIdx))
14238 Shuffles.push_back(Shuffle);
14243 // If we need the zero vector as an "ingredient" in the blend tree, add it
14244 // to the list of shuffles.
14245 if (UsesZeroVector)
14246 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
14247 : DAG.getConstantFP(0.0, DL, VT));
14249 // If we only have one shuffle, we're done.
14250 if (Shuffles.size() == 1)
14251 return Shuffles[0];
14253 // Update the vector mask to point to the post-shuffle vectors.
14254 for (int &Vec : VectorMask)
14256 Vec = Shuffles.size() - 1;
14258 Vec = (Vec - 1) / 2;
14260 // More than one shuffle. Generate a binary tree of blends, e.g. if from
14261 // the previous step we got the set of shuffles t10, t11, t12, t13, we will
14263 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
14264 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
14265 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
14266 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
14267 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
14268 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
14269 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
14271 // Make sure the initial size of the shuffle list is even.
14272 if (Shuffles.size() % 2)
14273 Shuffles.push_back(DAG.getUNDEF(VT));
14275 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
14277 Shuffles[CurSize] = DAG.getUNDEF(VT);
14280 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
14282 int Right = 2 * In + 1;
14283 SmallVector<int, 8> Mask(NumElems, -1);
14284 for (unsigned i = 0; i != NumElems; ++i) {
14285 if (VectorMask[i] == Left) {
14287 VectorMask[i] = In;
14288 } else if (VectorMask[i] == Right) {
14289 Mask[i] = i + NumElems;
14290 VectorMask[i] = In;
14295 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
14299 return Shuffles[0];
14302 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
14303 // operations which can be matched to a truncate.
14304 SDValue DAGCombiner::reduceBuildVecToTrunc(SDNode *N) {
14305 // TODO: Add support for big-endian.
14306 if (DAG.getDataLayout().isBigEndian())
14308 if (N->getNumOperands() < 2)
14311 EVT VT = N->getValueType(0);
14312 unsigned NumElems = N->getNumOperands();
14314 if (!isTypeLegal(VT))
14317 // If the input is something other than an EXTRACT_VECTOR_ELT with a constant
14318 // index, bail out.
14319 // TODO: Allow undef elements in some cases?
14320 if (any_of(N->ops(), [VT](SDValue Op) {
14321 return Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14322 !isa<ConstantSDNode>(Op.getOperand(1)) ||
14323 Op.getValueType() != VT.getVectorElementType();
14327 // Helper for obtaining an EXTRACT_VECTOR_ELT's constant index
14328 auto GetExtractIdx = [](SDValue Extract) {
14329 return cast<ConstantSDNode>(Extract.getOperand(1))->getSExtValue();
14332 // The first BUILD_VECTOR operand must be an an extract from index zero
14333 // (assuming no undef and little-endian).
14334 if (GetExtractIdx(N->getOperand(0)) != 0)
14337 // Compute the stride from the first index.
14338 int Stride = GetExtractIdx(N->getOperand(1));
14339 SDValue ExtractedFromVec = N->getOperand(0).getOperand(0);
14341 // Proceed only if the stride and the types can be matched to a truncate.
14342 if ((Stride == 1 || !isPowerOf2_32(Stride)) ||
14343 (ExtractedFromVec.getValueType().getVectorNumElements() !=
14344 Stride * NumElems) ||
14345 (VT.getScalarSizeInBits() * Stride > 64))
14348 // Check remaining operands are consistent with the computed stride.
14349 for (unsigned i = 1; i != NumElems; ++i) {
14350 SDValue Op = N->getOperand(i);
14352 if ((Op.getOperand(0) != ExtractedFromVec) ||
14353 (GetExtractIdx(Op) != Stride * i))
14357 // All checks were ok, construct the truncate.
14358 LLVMContext &Ctx = *DAG.getContext();
14359 EVT NewVT = VT.getVectorVT(
14360 Ctx, EVT::getIntegerVT(Ctx, VT.getScalarSizeInBits() * Stride), NumElems);
14362 VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
14364 SDValue Res = DAG.getBitcast(NewVT, ExtractedFromVec);
14365 Res = DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, Res);
14366 return DAG.getBitcast(VT, Res);
14369 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
14370 EVT VT = N->getValueType(0);
14372 // A vector built entirely of undefs is undef.
14373 if (ISD::allOperandsUndef(N))
14374 return DAG.getUNDEF(VT);
14376 // Check if we can express BUILD VECTOR via subvector extract.
14377 if (!LegalTypes && (N->getNumOperands() > 1)) {
14378 SDValue Op0 = N->getOperand(0);
14379 auto checkElem = [&](SDValue Op) -> uint64_t {
14380 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
14381 (Op0.getOperand(0) == Op.getOperand(0)))
14382 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
14383 return CNode->getZExtValue();
14387 int Offset = checkElem(Op0);
14388 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
14389 if (Offset + i != checkElem(N->getOperand(i))) {
14395 if ((Offset == 0) &&
14396 (Op0.getOperand(0).getValueType() == N->getValueType(0)))
14397 return Op0.getOperand(0);
14398 if ((Offset != -1) &&
14399 ((Offset % N->getValueType(0).getVectorNumElements()) ==
14400 0)) // IDX must be multiple of output size.
14401 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
14402 Op0.getOperand(0), Op0.getOperand(1));
14405 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
14408 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
14411 if (TLI.isDesirableToCombineBuildVectorToTruncate())
14412 if (SDValue V = reduceBuildVecToTrunc(N))
14415 if (SDValue V = reduceBuildVecToShuffle(N))
14421 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
14422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14423 EVT OpVT = N->getOperand(0).getValueType();
14425 // If the operands are legal vectors, leave them alone.
14426 if (TLI.isTypeLegal(OpVT))
14430 EVT VT = N->getValueType(0);
14431 SmallVector<SDValue, 8> Ops;
14433 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
14434 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14436 // Keep track of what we encounter.
14437 bool AnyInteger = false;
14438 bool AnyFP = false;
14439 for (const SDValue &Op : N->ops()) {
14440 if (ISD::BITCAST == Op.getOpcode() &&
14441 !Op.getOperand(0).getValueType().isVector())
14442 Ops.push_back(Op.getOperand(0));
14443 else if (ISD::UNDEF == Op.getOpcode())
14444 Ops.push_back(ScalarUndef);
14448 // Note whether we encounter an integer or floating point scalar.
14449 // If it's neither, bail out, it could be something weird like x86mmx.
14450 EVT LastOpVT = Ops.back().getValueType();
14451 if (LastOpVT.isFloatingPoint())
14453 else if (LastOpVT.isInteger())
14459 // If any of the operands is a floating point scalar bitcast to a vector,
14460 // use floating point types throughout, and bitcast everything.
14461 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
14463 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
14464 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
14466 for (SDValue &Op : Ops) {
14467 if (Op.getValueType() == SVT)
14472 Op = DAG.getBitcast(SVT, Op);
14477 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
14478 VT.getSizeInBits() / SVT.getSizeInBits());
14479 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
14482 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
14483 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
14484 // most two distinct vectors the same size as the result, attempt to turn this
14485 // into a legal shuffle.
14486 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
14487 EVT VT = N->getValueType(0);
14488 EVT OpVT = N->getOperand(0).getValueType();
14489 int NumElts = VT.getVectorNumElements();
14490 int NumOpElts = OpVT.getVectorNumElements();
14492 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
14493 SmallVector<int, 8> Mask;
14495 for (SDValue Op : N->ops()) {
14496 // Peek through any bitcast.
14497 while (Op.getOpcode() == ISD::BITCAST)
14498 Op = Op.getOperand(0);
14500 // UNDEF nodes convert to UNDEF shuffle mask values.
14501 if (Op.isUndef()) {
14502 Mask.append((unsigned)NumOpElts, -1);
14506 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14509 // What vector are we extracting the subvector from and at what index?
14510 SDValue ExtVec = Op.getOperand(0);
14512 // We want the EVT of the original extraction to correctly scale the
14513 // extraction index.
14514 EVT ExtVT = ExtVec.getValueType();
14516 // Peek through any bitcast.
14517 while (ExtVec.getOpcode() == ISD::BITCAST)
14518 ExtVec = ExtVec.getOperand(0);
14520 // UNDEF nodes convert to UNDEF shuffle mask values.
14521 if (ExtVec.isUndef()) {
14522 Mask.append((unsigned)NumOpElts, -1);
14526 if (!isa<ConstantSDNode>(Op.getOperand(1)))
14528 int ExtIdx = Op.getConstantOperandVal(1);
14530 // Ensure that we are extracting a subvector from a vector the same
14531 // size as the result.
14532 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
14535 // Scale the subvector index to account for any bitcast.
14536 int NumExtElts = ExtVT.getVectorNumElements();
14537 if (0 == (NumExtElts % NumElts))
14538 ExtIdx /= (NumExtElts / NumElts);
14539 else if (0 == (NumElts % NumExtElts))
14540 ExtIdx *= (NumElts / NumExtElts);
14544 // At most we can reference 2 inputs in the final shuffle.
14545 if (SV0.isUndef() || SV0 == ExtVec) {
14547 for (int i = 0; i != NumOpElts; ++i)
14548 Mask.push_back(i + ExtIdx);
14549 } else if (SV1.isUndef() || SV1 == ExtVec) {
14551 for (int i = 0; i != NumOpElts; ++i)
14552 Mask.push_back(i + ExtIdx + NumElts);
14558 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
14561 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
14562 DAG.getBitcast(VT, SV1), Mask);
14565 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
14566 // If we only have one input vector, we don't need to do any concatenation.
14567 if (N->getNumOperands() == 1)
14568 return N->getOperand(0);
14570 // Check if all of the operands are undefs.
14571 EVT VT = N->getValueType(0);
14572 if (ISD::allOperandsUndef(N))
14573 return DAG.getUNDEF(VT);
14575 // Optimize concat_vectors where all but the first of the vectors are undef.
14576 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
14577 return Op.isUndef();
14579 SDValue In = N->getOperand(0);
14580 assert(In.getValueType().isVector() && "Must concat vectors");
14582 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
14583 if (In->getOpcode() == ISD::BITCAST &&
14584 !In->getOperand(0)->getValueType(0).isVector()) {
14585 SDValue Scalar = In->getOperand(0);
14587 // If the bitcast type isn't legal, it might be a trunc of a legal type;
14588 // look through the trunc so we can still do the transform:
14589 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
14590 if (Scalar->getOpcode() == ISD::TRUNCATE &&
14591 !TLI.isTypeLegal(Scalar.getValueType()) &&
14592 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
14593 Scalar = Scalar->getOperand(0);
14595 EVT SclTy = Scalar->getValueType(0);
14597 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
14600 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
14601 if (VNTNumElms < 2)
14604 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
14605 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
14608 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
14609 return DAG.getBitcast(VT, Res);
14613 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
14614 // We have already tested above for an UNDEF only concatenation.
14615 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
14616 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
14617 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
14618 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
14620 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
14621 SmallVector<SDValue, 8> Opnds;
14622 EVT SVT = VT.getScalarType();
14625 if (!SVT.isFloatingPoint()) {
14626 // If BUILD_VECTOR are from built from integer, they may have different
14627 // operand types. Get the smallest type and truncate all operands to it.
14628 bool FoundMinVT = false;
14629 for (const SDValue &Op : N->ops())
14630 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14631 EVT OpSVT = Op.getOperand(0)->getValueType(0);
14632 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
14635 assert(FoundMinVT && "Concat vector type mismatch");
14638 for (const SDValue &Op : N->ops()) {
14639 EVT OpVT = Op.getValueType();
14640 unsigned NumElts = OpVT.getVectorNumElements();
14642 if (ISD::UNDEF == Op.getOpcode())
14643 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
14645 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
14646 if (SVT.isFloatingPoint()) {
14647 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
14648 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
14650 for (unsigned i = 0; i != NumElts; ++i)
14652 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
14657 assert(VT.getVectorNumElements() == Opnds.size() &&
14658 "Concat vector type mismatch");
14659 return DAG.getBuildVector(VT, SDLoc(N), Opnds);
14662 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
14663 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
14666 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
14667 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
14668 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
14671 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
14672 // nodes often generate nop CONCAT_VECTOR nodes.
14673 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
14674 // place the incoming vectors at the exact same location.
14675 SDValue SingleSource = SDValue();
14676 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
14678 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14679 SDValue Op = N->getOperand(i);
14684 // Check if this is the identity extract:
14685 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14688 // Find the single incoming vector for the extract_subvector.
14689 if (SingleSource.getNode()) {
14690 if (Op.getOperand(0) != SingleSource)
14693 SingleSource = Op.getOperand(0);
14695 // Check the source type is the same as the type of the result.
14696 // If not, this concat may extend the vector, so we can not
14697 // optimize it away.
14698 if (SingleSource.getValueType() != N->getValueType(0))
14702 unsigned IdentityIndex = i * PartNumElem;
14703 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14704 // The extract index must be constant.
14708 // Check that we are reading from the identity index.
14709 if (CS->getZExtValue() != IdentityIndex)
14713 if (SingleSource.getNode())
14714 return SingleSource;
14719 /// If we are extracting a subvector produced by a wide binary operator with at
14720 /// at least one operand that was the result of a vector concatenation, then try
14721 /// to use the narrow vector operands directly to avoid the concatenation and
14723 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) {
14724 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
14725 // some of these bailouts with other transforms.
14727 // The extract index must be a constant, so we can map it to a concat operand.
14728 auto *ExtractIndex = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14732 // Only handle the case where we are doubling and then halving. A larger ratio
14733 // may require more than two narrow binops to replace the wide binop.
14734 EVT VT = Extract->getValueType(0);
14735 unsigned NumElems = VT.getVectorNumElements();
14736 assert((ExtractIndex->getZExtValue() % NumElems) == 0 &&
14737 "Extract index is not a multiple of the vector length.");
14738 if (Extract->getOperand(0).getValueSizeInBits() != VT.getSizeInBits() * 2)
14741 // We are looking for an optionally bitcasted wide vector binary operator
14742 // feeding an extract subvector.
14743 SDValue BinOp = Extract->getOperand(0);
14744 if (BinOp.getOpcode() == ISD::BITCAST)
14745 BinOp = BinOp.getOperand(0);
14747 // TODO: The motivating case for this transform is an x86 AVX1 target. That
14748 // target has temptingly almost legal versions of bitwise logic ops in 256-bit
14749 // flavors, but no other 256-bit integer support. This could be extended to
14750 // handle any binop, but that may require fixing/adding other folds to avoid
14751 // codegen regressions.
14752 unsigned BOpcode = BinOp.getOpcode();
14753 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
14756 // The binop must be a vector type, so we can chop it in half.
14757 EVT WideBVT = BinOp.getValueType();
14758 if (!WideBVT.isVector())
14761 // Bail out if the target does not support a narrower version of the binop.
14762 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
14763 WideBVT.getVectorNumElements() / 2);
14764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14765 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
14768 // Peek through bitcasts of the binary operator operands if needed.
14769 SDValue LHS = BinOp.getOperand(0);
14770 if (LHS.getOpcode() == ISD::BITCAST)
14771 LHS = LHS.getOperand(0);
14773 SDValue RHS = BinOp.getOperand(1);
14774 if (RHS.getOpcode() == ISD::BITCAST)
14775 RHS = RHS.getOperand(0);
14777 // We need at least one concatenation operation of a binop operand to make
14778 // this transform worthwhile. The concat must double the input vector sizes.
14779 // TODO: Should we also handle INSERT_SUBVECTOR patterns?
14781 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2;
14783 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2;
14784 if (!ConcatL && !ConcatR)
14787 // If one of the binop operands was not the result of a concat, we must
14788 // extract a half-sized operand for our new narrow binop. We can't just reuse
14789 // the original extract index operand because we may have bitcasted.
14790 unsigned ConcatOpNum = ExtractIndex->getZExtValue() / NumElems;
14791 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
14792 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType();
14795 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
14796 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, N)
14797 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, N), YN
14798 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum))
14799 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14800 BinOp.getOperand(0),
14801 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14803 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum))
14804 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
14805 BinOp.getOperand(1),
14806 DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT));
14808 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
14809 return DAG.getBitcast(VT, NarrowBinOp);
14812 /// If we are extracting a subvector from a wide vector load, convert to a
14813 /// narrow load to eliminate the extraction:
14814 /// (extract_subvector (load wide vector)) --> (load narrow vector)
14815 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
14816 // TODO: Add support for big-endian. The offset calculation must be adjusted.
14817 if (DAG.getDataLayout().isBigEndian())
14820 // TODO: The one-use check is overly conservative. Check the cost of the
14821 // extract instead or remove that condition entirely.
14822 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
14823 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
14824 if (!Ld || !Ld->hasOneUse() || Ld->getExtensionType() || Ld->isVolatile() ||
14828 // The narrow load will be offset from the base address of the old load if
14829 // we are extracting from something besides index 0 (little-endian).
14830 EVT VT = Extract->getValueType(0);
14832 SDValue BaseAddr = Ld->getOperand(1);
14833 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize();
14835 // TODO: Use "BaseIndexOffset" to make this more effective.
14836 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
14837 MachineFunction &MF = DAG.getMachineFunction();
14838 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset,
14839 VT.getStoreSize());
14840 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
14841 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
14845 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
14846 EVT NVT = N->getValueType(0);
14847 SDValue V = N->getOperand(0);
14849 // Extract from UNDEF is UNDEF.
14851 return DAG.getUNDEF(NVT);
14853 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
14854 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
14858 // (extract_subvec (concat V1, V2, ...), i)
14861 // Only operand 0 is checked as 'concat' assumes all inputs of the same
14863 if (V->getOpcode() == ISD::CONCAT_VECTORS &&
14864 isa<ConstantSDNode>(N->getOperand(1)) &&
14865 V->getOperand(0).getValueType() == NVT) {
14866 unsigned Idx = N->getConstantOperandVal(1);
14867 unsigned NumElems = NVT.getVectorNumElements();
14868 assert((Idx % NumElems) == 0 &&
14869 "IDX in concat is not a multiple of the result vector length.");
14870 return V->getOperand(Idx / NumElems);
14874 if (V->getOpcode() == ISD::BITCAST)
14875 V = V.getOperand(0);
14877 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
14878 // Handle only simple case where vector being inserted and vector
14879 // being extracted are of same size.
14880 EVT SmallVT = V->getOperand(1).getValueType();
14881 if (!NVT.bitsEq(SmallVT))
14884 // Only handle cases where both indexes are constants.
14885 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
14886 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
14888 if (InsIdx && ExtIdx) {
14890 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
14892 // indices are equal or bit offsets are equal => V1
14893 // otherwise => (extract_subvec V1, ExtIdx)
14894 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
14895 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
14896 return DAG.getBitcast(NVT, V->getOperand(1));
14897 return DAG.getNode(
14898 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
14899 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
14904 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG))
14910 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
14911 SDValue V, SelectionDAG &DAG) {
14913 EVT VT = V.getValueType();
14915 switch (V.getOpcode()) {
14919 case ISD::CONCAT_VECTORS: {
14920 EVT OpVT = V->getOperand(0).getValueType();
14921 int OpSize = OpVT.getVectorNumElements();
14922 SmallBitVector OpUsedElements(OpSize, false);
14923 bool FoundSimplification = false;
14924 SmallVector<SDValue, 4> NewOps;
14925 NewOps.reserve(V->getNumOperands());
14926 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
14927 SDValue Op = V->getOperand(i);
14928 bool OpUsed = false;
14929 for (int j = 0; j < OpSize; ++j)
14930 if (UsedElements[i * OpSize + j]) {
14931 OpUsedElements[j] = true;
14935 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
14936 : DAG.getUNDEF(OpVT));
14937 FoundSimplification |= Op == NewOps.back();
14938 OpUsedElements.reset();
14940 if (FoundSimplification)
14941 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
14945 case ISD::INSERT_SUBVECTOR: {
14946 SDValue BaseV = V->getOperand(0);
14947 SDValue SubV = V->getOperand(1);
14948 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
14952 int SubSize = SubV.getValueType().getVectorNumElements();
14953 int Idx = IdxN->getZExtValue();
14954 bool SubVectorUsed = false;
14955 SmallBitVector SubUsedElements(SubSize, false);
14956 for (int i = 0; i < SubSize; ++i)
14957 if (UsedElements[i + Idx]) {
14958 SubVectorUsed = true;
14959 SubUsedElements[i] = true;
14960 UsedElements[i + Idx] = false;
14963 // Now recurse on both the base and sub vectors.
14964 SDValue SimplifiedSubV =
14966 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
14967 : DAG.getUNDEF(SubV.getValueType());
14968 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
14969 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
14970 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14971 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
14977 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
14978 SDValue N1, SelectionDAG &DAG) {
14979 EVT VT = SVN->getValueType(0);
14980 int NumElts = VT.getVectorNumElements();
14981 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
14982 for (int M : SVN->getMask())
14983 if (M >= 0 && M < NumElts)
14984 N0UsedElements[M] = true;
14985 else if (M >= NumElts)
14986 N1UsedElements[M - NumElts] = true;
14988 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
14989 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
14990 if (S0 == N0 && S1 == N1)
14993 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
14996 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
14997 // or turn a shuffle of a single concat into simpler shuffle then concat.
14998 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
14999 EVT VT = N->getValueType(0);
15000 unsigned NumElts = VT.getVectorNumElements();
15002 SDValue N0 = N->getOperand(0);
15003 SDValue N1 = N->getOperand(1);
15004 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15006 SmallVector<SDValue, 4> Ops;
15007 EVT ConcatVT = N0.getOperand(0).getValueType();
15008 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
15009 unsigned NumConcats = NumElts / NumElemsPerConcat;
15011 // Special case: shuffle(concat(A,B)) can be more efficiently represented
15012 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
15013 // half vector elements.
15014 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
15015 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
15016 SVN->getMask().end(), [](int i) { return i == -1; })) {
15017 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
15018 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
15019 N1 = DAG.getUNDEF(ConcatVT);
15020 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
15023 // Look at every vector that's inserted. We're looking for exact
15024 // subvector-sized copies from a concatenated vector
15025 for (unsigned I = 0; I != NumConcats; ++I) {
15026 // Make sure we're dealing with a copy.
15027 unsigned Begin = I * NumElemsPerConcat;
15028 bool AllUndef = true, NoUndef = true;
15029 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
15030 if (SVN->getMaskElt(J) >= 0)
15037 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
15040 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
15041 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
15044 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
15045 if (FirstElt < N0.getNumOperands())
15046 Ops.push_back(N0.getOperand(FirstElt));
15048 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
15050 } else if (AllUndef) {
15051 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
15052 } else { // Mixed with general masks and undefs, can't do optimization.
15057 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15060 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15061 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15063 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
15064 // a simplification in some sense, but it isn't appropriate in general: some
15065 // BUILD_VECTORs are substantially cheaper than others. The general case
15066 // of a BUILD_VECTOR requires inserting each element individually (or
15067 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
15068 // all constants is a single constant pool load. A BUILD_VECTOR where each
15069 // element is identical is a splat. A BUILD_VECTOR where most of the operands
15070 // are undef lowers to a small number of element insertions.
15072 // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
15073 // We don't fold shuffles where one side is a non-zero constant, and we don't
15074 // fold shuffles if the resulting BUILD_VECTOR would have duplicate
15075 // non-constant operands. This seems to work out reasonably well in practice.
15076 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
15078 const TargetLowering &TLI) {
15079 EVT VT = SVN->getValueType(0);
15080 unsigned NumElts = VT.getVectorNumElements();
15081 SDValue N0 = SVN->getOperand(0);
15082 SDValue N1 = SVN->getOperand(1);
15084 if (!N0->hasOneUse() || !N1->hasOneUse())
15086 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
15087 // discussed above.
15088 if (!N1.isUndef()) {
15089 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
15090 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
15091 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
15093 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
15097 SmallVector<SDValue, 8> Ops;
15098 SmallSet<SDValue, 16> DuplicateOps;
15099 for (int M : SVN->getMask()) {
15100 SDValue Op = DAG.getUNDEF(VT.getScalarType());
15102 int Idx = M < (int)NumElts ? M : M - NumElts;
15103 SDValue &S = (M < (int)NumElts ? N0 : N1);
15104 if (S.getOpcode() == ISD::BUILD_VECTOR) {
15105 Op = S.getOperand(Idx);
15106 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
15108 Op = S.getOperand(0);
15110 // Operand can't be combined - bail out.
15115 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
15116 // fine, but it's likely to generate low-quality code if the target can't
15117 // reconstruct an appropriate shuffle.
15118 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
15119 if (!DuplicateOps.insert(Op).second)
15124 // BUILD_VECTOR requires all inputs to be of the same type, find the
15125 // maximum type and extend them all.
15126 EVT SVT = VT.getScalarType();
15127 if (SVT.isInteger())
15128 for (SDValue &Op : Ops)
15129 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
15130 if (SVT != VT.getScalarType())
15131 for (SDValue &Op : Ops)
15132 Op = TLI.isZExtFree(Op.getValueType(), SVT)
15133 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
15134 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
15135 return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
15138 // Match shuffles that can be converted to any_vector_extend_in_reg.
15139 // This is often generated during legalization.
15140 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
15141 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
15142 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
15144 const TargetLowering &TLI,
15145 bool LegalOperations) {
15146 EVT VT = SVN->getValueType(0);
15147 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15149 // TODO Add support for big-endian when we have a test case.
15150 if (!VT.isInteger() || IsBigEndian)
15153 unsigned NumElts = VT.getVectorNumElements();
15154 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15155 ArrayRef<int> Mask = SVN->getMask();
15156 SDValue N0 = SVN->getOperand(0);
15158 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
15159 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
15160 for (unsigned i = 0; i != NumElts; ++i) {
15163 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
15170 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
15171 // power-of-2 extensions as they are the most likely.
15172 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
15173 if (!isAnyExtend(Scale))
15176 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
15177 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
15178 if (!LegalOperations ||
15179 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
15180 return DAG.getBitcast(VT,
15181 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
15187 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
15188 // each source element of a large type into the lowest elements of a smaller
15189 // destination type. This is often generated during legalization.
15190 // If the source node itself was a '*_extend_vector_inreg' node then we should
15191 // then be able to remove it.
15192 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
15193 SelectionDAG &DAG) {
15194 EVT VT = SVN->getValueType(0);
15195 bool IsBigEndian = DAG.getDataLayout().isBigEndian();
15197 // TODO Add support for big-endian when we have a test case.
15198 if (!VT.isInteger() || IsBigEndian)
15201 SDValue N0 = SVN->getOperand(0);
15202 while (N0.getOpcode() == ISD::BITCAST)
15203 N0 = N0.getOperand(0);
15205 unsigned Opcode = N0.getOpcode();
15206 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
15207 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
15208 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
15211 SDValue N00 = N0.getOperand(0);
15212 ArrayRef<int> Mask = SVN->getMask();
15213 unsigned NumElts = VT.getVectorNumElements();
15214 unsigned EltSizeInBits = VT.getScalarSizeInBits();
15215 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
15216 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
15218 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
15220 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
15222 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
15223 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
15224 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
15225 auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
15226 for (unsigned i = 0; i != NumElts; ++i) {
15229 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
15236 // At the moment we just handle the case where we've truncated back to the
15237 // same size as before the extension.
15238 // TODO: handle more extension/truncation cases as cases arise.
15239 if (EltSizeInBits != ExtSrcSizeInBits)
15242 // We can remove *extend_vector_inreg only if the truncation happens at
15243 // the same scale as the extension.
15244 if (isTruncate(ExtScale))
15245 return DAG.getBitcast(VT, N00);
15250 // Combine shuffles of splat-shuffles of the form:
15251 // shuffle (shuffle V, undef, splat-mask), undef, M
15252 // If splat-mask contains undef elements, we need to be careful about
15253 // introducing undef's in the folded mask which are not the result of composing
15254 // the masks of the shuffles.
15255 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask,
15256 ShuffleVectorSDNode *Splat,
15257 SelectionDAG &DAG) {
15258 ArrayRef<int> SplatMask = Splat->getMask();
15259 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch");
15261 // Prefer simplifying to the splat-shuffle, if possible. This is legal if
15262 // every undef mask element in the splat-shuffle has a corresponding undef
15263 // element in the user-shuffle's mask or if the composition of mask elements
15264 // would result in undef.
15265 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
15266 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
15267 // In this case it is not legal to simplify to the splat-shuffle because we
15268 // may be exposing the users of the shuffle an undef element at index 1
15269 // which was not there before the combine.
15270 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
15271 // In this case the composition of masks yields SplatMask, so it's ok to
15272 // simplify to the splat-shuffle.
15273 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
15274 // In this case the composed mask includes all undef elements of SplatMask
15275 // and in addition sets element zero to undef. It is safe to simplify to
15276 // the splat-shuffle.
15277 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
15278 ArrayRef<int> SplatMask) {
15279 for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
15280 if (UserMask[i] != -1 && SplatMask[i] == -1 &&
15281 SplatMask[UserMask[i]] != -1)
15285 if (CanSimplifyToExistingSplat(UserMask, SplatMask))
15286 return SDValue(Splat, 0);
15288 // Create a new shuffle with a mask that is composed of the two shuffles'
15290 SmallVector<int, 32> NewMask;
15291 for (int Idx : UserMask)
15292 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
15294 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
15295 Splat->getOperand(0), Splat->getOperand(1),
15299 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
15300 EVT VT = N->getValueType(0);
15301 unsigned NumElts = VT.getVectorNumElements();
15303 SDValue N0 = N->getOperand(0);
15304 SDValue N1 = N->getOperand(1);
15306 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
15308 // Canonicalize shuffle undef, undef -> undef
15309 if (N0.isUndef() && N1.isUndef())
15310 return DAG.getUNDEF(VT);
15312 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15314 // Canonicalize shuffle v, v -> v, undef
15316 SmallVector<int, 8> NewMask;
15317 for (unsigned i = 0; i != NumElts; ++i) {
15318 int Idx = SVN->getMaskElt(i);
15319 if (Idx >= (int)NumElts) Idx -= NumElts;
15320 NewMask.push_back(Idx);
15322 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
15325 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
15327 return DAG.getCommutedVectorShuffle(*SVN);
15329 // Remove references to rhs if it is undef
15330 if (N1.isUndef()) {
15331 bool Changed = false;
15332 SmallVector<int, 8> NewMask;
15333 for (unsigned i = 0; i != NumElts; ++i) {
15334 int Idx = SVN->getMaskElt(i);
15335 if (Idx >= (int)NumElts) {
15339 NewMask.push_back(Idx);
15342 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
15345 // A shuffle of a single vector that is a splat can always be folded.
15346 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0))
15347 if (N1->isUndef() && N0Shuf->isSplat())
15348 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG);
15350 // If it is a splat, check if the argument vector is another splat or a
15352 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
15353 SDNode *V = N0.getNode();
15355 // If this is a bit convert that changes the element type of the vector but
15356 // not the number of vector elements, look through it. Be careful not to
15357 // look though conversions that change things like v4f32 to v2f64.
15358 if (V->getOpcode() == ISD::BITCAST) {
15359 SDValue ConvInput = V->getOperand(0);
15360 if (ConvInput.getValueType().isVector() &&
15361 ConvInput.getValueType().getVectorNumElements() == NumElts)
15362 V = ConvInput.getNode();
15365 if (V->getOpcode() == ISD::BUILD_VECTOR) {
15366 assert(V->getNumOperands() == NumElts &&
15367 "BUILD_VECTOR has wrong number of operands");
15369 bool AllSame = true;
15370 for (unsigned i = 0; i != NumElts; ++i) {
15371 if (!V->getOperand(i).isUndef()) {
15372 Base = V->getOperand(i);
15376 // Splat of <u, u, u, u>, return <u, u, u, u>
15377 if (!Base.getNode())
15379 for (unsigned i = 0; i != NumElts; ++i) {
15380 if (V->getOperand(i) != Base) {
15385 // Splat of <x, x, x, x>, return <x, x, x, x>
15389 // Canonicalize any other splat as a build_vector.
15390 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
15391 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
15392 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
15394 // We may have jumped through bitcasts, so the type of the
15395 // BUILD_VECTOR may not match the type of the shuffle.
15396 if (V->getValueType(0) != VT)
15397 NewBV = DAG.getBitcast(VT, NewBV);
15402 // There are various patterns used to build up a vector from smaller vectors,
15403 // subvectors, or elements. Scan chains of these and replace unused insertions
15404 // or components with undef.
15405 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
15408 // Match shuffles that can be converted to any_vector_extend_in_reg.
15409 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
15412 // Combine "truncate_vector_in_reg" style shuffles.
15413 if (SDValue V = combineTruncationShuffle(SVN, DAG))
15416 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
15417 Level < AfterLegalizeVectorOps &&
15419 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
15420 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
15421 if (SDValue V = partitionShuffleOfConcats(N, DAG))
15425 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
15426 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
15427 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
15428 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
15431 // If this shuffle only has a single input that is a bitcasted shuffle,
15432 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
15433 // back to their original types.
15434 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
15435 N1.isUndef() && Level < AfterLegalizeVectorOps &&
15436 TLI.isTypeLegal(VT)) {
15438 // Peek through the bitcast only if there is one user.
15440 while (BC0.getOpcode() == ISD::BITCAST) {
15441 if (!BC0.hasOneUse())
15443 BC0 = BC0.getOperand(0);
15446 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
15448 return SmallVector<int, 8>(Mask.begin(), Mask.end());
15450 SmallVector<int, 8> NewMask;
15452 for (int s = 0; s != Scale; ++s)
15453 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
15457 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
15458 EVT SVT = VT.getScalarType();
15459 EVT InnerVT = BC0->getValueType(0);
15460 EVT InnerSVT = InnerVT.getScalarType();
15462 // Determine which shuffle works with the smaller scalar type.
15463 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
15464 EVT ScaleSVT = ScaleVT.getScalarType();
15466 if (TLI.isTypeLegal(ScaleVT) &&
15467 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
15468 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
15470 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15471 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
15473 // Scale the shuffle masks to the smaller scalar type.
15474 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
15475 SmallVector<int, 8> InnerMask =
15476 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
15477 SmallVector<int, 8> OuterMask =
15478 ScaleShuffleMask(SVN->getMask(), OuterScale);
15480 // Merge the shuffle masks.
15481 SmallVector<int, 8> NewMask;
15482 for (int M : OuterMask)
15483 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
15485 // Test for shuffle mask legality over both commutations.
15486 SDValue SV0 = BC0->getOperand(0);
15487 SDValue SV1 = BC0->getOperand(1);
15488 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15490 std::swap(SV0, SV1);
15491 ShuffleVectorSDNode::commuteMask(NewMask);
15492 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
15496 SV0 = DAG.getBitcast(ScaleVT, SV0);
15497 SV1 = DAG.getBitcast(ScaleVT, SV1);
15498 return DAG.getBitcast(
15499 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
15505 // Canonicalize shuffles according to rules:
15506 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
15507 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
15508 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
15509 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
15510 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
15511 TLI.isTypeLegal(VT)) {
15512 // The incoming shuffle must be of the same type as the result of the
15513 // current shuffle.
15514 assert(N1->getOperand(0).getValueType() == VT &&
15515 "Shuffle types don't match");
15517 SDValue SV0 = N1->getOperand(0);
15518 SDValue SV1 = N1->getOperand(1);
15519 bool HasSameOp0 = N0 == SV0;
15520 bool IsSV1Undef = SV1.isUndef();
15521 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
15522 // Commute the operands of this shuffle so that next rule
15524 return DAG.getCommutedVectorShuffle(*SVN);
15527 // Try to fold according to rules:
15528 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15529 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15530 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15531 // Don't try to fold shuffles with illegal type.
15532 // Only fold if this shuffle is the only user of the other shuffle.
15533 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
15534 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
15535 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
15537 // Don't try to fold splats; they're likely to simplify somehow, or they
15539 if (OtherSV->isSplat())
15542 // The incoming shuffle must be of the same type as the result of the
15543 // current shuffle.
15544 assert(OtherSV->getOperand(0).getValueType() == VT &&
15545 "Shuffle types don't match");
15548 SmallVector<int, 4> Mask;
15549 // Compute the combined shuffle mask for a shuffle with SV0 as the first
15550 // operand, and SV1 as the second operand.
15551 for (unsigned i = 0; i != NumElts; ++i) {
15552 int Idx = SVN->getMaskElt(i);
15554 // Propagate Undef.
15555 Mask.push_back(Idx);
15559 SDValue CurrentVec;
15560 if (Idx < (int)NumElts) {
15561 // This shuffle index refers to the inner shuffle N0. Lookup the inner
15562 // shuffle mask to identify which vector is actually referenced.
15563 Idx = OtherSV->getMaskElt(Idx);
15565 // Propagate Undef.
15566 Mask.push_back(Idx);
15570 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
15571 : OtherSV->getOperand(1);
15573 // This shuffle index references an element within N1.
15577 // Simple case where 'CurrentVec' is UNDEF.
15578 if (CurrentVec.isUndef()) {
15579 Mask.push_back(-1);
15583 // Canonicalize the shuffle index. We don't know yet if CurrentVec
15584 // will be the first or second operand of the combined shuffle.
15585 Idx = Idx % NumElts;
15586 if (!SV0.getNode() || SV0 == CurrentVec) {
15587 // Ok. CurrentVec is the left hand side.
15588 // Update the mask accordingly.
15590 Mask.push_back(Idx);
15594 // Bail out if we cannot convert the shuffle pair into a single shuffle.
15595 if (SV1.getNode() && SV1 != CurrentVec)
15598 // Ok. CurrentVec is the right hand side.
15599 // Update the mask accordingly.
15601 Mask.push_back(Idx + NumElts);
15604 // Check if all indices in Mask are Undef. In case, propagate Undef.
15605 bool isUndefMask = true;
15606 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
15607 isUndefMask &= Mask[i] < 0;
15610 return DAG.getUNDEF(VT);
15612 if (!SV0.getNode())
15613 SV0 = DAG.getUNDEF(VT);
15614 if (!SV1.getNode())
15615 SV1 = DAG.getUNDEF(VT);
15617 // Avoid introducing shuffles with illegal mask.
15618 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
15619 ShuffleVectorSDNode::commuteMask(Mask);
15621 if (!TLI.isShuffleMaskLegal(Mask, VT))
15624 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
15625 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
15626 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
15627 std::swap(SV0, SV1);
15630 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
15631 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
15632 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
15633 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
15639 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
15640 SDValue InVal = N->getOperand(0);
15641 EVT VT = N->getValueType(0);
15643 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
15644 // with a VECTOR_SHUFFLE.
15645 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15646 SDValue InVec = InVal->getOperand(0);
15647 SDValue EltNo = InVal->getOperand(1);
15649 // FIXME: We could support implicit truncation if the shuffle can be
15650 // scaled to a smaller vector scalar type.
15651 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
15652 if (C0 && VT == InVec.getValueType() &&
15653 VT.getScalarType() == InVal.getValueType()) {
15654 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
15655 int Elt = C0->getZExtValue();
15658 if (TLI.isShuffleMaskLegal(NewMask, VT))
15659 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
15667 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
15668 EVT VT = N->getValueType(0);
15669 SDValue N0 = N->getOperand(0);
15670 SDValue N1 = N->getOperand(1);
15671 SDValue N2 = N->getOperand(2);
15673 // If inserting an UNDEF, just return the original vector.
15677 // If this is an insert of an extracted vector into an undef vector, we can
15678 // just use the input to the extract.
15679 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
15680 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
15681 return N1.getOperand(0);
15683 // Combine INSERT_SUBVECTORs where we are inserting to the same index.
15684 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
15685 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
15686 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
15687 N0.getOperand(1).getValueType() == N1.getValueType() &&
15688 N0.getOperand(2) == N2)
15689 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
15692 if (!isa<ConstantSDNode>(N2))
15695 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
15697 // Canonicalize insert_subvector dag nodes.
15699 // (insert_subvector (insert_subvector A, Idx0), Idx1)
15700 // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
15701 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
15702 N1.getValueType() == N0.getOperand(1).getValueType() &&
15703 isa<ConstantSDNode>(N0.getOperand(2))) {
15704 unsigned OtherIdx = N0.getConstantOperandVal(2);
15705 if (InsIdx < OtherIdx) {
15707 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
15708 N0.getOperand(0), N1, N2);
15709 AddToWorklist(NewOp.getNode());
15710 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
15711 VT, NewOp, N0.getOperand(1), N0.getOperand(2));
15715 // If the input vector is a concatenation, and the insert replaces
15716 // one of the pieces, we can optimize into a single concat_vectors.
15717 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
15718 N0.getOperand(0).getValueType() == N1.getValueType()) {
15719 unsigned Factor = N1.getValueType().getVectorNumElements();
15721 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
15722 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
15724 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
15730 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
15731 SDValue N0 = N->getOperand(0);
15733 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
15734 if (N0->getOpcode() == ISD::FP16_TO_FP)
15735 return N0->getOperand(0);
15740 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
15741 SDValue N0 = N->getOperand(0);
15743 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
15744 if (N0->getOpcode() == ISD::AND) {
15745 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
15746 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
15747 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
15755 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
15756 /// with the destination vector and a zero vector.
15757 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
15758 /// vector_shuffle V, Zero, <0, 4, 2, 4>
15759 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
15760 EVT VT = N->getValueType(0);
15761 SDValue LHS = N->getOperand(0);
15762 SDValue RHS = N->getOperand(1);
15765 // Make sure we're not running after operation legalization where it
15766 // may have custom lowered the vector shuffles.
15767 if (LegalOperations)
15770 if (N->getOpcode() != ISD::AND)
15773 if (RHS.getOpcode() == ISD::BITCAST)
15774 RHS = RHS.getOperand(0);
15776 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
15779 EVT RVT = RHS.getValueType();
15780 unsigned NumElts = RHS.getNumOperands();
15782 // Attempt to create a valid clear mask, splitting the mask into
15783 // sub elements and checking to see if each is
15784 // all zeros or all ones - suitable for shuffle masking.
15785 auto BuildClearMask = [&](int Split) {
15786 int NumSubElts = NumElts * Split;
15787 int NumSubBits = RVT.getScalarSizeInBits() / Split;
15789 SmallVector<int, 8> Indices;
15790 for (int i = 0; i != NumSubElts; ++i) {
15791 int EltIdx = i / Split;
15792 int SubIdx = i % Split;
15793 SDValue Elt = RHS.getOperand(EltIdx);
15794 if (Elt.isUndef()) {
15795 Indices.push_back(-1);
15800 if (isa<ConstantSDNode>(Elt))
15801 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
15802 else if (isa<ConstantFPSDNode>(Elt))
15803 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
15807 // Extract the sub element from the constant bit mask.
15808 if (DAG.getDataLayout().isBigEndian()) {
15809 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits);
15811 Bits.lshrInPlace(SubIdx * NumSubBits);
15815 Bits = Bits.trunc(NumSubBits);
15817 if (Bits.isAllOnesValue())
15818 Indices.push_back(i);
15819 else if (Bits == 0)
15820 Indices.push_back(i + NumSubElts);
15825 // Let's see if the target supports this vector_shuffle.
15826 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
15827 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
15828 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
15831 SDValue Zero = DAG.getConstant(0, DL, ClearVT);
15832 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
15833 DAG.getBitcast(ClearVT, LHS),
15837 // Determine maximum split level (byte level masking).
15839 if (RVT.getScalarSizeInBits() % 8 == 0)
15840 MaxSplit = RVT.getScalarSizeInBits() / 8;
15842 for (int Split = 1; Split <= MaxSplit; ++Split)
15843 if (RVT.getScalarSizeInBits() % Split == 0)
15844 if (SDValue S = BuildClearMask(Split))
15850 /// Visit a binary vector operation, like ADD.
15851 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
15852 assert(N->getValueType(0).isVector() &&
15853 "SimplifyVBinOp only works on vectors!");
15855 SDValue LHS = N->getOperand(0);
15856 SDValue RHS = N->getOperand(1);
15857 SDValue Ops[] = {LHS, RHS};
15859 // See if we can constant fold the vector operation.
15860 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
15861 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
15864 // Try to convert a constant mask AND into a shuffle clear mask.
15865 if (SDValue Shuffle = XformToShuffleWithZero(N))
15868 // Type legalization might introduce new shuffles in the DAG.
15869 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
15870 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
15871 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
15872 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
15873 LHS.getOperand(1).isUndef() &&
15874 RHS.getOperand(1).isUndef()) {
15875 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
15876 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
15878 if (SVN0->getMask().equals(SVN1->getMask())) {
15879 EVT VT = N->getValueType(0);
15880 SDValue UndefVector = LHS.getOperand(1);
15881 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
15882 LHS.getOperand(0), RHS.getOperand(0),
15884 AddUsersToWorklist(N);
15885 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
15893 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
15895 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
15897 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
15898 cast<CondCodeSDNode>(N0.getOperand(2))->get());
15900 // If we got a simplified select_cc node back from SimplifySelectCC, then
15901 // break it down into a new SETCC node, and a new SELECT node, and then return
15902 // the SELECT node, since we were called with a SELECT node.
15903 if (SCC.getNode()) {
15904 // Check to see if we got a select_cc back (to turn into setcc/select).
15905 // Otherwise, just return whatever node we got back, like fabs.
15906 if (SCC.getOpcode() == ISD::SELECT_CC) {
15907 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
15909 SCC.getOperand(0), SCC.getOperand(1),
15910 SCC.getOperand(4));
15911 AddToWorklist(SETCC.getNode());
15912 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
15913 SCC.getOperand(2), SCC.getOperand(3));
15921 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
15922 /// being selected between, see if we can simplify the select. Callers of this
15923 /// should assume that TheSelect is deleted if this returns true. As such, they
15924 /// should return the appropriate thing (e.g. the node) back to the top-level of
15925 /// the DAG combiner loop to avoid it being looked at.
15926 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
15929 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15930 // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
15931 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
15932 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
15933 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
15934 SDValue Sqrt = RHS;
15937 const ConstantFPSDNode *Zero = nullptr;
15939 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
15940 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
15941 CmpLHS = TheSelect->getOperand(0);
15942 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
15944 // SELECT or VSELECT
15945 SDValue Cmp = TheSelect->getOperand(0);
15946 if (Cmp.getOpcode() == ISD::SETCC) {
15947 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
15948 CmpLHS = Cmp.getOperand(0);
15949 Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
15952 if (Zero && Zero->isZero() &&
15953 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
15954 CC == ISD::SETULT || CC == ISD::SETLT)) {
15955 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
15956 CombineTo(TheSelect, Sqrt);
15961 // Cannot simplify select with vector condition
15962 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
15964 // If this is a select from two identical things, try to pull the operation
15965 // through the select.
15966 if (LHS.getOpcode() != RHS.getOpcode() ||
15967 !LHS.hasOneUse() || !RHS.hasOneUse())
15970 // If this is a load and the token chain is identical, replace the select
15971 // of two loads with a load through a select of the address to load from.
15972 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
15973 // constants have been dropped into the constant pool.
15974 if (LHS.getOpcode() == ISD::LOAD) {
15975 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
15976 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
15978 // Token chains must be identical.
15979 if (LHS.getOperand(0) != RHS.getOperand(0) ||
15980 // Do not let this transformation reduce the number of volatile loads.
15981 LLD->isVolatile() || RLD->isVolatile() ||
15982 // FIXME: If either is a pre/post inc/dec load,
15983 // we'd need to split out the address adjustment.
15984 LLD->isIndexed() || RLD->isIndexed() ||
15985 // If this is an EXTLOAD, the VT's must match.
15986 LLD->getMemoryVT() != RLD->getMemoryVT() ||
15987 // If this is an EXTLOAD, the kind of extension must match.
15988 (LLD->getExtensionType() != RLD->getExtensionType() &&
15989 // The only exception is if one of the extensions is anyext.
15990 LLD->getExtensionType() != ISD::EXTLOAD &&
15991 RLD->getExtensionType() != ISD::EXTLOAD) ||
15992 // FIXME: this discards src value information. This is
15993 // over-conservative. It would be beneficial to be able to remember
15994 // both potential memory locations. Since we are discarding
15995 // src value info, don't do the transformation if the memory
15996 // locations are not in the default address space.
15997 LLD->getPointerInfo().getAddrSpace() != 0 ||
15998 RLD->getPointerInfo().getAddrSpace() != 0 ||
15999 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
16000 LLD->getBasePtr().getValueType()))
16003 // Check that the select condition doesn't reach either load. If so,
16004 // folding this will induce a cycle into the DAG. If not, this is safe to
16005 // xform, so create a select of the addresses.
16007 if (TheSelect->getOpcode() == ISD::SELECT) {
16008 SDNode *CondNode = TheSelect->getOperand(0).getNode();
16009 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
16010 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
16012 // The loads must not depend on one another.
16013 if (LLD->isPredecessorOf(RLD) ||
16014 RLD->isPredecessorOf(LLD))
16016 Addr = DAG.getSelect(SDLoc(TheSelect),
16017 LLD->getBasePtr().getValueType(),
16018 TheSelect->getOperand(0), LLD->getBasePtr(),
16019 RLD->getBasePtr());
16020 } else { // Otherwise SELECT_CC
16021 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
16022 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
16024 if ((LLD->hasAnyUseOfValue(1) &&
16025 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
16026 (RLD->hasAnyUseOfValue(1) &&
16027 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
16030 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
16031 LLD->getBasePtr().getValueType(),
16032 TheSelect->getOperand(0),
16033 TheSelect->getOperand(1),
16034 LLD->getBasePtr(), RLD->getBasePtr(),
16035 TheSelect->getOperand(4));
16039 // It is safe to replace the two loads if they have different alignments,
16040 // but the new load must be the minimum (most restrictive) alignment of the
16042 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
16043 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
16044 if (!RLD->isInvariant())
16045 MMOFlags &= ~MachineMemOperand::MOInvariant;
16046 if (!RLD->isDereferenceable())
16047 MMOFlags &= ~MachineMemOperand::MODereferenceable;
16048 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
16049 // FIXME: Discards pointer and AA info.
16050 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
16051 LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
16054 // FIXME: Discards pointer and AA info.
16055 Load = DAG.getExtLoad(
16056 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
16057 : LLD->getExtensionType(),
16058 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
16059 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
16062 // Users of the select now use the result of the load.
16063 CombineTo(TheSelect, Load);
16065 // Users of the old loads now use the new load's chain. We know the
16066 // old-load value is dead now.
16067 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
16068 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
16075 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
16077 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
16078 SDValue N1, SDValue N2, SDValue N3,
16079 ISD::CondCode CC) {
16080 // If this is a select where the false operand is zero and the compare is a
16081 // check of the sign bit, see if we can perform the "gzip trick":
16082 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
16083 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
16084 EVT XType = N0.getValueType();
16085 EVT AType = N2.getValueType();
16086 if (!isNullConstant(N3) || !XType.bitsGE(AType))
16089 // If the comparison is testing for a positive value, we have to invert
16090 // the sign bit mask, so only do that transform if the target has a bitwise
16091 // 'and not' instruction (the invert is free).
16092 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
16093 // (X > -1) ? A : 0
16094 // (X > 0) ? X : 0 <-- This is canonical signed max.
16095 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
16097 } else if (CC == ISD::SETLT) {
16099 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
16100 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
16106 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
16108 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
16109 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16110 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
16111 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
16112 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
16113 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
16114 AddToWorklist(Shift.getNode());
16116 if (XType.bitsGT(AType)) {
16117 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16118 AddToWorklist(Shift.getNode());
16121 if (CC == ISD::SETGT)
16122 Shift = DAG.getNOT(DL, Shift, AType);
16124 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16127 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
16128 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
16129 AddToWorklist(Shift.getNode());
16131 if (XType.bitsGT(AType)) {
16132 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
16133 AddToWorklist(Shift.getNode());
16136 if (CC == ISD::SETGT)
16137 Shift = DAG.getNOT(DL, Shift, AType);
16139 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
16142 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
16143 /// where 'cond' is the comparison specified by CC.
16144 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
16145 SDValue N2, SDValue N3, ISD::CondCode CC,
16146 bool NotExtCompare) {
16147 // (x ? y : y) -> y.
16148 if (N2 == N3) return N2;
16150 EVT VT = N2.getValueType();
16151 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
16152 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
16154 // Determine if the condition we're dealing with is constant
16155 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
16156 N0, N1, CC, DL, false);
16157 if (SCC.getNode()) AddToWorklist(SCC.getNode());
16159 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
16160 // fold select_cc true, x, y -> x
16161 // fold select_cc false, x, y -> y
16162 return !SCCC->isNullValue() ? N2 : N3;
16165 // Check to see if we can simplify the select into an fabs node
16166 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
16167 // Allow either -0.0 or 0.0
16168 if (CFP->isZero()) {
16169 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
16170 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
16171 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
16172 N2 == N3.getOperand(0))
16173 return DAG.getNode(ISD::FABS, DL, VT, N0);
16175 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
16176 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
16177 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
16178 N2.getOperand(0) == N3)
16179 return DAG.getNode(ISD::FABS, DL, VT, N3);
16183 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
16184 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
16185 // in it. This is a win when the constant is not otherwise available because
16186 // it replaces two constant pool loads with one. We only do this if the FP
16187 // type is known to be legal, because if it isn't, then we are before legalize
16188 // types an we want the other legalization to happen first (e.g. to avoid
16189 // messing with soft float) and if the ConstantFP is not legal, because if
16190 // it is legal, we may not need to store the FP constant in a constant pool.
16191 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
16192 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
16193 if (TLI.isTypeLegal(N2.getValueType()) &&
16194 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
16195 TargetLowering::Legal &&
16196 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
16197 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
16198 // If both constants have multiple uses, then we won't need to do an
16199 // extra load, they are likely around in registers for other users.
16200 (TV->hasOneUse() || FV->hasOneUse())) {
16201 Constant *Elts[] = {
16202 const_cast<ConstantFP*>(FV->getConstantFPValue()),
16203 const_cast<ConstantFP*>(TV->getConstantFPValue())
16205 Type *FPTy = Elts[0]->getType();
16206 const DataLayout &TD = DAG.getDataLayout();
16208 // Create a ConstantArray of the two constants.
16209 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
16211 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
16212 TD.getPrefTypeAlignment(FPTy));
16213 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
16215 // Get the offsets to the 0 and 1 element of the array so that we can
16216 // select between them.
16217 SDValue Zero = DAG.getIntPtrConstant(0, DL);
16218 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
16219 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
16221 SDValue Cond = DAG.getSetCC(DL,
16222 getSetCCResultType(N0.getValueType()),
16224 AddToWorklist(Cond.getNode());
16225 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
16227 AddToWorklist(CstOffset.getNode());
16228 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
16230 AddToWorklist(CPIdx.getNode());
16231 return DAG.getLoad(
16232 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
16233 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
16238 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
16241 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
16242 // where y is has a single bit set.
16243 // A plaintext description would be, we can turn the SELECT_CC into an AND
16244 // when the condition can be materialized as an all-ones register. Any
16245 // single bit-test can be materialized as an all-ones register with
16246 // shift-left and shift-right-arith.
16247 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
16248 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
16249 SDValue AndLHS = N0->getOperand(0);
16250 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16251 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
16252 // Shift the tested bit over the sign bit.
16253 const APInt &AndMask = ConstAndRHS->getAPIntValue();
16255 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
16256 getShiftAmountTy(AndLHS.getValueType()));
16257 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
16259 // Now arithmetic right shift it all the way over, so the result is either
16260 // all-ones, or zero.
16262 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
16263 getShiftAmountTy(Shl.getValueType()));
16264 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
16266 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
16270 // fold select C, 16, 0 -> shl C, 4
16271 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
16272 TLI.getBooleanContents(N0.getValueType()) ==
16273 TargetLowering::ZeroOrOneBooleanContent) {
16275 // If the caller doesn't want us to simplify this into a zext of a compare,
16277 if (NotExtCompare && N2C->isOne())
16280 // Get a SetCC of the condition
16281 // NOTE: Don't create a SETCC if it's not legal on this target.
16282 if (!LegalOperations ||
16283 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
16285 // cast from setcc result type to select result type
16287 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
16289 if (N2.getValueType().bitsLT(SCC.getValueType()))
16290 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
16291 N2.getValueType());
16293 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16294 N2.getValueType(), SCC);
16296 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
16297 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
16298 N2.getValueType(), SCC);
16301 AddToWorklist(SCC.getNode());
16302 AddToWorklist(Temp.getNode());
16307 // shl setcc result by log2 n2c
16308 return DAG.getNode(
16309 ISD::SHL, DL, N2.getValueType(), Temp,
16310 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
16311 getShiftAmountTy(Temp.getValueType())));
16315 // Check to see if this is an integer abs.
16316 // select_cc setg[te] X, 0, X, -X ->
16317 // select_cc setgt X, -1, X, -X ->
16318 // select_cc setl[te] X, 0, -X, X ->
16319 // select_cc setlt X, 1, -X, X ->
16320 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
16322 ConstantSDNode *SubC = nullptr;
16323 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
16324 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
16325 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
16326 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
16327 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
16328 (N1C->isOne() && CC == ISD::SETLT)) &&
16329 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
16330 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
16332 EVT XType = N0.getValueType();
16333 if (SubC && SubC->isNullValue() && XType.isInteger()) {
16335 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
16337 DAG.getConstant(XType.getSizeInBits() - 1, DL,
16338 getShiftAmountTy(N0.getValueType())));
16339 SDValue Add = DAG.getNode(ISD::ADD, DL,
16341 AddToWorklist(Shift.getNode());
16342 AddToWorklist(Add.getNode());
16343 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
16347 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
16348 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
16349 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
16350 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
16351 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
16352 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
16353 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
16354 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
16355 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
16356 SDValue ValueOnZero = N2;
16357 SDValue Count = N3;
16358 // If the condition is NE instead of E, swap the operands.
16359 if (CC == ISD::SETNE)
16360 std::swap(ValueOnZero, Count);
16361 // Check if the value on zero is a constant equal to the bits in the type.
16362 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
16363 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
16364 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
16365 // legal, combine to just cttz.
16366 if ((Count.getOpcode() == ISD::CTTZ ||
16367 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
16368 N0 == Count.getOperand(0) &&
16369 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
16370 return DAG.getNode(ISD::CTTZ, DL, VT, N0);
16371 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
16372 // legal, combine to just ctlz.
16373 if ((Count.getOpcode() == ISD::CTLZ ||
16374 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
16375 N0 == Count.getOperand(0) &&
16376 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
16377 return DAG.getNode(ISD::CTLZ, DL, VT, N0);
16385 /// This is a stub for TargetLowering::SimplifySetCC.
16386 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
16387 ISD::CondCode Cond, const SDLoc &DL,
16388 bool foldBooleans) {
16389 TargetLowering::DAGCombinerInfo
16390 DagCombineInfo(DAG, Level, false, this);
16391 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
16394 /// Given an ISD::SDIV node expressing a divide by constant, return
16395 /// a DAG expression to select that will generate the same value by multiplying
16396 /// by a magic number.
16397 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16398 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
16399 // when optimising for minimum size, we don't want to expand a div to a mul
16401 if (DAG.getMachineFunction().getFunction()->optForMinSize())
16404 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16408 // Avoid division by zero.
16409 if (C->isNullValue())
16412 std::vector<SDNode*> Built;
16414 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16416 for (SDNode *N : Built)
16421 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
16422 /// DAG expression that will generate the same value by right shifting.
16423 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
16424 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16428 // Avoid division by zero.
16429 if (C->isNullValue())
16432 std::vector<SDNode *> Built;
16433 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
16435 for (SDNode *N : Built)
16440 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
16441 /// expression that will generate the same value by multiplying by a magic
16443 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
16444 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
16445 // when optimising for minimum size, we don't want to expand a div to a mul
16447 if (DAG.getMachineFunction().getFunction()->optForMinSize())
16450 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
16454 // Avoid division by zero.
16455 if (C->isNullValue())
16458 std::vector<SDNode*> Built;
16460 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
16462 for (SDNode *N : Built)
16467 /// Determines the LogBase2 value for a non-null input value using the
16468 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
16469 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
16470 EVT VT = V.getValueType();
16471 unsigned EltBits = VT.getScalarSizeInBits();
16472 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
16473 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
16474 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
16478 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16479 /// For the reciprocal, we need to find the zero of the function:
16480 /// F(X) = A X - 1 [which has a zero at X = 1/A]
16482 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
16483 /// does not require additional intermediate precision]
16484 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) {
16485 if (Level >= AfterLegalizeDAG)
16488 // TODO: Handle half and/or extended types?
16489 EVT VT = Op.getValueType();
16490 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16493 // If estimates are explicitly disabled for this function, we're done.
16494 MachineFunction &MF = DAG.getMachineFunction();
16495 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
16496 if (Enabled == TLI.ReciprocalEstimate::Disabled)
16499 // Estimates may be explicitly enabled for this type with a custom number of
16500 // refinement steps.
16501 int Iterations = TLI.getDivRefinementSteps(VT, MF);
16502 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
16503 AddToWorklist(Est.getNode());
16506 EVT VT = Op.getValueType();
16508 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
16510 // Newton iterations: Est = Est + Est (1 - Arg * Est)
16511 for (int i = 0; i < Iterations; ++i) {
16512 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
16513 AddToWorklist(NewEst.getNode());
16515 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
16516 AddToWorklist(NewEst.getNode());
16518 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16519 AddToWorklist(NewEst.getNode());
16521 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
16522 AddToWorklist(Est.getNode());
16531 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16532 /// For the reciprocal sqrt, we need to find the zero of the function:
16533 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16535 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
16536 /// As a result, we precompute A/2 prior to the iteration loop.
16537 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
16538 unsigned Iterations,
16539 SDNodeFlags Flags, bool Reciprocal) {
16540 EVT VT = Arg.getValueType();
16542 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
16544 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
16545 // this entire sequence requires only one FP constant.
16546 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
16547 AddToWorklist(HalfArg.getNode());
16549 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
16550 AddToWorklist(HalfArg.getNode());
16552 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
16553 for (unsigned i = 0; i < Iterations; ++i) {
16554 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
16555 AddToWorklist(NewEst.getNode());
16557 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
16558 AddToWorklist(NewEst.getNode());
16560 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
16561 AddToWorklist(NewEst.getNode());
16563 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
16564 AddToWorklist(Est.getNode());
16567 // If non-reciprocal square root is requested, multiply the result by Arg.
16569 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
16570 AddToWorklist(Est.getNode());
16576 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
16577 /// For the reciprocal sqrt, we need to find the zero of the function:
16578 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
16580 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
16581 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
16582 unsigned Iterations,
16583 SDNodeFlags Flags, bool Reciprocal) {
16584 EVT VT = Arg.getValueType();
16586 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
16587 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
16589 // This routine must enter the loop below to work correctly
16590 // when (Reciprocal == false).
16591 assert(Iterations > 0);
16593 // Newton iterations for reciprocal square root:
16594 // E = (E * -0.5) * ((A * E) * E + -3.0)
16595 for (unsigned i = 0; i < Iterations; ++i) {
16596 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
16597 AddToWorklist(AE.getNode());
16599 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
16600 AddToWorklist(AEE.getNode());
16602 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
16603 AddToWorklist(RHS.getNode());
16605 // When calculating a square root at the last iteration build:
16606 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
16607 // (notice a common subexpression)
16609 if (Reciprocal || (i + 1) < Iterations) {
16610 // RSQRT: LHS = (E * -0.5)
16611 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
16613 // SQRT: LHS = (A * E) * -0.5
16614 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
16616 AddToWorklist(LHS.getNode());
16618 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
16619 AddToWorklist(Est.getNode());
16625 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
16626 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
16627 /// Op can be zero.
16628 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
16630 if (Level >= AfterLegalizeDAG)
16633 // TODO: Handle half and/or extended types?
16634 EVT VT = Op.getValueType();
16635 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
16638 // If estimates are explicitly disabled for this function, we're done.
16639 MachineFunction &MF = DAG.getMachineFunction();
16640 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
16641 if (Enabled == TLI.ReciprocalEstimate::Disabled)
16644 // Estimates may be explicitly enabled for this type with a custom number of
16645 // refinement steps.
16646 int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
16648 bool UseOneConstNR = false;
16650 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
16652 AddToWorklist(Est.getNode());
16655 Est = UseOneConstNR
16656 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
16657 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
16660 // Unfortunately, Est is now NaN if the input was exactly 0.0.
16661 // Select out this case and force the answer to 0.0.
16662 EVT VT = Op.getValueType();
16665 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
16666 EVT CCVT = getSetCCResultType(VT);
16667 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
16668 AddToWorklist(ZeroCmp.getNode());
16670 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
16671 ZeroCmp, FPZero, Est);
16672 AddToWorklist(Est.getNode());
16681 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16682 return buildSqrtEstimateImpl(Op, Flags, true);
16685 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
16686 return buildSqrtEstimateImpl(Op, Flags, false);
16689 /// Return true if base is a frame index, which is known not to alias with
16690 /// anything but itself. Provides base object and offset as results.
16691 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
16692 const GlobalValue *&GV, const void *&CV) {
16693 // Assume it is a primitive operation.
16694 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
16696 // If it's an adding a simple constant then integrate the offset.
16697 if (Base.getOpcode() == ISD::ADD) {
16698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
16699 Base = Base.getOperand(0);
16700 Offset += C->getSExtValue();
16704 // Return the underlying GlobalValue, and update the Offset. Return false
16705 // for GlobalAddressSDNode since the same GlobalAddress may be represented
16706 // by multiple nodes with different offsets.
16707 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
16708 GV = G->getGlobal();
16709 Offset += G->getOffset();
16713 // Return the underlying Constant value, and update the Offset. Return false
16714 // for ConstantSDNodes since the same constant pool entry may be represented
16715 // by multiple nodes with different offsets.
16716 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
16717 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
16718 : (const void *)C->getConstVal();
16719 Offset += C->getOffset();
16722 // If it's any of the following then it can't alias with anything but itself.
16723 return isa<FrameIndexSDNode>(Base);
16726 /// Return true if there is any possibility that the two addresses overlap.
16727 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
16728 // If they are the same then they must be aliases.
16729 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
16731 // If they are both volatile then they cannot be reordered.
16732 if (Op0->isVolatile() && Op1->isVolatile()) return true;
16734 // If one operation reads from invariant memory, and the other may store, they
16735 // cannot alias. These should really be checking the equivalent of mayWrite,
16736 // but it only matters for memory nodes other than load /store.
16737 if (Op0->isInvariant() && Op1->writeMem())
16740 if (Op1->isInvariant() && Op0->writeMem())
16743 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3;
16744 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3;
16746 // Check for BaseIndexOffset matching.
16747 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG);
16748 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG);
16750 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff))
16751 return !((NumBytes0 <= PtrDiff) || (PtrDiff + NumBytes1 <= 0));
16753 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
16754 // able to calculate their relative offset if at least one arises
16755 // from an alloca. However, these allocas cannot overlap and we
16756 // can infer there is no alias.
16757 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
16758 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
16759 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16760 // If the base are the same frame index but the we couldn't find a
16761 // constant offset, (indices are different) be conservative.
16762 if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
16763 !MFI.isFixedObjectIndex(B->getIndex())))
16767 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis
16768 // modified to use BaseIndexOffset.
16770 // Gather base node and offset information.
16771 SDValue Base0, Base1;
16772 int64_t Offset0, Offset1;
16773 const GlobalValue *GV0, *GV1;
16774 const void *CV0, *CV1;
16775 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(),
16776 Base0, Offset0, GV0, CV0);
16777 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(),
16778 Base1, Offset1, GV1, CV1);
16780 // If they have the same base address, then check to see if they overlap.
16781 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1)))
16782 return !((Offset0 + NumBytes0) <= Offset1 ||
16783 (Offset1 + NumBytes1) <= Offset0);
16785 // It is possible for different frame indices to alias each other, mostly
16786 // when tail call optimization reuses return address slots for arguments.
16787 // To catch this case, look up the actual index of frame indices to compute
16788 // the real alias relationship.
16789 if (IsFrameIndex0 && IsFrameIndex1) {
16790 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
16791 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex());
16792 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
16793 return !((Offset0 + NumBytes0) <= Offset1 ||
16794 (Offset1 + NumBytes1) <= Offset0);
16797 // Otherwise, if we know what the bases are, and they aren't identical, then
16798 // we know they cannot alias.
16799 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1))
16802 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
16803 // compared to the size and offset of the access, we may be able to prove they
16804 // do not alias. This check is conservative for now to catch cases created by
16805 // splitting vector types.
16806 int64_t SrcValOffset0 = Op0->getSrcValueOffset();
16807 int64_t SrcValOffset1 = Op1->getSrcValueOffset();
16808 unsigned OrigAlignment0 = Op0->getOriginalAlignment();
16809 unsigned OrigAlignment1 = Op1->getOriginalAlignment();
16810 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
16811 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) {
16812 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0;
16813 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1;
16815 // There is no overlap between these relatively aligned accesses of similar
16816 // size. Return no alias.
16817 if ((OffAlign0 + NumBytes0) <= OffAlign1 ||
16818 (OffAlign1 + NumBytes1) <= OffAlign0)
16822 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
16824 : DAG.getSubtarget().useAA();
16826 if (CombinerAAOnlyFunc.getNumOccurrences() &&
16827 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
16832 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
16833 // Use alias analysis information.
16834 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
16835 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset;
16836 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset;
16837 AliasResult AAResult =
16838 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0,
16839 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
16840 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1,
16841 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) );
16842 if (AAResult == NoAlias)
16846 // Otherwise we have to assume they alias.
16850 /// Walk up chain skipping non-aliasing memory nodes,
16851 /// looking for aliasing nodes and adding them to the Aliases vector.
16852 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
16853 SmallVectorImpl<SDValue> &Aliases) {
16854 SmallVector<SDValue, 8> Chains; // List of chains to visit.
16855 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
16857 // Get alias information for node.
16858 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
16861 Chains.push_back(OriginalChain);
16862 unsigned Depth = 0;
16864 // Look at each chain and determine if it is an alias. If so, add it to the
16865 // aliases list. If not, then continue up the chain looking for the next
16867 while (!Chains.empty()) {
16868 SDValue Chain = Chains.pop_back_val();
16870 // For TokenFactor nodes, look at each operand and only continue up the
16871 // chain until we reach the depth limit.
16873 // FIXME: The depth check could be made to return the last non-aliasing
16874 // chain we found before we hit a tokenfactor rather than the original
16876 if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
16878 Aliases.push_back(OriginalChain);
16882 // Don't bother if we've been before.
16883 if (!Visited.insert(Chain.getNode()).second)
16886 switch (Chain.getOpcode()) {
16887 case ISD::EntryToken:
16888 // Entry token is ideal chain operand, but handled in FindBetterChain.
16893 // Get alias information for Chain.
16894 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
16895 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
16897 // If chain is alias then stop here.
16898 if (!(IsLoad && IsOpLoad) &&
16899 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
16900 Aliases.push_back(Chain);
16902 // Look further up the chain.
16903 Chains.push_back(Chain.getOperand(0));
16909 case ISD::TokenFactor:
16910 // We have to check each of the operands of the token factor for "small"
16911 // token factors, so we queue them up. Adding the operands to the queue
16912 // (stack) in reverse order maintains the original order and increases the
16913 // likelihood that getNode will find a matching token factor (CSE.)
16914 if (Chain.getNumOperands() > 16) {
16915 Aliases.push_back(Chain);
16918 for (unsigned n = Chain.getNumOperands(); n;)
16919 Chains.push_back(Chain.getOperand(--n));
16923 case ISD::CopyFromReg:
16924 // Forward past CopyFromReg.
16925 Chains.push_back(Chain.getOperand(0));
16930 // For all other instructions we will just have to take what we can get.
16931 Aliases.push_back(Chain);
16937 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
16938 /// (aliasing node.)
16939 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
16940 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
16942 // Accumulate all the aliases to this node.
16943 GatherAllAliases(N, OldChain, Aliases);
16945 // If no operands then chain to entry token.
16946 if (Aliases.size() == 0)
16947 return DAG.getEntryNode();
16949 // If a single operand then chain to it. We don't need to revisit it.
16950 if (Aliases.size() == 1)
16953 // Construct a custom tailored token factor.
16954 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
16957 // This function tries to collect a bunch of potentially interesting
16958 // nodes to improve the chains of, all at once. This might seem
16959 // redundant, as this function gets called when visiting every store
16960 // node, so why not let the work be done on each store as it's visited?
16962 // I believe this is mainly important because MergeConsecutiveStores
16963 // is unable to deal with merging stores of different sizes, so unless
16964 // we improve the chains of all the potential candidates up-front
16965 // before running MergeConsecutiveStores, it might only see some of
16966 // the nodes that will eventually be candidates, and then not be able
16967 // to go from a partially-merged state to the desired final
16968 // fully-merged state.
16969 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
16970 // This holds the base pointer, index, and the offset in bytes from the base
16972 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
16974 // We must have a base and an offset.
16975 if (!BasePtr.getBase().getNode())
16978 // Do not handle stores to undef base pointers.
16979 if (BasePtr.getBase().isUndef())
16982 SmallVector<StoreSDNode *, 8> ChainedStores;
16983 ChainedStores.push_back(St);
16985 // Walk up the chain and look for nodes with offsets from the same
16986 // base pointer. Stop when reaching an instruction with a different kind
16987 // or instruction which has a different base pointer.
16988 StoreSDNode *Index = St;
16990 // If the chain has more than one use, then we can't reorder the mem ops.
16991 if (Index != St && !SDValue(Index, 0)->hasOneUse())
16994 if (Index->isVolatile() || Index->isIndexed())
16997 // Find the base pointer and offset for this memory node.
16998 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
17000 // Check that the base pointer is the same as the original one.
17001 if (!BasePtr.equalBaseIndex(Ptr, DAG))
17004 // Walk up the chain to find the next store node, ignoring any
17005 // intermediate loads. Any other kind of node will halt the loop.
17006 SDNode *NextInChain = Index->getChain().getNode();
17008 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
17009 // We found a store node. Use it for the next iteration.
17010 if (STn->isVolatile() || STn->isIndexed()) {
17014 ChainedStores.push_back(STn);
17017 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
17018 NextInChain = Ldn->getChain().getNode();
17027 // At this point, ChainedStores lists all of the Store nodes
17028 // reachable by iterating up through chain nodes matching the above
17029 // conditions. For each such store identified, try to find an
17030 // earlier chain to attach the store to which won't violate the
17031 // required ordering.
17032 bool MadeChangeToSt = false;
17033 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
17035 for (StoreSDNode *ChainedStore : ChainedStores) {
17036 SDValue Chain = ChainedStore->getChain();
17037 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
17039 if (Chain != BetterChain) {
17040 if (ChainedStore == St)
17041 MadeChangeToSt = true;
17042 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
17046 // Do all replacements after finding the replacements to make to avoid making
17047 // the chains more complicated by introducing new TokenFactors.
17048 for (auto Replacement : BetterChains)
17049 replaceStoreChain(Replacement.first, Replacement.second);
17051 return MadeChangeToSt;
17054 /// This is the entry point for the file.
17055 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
17056 CodeGenOpt::Level OptLevel) {
17057 /// This is the main entry point to this class.
17058 DAGCombiner(*this, AA, OptLevel).Run(Level);