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/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
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 *, 64> 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 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitIMINMAX(SDNode *N);
249 SDValue visitAND(SDNode *N);
250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
251 SDValue visitOR(SDNode *N);
252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
253 SDValue visitXOR(SDNode *N);
254 SDValue SimplifyVBinOp(SDNode *N);
255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
258 SDValue visitRotate(SDNode *N);
259 SDValue visitBSWAP(SDNode *N);
260 SDValue visitCTLZ(SDNode *N);
261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTTZ(SDNode *N);
263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
264 SDValue visitCTPOP(SDNode *N);
265 SDValue visitSELECT(SDNode *N);
266 SDValue visitVSELECT(SDNode *N);
267 SDValue visitSELECT_CC(SDNode *N);
268 SDValue visitSETCC(SDNode *N);
269 SDValue visitSIGN_EXTEND(SDNode *N);
270 SDValue visitZERO_EXTEND(SDNode *N);
271 SDValue visitANY_EXTEND(SDNode *N);
272 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
274 SDValue visitTRUNCATE(SDNode *N);
275 SDValue visitBITCAST(SDNode *N);
276 SDValue visitBUILD_PAIR(SDNode *N);
277 SDValue visitFADD(SDNode *N);
278 SDValue visitFSUB(SDNode *N);
279 SDValue visitFMUL(SDNode *N);
280 SDValue visitFMA(SDNode *N);
281 SDValue visitFDIV(SDNode *N);
282 SDValue visitFREM(SDNode *N);
283 SDValue visitFSQRT(SDNode *N);
284 SDValue visitFCOPYSIGN(SDNode *N);
285 SDValue visitSINT_TO_FP(SDNode *N);
286 SDValue visitUINT_TO_FP(SDNode *N);
287 SDValue visitFP_TO_SINT(SDNode *N);
288 SDValue visitFP_TO_UINT(SDNode *N);
289 SDValue visitFP_ROUND(SDNode *N);
290 SDValue visitFP_ROUND_INREG(SDNode *N);
291 SDValue visitFP_EXTEND(SDNode *N);
292 SDValue visitFNEG(SDNode *N);
293 SDValue visitFABS(SDNode *N);
294 SDValue visitFCEIL(SDNode *N);
295 SDValue visitFTRUNC(SDNode *N);
296 SDValue visitFFLOOR(SDNode *N);
297 SDValue visitFMINNUM(SDNode *N);
298 SDValue visitFMAXNUM(SDNode *N);
299 SDValue visitBRCOND(SDNode *N);
300 SDValue visitBR_CC(SDNode *N);
301 SDValue visitLOAD(SDNode *N);
303 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305 SDValue visitSTORE(SDNode *N);
306 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
307 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
308 SDValue visitBUILD_VECTOR(SDNode *N);
309 SDValue visitCONCAT_VECTORS(SDNode *N);
310 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
311 SDValue visitVECTOR_SHUFFLE(SDNode *N);
312 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
313 SDValue visitINSERT_SUBVECTOR(SDNode *N);
314 SDValue visitMLOAD(SDNode *N);
315 SDValue visitMSTORE(SDNode *N);
316 SDValue visitMGATHER(SDNode *N);
317 SDValue visitMSCATTER(SDNode *N);
318 SDValue visitFP_TO_FP16(SDNode *N);
319 SDValue visitFP16_TO_FP(SDNode *N);
321 SDValue visitFADDForFMACombine(SDNode *N);
322 SDValue visitFSUBForFMACombine(SDNode *N);
324 SDValue XformToShuffleWithZero(SDNode *N);
325 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
327 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
329 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
330 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
331 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
332 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
333 SDValue N3, ISD::CondCode CC,
334 bool NotExtCompare = false);
335 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
336 SDLoc DL, bool foldBooleans = true);
338 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
340 bool isOneUseSetCC(SDValue N) const;
342 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
344 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
345 SDValue CombineExtLoad(SDNode *N);
346 SDValue combineRepeatedFPDivisors(SDNode *N);
347 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
348 SDValue BuildSDIV(SDNode *N);
349 SDValue BuildSDIVPow2(SDNode *N);
350 SDValue BuildUDIV(SDNode *N);
351 SDValue BuildReciprocalEstimate(SDValue Op);
352 SDValue BuildRsqrtEstimate(SDValue Op);
353 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
354 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
355 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
356 bool DemandHighBits = true);
357 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
358 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
359 SDValue InnerPos, SDValue InnerNeg,
360 unsigned PosOpcode, unsigned NegOpcode,
362 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
363 SDValue ReduceLoadWidth(SDNode *N);
364 SDValue ReduceLoadOpStoreWidth(SDNode *N);
365 SDValue TransformFPLoadStorePair(SDNode *N);
366 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
367 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
369 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
371 /// Walk up chain skipping non-aliasing memory nodes,
372 /// looking for aliasing nodes and adding them to the Aliases vector.
373 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
374 SmallVectorImpl<SDValue> &Aliases);
376 /// Return true if there is any possibility that the two addresses overlap.
377 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
379 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
380 /// chain (aliasing node.)
381 SDValue FindBetterChain(SDNode *N, SDValue Chain);
383 /// Do FindBetterChain for a store and any possibly adjacent stores on
384 /// consecutive chains.
385 bool findBetterNeighborChains(StoreSDNode *St);
387 /// Holds a pointer to an LSBaseSDNode as well as information on where it
388 /// is located in a sequence of memory operations connected by a chain.
390 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
391 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
392 // Ptr to the mem node.
393 LSBaseSDNode *MemNode;
394 // Offset from the base ptr.
395 int64_t OffsetFromBase;
396 // What is the sequence number of this mem node.
397 // Lowest mem operand in the DAG starts at zero.
398 unsigned SequenceNum;
401 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
402 /// constant build_vector of the stored constant values in Stores.
403 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
405 ArrayRef<MemOpLink> Stores,
408 /// This is a helper function for MergeConsecutiveStores. When the source
409 /// elements of the consecutive stores are all constants or all extracted
410 /// vector elements, try to merge them into one larger store.
411 /// \return True if a merged store was created.
412 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
413 EVT MemVT, unsigned NumStores,
414 bool IsConstantSrc, bool UseVector);
416 /// This is a helper function for MergeConsecutiveStores.
417 /// Stores that may be merged are placed in StoreNodes.
418 /// Loads that may alias with those stores are placed in AliasLoadNodes.
419 void getStoreMergeAndAliasCandidates(
420 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
421 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
423 /// Merge consecutive store operations into a wide store.
424 /// This optimization uses wide integers or vectors when possible.
425 /// \return True if some memory operations were changed.
426 bool MergeConsecutiveStores(StoreSDNode *N);
428 /// \brief Try to transform a truncation where C is a constant:
429 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
431 /// \p N needs to be a truncation and its first operand an AND. Other
432 /// requirements are checked by the function (e.g. that trunc is
433 /// single-use) and if missed an empty SDValue is returned.
434 SDValue distributeTruncateThroughAnd(SDNode *N);
437 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
438 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
439 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
440 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
443 /// Runs the dag combiner on all nodes in the work list
444 void Run(CombineLevel AtLevel);
446 SelectionDAG &getDAG() const { return DAG; }
448 /// Returns a type large enough to hold any valid shift amount - before type
449 /// legalization these can be huge.
450 EVT getShiftAmountTy(EVT LHSTy) {
451 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
452 if (LHSTy.isVector())
454 auto &DL = DAG.getDataLayout();
455 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
456 : TLI.getPointerTy(DL);
459 /// This method returns true if we are running before type legalization or
460 /// if the specified VT is legal.
461 bool isTypeLegal(const EVT &VT) {
462 if (!LegalTypes) return true;
463 return TLI.isTypeLegal(VT);
466 /// Convenience wrapper around TargetLowering::getSetCCResultType
467 EVT getSetCCResultType(EVT VT) const {
468 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
475 /// This class is a DAGUpdateListener that removes any deleted
476 /// nodes from the worklist.
477 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
480 explicit WorklistRemover(DAGCombiner &dc)
481 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
483 void NodeDeleted(SDNode *N, SDNode *E) override {
484 DC.removeFromWorklist(N);
489 //===----------------------------------------------------------------------===//
490 // TargetLowering::DAGCombinerInfo implementation
491 //===----------------------------------------------------------------------===//
493 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
494 ((DAGCombiner*)DC)->AddToWorklist(N);
497 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
498 ((DAGCombiner*)DC)->removeFromWorklist(N);
501 SDValue TargetLowering::DAGCombinerInfo::
502 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
503 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
506 SDValue TargetLowering::DAGCombinerInfo::
507 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
508 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
512 SDValue TargetLowering::DAGCombinerInfo::
513 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
514 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
517 void TargetLowering::DAGCombinerInfo::
518 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
519 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
522 //===----------------------------------------------------------------------===//
524 //===----------------------------------------------------------------------===//
526 void DAGCombiner::deleteAndRecombine(SDNode *N) {
527 removeFromWorklist(N);
529 // If the operands of this node are only used by the node, they will now be
530 // dead. Make sure to re-visit them and recursively delete dead nodes.
531 for (const SDValue &Op : N->ops())
532 // For an operand generating multiple values, one of the values may
533 // become dead allowing further simplification (e.g. split index
534 // arithmetic from an indexed load).
535 if (Op->hasOneUse() || Op->getNumValues() > 1)
536 AddToWorklist(Op.getNode());
541 /// Return 1 if we can compute the negated form of the specified expression for
542 /// the same cost as the expression itself, or 2 if we can compute the negated
543 /// form more cheaply than the expression itself.
544 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
545 const TargetLowering &TLI,
546 const TargetOptions *Options,
547 unsigned Depth = 0) {
548 // fneg is removable even if it has multiple uses.
549 if (Op.getOpcode() == ISD::FNEG) return 2;
551 // Don't allow anything with multiple uses.
552 if (!Op.hasOneUse()) return 0;
554 // Don't recurse exponentially.
555 if (Depth > 6) return 0;
557 switch (Op.getOpcode()) {
558 default: return false;
559 case ISD::ConstantFP:
560 // Don't invert constant FP values after legalize. The negated constant
561 // isn't necessarily legal.
562 return LegalOperations ? 0 : 1;
564 // FIXME: determine better conditions for this xform.
565 if (!Options->UnsafeFPMath) return 0;
567 // After operation legalization, it might not be legal to create new FSUBs.
568 if (LegalOperations &&
569 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
572 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
573 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
576 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
577 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
580 // We can't turn -(A-B) into B-A when we honor signed zeros.
581 if (!Options->UnsafeFPMath) return 0;
583 // fold (fneg (fsub A, B)) -> (fsub B, A)
588 if (Options->HonorSignDependentRoundingFPMath()) return 0;
590 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
591 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
595 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
601 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
606 /// If isNegatibleForFree returns true, return the newly negated expression.
607 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
608 bool LegalOperations, unsigned Depth = 0) {
609 const TargetOptions &Options = DAG.getTarget().Options;
610 // fneg is removable even if it has multiple uses.
611 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
613 // Don't allow anything with multiple uses.
614 assert(Op.hasOneUse() && "Unknown reuse!");
616 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
617 switch (Op.getOpcode()) {
618 default: llvm_unreachable("Unknown code");
619 case ISD::ConstantFP: {
620 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
622 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
625 // FIXME: determine better conditions for this xform.
626 assert(Options.UnsafeFPMath);
628 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
629 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
630 DAG.getTargetLoweringInfo(), &Options, Depth+1))
631 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
632 GetNegatedExpression(Op.getOperand(0), DAG,
633 LegalOperations, Depth+1),
635 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
636 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
637 GetNegatedExpression(Op.getOperand(1), DAG,
638 LegalOperations, Depth+1),
641 // We can't turn -(A-B) into B-A when we honor signed zeros.
642 assert(Options.UnsafeFPMath);
644 // fold (fneg (fsub 0, B)) -> B
645 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
647 return Op.getOperand(1);
649 // fold (fneg (fsub A, B)) -> (fsub B, A)
650 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
651 Op.getOperand(1), Op.getOperand(0));
655 assert(!Options.HonorSignDependentRoundingFPMath());
657 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
658 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
659 DAG.getTargetLoweringInfo(), &Options, Depth+1))
660 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
661 GetNegatedExpression(Op.getOperand(0), DAG,
662 LegalOperations, Depth+1),
665 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
666 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
668 GetNegatedExpression(Op.getOperand(1), DAG,
669 LegalOperations, Depth+1));
673 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
674 GetNegatedExpression(Op.getOperand(0), DAG,
675 LegalOperations, Depth+1));
677 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(0), DAG,
679 LegalOperations, Depth+1),
684 // Return true if this node is a setcc, or is a select_cc
685 // that selects between the target values used for true and false, making it
686 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
687 // the appropriate nodes based on the type of node we are checking. This
688 // simplifies life a bit for the callers.
689 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
691 if (N.getOpcode() == ISD::SETCC) {
692 LHS = N.getOperand(0);
693 RHS = N.getOperand(1);
694 CC = N.getOperand(2);
698 if (N.getOpcode() != ISD::SELECT_CC ||
699 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
700 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
703 if (TLI.getBooleanContents(N.getValueType()) ==
704 TargetLowering::UndefinedBooleanContent)
707 LHS = N.getOperand(0);
708 RHS = N.getOperand(1);
709 CC = N.getOperand(4);
713 /// Return true if this is a SetCC-equivalent operation with only one use.
714 /// If this is true, it allows the users to invert the operation for free when
715 /// it is profitable to do so.
716 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
718 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
723 /// Returns true if N is a BUILD_VECTOR node whose
724 /// elements are all the same constant or undefined.
725 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
726 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
731 unsigned SplatBitSize;
733 EVT EltVT = N->getValueType(0).getVectorElementType();
734 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
736 EltVT.getSizeInBits() >= SplatBitSize);
739 // \brief Returns the SDNode if it is a constant integer BuildVector
740 // or constant integer.
741 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
742 if (isa<ConstantSDNode>(N))
744 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
749 // \brief Returns the SDNode if it is a constant float BuildVector
750 // or constant float.
751 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
752 if (isa<ConstantFPSDNode>(N))
754 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
759 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
761 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
762 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
765 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
766 BitVector UndefElements;
767 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
769 // BuildVectors can truncate their operands. Ignore that case here.
770 // FIXME: We blindly ignore splats which include undef which is overly
772 if (CN && UndefElements.none() &&
773 CN->getValueType(0) == N.getValueType().getScalarType())
780 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
782 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
783 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
786 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
787 BitVector UndefElements;
788 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
790 if (CN && UndefElements.none())
797 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
798 SDValue N0, SDValue N1) {
799 EVT VT = N0.getValueType();
800 if (N0.getOpcode() == Opc) {
801 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
802 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
803 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
804 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
805 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
808 if (N0.hasOneUse()) {
809 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
811 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
812 if (!OpNode.getNode())
814 AddToWorklist(OpNode.getNode());
815 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
820 if (N1.getOpcode() == Opc) {
821 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
822 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
823 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
824 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
825 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
828 if (N1.hasOneUse()) {
829 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
831 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
832 if (!OpNode.getNode())
834 AddToWorklist(OpNode.getNode());
835 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
843 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
845 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
847 DEBUG(dbgs() << "\nReplacing.1 ";
849 dbgs() << "\nWith: ";
850 To[0].getNode()->dump(&DAG);
851 dbgs() << " and " << NumTo-1 << " other values\n");
852 for (unsigned i = 0, e = NumTo; i != e; ++i)
853 assert((!To[i].getNode() ||
854 N->getValueType(i) == To[i].getValueType()) &&
855 "Cannot combine value to value of different type!");
857 WorklistRemover DeadNodes(*this);
858 DAG.ReplaceAllUsesWith(N, To);
860 // Push the new nodes and any users onto the worklist
861 for (unsigned i = 0, e = NumTo; i != e; ++i) {
862 if (To[i].getNode()) {
863 AddToWorklist(To[i].getNode());
864 AddUsersToWorklist(To[i].getNode());
869 // Finally, if the node is now dead, remove it from the graph. The node
870 // may not be dead if the replacement process recursively simplified to
871 // something else needing this node.
873 deleteAndRecombine(N);
874 return SDValue(N, 0);
878 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
879 // Replace all uses. If any nodes become isomorphic to other nodes and
880 // are deleted, make sure to remove them from our worklist.
881 WorklistRemover DeadNodes(*this);
882 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
884 // Push the new node and any (possibly new) users onto the worklist.
885 AddToWorklist(TLO.New.getNode());
886 AddUsersToWorklist(TLO.New.getNode());
888 // Finally, if the node is now dead, remove it from the graph. The node
889 // may not be dead if the replacement process recursively simplified to
890 // something else needing this node.
891 if (TLO.Old.getNode()->use_empty())
892 deleteAndRecombine(TLO.Old.getNode());
895 /// Check the specified integer node value to see if it can be simplified or if
896 /// things it uses can be simplified by bit propagation. If so, return true.
897 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
898 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
899 APInt KnownZero, KnownOne;
900 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
904 AddToWorklist(Op.getNode());
906 // Replace the old value with the new one.
908 DEBUG(dbgs() << "\nReplacing.2 ";
909 TLO.Old.getNode()->dump(&DAG);
910 dbgs() << "\nWith: ";
911 TLO.New.getNode()->dump(&DAG);
914 CommitTargetLoweringOpt(TLO);
918 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
920 EVT VT = Load->getValueType(0);
921 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
923 DEBUG(dbgs() << "\nReplacing.9 ";
925 dbgs() << "\nWith: ";
926 Trunc.getNode()->dump(&DAG);
928 WorklistRemover DeadNodes(*this);
929 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
930 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
931 deleteAndRecombine(Load);
932 AddToWorklist(Trunc.getNode());
935 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
938 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
939 EVT MemVT = LD->getMemoryVT();
940 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
941 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
943 : LD->getExtensionType();
945 return DAG.getExtLoad(ExtType, dl, PVT,
946 LD->getChain(), LD->getBasePtr(),
947 MemVT, LD->getMemOperand());
950 unsigned Opc = Op.getOpcode();
953 case ISD::AssertSext:
954 return DAG.getNode(ISD::AssertSext, dl, PVT,
955 SExtPromoteOperand(Op.getOperand(0), PVT),
957 case ISD::AssertZext:
958 return DAG.getNode(ISD::AssertZext, dl, PVT,
959 ZExtPromoteOperand(Op.getOperand(0), PVT),
961 case ISD::Constant: {
963 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
964 return DAG.getNode(ExtOpc, dl, PVT, Op);
968 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
970 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
973 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
974 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
976 EVT OldVT = Op.getValueType();
978 bool Replace = false;
979 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
980 if (!NewOp.getNode())
982 AddToWorklist(NewOp.getNode());
985 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
986 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
987 DAG.getValueType(OldVT));
990 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
991 EVT OldVT = Op.getValueType();
993 bool Replace = false;
994 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
995 if (!NewOp.getNode())
997 AddToWorklist(NewOp.getNode());
1000 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1001 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1004 /// Promote the specified integer binary operation if the target indicates it is
1005 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1006 /// i32 since i16 instructions are longer.
1007 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1008 if (!LegalOperations)
1011 EVT VT = Op.getValueType();
1012 if (VT.isVector() || !VT.isInteger())
1015 // If operation type is 'undesirable', e.g. i16 on x86, consider
1017 unsigned Opc = Op.getOpcode();
1018 if (TLI.isTypeDesirableForOp(Opc, VT))
1022 // Consult target whether it is a good idea to promote this operation and
1023 // what's the right type to promote it to.
1024 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1025 assert(PVT != VT && "Don't know what type to promote to!");
1027 bool Replace0 = false;
1028 SDValue N0 = Op.getOperand(0);
1029 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1033 bool Replace1 = false;
1034 SDValue N1 = Op.getOperand(1);
1039 NN1 = PromoteOperand(N1, PVT, Replace1);
1044 AddToWorklist(NN0.getNode());
1046 AddToWorklist(NN1.getNode());
1049 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1051 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1053 DEBUG(dbgs() << "\nPromoting ";
1054 Op.getNode()->dump(&DAG));
1056 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1057 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1062 /// Promote the specified integer shift operation if the target indicates it is
1063 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1064 /// i32 since i16 instructions are longer.
1065 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1066 if (!LegalOperations)
1069 EVT VT = Op.getValueType();
1070 if (VT.isVector() || !VT.isInteger())
1073 // If operation type is 'undesirable', e.g. i16 on x86, consider
1075 unsigned Opc = Op.getOpcode();
1076 if (TLI.isTypeDesirableForOp(Opc, VT))
1080 // Consult target whether it is a good idea to promote this operation and
1081 // what's the right type to promote it to.
1082 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1083 assert(PVT != VT && "Don't know what type to promote to!");
1085 bool Replace = false;
1086 SDValue N0 = Op.getOperand(0);
1087 if (Opc == ISD::SRA)
1088 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1089 else if (Opc == ISD::SRL)
1090 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1092 N0 = PromoteOperand(N0, PVT, Replace);
1096 AddToWorklist(N0.getNode());
1098 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1100 DEBUG(dbgs() << "\nPromoting ";
1101 Op.getNode()->dump(&DAG));
1103 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1104 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1109 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1110 if (!LegalOperations)
1113 EVT VT = Op.getValueType();
1114 if (VT.isVector() || !VT.isInteger())
1117 // If operation type is 'undesirable', e.g. i16 on x86, consider
1119 unsigned Opc = Op.getOpcode();
1120 if (TLI.isTypeDesirableForOp(Opc, VT))
1124 // Consult target whether it is a good idea to promote this operation and
1125 // what's the right type to promote it to.
1126 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1127 assert(PVT != VT && "Don't know what type to promote to!");
1128 // fold (aext (aext x)) -> (aext x)
1129 // fold (aext (zext x)) -> (zext x)
1130 // fold (aext (sext x)) -> (sext x)
1131 DEBUG(dbgs() << "\nPromoting ";
1132 Op.getNode()->dump(&DAG));
1133 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1138 bool DAGCombiner::PromoteLoad(SDValue Op) {
1139 if (!LegalOperations)
1142 EVT VT = Op.getValueType();
1143 if (VT.isVector() || !VT.isInteger())
1146 // If operation type is 'undesirable', e.g. i16 on x86, consider
1148 unsigned Opc = Op.getOpcode();
1149 if (TLI.isTypeDesirableForOp(Opc, VT))
1153 // Consult target whether it is a good idea to promote this operation and
1154 // what's the right type to promote it to.
1155 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1156 assert(PVT != VT && "Don't know what type to promote to!");
1159 SDNode *N = Op.getNode();
1160 LoadSDNode *LD = cast<LoadSDNode>(N);
1161 EVT MemVT = LD->getMemoryVT();
1162 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1163 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1165 : LD->getExtensionType();
1166 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1167 LD->getChain(), LD->getBasePtr(),
1168 MemVT, LD->getMemOperand());
1169 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1171 DEBUG(dbgs() << "\nPromoting ";
1174 Result.getNode()->dump(&DAG);
1176 WorklistRemover DeadNodes(*this);
1177 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1178 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1179 deleteAndRecombine(N);
1180 AddToWorklist(Result.getNode());
1186 /// \brief Recursively delete a node which has no uses and any operands for
1187 /// which it is the only use.
1189 /// Note that this both deletes the nodes and removes them from the worklist.
1190 /// It also adds any nodes who have had a user deleted to the worklist as they
1191 /// may now have only one use and subject to other combines.
1192 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1193 if (!N->use_empty())
1196 SmallSetVector<SDNode *, 16> Nodes;
1199 N = Nodes.pop_back_val();
1203 if (N->use_empty()) {
1204 for (const SDValue &ChildN : N->op_values())
1205 Nodes.insert(ChildN.getNode());
1207 removeFromWorklist(N);
1212 } while (!Nodes.empty());
1216 //===----------------------------------------------------------------------===//
1217 // Main DAG Combiner implementation
1218 //===----------------------------------------------------------------------===//
1220 void DAGCombiner::Run(CombineLevel AtLevel) {
1221 // set the instance variables, so that the various visit routines may use it.
1223 LegalOperations = Level >= AfterLegalizeVectorOps;
1224 LegalTypes = Level >= AfterLegalizeTypes;
1226 // Add all the dag nodes to the worklist.
1227 for (SDNode &Node : DAG.allnodes())
1228 AddToWorklist(&Node);
1230 // Create a dummy node (which is not added to allnodes), that adds a reference
1231 // to the root node, preventing it from being deleted, and tracking any
1232 // changes of the root.
1233 HandleSDNode Dummy(DAG.getRoot());
1235 // while the worklist isn't empty, find a node and
1236 // try and combine it.
1237 while (!WorklistMap.empty()) {
1239 // The Worklist holds the SDNodes in order, but it may contain null entries.
1241 N = Worklist.pop_back_val();
1244 bool GoodWorklistEntry = WorklistMap.erase(N);
1245 (void)GoodWorklistEntry;
1246 assert(GoodWorklistEntry &&
1247 "Found a worklist entry without a corresponding map entry!");
1249 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1250 // N is deleted from the DAG, since they too may now be dead or may have a
1251 // reduced number of uses, allowing other xforms.
1252 if (recursivelyDeleteUnusedNodes(N))
1255 WorklistRemover DeadNodes(*this);
1257 // If this combine is running after legalizing the DAG, re-legalize any
1258 // nodes pulled off the worklist.
1259 if (Level == AfterLegalizeDAG) {
1260 SmallSetVector<SDNode *, 16> UpdatedNodes;
1261 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1263 for (SDNode *LN : UpdatedNodes) {
1265 AddUsersToWorklist(LN);
1271 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1273 // Add any operands of the new node which have not yet been combined to the
1274 // worklist as well. Because the worklist uniques things already, this
1275 // won't repeatedly process the same operand.
1276 CombinedNodes.insert(N);
1277 for (const SDValue &ChildN : N->op_values())
1278 if (!CombinedNodes.count(ChildN.getNode()))
1279 AddToWorklist(ChildN.getNode());
1281 SDValue RV = combine(N);
1288 // If we get back the same node we passed in, rather than a new node or
1289 // zero, we know that the node must have defined multiple values and
1290 // CombineTo was used. Since CombineTo takes care of the worklist
1291 // mechanics for us, we have no work to do in this case.
1292 if (RV.getNode() == N)
1295 assert(N->getOpcode() != ISD::DELETED_NODE &&
1296 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1297 "Node was deleted but visit returned new node!");
1299 DEBUG(dbgs() << " ... into: ";
1300 RV.getNode()->dump(&DAG));
1302 // Transfer debug value.
1303 DAG.TransferDbgValues(SDValue(N, 0), RV);
1304 if (N->getNumValues() == RV.getNode()->getNumValues())
1305 DAG.ReplaceAllUsesWith(N, RV.getNode());
1307 assert(N->getValueType(0) == RV.getValueType() &&
1308 N->getNumValues() == 1 && "Type mismatch");
1310 DAG.ReplaceAllUsesWith(N, &OpV);
1313 // Push the new node and any users onto the worklist
1314 AddToWorklist(RV.getNode());
1315 AddUsersToWorklist(RV.getNode());
1317 // Finally, if the node is now dead, remove it from the graph. The node
1318 // may not be dead if the replacement process recursively simplified to
1319 // something else needing this node. This will also take care of adding any
1320 // operands which have lost a user to the worklist.
1321 recursivelyDeleteUnusedNodes(N);
1324 // If the root changed (e.g. it was a dead load, update the root).
1325 DAG.setRoot(Dummy.getValue());
1326 DAG.RemoveDeadNodes();
1329 SDValue DAGCombiner::visit(SDNode *N) {
1330 switch (N->getOpcode()) {
1332 case ISD::TokenFactor: return visitTokenFactor(N);
1333 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1334 case ISD::ADD: return visitADD(N);
1335 case ISD::SUB: return visitSUB(N);
1336 case ISD::ADDC: return visitADDC(N);
1337 case ISD::SUBC: return visitSUBC(N);
1338 case ISD::ADDE: return visitADDE(N);
1339 case ISD::SUBE: return visitSUBE(N);
1340 case ISD::MUL: return visitMUL(N);
1341 case ISD::SDIV: return visitSDIV(N);
1342 case ISD::UDIV: return visitUDIV(N);
1343 case ISD::SREM: return visitSREM(N);
1344 case ISD::UREM: return visitUREM(N);
1345 case ISD::MULHU: return visitMULHU(N);
1346 case ISD::MULHS: return visitMULHS(N);
1347 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1348 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1349 case ISD::SMULO: return visitSMULO(N);
1350 case ISD::UMULO: return visitUMULO(N);
1351 case ISD::SDIVREM: return visitSDIVREM(N);
1352 case ISD::UDIVREM: return visitUDIVREM(N);
1356 case ISD::UMAX: return visitIMINMAX(N);
1357 case ISD::AND: return visitAND(N);
1358 case ISD::OR: return visitOR(N);
1359 case ISD::XOR: return visitXOR(N);
1360 case ISD::SHL: return visitSHL(N);
1361 case ISD::SRA: return visitSRA(N);
1362 case ISD::SRL: return visitSRL(N);
1364 case ISD::ROTL: return visitRotate(N);
1365 case ISD::BSWAP: return visitBSWAP(N);
1366 case ISD::CTLZ: return visitCTLZ(N);
1367 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1368 case ISD::CTTZ: return visitCTTZ(N);
1369 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1370 case ISD::CTPOP: return visitCTPOP(N);
1371 case ISD::SELECT: return visitSELECT(N);
1372 case ISD::VSELECT: return visitVSELECT(N);
1373 case ISD::SELECT_CC: return visitSELECT_CC(N);
1374 case ISD::SETCC: return visitSETCC(N);
1375 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1376 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1377 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1378 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1379 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1380 case ISD::TRUNCATE: return visitTRUNCATE(N);
1381 case ISD::BITCAST: return visitBITCAST(N);
1382 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1383 case ISD::FADD: return visitFADD(N);
1384 case ISD::FSUB: return visitFSUB(N);
1385 case ISD::FMUL: return visitFMUL(N);
1386 case ISD::FMA: return visitFMA(N);
1387 case ISD::FDIV: return visitFDIV(N);
1388 case ISD::FREM: return visitFREM(N);
1389 case ISD::FSQRT: return visitFSQRT(N);
1390 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1391 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1392 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1393 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1394 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1395 case ISD::FP_ROUND: return visitFP_ROUND(N);
1396 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1397 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1398 case ISD::FNEG: return visitFNEG(N);
1399 case ISD::FABS: return visitFABS(N);
1400 case ISD::FFLOOR: return visitFFLOOR(N);
1401 case ISD::FMINNUM: return visitFMINNUM(N);
1402 case ISD::FMAXNUM: return visitFMAXNUM(N);
1403 case ISD::FCEIL: return visitFCEIL(N);
1404 case ISD::FTRUNC: return visitFTRUNC(N);
1405 case ISD::BRCOND: return visitBRCOND(N);
1406 case ISD::BR_CC: return visitBR_CC(N);
1407 case ISD::LOAD: return visitLOAD(N);
1408 case ISD::STORE: return visitSTORE(N);
1409 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1410 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1411 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1412 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1413 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1414 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1415 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1416 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1417 case ISD::MGATHER: return visitMGATHER(N);
1418 case ISD::MLOAD: return visitMLOAD(N);
1419 case ISD::MSCATTER: return visitMSCATTER(N);
1420 case ISD::MSTORE: return visitMSTORE(N);
1421 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1422 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1427 SDValue DAGCombiner::combine(SDNode *N) {
1428 SDValue RV = visit(N);
1430 // If nothing happened, try a target-specific DAG combine.
1431 if (!RV.getNode()) {
1432 assert(N->getOpcode() != ISD::DELETED_NODE &&
1433 "Node was deleted but visit returned NULL!");
1435 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1436 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1438 // Expose the DAG combiner to the target combiner impls.
1439 TargetLowering::DAGCombinerInfo
1440 DagCombineInfo(DAG, Level, false, this);
1442 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1446 // If nothing happened still, try promoting the operation.
1447 if (!RV.getNode()) {
1448 switch (N->getOpcode()) {
1456 RV = PromoteIntBinOp(SDValue(N, 0));
1461 RV = PromoteIntShiftOp(SDValue(N, 0));
1463 case ISD::SIGN_EXTEND:
1464 case ISD::ZERO_EXTEND:
1465 case ISD::ANY_EXTEND:
1466 RV = PromoteExtend(SDValue(N, 0));
1469 if (PromoteLoad(SDValue(N, 0)))
1475 // If N is a commutative binary node, try commuting it to enable more
1477 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1478 N->getNumValues() == 1) {
1479 SDValue N0 = N->getOperand(0);
1480 SDValue N1 = N->getOperand(1);
1482 // Constant operands are canonicalized to RHS.
1483 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1484 SDValue Ops[] = {N1, N0};
1486 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1487 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1490 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1493 return SDValue(CSENode, 0);
1500 /// Given a node, return its input chain if it has one, otherwise return a null
1502 static SDValue getInputChainForNode(SDNode *N) {
1503 if (unsigned NumOps = N->getNumOperands()) {
1504 if (N->getOperand(0).getValueType() == MVT::Other)
1505 return N->getOperand(0);
1506 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1507 return N->getOperand(NumOps-1);
1508 for (unsigned i = 1; i < NumOps-1; ++i)
1509 if (N->getOperand(i).getValueType() == MVT::Other)
1510 return N->getOperand(i);
1515 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1516 // If N has two operands, where one has an input chain equal to the other,
1517 // the 'other' chain is redundant.
1518 if (N->getNumOperands() == 2) {
1519 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1520 return N->getOperand(0);
1521 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1522 return N->getOperand(1);
1525 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1526 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1527 SmallPtrSet<SDNode*, 16> SeenOps;
1528 bool Changed = false; // If we should replace this token factor.
1530 // Start out with this token factor.
1533 // Iterate through token factors. The TFs grows when new token factors are
1535 for (unsigned i = 0; i < TFs.size(); ++i) {
1536 SDNode *TF = TFs[i];
1538 // Check each of the operands.
1539 for (const SDValue &Op : TF->op_values()) {
1541 switch (Op.getOpcode()) {
1542 case ISD::EntryToken:
1543 // Entry tokens don't need to be added to the list. They are
1548 case ISD::TokenFactor:
1549 if (Op.hasOneUse() &&
1550 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1551 // Queue up for processing.
1552 TFs.push_back(Op.getNode());
1553 // Clean up in case the token factor is removed.
1554 AddToWorklist(Op.getNode());
1561 // Only add if it isn't already in the list.
1562 if (SeenOps.insert(Op.getNode()).second)
1573 // If we've changed things around then replace token factor.
1576 // The entry token is the only possible outcome.
1577 Result = DAG.getEntryNode();
1579 // New and improved token factor.
1580 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1583 // Add users to worklist if AA is enabled, since it may introduce
1584 // a lot of new chained token factors while removing memory deps.
1585 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1586 : DAG.getSubtarget().useAA();
1587 return CombineTo(N, Result, UseAA /*add to worklist*/);
1593 /// MERGE_VALUES can always be eliminated.
1594 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1595 WorklistRemover DeadNodes(*this);
1596 // Replacing results may cause a different MERGE_VALUES to suddenly
1597 // be CSE'd with N, and carry its uses with it. Iterate until no
1598 // uses remain, to ensure that the node can be safely deleted.
1599 // First add the users of this node to the work list so that they
1600 // can be tried again once they have new operands.
1601 AddUsersToWorklist(N);
1603 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1604 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1605 } while (!N->use_empty());
1606 deleteAndRecombine(N);
1607 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1610 static bool isNullConstant(SDValue V) {
1611 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1612 return Const != nullptr && Const->isNullValue();
1615 static bool isNullFPConstant(SDValue V) {
1616 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1617 return Const != nullptr && Const->isZero() && !Const->isNegative();
1620 static bool isAllOnesConstant(SDValue V) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622 return Const != nullptr && Const->isAllOnesValue();
1625 static bool isOneConstant(SDValue V) {
1626 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1627 return Const != nullptr && Const->isOne();
1630 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1631 /// ContantSDNode pointer else nullptr.
1632 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1633 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1634 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1637 SDValue DAGCombiner::visitADD(SDNode *N) {
1638 SDValue N0 = N->getOperand(0);
1639 SDValue N1 = N->getOperand(1);
1640 EVT VT = N0.getValueType();
1643 if (VT.isVector()) {
1644 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1647 // fold (add x, 0) -> x, vector edition
1648 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1650 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1654 // fold (add x, undef) -> undef
1655 if (N0.getOpcode() == ISD::UNDEF)
1657 if (N1.getOpcode() == ISD::UNDEF)
1659 // fold (add c1, c2) -> c1+c2
1660 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1661 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1663 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1664 // canonicalize constant to RHS
1665 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1666 !isConstantIntBuildVectorOrConstantInt(N1))
1667 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1668 // fold (add x, 0) -> x
1669 if (isNullConstant(N1))
1671 // fold (add Sym, c) -> Sym+c
1672 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1673 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1674 GA->getOpcode() == ISD::GlobalAddress)
1675 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1677 (uint64_t)N1C->getSExtValue());
1678 // fold ((c1-A)+c2) -> (c1+c2)-A
1679 if (N1C && N0.getOpcode() == ISD::SUB)
1680 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1682 return DAG.getNode(ISD::SUB, DL, VT,
1683 DAG.getConstant(N1C->getAPIntValue()+
1684 N0C->getAPIntValue(), DL, VT),
1688 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1690 // fold ((0-A) + B) -> B-A
1691 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1693 // fold (A + (0-B)) -> A-B
1694 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1696 // fold (A+(B-A)) -> B
1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1698 return N1.getOperand(0);
1699 // fold ((B-A)+A) -> B
1700 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1701 return N0.getOperand(0);
1702 // fold (A+(B-(A+C))) to (B-C)
1703 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1704 N0 == N1.getOperand(1).getOperand(0))
1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1706 N1.getOperand(1).getOperand(1));
1707 // fold (A+(B-(C+A))) to (B-C)
1708 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1709 N0 == N1.getOperand(1).getOperand(1))
1710 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1711 N1.getOperand(1).getOperand(0));
1712 // fold (A+((B-A)+or-C)) to (B+or-C)
1713 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1714 N1.getOperand(0).getOpcode() == ISD::SUB &&
1715 N0 == N1.getOperand(0).getOperand(1))
1716 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1717 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1719 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1720 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1721 SDValue N00 = N0.getOperand(0);
1722 SDValue N01 = N0.getOperand(1);
1723 SDValue N10 = N1.getOperand(0);
1724 SDValue N11 = N1.getOperand(1);
1726 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1727 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1728 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1729 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1733 return SDValue(N, 0);
1735 // fold (a+b) -> (a|b) iff a and b share no bits.
1736 if (VT.isInteger() && !VT.isVector()) {
1737 APInt LHSZero, LHSOne;
1738 APInt RHSZero, RHSOne;
1739 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1741 if (LHSZero.getBoolValue()) {
1742 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1744 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1747 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1748 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1753 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1754 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1755 isNullConstant(N1.getOperand(0).getOperand(0)))
1756 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1757 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1758 N1.getOperand(0).getOperand(1),
1760 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1761 isNullConstant(N0.getOperand(0).getOperand(0)))
1762 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1763 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1764 N0.getOperand(0).getOperand(1),
1767 if (N1.getOpcode() == ISD::AND) {
1768 SDValue AndOp0 = N1.getOperand(0);
1769 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1770 unsigned DestBits = VT.getScalarType().getSizeInBits();
1772 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1773 // and similar xforms where the inner op is either ~0 or 0.
1774 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1776 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1780 // add (sext i1), X -> sub X, (zext i1)
1781 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1782 N0.getOperand(0).getValueType() == MVT::i1 &&
1783 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1785 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1786 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1789 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1790 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1791 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1792 if (TN->getVT() == MVT::i1) {
1794 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1795 DAG.getConstant(1, DL, VT));
1796 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1803 SDValue DAGCombiner::visitADDC(SDNode *N) {
1804 SDValue N0 = N->getOperand(0);
1805 SDValue N1 = N->getOperand(1);
1806 EVT VT = N0.getValueType();
1808 // If the flag result is dead, turn this into an ADD.
1809 if (!N->hasAnyUseOfValue(1))
1810 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1811 DAG.getNode(ISD::CARRY_FALSE,
1812 SDLoc(N), MVT::Glue));
1814 // canonicalize constant to RHS.
1815 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1816 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1820 // fold (addc x, 0) -> x + no carry out
1821 if (isNullConstant(N1))
1822 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1823 SDLoc(N), MVT::Glue));
1825 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1826 APInt LHSZero, LHSOne;
1827 APInt RHSZero, RHSOne;
1828 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1830 if (LHSZero.getBoolValue()) {
1831 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1833 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1834 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1835 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1836 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1837 DAG.getNode(ISD::CARRY_FALSE,
1838 SDLoc(N), MVT::Glue));
1844 SDValue DAGCombiner::visitADDE(SDNode *N) {
1845 SDValue N0 = N->getOperand(0);
1846 SDValue N1 = N->getOperand(1);
1847 SDValue CarryIn = N->getOperand(2);
1849 // canonicalize constant to RHS
1850 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1851 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1853 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1856 // fold (adde x, y, false) -> (addc x, y)
1857 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1863 // Since it may not be valid to emit a fold to zero for vector initializers
1864 // check if we can before folding.
1865 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1867 bool LegalOperations, bool LegalTypes) {
1869 return DAG.getConstant(0, DL, VT);
1870 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1871 return DAG.getConstant(0, DL, VT);
1875 SDValue DAGCombiner::visitSUB(SDNode *N) {
1876 SDValue N0 = N->getOperand(0);
1877 SDValue N1 = N->getOperand(1);
1878 EVT VT = N0.getValueType();
1881 if (VT.isVector()) {
1882 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1885 // fold (sub x, 0) -> x, vector edition
1886 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1890 // fold (sub x, x) -> 0
1891 // FIXME: Refactor this and xor and other similar operations together.
1893 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1894 // fold (sub c1, c2) -> c1-c2
1895 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1896 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1898 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1899 // fold (sub x, c) -> (add x, -c)
1902 return DAG.getNode(ISD::ADD, DL, VT, N0,
1903 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1905 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1906 if (isAllOnesConstant(N0))
1907 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1908 // fold A-(A-B) -> B
1909 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1910 return N1.getOperand(1);
1911 // fold (A+B)-A -> B
1912 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1913 return N0.getOperand(1);
1914 // fold (A+B)-B -> A
1915 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1916 return N0.getOperand(0);
1917 // fold C2-(A+C1) -> (C2-C1)-A
1918 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1919 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1920 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1922 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1924 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1927 // fold ((A+(B+or-C))-B) -> A+or-C
1928 if (N0.getOpcode() == ISD::ADD &&
1929 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1930 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1931 N0.getOperand(1).getOperand(0) == N1)
1932 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1933 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1934 // fold ((A+(C+B))-B) -> A+C
1935 if (N0.getOpcode() == ISD::ADD &&
1936 N0.getOperand(1).getOpcode() == ISD::ADD &&
1937 N0.getOperand(1).getOperand(1) == N1)
1938 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1939 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1940 // fold ((A-(B-C))-C) -> A-B
1941 if (N0.getOpcode() == ISD::SUB &&
1942 N0.getOperand(1).getOpcode() == ISD::SUB &&
1943 N0.getOperand(1).getOperand(1) == N1)
1944 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1945 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1947 // If either operand of a sub is undef, the result is undef
1948 if (N0.getOpcode() == ISD::UNDEF)
1950 if (N1.getOpcode() == ISD::UNDEF)
1953 // If the relocation model supports it, consider symbol offsets.
1954 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1955 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1956 // fold (sub Sym, c) -> Sym-c
1957 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1958 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1960 (uint64_t)N1C->getSExtValue());
1961 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1962 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1963 if (GA->getGlobal() == GB->getGlobal())
1964 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1968 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1969 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1970 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1971 if (TN->getVT() == MVT::i1) {
1973 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1974 DAG.getConstant(1, DL, VT));
1975 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1982 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1983 SDValue N0 = N->getOperand(0);
1984 SDValue N1 = N->getOperand(1);
1985 EVT VT = N0.getValueType();
1987 // If the flag result is dead, turn this into an SUB.
1988 if (!N->hasAnyUseOfValue(1))
1989 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1990 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1993 // fold (subc x, x) -> 0 + no borrow
1996 return CombineTo(N, DAG.getConstant(0, DL, VT),
1997 DAG.getNode(ISD::CARRY_FALSE, DL,
2001 // fold (subc x, 0) -> x + no borrow
2002 if (isNullConstant(N1))
2003 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2006 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2007 if (isAllOnesConstant(N0))
2008 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
2009 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2015 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2016 SDValue N0 = N->getOperand(0);
2017 SDValue N1 = N->getOperand(1);
2018 SDValue CarryIn = N->getOperand(2);
2020 // fold (sube x, y, false) -> (subc x, y)
2021 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2022 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2027 SDValue DAGCombiner::visitMUL(SDNode *N) {
2028 SDValue N0 = N->getOperand(0);
2029 SDValue N1 = N->getOperand(1);
2030 EVT VT = N0.getValueType();
2032 // fold (mul x, undef) -> 0
2033 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, SDLoc(N), VT);
2036 bool N0IsConst = false;
2037 bool N1IsConst = false;
2038 bool N1IsOpaqueConst = false;
2039 bool N0IsOpaqueConst = false;
2040 APInt ConstValue0, ConstValue1;
2042 if (VT.isVector()) {
2043 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2046 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2047 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2049 N0IsConst = isa<ConstantSDNode>(N0);
2051 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2052 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2054 N1IsConst = isa<ConstantSDNode>(N1);
2056 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2057 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2061 // fold (mul c1, c2) -> c1*c2
2062 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2063 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2064 N0.getNode(), N1.getNode());
2066 // canonicalize constant to RHS (vector doesn't have to splat)
2067 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2068 !isConstantIntBuildVectorOrConstantInt(N1))
2069 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2070 // fold (mul x, 0) -> 0
2071 if (N1IsConst && ConstValue1 == 0)
2073 // We require a splat of the entire scalar bit width for non-contiguous
2076 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2077 // fold (mul x, 1) -> x
2078 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2080 // fold (mul x, -1) -> 0-x
2081 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2083 return DAG.getNode(ISD::SUB, DL, VT,
2084 DAG.getConstant(0, DL, VT), N0);
2086 // fold (mul x, (1 << c)) -> x << c
2087 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2090 return DAG.getNode(ISD::SHL, DL, VT, N0,
2091 DAG.getConstant(ConstValue1.logBase2(), DL,
2092 getShiftAmountTy(N0.getValueType())));
2094 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2095 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2097 unsigned Log2Val = (-ConstValue1).logBase2();
2099 // FIXME: If the input is something that is easily negated (e.g. a
2100 // single-use add), we should put the negate there.
2101 return DAG.getNode(ISD::SUB, DL, VT,
2102 DAG.getConstant(0, DL, VT),
2103 DAG.getNode(ISD::SHL, DL, VT, N0,
2104 DAG.getConstant(Log2Val, DL,
2105 getShiftAmountTy(N0.getValueType()))));
2109 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2110 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2111 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2112 isa<ConstantSDNode>(N0.getOperand(1)))) {
2113 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2114 N1, N0.getOperand(1));
2115 AddToWorklist(C3.getNode());
2116 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2117 N0.getOperand(0), C3);
2120 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2123 SDValue Sh(nullptr,0), Y(nullptr,0);
2124 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2125 if (N0.getOpcode() == ISD::SHL &&
2126 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2127 isa<ConstantSDNode>(N0.getOperand(1))) &&
2128 N0.getNode()->hasOneUse()) {
2130 } else if (N1.getOpcode() == ISD::SHL &&
2131 isa<ConstantSDNode>(N1.getOperand(1)) &&
2132 N1.getNode()->hasOneUse()) {
2137 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138 Sh.getOperand(0), Y);
2139 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2140 Mul, Sh.getOperand(1));
2144 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2145 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2146 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2147 isa<ConstantSDNode>(N0.getOperand(1))))
2148 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2149 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2150 N0.getOperand(0), N1),
2151 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2152 N0.getOperand(1), N1));
2155 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2161 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2162 SDValue N0 = N->getOperand(0);
2163 SDValue N1 = N->getOperand(1);
2164 EVT VT = N->getValueType(0);
2168 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2171 // fold (sdiv c1, c2) -> c1/c2
2172 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2174 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2175 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2176 // fold (sdiv X, 1) -> X
2177 if (N1C && N1C->isOne())
2179 // fold (sdiv X, -1) -> 0-X
2180 if (N1C && N1C->isAllOnesValue()) {
2182 return DAG.getNode(ISD::SUB, DL, VT,
2183 DAG.getConstant(0, DL, VT), N0);
2185 // If we know the sign bits of both operands are zero, strength reduce to a
2186 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2187 if (!VT.isVector()) {
2188 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2189 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2193 // fold (sdiv X, pow2) -> simple ops after legalize
2194 // FIXME: We check for the exact bit here because the generic lowering gives
2195 // better results in that case. The target-specific lowering should learn how
2196 // to handle exact sdivs efficiently.
2197 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2198 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2199 (N1C->getAPIntValue().isPowerOf2() ||
2200 (-N1C->getAPIntValue()).isPowerOf2())) {
2201 // Target-specific implementation of sdiv x, pow2.
2202 if (SDValue Res = BuildSDIVPow2(N))
2205 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2208 // Splat the sign bit into the register
2210 DAG.getNode(ISD::SRA, DL, VT, N0,
2211 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2212 getShiftAmountTy(N0.getValueType())));
2213 AddToWorklist(SGN.getNode());
2215 // Add (N0 < 0) ? abs2 - 1 : 0;
2217 DAG.getNode(ISD::SRL, DL, VT, SGN,
2218 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2219 getShiftAmountTy(SGN.getValueType())));
2220 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2221 AddToWorklist(SRL.getNode());
2222 AddToWorklist(ADD.getNode()); // Divide by pow2
2223 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2224 DAG.getConstant(lg2, DL,
2225 getShiftAmountTy(ADD.getValueType())));
2227 // If we're dividing by a positive value, we're done. Otherwise, we must
2228 // negate the result.
2229 if (N1C->getAPIntValue().isNonNegative())
2232 AddToWorklist(SRA.getNode());
2233 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2236 // If integer divide is expensive and we satisfy the requirements, emit an
2237 // alternate sequence. Targets may check function attributes for size/speed
2239 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2240 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2241 if (SDValue Op = BuildSDIV(N))
2245 if (N0.getOpcode() == ISD::UNDEF)
2246 return DAG.getConstant(0, SDLoc(N), VT);
2247 // X / undef -> undef
2248 if (N1.getOpcode() == ISD::UNDEF)
2254 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2255 SDValue N0 = N->getOperand(0);
2256 SDValue N1 = N->getOperand(1);
2257 EVT VT = N->getValueType(0);
2261 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2264 // fold (udiv c1, c2) -> c1/c2
2265 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2266 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2268 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2271 // fold (udiv x, (1 << c)) -> x >>u c
2272 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2274 return DAG.getNode(ISD::SRL, DL, VT, N0,
2275 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2276 getShiftAmountTy(N0.getValueType())));
2278 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2279 if (N1.getOpcode() == ISD::SHL) {
2280 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2281 if (SHC->getAPIntValue().isPowerOf2()) {
2282 EVT ADDVT = N1.getOperand(1).getValueType();
2284 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2286 DAG.getConstant(SHC->getAPIntValue()
2289 AddToWorklist(Add.getNode());
2290 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2295 // fold (udiv x, c) -> alternate
2296 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2297 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2298 if (SDValue Op = BuildUDIV(N))
2302 if (N0.getOpcode() == ISD::UNDEF)
2303 return DAG.getConstant(0, SDLoc(N), VT);
2304 // X / undef -> undef
2305 if (N1.getOpcode() == ISD::UNDEF)
2311 SDValue DAGCombiner::visitSREM(SDNode *N) {
2312 SDValue N0 = N->getOperand(0);
2313 SDValue N1 = N->getOperand(1);
2314 EVT VT = N->getValueType(0);
2316 // fold (srem c1, c2) -> c1%c2
2317 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2318 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2320 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2323 // If we know the sign bits of both operands are zero, strength reduce to a
2324 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2325 if (!VT.isVector()) {
2326 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2327 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2330 // If X/C can be simplified by the division-by-constant logic, lower
2331 // X%C to the equivalent of X-X/C*C.
2332 if (N1C && !N1C->isNullValue()) {
2333 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2334 AddToWorklist(Div.getNode());
2335 SDValue OptimizedDiv = combine(Div.getNode());
2336 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2339 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340 AddToWorklist(Mul.getNode());
2346 if (N0.getOpcode() == ISD::UNDEF)
2347 return DAG.getConstant(0, SDLoc(N), VT);
2348 // X % undef -> undef
2349 if (N1.getOpcode() == ISD::UNDEF)
2355 SDValue DAGCombiner::visitUREM(SDNode *N) {
2356 SDValue N0 = N->getOperand(0);
2357 SDValue N1 = N->getOperand(1);
2358 EVT VT = N->getValueType(0);
2360 // fold (urem c1, c2) -> c1%c2
2361 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2364 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2367 // fold (urem x, pow2) -> (and x, pow2-1)
2368 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2369 N1C->getAPIntValue().isPowerOf2()) {
2371 return DAG.getNode(ISD::AND, DL, VT, N0,
2372 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2374 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2375 if (N1.getOpcode() == ISD::SHL) {
2376 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2377 if (SHC->getAPIntValue().isPowerOf2()) {
2380 DAG.getNode(ISD::ADD, DL, VT, N1,
2381 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2383 AddToWorklist(Add.getNode());
2384 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2389 // If X/C can be simplified by the division-by-constant logic, lower
2390 // X%C to the equivalent of X-X/C*C.
2391 if (N1C && !N1C->isNullValue()) {
2392 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2393 AddToWorklist(Div.getNode());
2394 SDValue OptimizedDiv = combine(Div.getNode());
2395 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2396 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2398 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2399 AddToWorklist(Mul.getNode());
2405 if (N0.getOpcode() == ISD::UNDEF)
2406 return DAG.getConstant(0, SDLoc(N), VT);
2407 // X % undef -> undef
2408 if (N1.getOpcode() == ISD::UNDEF)
2414 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2415 SDValue N0 = N->getOperand(0);
2416 SDValue N1 = N->getOperand(1);
2417 EVT VT = N->getValueType(0);
2420 // fold (mulhs x, 0) -> 0
2421 if (isNullConstant(N1))
2423 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2424 if (isOneConstant(N1)) {
2426 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2427 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2429 getShiftAmountTy(N0.getValueType())));
2431 // fold (mulhs x, undef) -> 0
2432 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2433 return DAG.getConstant(0, SDLoc(N), VT);
2435 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2437 if (VT.isSimple() && !VT.isVector()) {
2438 MVT Simple = VT.getSimpleVT();
2439 unsigned SimpleSize = Simple.getSizeInBits();
2440 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2441 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2442 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2443 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2444 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2445 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2446 DAG.getConstant(SimpleSize, DL,
2447 getShiftAmountTy(N1.getValueType())));
2448 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2455 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2456 SDValue N0 = N->getOperand(0);
2457 SDValue N1 = N->getOperand(1);
2458 EVT VT = N->getValueType(0);
2461 // fold (mulhu x, 0) -> 0
2462 if (isNullConstant(N1))
2464 // fold (mulhu x, 1) -> 0
2465 if (isOneConstant(N1))
2466 return DAG.getConstant(0, DL, N0.getValueType());
2467 // fold (mulhu x, undef) -> 0
2468 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2469 return DAG.getConstant(0, DL, VT);
2471 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2473 if (VT.isSimple() && !VT.isVector()) {
2474 MVT Simple = VT.getSimpleVT();
2475 unsigned SimpleSize = Simple.getSizeInBits();
2476 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2477 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2478 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2479 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2480 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2481 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2482 DAG.getConstant(SimpleSize, DL,
2483 getShiftAmountTy(N1.getValueType())));
2484 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2491 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2492 /// give the opcodes for the two computations that are being performed. Return
2493 /// true if a simplification was made.
2494 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2496 // If the high half is not needed, just compute the low half.
2497 bool HiExists = N->hasAnyUseOfValue(1);
2499 (!LegalOperations ||
2500 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2501 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2502 return CombineTo(N, Res, Res);
2505 // If the low half is not needed, just compute the high half.
2506 bool LoExists = N->hasAnyUseOfValue(0);
2508 (!LegalOperations ||
2509 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2510 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2511 return CombineTo(N, Res, Res);
2514 // If both halves are used, return as it is.
2515 if (LoExists && HiExists)
2518 // If the two computed results can be simplified separately, separate them.
2520 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2521 AddToWorklist(Lo.getNode());
2522 SDValue LoOpt = combine(Lo.getNode());
2523 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2524 (!LegalOperations ||
2525 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2526 return CombineTo(N, LoOpt, LoOpt);
2530 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2531 AddToWorklist(Hi.getNode());
2532 SDValue HiOpt = combine(Hi.getNode());
2533 if (HiOpt.getNode() && HiOpt != Hi &&
2534 (!LegalOperations ||
2535 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2536 return CombineTo(N, HiOpt, HiOpt);
2542 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2543 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2546 EVT VT = N->getValueType(0);
2549 // If the type is twice as wide is legal, transform the mulhu to a wider
2550 // multiply plus a shift.
2551 if (VT.isSimple() && !VT.isVector()) {
2552 MVT Simple = VT.getSimpleVT();
2553 unsigned SimpleSize = Simple.getSizeInBits();
2554 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2555 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2556 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2557 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2558 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2559 // Compute the high part as N1.
2560 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2561 DAG.getConstant(SimpleSize, DL,
2562 getShiftAmountTy(Lo.getValueType())));
2563 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2564 // Compute the low part as N0.
2565 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2566 return CombineTo(N, Lo, Hi);
2573 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2574 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2577 EVT VT = N->getValueType(0);
2580 // If the type is twice as wide is legal, transform the mulhu to a wider
2581 // multiply plus a shift.
2582 if (VT.isSimple() && !VT.isVector()) {
2583 MVT Simple = VT.getSimpleVT();
2584 unsigned SimpleSize = Simple.getSizeInBits();
2585 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2586 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2587 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2588 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2589 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2590 // Compute the high part as N1.
2591 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2592 DAG.getConstant(SimpleSize, DL,
2593 getShiftAmountTy(Lo.getValueType())));
2594 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2595 // Compute the low part as N0.
2596 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2597 return CombineTo(N, Lo, Hi);
2604 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2605 // (smulo x, 2) -> (saddo x, x)
2606 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2607 if (C2->getAPIntValue() == 2)
2608 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2609 N->getOperand(0), N->getOperand(0));
2614 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2615 // (umulo x, 2) -> (uaddo x, x)
2616 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2617 if (C2->getAPIntValue() == 2)
2618 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2619 N->getOperand(0), N->getOperand(0));
2624 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2631 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2632 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2638 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2639 SDValue N0 = N->getOperand(0);
2640 SDValue N1 = N->getOperand(1);
2641 EVT VT = N0.getValueType();
2645 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2648 // fold (add c1, c2) -> c1+c2
2649 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2650 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2652 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2654 // canonicalize constant to RHS
2655 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2656 !isConstantIntBuildVectorOrConstantInt(N1))
2657 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2662 /// If this is a binary operator with two operands of the same opcode, try to
2664 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2665 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2666 EVT VT = N0.getValueType();
2667 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2669 // Bail early if none of these transforms apply.
2670 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2672 // For each of OP in AND/OR/XOR:
2673 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2674 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2675 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2676 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2677 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2679 // do not sink logical op inside of a vector extend, since it may combine
2681 EVT Op0VT = N0.getOperand(0).getValueType();
2682 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2683 N0.getOpcode() == ISD::SIGN_EXTEND ||
2684 N0.getOpcode() == ISD::BSWAP ||
2685 // Avoid infinite looping with PromoteIntBinOp.
2686 (N0.getOpcode() == ISD::ANY_EXTEND &&
2687 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2688 (N0.getOpcode() == ISD::TRUNCATE &&
2689 (!TLI.isZExtFree(VT, Op0VT) ||
2690 !TLI.isTruncateFree(Op0VT, VT)) &&
2691 TLI.isTypeLegal(Op0VT))) &&
2693 Op0VT == N1.getOperand(0).getValueType() &&
2694 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2695 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2696 N0.getOperand(0).getValueType(),
2697 N0.getOperand(0), N1.getOperand(0));
2698 AddToWorklist(ORNode.getNode());
2699 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2702 // For each of OP in SHL/SRL/SRA/AND...
2703 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2704 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2705 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2706 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2707 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2708 N0.getOperand(1) == N1.getOperand(1)) {
2709 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2710 N0.getOperand(0).getValueType(),
2711 N0.getOperand(0), N1.getOperand(0));
2712 AddToWorklist(ORNode.getNode());
2713 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2714 ORNode, N0.getOperand(1));
2717 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2718 // Only perform this optimization after type legalization and before
2719 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2720 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2721 // we don't want to undo this promotion.
2722 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2724 if ((N0.getOpcode() == ISD::BITCAST ||
2725 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2726 Level == AfterLegalizeTypes) {
2727 SDValue In0 = N0.getOperand(0);
2728 SDValue In1 = N1.getOperand(0);
2729 EVT In0Ty = In0.getValueType();
2730 EVT In1Ty = In1.getValueType();
2732 // If both incoming values are integers, and the original types are the
2734 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2735 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2736 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2737 AddToWorklist(Op.getNode());
2742 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2743 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2744 // If both shuffles use the same mask, and both shuffle within a single
2745 // vector, then it is worthwhile to move the swizzle after the operation.
2746 // The type-legalizer generates this pattern when loading illegal
2747 // vector types from memory. In many cases this allows additional shuffle
2749 // There are other cases where moving the shuffle after the xor/and/or
2750 // is profitable even if shuffles don't perform a swizzle.
2751 // If both shuffles use the same mask, and both shuffles have the same first
2752 // or second operand, then it might still be profitable to move the shuffle
2753 // after the xor/and/or operation.
2754 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2755 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2756 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2758 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2759 "Inputs to shuffles are not the same type");
2761 // Check that both shuffles use the same mask. The masks are known to be of
2762 // the same length because the result vector type is the same.
2763 // Check also that shuffles have only one use to avoid introducing extra
2765 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2766 SVN0->getMask().equals(SVN1->getMask())) {
2767 SDValue ShOp = N0->getOperand(1);
2769 // Don't try to fold this node if it requires introducing a
2770 // build vector of all zeros that might be illegal at this stage.
2771 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2773 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2778 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2779 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2780 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2781 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2782 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2783 N0->getOperand(0), N1->getOperand(0));
2784 AddToWorklist(NewNode.getNode());
2785 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2786 &SVN0->getMask()[0]);
2789 // Don't try to fold this node if it requires introducing a
2790 // build vector of all zeros that might be illegal at this stage.
2791 ShOp = N0->getOperand(0);
2792 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2794 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2799 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2800 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2801 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2802 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2803 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2804 N0->getOperand(1), N1->getOperand(1));
2805 AddToWorklist(NewNode.getNode());
2806 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2807 &SVN0->getMask()[0]);
2815 /// This contains all DAGCombine rules which reduce two values combined by
2816 /// an And operation to a single value. This makes them reusable in the context
2817 /// of visitSELECT(). Rules involving constants are not included as
2818 /// visitSELECT() already handles those cases.
2819 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2820 SDNode *LocReference) {
2821 EVT VT = N1.getValueType();
2823 // fold (and x, undef) -> 0
2824 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2825 return DAG.getConstant(0, SDLoc(LocReference), VT);
2826 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2827 SDValue LL, LR, RL, RR, CC0, CC1;
2828 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2832 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833 LL.getValueType().isInteger()) {
2834 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2836 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837 LR.getValueType(), LL, RL);
2838 AddToWorklist(ORNode.getNode());
2839 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2841 if (isAllOnesConstant(LR)) {
2842 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2843 if (Op1 == ISD::SETEQ) {
2844 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2845 LR.getValueType(), LL, RL);
2846 AddToWorklist(ANDNode.getNode());
2847 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2849 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2850 if (Op1 == ISD::SETGT) {
2851 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2852 LR.getValueType(), LL, RL);
2853 AddToWorklist(ORNode.getNode());
2854 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2858 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2859 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2860 Op0 == Op1 && LL.getValueType().isInteger() &&
2861 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2862 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2864 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2865 LL, DAG.getConstant(1, DL,
2866 LL.getValueType()));
2867 AddToWorklist(ADDNode.getNode());
2868 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2869 DAG.getConstant(2, DL, LL.getValueType()),
2872 // canonicalize equivalent to ll == rl
2873 if (LL == RR && LR == RL) {
2874 Op1 = ISD::getSetCCSwappedOperands(Op1);
2877 if (LL == RL && LR == RR) {
2878 bool isInteger = LL.getValueType().isInteger();
2879 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2880 if (Result != ISD::SETCC_INVALID &&
2881 (!LegalOperations ||
2882 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2883 TLI.isOperationLegal(ISD::SETCC,
2884 getSetCCResultType(N0.getSimpleValueType())))))
2885 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2890 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2891 VT.getSizeInBits() <= 64) {
2892 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2893 APInt ADDC = ADDI->getAPIntValue();
2894 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2895 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2896 // immediate for an add, but it is legal if its top c2 bits are set,
2897 // transform the ADD so the immediate doesn't need to be materialized
2899 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2900 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2901 SRLI->getZExtValue());
2902 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2904 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2907 DAG.getNode(ISD::ADD, DL, VT,
2908 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2909 CombineTo(N0.getNode(), NewAdd);
2910 // Return N so it doesn't get rechecked!
2911 return SDValue(LocReference, 0);
2922 SDValue DAGCombiner::visitAND(SDNode *N) {
2923 SDValue N0 = N->getOperand(0);
2924 SDValue N1 = N->getOperand(1);
2925 EVT VT = N1.getValueType();
2928 if (VT.isVector()) {
2929 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2932 // fold (and x, 0) -> 0, vector edition
2933 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2934 // do not return N0, because undef node may exist in N0
2935 return DAG.getConstant(
2936 APInt::getNullValue(
2937 N0.getValueType().getScalarType().getSizeInBits()),
2938 SDLoc(N), N0.getValueType());
2939 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2940 // do not return N1, because undef node may exist in N1
2941 return DAG.getConstant(
2942 APInt::getNullValue(
2943 N1.getValueType().getScalarType().getSizeInBits()),
2944 SDLoc(N), N1.getValueType());
2946 // fold (and x, -1) -> x, vector edition
2947 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2949 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2953 // fold (and c1, c2) -> c1&c2
2954 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2955 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2956 if (N0C && N1C && !N1C->isOpaque())
2957 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2958 // canonicalize constant to RHS
2959 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2960 !isConstantIntBuildVectorOrConstantInt(N1))
2961 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2962 // fold (and x, -1) -> x
2963 if (isAllOnesConstant(N1))
2965 // if (and x, c) is known to be zero, return 0
2966 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2967 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2968 APInt::getAllOnesValue(BitWidth)))
2969 return DAG.getConstant(0, SDLoc(N), VT);
2971 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2973 // fold (and (or x, C), D) -> D if (C & D) == D
2974 if (N1C && N0.getOpcode() == ISD::OR)
2975 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2976 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2978 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2979 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2980 SDValue N0Op0 = N0.getOperand(0);
2981 APInt Mask = ~N1C->getAPIntValue();
2982 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2983 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2984 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2985 N0.getValueType(), N0Op0);
2987 // Replace uses of the AND with uses of the Zero extend node.
2990 // We actually want to replace all uses of the any_extend with the
2991 // zero_extend, to avoid duplicating things. This will later cause this
2992 // AND to be folded.
2993 CombineTo(N0.getNode(), Zext);
2994 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2997 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2998 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2999 // already be zero by virtue of the width of the base type of the load.
3001 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3003 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3004 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3005 N0.getOpcode() == ISD::LOAD) {
3006 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3007 N0 : N0.getOperand(0) );
3009 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3010 // This can be a pure constant or a vector splat, in which case we treat the
3011 // vector as a scalar and use the splat value.
3012 APInt Constant = APInt::getNullValue(1);
3013 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3014 Constant = C->getAPIntValue();
3015 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3016 APInt SplatValue, SplatUndef;
3017 unsigned SplatBitSize;
3019 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3020 SplatBitSize, HasAnyUndefs);
3022 // Undef bits can contribute to a possible optimisation if set, so
3024 SplatValue |= SplatUndef;
3026 // The splat value may be something like "0x00FFFFFF", which means 0 for
3027 // the first vector value and FF for the rest, repeating. We need a mask
3028 // that will apply equally to all members of the vector, so AND all the
3029 // lanes of the constant together.
3030 EVT VT = Vector->getValueType(0);
3031 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3033 // If the splat value has been compressed to a bitlength lower
3034 // than the size of the vector lane, we need to re-expand it to
3036 if (BitWidth > SplatBitSize)
3037 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3038 SplatBitSize < BitWidth;
3039 SplatBitSize = SplatBitSize * 2)
3040 SplatValue |= SplatValue.shl(SplatBitSize);
3042 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3043 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3044 if (SplatBitSize % BitWidth == 0) {
3045 Constant = APInt::getAllOnesValue(BitWidth);
3046 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3047 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3052 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3053 // actually legal and isn't going to get expanded, else this is a false
3055 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3056 Load->getValueType(0),
3057 Load->getMemoryVT());
3059 // Resize the constant to the same size as the original memory access before
3060 // extension. If it is still the AllOnesValue then this AND is completely
3063 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3066 switch (Load->getExtensionType()) {
3067 default: B = false; break;
3068 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3070 case ISD::NON_EXTLOAD: B = true; break;
3073 if (B && Constant.isAllOnesValue()) {
3074 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3075 // preserve semantics once we get rid of the AND.
3076 SDValue NewLoad(Load, 0);
3077 if (Load->getExtensionType() == ISD::EXTLOAD) {
3078 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3079 Load->getValueType(0), SDLoc(Load),
3080 Load->getChain(), Load->getBasePtr(),
3081 Load->getOffset(), Load->getMemoryVT(),
3082 Load->getMemOperand());
3083 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3084 if (Load->getNumValues() == 3) {
3085 // PRE/POST_INC loads have 3 values.
3086 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3087 NewLoad.getValue(2) };
3088 CombineTo(Load, To, 3, true);
3090 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3094 // Fold the AND away, taking care not to fold to the old load node if we
3096 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3098 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3102 // fold (and (load x), 255) -> (zextload x, i8)
3103 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3104 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3105 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3106 (N0.getOpcode() == ISD::ANY_EXTEND &&
3107 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3108 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3109 LoadSDNode *LN0 = HasAnyExt
3110 ? cast<LoadSDNode>(N0.getOperand(0))
3111 : cast<LoadSDNode>(N0);
3112 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3113 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3114 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3115 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3116 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3117 EVT LoadedVT = LN0->getMemoryVT();
3118 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3120 if (ExtVT == LoadedVT &&
3121 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3125 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3126 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3127 LN0->getMemOperand());
3129 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3130 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3133 // Do not change the width of a volatile load.
3134 // Do not generate loads of non-round integer types since these can
3135 // be expensive (and would be wrong if the type is not byte sized).
3136 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3137 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3139 EVT PtrType = LN0->getOperand(1).getValueType();
3141 unsigned Alignment = LN0->getAlignment();
3142 SDValue NewPtr = LN0->getBasePtr();
3144 // For big endian targets, we need to add an offset to the pointer
3145 // to load the correct bytes. For little endian systems, we merely
3146 // need to read fewer bytes from the same pointer.
3147 if (DAG.getDataLayout().isBigEndian()) {
3148 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3149 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3150 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3152 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3153 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3154 Alignment = MinAlign(Alignment, PtrOff);
3157 AddToWorklist(NewPtr.getNode());
3160 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3161 LN0->getChain(), NewPtr,
3162 LN0->getPointerInfo(),
3163 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3164 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3166 CombineTo(LN0, Load, Load.getValue(1));
3167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3173 if (SDValue Combined = visitANDLike(N0, N1, N))
3176 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3177 if (N0.getOpcode() == N1.getOpcode())
3178 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3181 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3182 // fold (and (sra)) -> (and (srl)) when possible.
3183 if (!VT.isVector() &&
3184 SimplifyDemandedBits(SDValue(N, 0)))
3185 return SDValue(N, 0);
3187 // fold (zext_inreg (extload x)) -> (zextload x)
3188 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3189 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3190 EVT MemVT = LN0->getMemoryVT();
3191 // If we zero all the possible extended bits, then we can turn this into
3192 // a zextload if we are running before legalize or the operation is legal.
3193 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3194 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3195 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3196 ((!LegalOperations && !LN0->isVolatile()) ||
3197 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3198 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3199 LN0->getChain(), LN0->getBasePtr(),
3200 MemVT, LN0->getMemOperand());
3202 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3203 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3206 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3207 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3209 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3210 EVT MemVT = LN0->getMemoryVT();
3211 // If we zero all the possible extended bits, then we can turn this into
3212 // a zextload if we are running before legalize or the operation is legal.
3213 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3214 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3215 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3216 ((!LegalOperations && !LN0->isVolatile()) ||
3217 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3218 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3219 LN0->getChain(), LN0->getBasePtr(),
3220 MemVT, LN0->getMemOperand());
3222 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3223 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3226 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3227 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3228 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3229 N0.getOperand(1), false);
3230 if (BSwap.getNode())
3237 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3238 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3239 bool DemandHighBits) {
3240 if (!LegalOperations)
3243 EVT VT = N->getValueType(0);
3244 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3246 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3249 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3250 bool LookPassAnd0 = false;
3251 bool LookPassAnd1 = false;
3252 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3254 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3256 if (N0.getOpcode() == ISD::AND) {
3257 if (!N0.getNode()->hasOneUse())
3259 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3260 if (!N01C || N01C->getZExtValue() != 0xFF00)
3262 N0 = N0.getOperand(0);
3263 LookPassAnd0 = true;
3266 if (N1.getOpcode() == ISD::AND) {
3267 if (!N1.getNode()->hasOneUse())
3269 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3270 if (!N11C || N11C->getZExtValue() != 0xFF)
3272 N1 = N1.getOperand(0);
3273 LookPassAnd1 = true;
3276 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3278 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3280 if (!N0.getNode()->hasOneUse() ||
3281 !N1.getNode()->hasOneUse())
3284 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3285 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3288 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3291 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3292 SDValue N00 = N0->getOperand(0);
3293 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3294 if (!N00.getNode()->hasOneUse())
3296 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3297 if (!N001C || N001C->getZExtValue() != 0xFF)
3299 N00 = N00.getOperand(0);
3300 LookPassAnd0 = true;
3303 SDValue N10 = N1->getOperand(0);
3304 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3305 if (!N10.getNode()->hasOneUse())
3307 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3308 if (!N101C || N101C->getZExtValue() != 0xFF00)
3310 N10 = N10.getOperand(0);
3311 LookPassAnd1 = true;
3317 // Make sure everything beyond the low halfword gets set to zero since the SRL
3318 // 16 will clear the top bits.
3319 unsigned OpSizeInBits = VT.getSizeInBits();
3320 if (DemandHighBits && OpSizeInBits > 16) {
3321 // If the left-shift isn't masked out then the only way this is a bswap is
3322 // if all bits beyond the low 8 are 0. In that case the entire pattern
3323 // reduces to a left shift anyway: leave it for other parts of the combiner.
3327 // However, if the right shift isn't masked out then it might be because
3328 // it's not needed. See if we can spot that too.
3329 if (!LookPassAnd1 &&
3330 !DAG.MaskedValueIsZero(
3331 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3335 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3336 if (OpSizeInBits > 16) {
3338 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3339 DAG.getConstant(OpSizeInBits - 16, DL,
3340 getShiftAmountTy(VT)));
3345 /// Return true if the specified node is an element that makes up a 32-bit
3346 /// packed halfword byteswap.
3347 /// ((x & 0x000000ff) << 8) |
3348 /// ((x & 0x0000ff00) >> 8) |
3349 /// ((x & 0x00ff0000) << 8) |
3350 /// ((x & 0xff000000) >> 8)
3351 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3352 if (!N.getNode()->hasOneUse())
3355 unsigned Opc = N.getOpcode();
3356 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3359 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3364 switch (N1C->getZExtValue()) {
3367 case 0xFF: Num = 0; break;
3368 case 0xFF00: Num = 1; break;
3369 case 0xFF0000: Num = 2; break;
3370 case 0xFF000000: Num = 3; break;
3373 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3374 SDValue N0 = N.getOperand(0);
3375 if (Opc == ISD::AND) {
3376 if (Num == 0 || Num == 2) {
3378 // (x >> 8) & 0xff0000
3379 if (N0.getOpcode() != ISD::SRL)
3381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3382 if (!C || C->getZExtValue() != 8)
3385 // (x << 8) & 0xff00
3386 // (x << 8) & 0xff000000
3387 if (N0.getOpcode() != ISD::SHL)
3389 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3390 if (!C || C->getZExtValue() != 8)
3393 } else if (Opc == ISD::SHL) {
3395 // (x & 0xff0000) << 8
3396 if (Num != 0 && Num != 2)
3398 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3399 if (!C || C->getZExtValue() != 8)
3401 } else { // Opc == ISD::SRL
3402 // (x & 0xff00) >> 8
3403 // (x & 0xff000000) >> 8
3404 if (Num != 1 && Num != 3)
3406 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3407 if (!C || C->getZExtValue() != 8)
3414 Parts[Num] = N0.getOperand(0).getNode();
3418 /// Match a 32-bit packed halfword bswap. That is
3419 /// ((x & 0x000000ff) << 8) |
3420 /// ((x & 0x0000ff00) >> 8) |
3421 /// ((x & 0x00ff0000) << 8) |
3422 /// ((x & 0xff000000) >> 8)
3423 /// => (rotl (bswap x), 16)
3424 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3425 if (!LegalOperations)
3428 EVT VT = N->getValueType(0);
3431 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3435 // (or (or (and), (and)), (or (and), (and)))
3436 // (or (or (or (and), (and)), (and)), (and))
3437 if (N0.getOpcode() != ISD::OR)
3439 SDValue N00 = N0.getOperand(0);
3440 SDValue N01 = N0.getOperand(1);
3441 SDNode *Parts[4] = {};
3443 if (N1.getOpcode() == ISD::OR &&
3444 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3445 // (or (or (and), (and)), (or (and), (and)))
3446 SDValue N000 = N00.getOperand(0);
3447 if (!isBSwapHWordElement(N000, Parts))
3450 SDValue N001 = N00.getOperand(1);
3451 if (!isBSwapHWordElement(N001, Parts))
3453 SDValue N010 = N01.getOperand(0);
3454 if (!isBSwapHWordElement(N010, Parts))
3456 SDValue N011 = N01.getOperand(1);
3457 if (!isBSwapHWordElement(N011, Parts))
3460 // (or (or (or (and), (and)), (and)), (and))
3461 if (!isBSwapHWordElement(N1, Parts))
3463 if (!isBSwapHWordElement(N01, Parts))
3465 if (N00.getOpcode() != ISD::OR)
3467 SDValue N000 = N00.getOperand(0);
3468 if (!isBSwapHWordElement(N000, Parts))
3470 SDValue N001 = N00.getOperand(1);
3471 if (!isBSwapHWordElement(N001, Parts))
3475 // Make sure the parts are all coming from the same node.
3476 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3480 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3481 SDValue(Parts[0], 0));
3483 // Result of the bswap should be rotated by 16. If it's not legal, then
3484 // do (x << 16) | (x >> 16).
3485 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3486 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3487 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3488 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3489 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3490 return DAG.getNode(ISD::OR, DL, VT,
3491 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3492 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3495 /// This contains all DAGCombine rules which reduce two values combined by
3496 /// an Or operation to a single value \see visitANDLike().
3497 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3498 EVT VT = N1.getValueType();
3499 // fold (or x, undef) -> -1
3500 if (!LegalOperations &&
3501 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3502 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3503 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3504 SDLoc(LocReference), VT);
3506 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3507 SDValue LL, LR, RL, RR, CC0, CC1;
3508 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3509 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3510 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3512 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3513 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3514 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3515 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3516 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3517 LR.getValueType(), LL, RL);
3518 AddToWorklist(ORNode.getNode());
3519 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3521 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3522 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3523 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3524 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3525 LR.getValueType(), LL, RL);
3526 AddToWorklist(ANDNode.getNode());
3527 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3530 // canonicalize equivalent to ll == rl
3531 if (LL == RR && LR == RL) {
3532 Op1 = ISD::getSetCCSwappedOperands(Op1);
3535 if (LL == RL && LR == RR) {
3536 bool isInteger = LL.getValueType().isInteger();
3537 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3538 if (Result != ISD::SETCC_INVALID &&
3539 (!LegalOperations ||
3540 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3541 TLI.isOperationLegal(ISD::SETCC,
3542 getSetCCResultType(N0.getValueType())))))
3543 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3548 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3549 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3550 // Don't increase # computations.
3551 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3552 // We can only do this xform if we know that bits from X that are set in C2
3553 // but not in C1 are already zero. Likewise for Y.
3554 if (const ConstantSDNode *N0O1C =
3555 getAsNonOpaqueConstant(N0.getOperand(1))) {
3556 if (const ConstantSDNode *N1O1C =
3557 getAsNonOpaqueConstant(N1.getOperand(1))) {
3558 // We can only do this xform if we know that bits from X that are set in
3559 // C2 but not in C1 are already zero. Likewise for Y.
3560 const APInt &LHSMask = N0O1C->getAPIntValue();
3561 const APInt &RHSMask = N1O1C->getAPIntValue();
3563 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3564 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3565 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3566 N0.getOperand(0), N1.getOperand(0));
3567 SDLoc DL(LocReference);
3568 return DAG.getNode(ISD::AND, DL, VT, X,
3569 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3575 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3576 if (N0.getOpcode() == ISD::AND &&
3577 N1.getOpcode() == ISD::AND &&
3578 N0.getOperand(0) == N1.getOperand(0) &&
3579 // Don't increase # computations.
3580 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3581 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3582 N0.getOperand(1), N1.getOperand(1));
3583 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3589 SDValue DAGCombiner::visitOR(SDNode *N) {
3590 SDValue N0 = N->getOperand(0);
3591 SDValue N1 = N->getOperand(1);
3592 EVT VT = N1.getValueType();
3595 if (VT.isVector()) {
3596 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3599 // fold (or x, 0) -> x, vector edition
3600 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3602 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3605 // fold (or x, -1) -> -1, vector edition
3606 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3607 // do not return N0, because undef node may exist in N0
3608 return DAG.getConstant(
3609 APInt::getAllOnesValue(
3610 N0.getValueType().getScalarType().getSizeInBits()),
3611 SDLoc(N), N0.getValueType());
3612 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3613 // do not return N1, because undef node may exist in N1
3614 return DAG.getConstant(
3615 APInt::getAllOnesValue(
3616 N1.getValueType().getScalarType().getSizeInBits()),
3617 SDLoc(N), N1.getValueType());
3619 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3620 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3621 // Do this only if the resulting shuffle is legal.
3622 if (isa<ShuffleVectorSDNode>(N0) &&
3623 isa<ShuffleVectorSDNode>(N1) &&
3624 // Avoid folding a node with illegal type.
3625 TLI.isTypeLegal(VT) &&
3626 N0->getOperand(1) == N1->getOperand(1) &&
3627 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3628 bool CanFold = true;
3629 unsigned NumElts = VT.getVectorNumElements();
3630 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3631 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3632 // We construct two shuffle masks:
3633 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3634 // and N1 as the second operand.
3635 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3636 // and N0 as the second operand.
3637 // We do this because OR is commutable and therefore there might be
3638 // two ways to fold this node into a shuffle.
3639 SmallVector<int,4> Mask1;
3640 SmallVector<int,4> Mask2;
3642 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3643 int M0 = SV0->getMaskElt(i);
3644 int M1 = SV1->getMaskElt(i);
3646 // Both shuffle indexes are undef. Propagate Undef.
3647 if (M0 < 0 && M1 < 0) {
3648 Mask1.push_back(M0);
3649 Mask2.push_back(M0);
3653 if (M0 < 0 || M1 < 0 ||
3654 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3655 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3660 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3661 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3665 // Fold this sequence only if the resulting shuffle is 'legal'.
3666 if (TLI.isShuffleMaskLegal(Mask1, VT))
3667 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3668 N1->getOperand(0), &Mask1[0]);
3669 if (TLI.isShuffleMaskLegal(Mask2, VT))
3670 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3671 N0->getOperand(0), &Mask2[0]);
3676 // fold (or c1, c2) -> c1|c2
3677 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3679 if (N0C && N1C && !N1C->isOpaque())
3680 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3681 // canonicalize constant to RHS
3682 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3683 !isConstantIntBuildVectorOrConstantInt(N1))
3684 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3685 // fold (or x, 0) -> x
3686 if (isNullConstant(N1))
3688 // fold (or x, -1) -> -1
3689 if (isAllOnesConstant(N1))
3691 // fold (or x, c) -> c iff (x & ~c) == 0
3692 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3695 if (SDValue Combined = visitORLike(N0, N1, N))
3698 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3699 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3701 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3705 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3707 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3708 // iff (c1 & c2) == 0.
3709 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3710 isa<ConstantSDNode>(N0.getOperand(1))) {
3711 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3712 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3713 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3716 ISD::AND, SDLoc(N), VT,
3717 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3721 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3722 if (N0.getOpcode() == N1.getOpcode())
3723 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3726 // See if this is some rotate idiom.
3727 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3728 return SDValue(Rot, 0);
3730 // Simplify the operands using demanded-bits information.
3731 if (!VT.isVector() &&
3732 SimplifyDemandedBits(SDValue(N, 0)))
3733 return SDValue(N, 0);
3738 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3739 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3740 if (Op.getOpcode() == ISD::AND) {
3741 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3742 Mask = Op.getOperand(1);
3743 Op = Op.getOperand(0);
3749 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3757 // Return true if we can prove that, whenever Neg and Pos are both in the
3758 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3759 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3761 // (or (shift1 X, Neg), (shift2 X, Pos))
3763 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3764 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3765 // to consider shift amounts with defined behavior.
3766 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3767 // If OpSize is a power of 2 then:
3769 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3770 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3772 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3773 // for the stronger condition:
3775 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3777 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3778 // we can just replace Neg with Neg' for the rest of the function.
3780 // In other cases we check for the even stronger condition:
3782 // Neg == OpSize - Pos [B]
3784 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3785 // behavior if Pos == 0 (and consequently Neg == OpSize).
3787 // We could actually use [A] whenever OpSize is a power of 2, but the
3788 // only extra cases that it would match are those uninteresting ones
3789 // where Neg and Pos are never in range at the same time. E.g. for
3790 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3791 // as well as (sub 32, Pos), but:
3793 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3795 // always invokes undefined behavior for 32-bit X.
3797 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3798 unsigned MaskLoBits = 0;
3799 if (Neg.getOpcode() == ISD::AND &&
3800 isPowerOf2_64(OpSize) &&
3801 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3802 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3803 Neg = Neg.getOperand(0);
3804 MaskLoBits = Log2_64(OpSize);
3807 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3808 if (Neg.getOpcode() != ISD::SUB)
3810 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3813 SDValue NegOp1 = Neg.getOperand(1);
3815 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3816 // Pos'. The truncation is redundant for the purpose of the equality.
3818 Pos.getOpcode() == ISD::AND &&
3819 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3820 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3821 Pos = Pos.getOperand(0);
3823 // The condition we need is now:
3825 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3827 // If NegOp1 == Pos then we need:
3829 // OpSize & Mask == NegC & Mask
3831 // (because "x & Mask" is a truncation and distributes through subtraction).
3834 Width = NegC->getAPIntValue();
3835 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3836 // Then the condition we want to prove becomes:
3838 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3840 // which, again because "x & Mask" is a truncation, becomes:
3842 // NegC & Mask == (OpSize - PosC) & Mask
3843 // OpSize & Mask == (NegC + PosC) & Mask
3844 else if (Pos.getOpcode() == ISD::ADD &&
3845 Pos.getOperand(0) == NegOp1 &&
3846 Pos.getOperand(1).getOpcode() == ISD::Constant)
3847 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3848 NegC->getAPIntValue());
3852 // Now we just need to check that OpSize & Mask == Width & Mask.
3854 // Opsize & Mask is 0 since Mask is Opsize - 1.
3855 return Width.getLoBits(MaskLoBits) == 0;
3856 return Width == OpSize;
3859 // A subroutine of MatchRotate used once we have found an OR of two opposite
3860 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3861 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3862 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3863 // Neg with outer conversions stripped away.
3864 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3865 SDValue Neg, SDValue InnerPos,
3866 SDValue InnerNeg, unsigned PosOpcode,
3867 unsigned NegOpcode, SDLoc DL) {
3868 // fold (or (shl x, (*ext y)),
3869 // (srl x, (*ext (sub 32, y)))) ->
3870 // (rotl x, y) or (rotr x, (sub 32, y))
3872 // fold (or (shl x, (*ext (sub 32, y))),
3873 // (srl x, (*ext y))) ->
3874 // (rotr x, y) or (rotl x, (sub 32, y))
3875 EVT VT = Shifted.getValueType();
3876 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3877 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3878 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3879 HasPos ? Pos : Neg).getNode();
3885 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3886 // idioms for rotate, and if the target supports rotation instructions, generate
3888 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3889 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3890 EVT VT = LHS.getValueType();
3891 if (!TLI.isTypeLegal(VT)) return nullptr;
3893 // The target must have at least one rotate flavor.
3894 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3895 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3896 if (!HasROTL && !HasROTR) return nullptr;
3898 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3899 SDValue LHSShift; // The shift.
3900 SDValue LHSMask; // AND value if any.
3901 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3902 return nullptr; // Not part of a rotate.
3904 SDValue RHSShift; // The shift.
3905 SDValue RHSMask; // AND value if any.
3906 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3907 return nullptr; // Not part of a rotate.
3909 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3910 return nullptr; // Not shifting the same value.
3912 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3913 return nullptr; // Shifts must disagree.
3915 // Canonicalize shl to left side in a shl/srl pair.
3916 if (RHSShift.getOpcode() == ISD::SHL) {
3917 std::swap(LHS, RHS);
3918 std::swap(LHSShift, RHSShift);
3919 std::swap(LHSMask , RHSMask );
3922 unsigned OpSizeInBits = VT.getSizeInBits();
3923 SDValue LHSShiftArg = LHSShift.getOperand(0);
3924 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3925 SDValue RHSShiftArg = RHSShift.getOperand(0);
3926 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3928 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3929 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3930 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3931 RHSShiftAmt.getOpcode() == ISD::Constant) {
3932 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3933 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3934 if ((LShVal + RShVal) != OpSizeInBits)
3937 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3938 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3940 // If there is an AND of either shifted operand, apply it to the result.
3941 if (LHSMask.getNode() || RHSMask.getNode()) {
3942 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3944 if (LHSMask.getNode()) {
3945 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3946 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3948 if (RHSMask.getNode()) {
3949 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3950 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3953 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3956 return Rot.getNode();
3959 // If there is a mask here, and we have a variable shift, we can't be sure
3960 // that we're masking out the right stuff.
3961 if (LHSMask.getNode() || RHSMask.getNode())
3964 // If the shift amount is sign/zext/any-extended just peel it off.
3965 SDValue LExtOp0 = LHSShiftAmt;
3966 SDValue RExtOp0 = RHSShiftAmt;
3967 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3968 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3969 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3970 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3971 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3972 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3973 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3974 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3975 LExtOp0 = LHSShiftAmt.getOperand(0);
3976 RExtOp0 = RHSShiftAmt.getOperand(0);
3979 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3980 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3984 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3985 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3992 SDValue DAGCombiner::visitXOR(SDNode *N) {
3993 SDValue N0 = N->getOperand(0);
3994 SDValue N1 = N->getOperand(1);
3995 EVT VT = N0.getValueType();
3998 if (VT.isVector()) {
3999 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4002 // fold (xor x, 0) -> x, vector edition
4003 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4005 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4009 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4010 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4011 return DAG.getConstant(0, SDLoc(N), VT);
4012 // fold (xor x, undef) -> undef
4013 if (N0.getOpcode() == ISD::UNDEF)
4015 if (N1.getOpcode() == ISD::UNDEF)
4017 // fold (xor c1, c2) -> c1^c2
4018 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4019 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4021 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4022 // canonicalize constant to RHS
4023 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4024 !isConstantIntBuildVectorOrConstantInt(N1))
4025 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4026 // fold (xor x, 0) -> x
4027 if (isNullConstant(N1))
4030 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4033 // fold !(x cc y) -> (x !cc y)
4034 SDValue LHS, RHS, CC;
4035 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4036 bool isInt = LHS.getValueType().isInteger();
4037 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4040 if (!LegalOperations ||
4041 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4042 switch (N0.getOpcode()) {
4044 llvm_unreachable("Unhandled SetCC Equivalent!");
4046 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4047 case ISD::SELECT_CC:
4048 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4049 N0.getOperand(3), NotCC);
4054 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4055 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4056 N0.getNode()->hasOneUse() &&
4057 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4058 SDValue V = N0.getOperand(0);
4060 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4061 DAG.getConstant(1, DL, V.getValueType()));
4062 AddToWorklist(V.getNode());
4063 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4066 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4067 if (isOneConstant(N1) && VT == MVT::i1 &&
4068 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4069 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4070 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4071 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4072 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4073 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4074 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4075 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4078 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4079 if (isAllOnesConstant(N1) &&
4080 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4081 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4082 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4083 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4084 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4085 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4086 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4087 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4090 // fold (xor (and x, y), y) -> (and (not x), y)
4091 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4092 N0->getOperand(1) == N1) {
4093 SDValue X = N0->getOperand(0);
4094 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4095 AddToWorklist(NotX.getNode());
4096 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4098 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4099 if (N1C && N0.getOpcode() == ISD::XOR) {
4100 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4102 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4103 DAG.getConstant(N1C->getAPIntValue() ^
4104 N00C->getAPIntValue(), DL, VT));
4106 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4108 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4109 DAG.getConstant(N1C->getAPIntValue() ^
4110 N01C->getAPIntValue(), DL, VT));
4113 // fold (xor x, x) -> 0
4115 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4117 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4118 // Here is a concrete example of this equivalence:
4120 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4121 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4125 // i16 ~1 == 0b1111111111111110
4126 // i16 rol(~1, 14) == 0b1011111111111111
4128 // Some additional tips to help conceptualize this transform:
4129 // - Try to see the operation as placing a single zero in a value of all ones.
4130 // - There exists no value for x which would allow the result to contain zero.
4131 // - Values of x larger than the bitwidth are undefined and do not require a
4132 // consistent result.
4133 // - Pushing the zero left requires shifting one bits in from the right.
4134 // A rotate left of ~1 is a nice way of achieving the desired result.
4135 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4136 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4138 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4142 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4143 if (N0.getOpcode() == N1.getOpcode())
4144 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4147 // Simplify the expression using non-local knowledge.
4148 if (!VT.isVector() &&
4149 SimplifyDemandedBits(SDValue(N, 0)))
4150 return SDValue(N, 0);
4155 /// Handle transforms common to the three shifts, when the shift amount is a
4157 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4158 SDNode *LHS = N->getOperand(0).getNode();
4159 if (!LHS->hasOneUse()) return SDValue();
4161 // We want to pull some binops through shifts, so that we have (and (shift))
4162 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4163 // thing happens with address calculations, so it's important to canonicalize
4165 bool HighBitSet = false; // Can we transform this if the high bit is set?
4167 switch (LHS->getOpcode()) {
4168 default: return SDValue();
4171 HighBitSet = false; // We can only transform sra if the high bit is clear.
4174 HighBitSet = true; // We can only transform sra if the high bit is set.
4177 if (N->getOpcode() != ISD::SHL)
4178 return SDValue(); // only shl(add) not sr[al](add).
4179 HighBitSet = false; // We can only transform sra if the high bit is clear.
4183 // We require the RHS of the binop to be a constant and not opaque as well.
4184 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4185 if (!BinOpCst) return SDValue();
4187 // FIXME: disable this unless the input to the binop is a shift by a constant.
4188 // If it is not a shift, it pessimizes some common cases like:
4190 // void foo(int *X, int i) { X[i & 1235] = 1; }
4191 // int bar(int *X, int i) { return X[i & 255]; }
4192 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4193 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4194 BinOpLHSVal->getOpcode() != ISD::SRA &&
4195 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4196 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4199 EVT VT = N->getValueType(0);
4201 // If this is a signed shift right, and the high bit is modified by the
4202 // logical operation, do not perform the transformation. The highBitSet
4203 // boolean indicates the value of the high bit of the constant which would
4204 // cause it to be modified for this operation.
4205 if (N->getOpcode() == ISD::SRA) {
4206 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4207 if (BinOpRHSSignSet != HighBitSet)
4211 if (!TLI.isDesirableToCommuteWithShift(LHS))
4214 // Fold the constants, shifting the binop RHS by the shift amount.
4215 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4217 LHS->getOperand(1), N->getOperand(1));
4218 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4220 // Create the new shift.
4221 SDValue NewShift = DAG.getNode(N->getOpcode(),
4222 SDLoc(LHS->getOperand(0)),
4223 VT, LHS->getOperand(0), N->getOperand(1));
4225 // Create the new binop.
4226 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4229 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4230 assert(N->getOpcode() == ISD::TRUNCATE);
4231 assert(N->getOperand(0).getOpcode() == ISD::AND);
4233 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4234 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4235 SDValue N01 = N->getOperand(0).getOperand(1);
4237 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4238 if (!N01C->isOpaque()) {
4239 EVT TruncVT = N->getValueType(0);
4240 SDValue N00 = N->getOperand(0).getOperand(0);
4241 APInt TruncC = N01C->getAPIntValue();
4242 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4245 return DAG.getNode(ISD::AND, DL, TruncVT,
4246 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4247 DAG.getConstant(TruncC, DL, TruncVT));
4255 SDValue DAGCombiner::visitRotate(SDNode *N) {
4256 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4257 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4258 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4259 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4260 if (NewOp1.getNode())
4261 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4262 N->getOperand(0), NewOp1);
4267 SDValue DAGCombiner::visitSHL(SDNode *N) {
4268 SDValue N0 = N->getOperand(0);
4269 SDValue N1 = N->getOperand(1);
4270 EVT VT = N0.getValueType();
4271 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4274 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4275 if (VT.isVector()) {
4276 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4279 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4280 // If setcc produces all-one true value then:
4281 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4282 if (N1CV && N1CV->isConstant()) {
4283 if (N0.getOpcode() == ISD::AND) {
4284 SDValue N00 = N0->getOperand(0);
4285 SDValue N01 = N0->getOperand(1);
4286 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4288 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4289 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4290 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4291 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4293 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4296 N1C = isConstOrConstSplat(N1);
4301 // fold (shl c1, c2) -> c1<<c2
4302 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4303 if (N0C && N1C && !N1C->isOpaque())
4304 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4305 // fold (shl 0, x) -> 0
4306 if (isNullConstant(N0))
4308 // fold (shl x, c >= size(x)) -> undef
4309 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4310 return DAG.getUNDEF(VT);
4311 // fold (shl x, 0) -> x
4312 if (N1C && N1C->isNullValue())
4314 // fold (shl undef, x) -> 0
4315 if (N0.getOpcode() == ISD::UNDEF)
4316 return DAG.getConstant(0, SDLoc(N), VT);
4317 // if (shl x, c) is known to be zero, return 0
4318 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4319 APInt::getAllOnesValue(OpSizeInBits)))
4320 return DAG.getConstant(0, SDLoc(N), VT);
4321 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4322 if (N1.getOpcode() == ISD::TRUNCATE &&
4323 N1.getOperand(0).getOpcode() == ISD::AND) {
4324 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4325 if (NewOp1.getNode())
4326 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4329 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4330 return SDValue(N, 0);
4332 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4333 if (N1C && N0.getOpcode() == ISD::SHL) {
4334 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4335 uint64_t c1 = N0C1->getZExtValue();
4336 uint64_t c2 = N1C->getZExtValue();
4338 if (c1 + c2 >= OpSizeInBits)
4339 return DAG.getConstant(0, DL, VT);
4340 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4341 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4345 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4346 // For this to be valid, the second form must not preserve any of the bits
4347 // that are shifted out by the inner shift in the first form. This means
4348 // the outer shift size must be >= the number of bits added by the ext.
4349 // As a corollary, we don't care what kind of ext it is.
4350 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4351 N0.getOpcode() == ISD::ANY_EXTEND ||
4352 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4353 N0.getOperand(0).getOpcode() == ISD::SHL) {
4354 SDValue N0Op0 = N0.getOperand(0);
4355 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4356 uint64_t c1 = N0Op0C1->getZExtValue();
4357 uint64_t c2 = N1C->getZExtValue();
4358 EVT InnerShiftVT = N0Op0.getValueType();
4359 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4360 if (c2 >= OpSizeInBits - InnerShiftSize) {
4362 if (c1 + c2 >= OpSizeInBits)
4363 return DAG.getConstant(0, DL, VT);
4364 return DAG.getNode(ISD::SHL, DL, VT,
4365 DAG.getNode(N0.getOpcode(), DL, VT,
4366 N0Op0->getOperand(0)),
4367 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4372 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4373 // Only fold this if the inner zext has no other uses to avoid increasing
4374 // the total number of instructions.
4375 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4376 N0.getOperand(0).getOpcode() == ISD::SRL) {
4377 SDValue N0Op0 = N0.getOperand(0);
4378 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4379 uint64_t c1 = N0Op0C1->getZExtValue();
4380 if (c1 < VT.getScalarSizeInBits()) {
4381 uint64_t c2 = N1C->getZExtValue();
4383 SDValue NewOp0 = N0.getOperand(0);
4384 EVT CountVT = NewOp0.getOperand(1).getValueType();
4386 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4388 DAG.getConstant(c2, DL, CountVT));
4389 AddToWorklist(NewSHL.getNode());
4390 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4396 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4397 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4398 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4399 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4400 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4401 uint64_t C1 = N0C1->getZExtValue();
4402 uint64_t C2 = N1C->getZExtValue();
4405 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4406 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4407 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4408 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4412 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4413 // (and (srl x, (sub c1, c2), MASK)
4414 // Only fold this if the inner shift has no other uses -- if it does, folding
4415 // this will increase the total number of instructions.
4416 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4417 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4418 uint64_t c1 = N0C1->getZExtValue();
4419 if (c1 < OpSizeInBits) {
4420 uint64_t c2 = N1C->getZExtValue();
4421 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4424 Mask = Mask.shl(c2 - c1);
4426 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4427 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4429 Mask = Mask.lshr(c1 - c2);
4431 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4432 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4435 return DAG.getNode(ISD::AND, DL, VT, Shift,
4436 DAG.getConstant(Mask, DL, VT));
4440 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4441 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4442 unsigned BitSize = VT.getScalarSizeInBits();
4444 SDValue HiBitsMask =
4445 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4446 BitSize - N1C->getZExtValue()),
4448 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4452 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4453 // Variant of version done on multiply, except mul by a power of 2 is turned
4456 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4457 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4458 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4459 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4460 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4461 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4464 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4465 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4466 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467 if (SDValue Folded =
4468 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4469 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4473 if (N1C && !N1C->isOpaque())
4474 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4480 SDValue DAGCombiner::visitSRA(SDNode *N) {
4481 SDValue N0 = N->getOperand(0);
4482 SDValue N1 = N->getOperand(1);
4483 EVT VT = N0.getValueType();
4484 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4487 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4488 if (VT.isVector()) {
4489 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4492 N1C = isConstOrConstSplat(N1);
4495 // fold (sra c1, c2) -> (sra c1, c2)
4496 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4497 if (N0C && N1C && !N1C->isOpaque())
4498 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4499 // fold (sra 0, x) -> 0
4500 if (isNullConstant(N0))
4502 // fold (sra -1, x) -> -1
4503 if (isAllOnesConstant(N0))
4505 // fold (sra x, (setge c, size(x))) -> undef
4506 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4507 return DAG.getUNDEF(VT);
4508 // fold (sra x, 0) -> x
4509 if (N1C && N1C->isNullValue())
4511 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4513 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4514 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4515 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4517 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4518 ExtVT, VT.getVectorNumElements());
4519 if ((!LegalOperations ||
4520 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4521 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4522 N0.getOperand(0), DAG.getValueType(ExtVT));
4525 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4526 if (N1C && N0.getOpcode() == ISD::SRA) {
4527 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4528 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4529 if (Sum >= OpSizeInBits)
4530 Sum = OpSizeInBits - 1;
4532 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4533 DAG.getConstant(Sum, DL, N1.getValueType()));
4537 // fold (sra (shl X, m), (sub result_size, n))
4538 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4539 // result_size - n != m.
4540 // If truncate is free for the target sext(shl) is likely to result in better
4542 if (N0.getOpcode() == ISD::SHL && N1C) {
4543 // Get the two constanst of the shifts, CN0 = m, CN = n.
4544 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4546 LLVMContext &Ctx = *DAG.getContext();
4547 // Determine what the truncate's result bitsize and type would be.
4548 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4551 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4553 // Determine the residual right-shift amount.
4554 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4556 // If the shift is not a no-op (in which case this should be just a sign
4557 // extend already), the truncated to type is legal, sign_extend is legal
4558 // on that type, and the truncate to that type is both legal and free,
4559 // perform the transform.
4560 if ((ShiftAmt > 0) &&
4561 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4562 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4563 TLI.isTruncateFree(VT, TruncVT)) {
4566 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4567 getShiftAmountTy(N0.getOperand(0).getValueType()));
4568 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4569 N0.getOperand(0), Amt);
4570 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4572 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4573 N->getValueType(0), Trunc);
4578 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4579 if (N1.getOpcode() == ISD::TRUNCATE &&
4580 N1.getOperand(0).getOpcode() == ISD::AND) {
4581 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4582 if (NewOp1.getNode())
4583 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4586 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4587 // if c1 is equal to the number of bits the trunc removes
4588 if (N0.getOpcode() == ISD::TRUNCATE &&
4589 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4590 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4591 N0.getOperand(0).hasOneUse() &&
4592 N0.getOperand(0).getOperand(1).hasOneUse() &&
4594 SDValue N0Op0 = N0.getOperand(0);
4595 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4596 unsigned LargeShiftVal = LargeShift->getZExtValue();
4597 EVT LargeVT = N0Op0.getValueType();
4599 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4602 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4603 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4604 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4605 N0Op0.getOperand(0), Amt);
4606 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4611 // Simplify, based on bits shifted out of the LHS.
4612 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4613 return SDValue(N, 0);
4616 // If the sign bit is known to be zero, switch this to a SRL.
4617 if (DAG.SignBitIsZero(N0))
4618 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4620 if (N1C && !N1C->isOpaque())
4621 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4627 SDValue DAGCombiner::visitSRL(SDNode *N) {
4628 SDValue N0 = N->getOperand(0);
4629 SDValue N1 = N->getOperand(1);
4630 EVT VT = N0.getValueType();
4631 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4634 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4635 if (VT.isVector()) {
4636 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4639 N1C = isConstOrConstSplat(N1);
4642 // fold (srl c1, c2) -> c1 >>u c2
4643 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4644 if (N0C && N1C && !N1C->isOpaque())
4645 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4646 // fold (srl 0, x) -> 0
4647 if (isNullConstant(N0))
4649 // fold (srl x, c >= size(x)) -> undef
4650 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4651 return DAG.getUNDEF(VT);
4652 // fold (srl x, 0) -> x
4653 if (N1C && N1C->isNullValue())
4655 // if (srl x, c) is known to be zero, return 0
4656 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4657 APInt::getAllOnesValue(OpSizeInBits)))
4658 return DAG.getConstant(0, SDLoc(N), VT);
4660 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4661 if (N1C && N0.getOpcode() == ISD::SRL) {
4662 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4663 uint64_t c1 = N01C->getZExtValue();
4664 uint64_t c2 = N1C->getZExtValue();
4666 if (c1 + c2 >= OpSizeInBits)
4667 return DAG.getConstant(0, DL, VT);
4668 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4669 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4673 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4674 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4675 N0.getOperand(0).getOpcode() == ISD::SRL &&
4676 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4678 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4679 uint64_t c2 = N1C->getZExtValue();
4680 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4681 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4682 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4683 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4684 if (c1 + OpSizeInBits == InnerShiftSize) {
4686 if (c1 + c2 >= InnerShiftSize)
4687 return DAG.getConstant(0, DL, VT);
4688 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4689 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4690 N0.getOperand(0)->getOperand(0),
4691 DAG.getConstant(c1 + c2, DL,
4696 // fold (srl (shl x, c), c) -> (and x, cst2)
4697 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4698 unsigned BitSize = N0.getScalarValueSizeInBits();
4699 if (BitSize <= 64) {
4700 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4702 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4703 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4707 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4708 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4709 // Shifting in all undef bits?
4710 EVT SmallVT = N0.getOperand(0).getValueType();
4711 unsigned BitSize = SmallVT.getScalarSizeInBits();
4712 if (N1C->getZExtValue() >= BitSize)
4713 return DAG.getUNDEF(VT);
4715 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4716 uint64_t ShiftAmt = N1C->getZExtValue();
4718 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4720 DAG.getConstant(ShiftAmt, DL0,
4721 getShiftAmountTy(SmallVT)));
4722 AddToWorklist(SmallShift.getNode());
4723 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4725 return DAG.getNode(ISD::AND, DL, VT,
4726 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4727 DAG.getConstant(Mask, DL, VT));
4731 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4732 // bit, which is unmodified by sra.
4733 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4734 if (N0.getOpcode() == ISD::SRA)
4735 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4738 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4739 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4740 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4741 APInt KnownZero, KnownOne;
4742 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4744 // If any of the input bits are KnownOne, then the input couldn't be all
4745 // zeros, thus the result of the srl will always be zero.
4746 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4748 // If all of the bits input the to ctlz node are known to be zero, then
4749 // the result of the ctlz is "32" and the result of the shift is one.
4750 APInt UnknownBits = ~KnownZero;
4751 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4753 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4754 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4755 // Okay, we know that only that the single bit specified by UnknownBits
4756 // could be set on input to the CTLZ node. If this bit is set, the SRL
4757 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4758 // to an SRL/XOR pair, which is likely to simplify more.
4759 unsigned ShAmt = UnknownBits.countTrailingZeros();
4760 SDValue Op = N0.getOperand(0);
4764 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4765 DAG.getConstant(ShAmt, DL,
4766 getShiftAmountTy(Op.getValueType())));
4767 AddToWorklist(Op.getNode());
4771 return DAG.getNode(ISD::XOR, DL, VT,
4772 Op, DAG.getConstant(1, DL, VT));
4776 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4777 if (N1.getOpcode() == ISD::TRUNCATE &&
4778 N1.getOperand(0).getOpcode() == ISD::AND) {
4779 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4780 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4783 // fold operands of srl based on knowledge that the low bits are not
4785 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4786 return SDValue(N, 0);
4788 if (N1C && !N1C->isOpaque())
4789 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4792 // Attempt to convert a srl of a load into a narrower zero-extending load.
4793 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4796 // Here is a common situation. We want to optimize:
4799 // %b = and i32 %a, 2
4800 // %c = srl i32 %b, 1
4801 // brcond i32 %c ...
4807 // %c = setcc eq %b, 0
4810 // However when after the source operand of SRL is optimized into AND, the SRL
4811 // itself may not be optimized further. Look for it and add the BRCOND into
4813 if (N->hasOneUse()) {
4814 SDNode *Use = *N->use_begin();
4815 if (Use->getOpcode() == ISD::BRCOND)
4817 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4818 // Also look pass the truncate.
4819 Use = *Use->use_begin();
4820 if (Use->getOpcode() == ISD::BRCOND)
4828 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4829 SDValue N0 = N->getOperand(0);
4830 EVT VT = N->getValueType(0);
4832 // fold (bswap c1) -> c2
4833 if (isConstantIntBuildVectorOrConstantInt(N0))
4834 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4835 // fold (bswap (bswap x)) -> x
4836 if (N0.getOpcode() == ISD::BSWAP)
4837 return N0->getOperand(0);
4841 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4842 SDValue N0 = N->getOperand(0);
4843 EVT VT = N->getValueType(0);
4845 // fold (ctlz c1) -> c2
4846 if (isConstantIntBuildVectorOrConstantInt(N0))
4847 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4851 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4852 SDValue N0 = N->getOperand(0);
4853 EVT VT = N->getValueType(0);
4855 // fold (ctlz_zero_undef c1) -> c2
4856 if (isConstantIntBuildVectorOrConstantInt(N0))
4857 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4861 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4862 SDValue N0 = N->getOperand(0);
4863 EVT VT = N->getValueType(0);
4865 // fold (cttz c1) -> c2
4866 if (isConstantIntBuildVectorOrConstantInt(N0))
4867 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4871 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4872 SDValue N0 = N->getOperand(0);
4873 EVT VT = N->getValueType(0);
4875 // fold (cttz_zero_undef c1) -> c2
4876 if (isConstantIntBuildVectorOrConstantInt(N0))
4877 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4881 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4882 SDValue N0 = N->getOperand(0);
4883 EVT VT = N->getValueType(0);
4885 // fold (ctpop c1) -> c2
4886 if (isConstantIntBuildVectorOrConstantInt(N0))
4887 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4892 /// \brief Generate Min/Max node
4893 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4894 SDValue True, SDValue False,
4895 ISD::CondCode CC, const TargetLowering &TLI,
4896 SelectionDAG &DAG) {
4897 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4907 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4908 if (TLI.isOperationLegal(Opcode, VT))
4909 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4918 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4919 if (TLI.isOperationLegal(Opcode, VT))
4920 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4928 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4929 SDValue N0 = N->getOperand(0);
4930 SDValue N1 = N->getOperand(1);
4931 SDValue N2 = N->getOperand(2);
4932 EVT VT = N->getValueType(0);
4933 EVT VT0 = N0.getValueType();
4935 // fold (select C, X, X) -> X
4938 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4939 // fold (select true, X, Y) -> X
4940 // fold (select false, X, Y) -> Y
4941 return !N0C->isNullValue() ? N1 : N2;
4943 // fold (select C, 1, X) -> (or C, X)
4944 if (VT == MVT::i1 && isOneConstant(N1))
4945 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4946 // fold (select C, 0, 1) -> (xor C, 1)
4947 // We can't do this reliably if integer based booleans have different contents
4948 // to floating point based booleans. This is because we can't tell whether we
4949 // have an integer-based boolean or a floating-point-based boolean unless we
4950 // can find the SETCC that produced it and inspect its operands. This is
4951 // fairly easy if C is the SETCC node, but it can potentially be
4952 // undiscoverable (or not reasonably discoverable). For example, it could be
4953 // in another basic block or it could require searching a complicated
4955 if (VT.isInteger() &&
4956 (VT0 == MVT::i1 || (VT0.isInteger() &&
4957 TLI.getBooleanContents(false, false) ==
4958 TLI.getBooleanContents(false, true) &&
4959 TLI.getBooleanContents(false, false) ==
4960 TargetLowering::ZeroOrOneBooleanContent)) &&
4961 isNullConstant(N1) && isOneConstant(N2)) {
4965 return DAG.getNode(ISD::XOR, DL, VT0,
4966 N0, DAG.getConstant(1, DL, VT0));
4969 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4970 N0, DAG.getConstant(1, DL0, VT0));
4971 AddToWorklist(XORNode.getNode());
4973 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4974 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4976 // fold (select C, 0, X) -> (and (not C), X)
4977 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4978 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4979 AddToWorklist(NOTNode.getNode());
4980 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4982 // fold (select C, X, 1) -> (or (not C), X)
4983 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4984 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4985 AddToWorklist(NOTNode.getNode());
4986 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4988 // fold (select C, X, 0) -> (and C, X)
4989 if (VT == MVT::i1 && isNullConstant(N2))
4990 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4991 // fold (select X, X, Y) -> (or X, Y)
4992 // fold (select X, 1, Y) -> (or X, Y)
4993 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4994 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4995 // fold (select X, Y, X) -> (and X, Y)
4996 // fold (select X, Y, 0) -> (and X, Y)
4997 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4998 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5000 // If we can fold this based on the true/false value, do so.
5001 if (SimplifySelectOps(N, N1, N2))
5002 return SDValue(N, 0); // Don't revisit N.
5004 if (VT0 == MVT::i1) {
5005 // The code in this block deals with the following 2 equivalences:
5006 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5007 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5008 // The target can specify its prefered form with the
5009 // shouldNormalizeToSelectSequence() callback. However we always transform
5010 // to the right anyway if we find the inner select exists in the DAG anyway
5011 // and we always transform to the left side if we know that we can further
5012 // optimize the combination of the conditions.
5013 bool normalizeToSequence
5014 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5015 // select (and Cond0, Cond1), X, Y
5016 // -> select Cond0, (select Cond1, X, Y), Y
5017 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5018 SDValue Cond0 = N0->getOperand(0);
5019 SDValue Cond1 = N0->getOperand(1);
5020 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5021 N1.getValueType(), Cond1, N1, N2);
5022 if (normalizeToSequence || !InnerSelect.use_empty())
5023 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5026 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5027 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5028 SDValue Cond0 = N0->getOperand(0);
5029 SDValue Cond1 = N0->getOperand(1);
5030 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5031 N1.getValueType(), Cond1, N1, N2);
5032 if (normalizeToSequence || !InnerSelect.use_empty())
5033 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5037 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5038 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5039 SDValue N1_0 = N1->getOperand(0);
5040 SDValue N1_1 = N1->getOperand(1);
5041 SDValue N1_2 = N1->getOperand(2);
5042 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5043 // Create the actual and node if we can generate good code for it.
5044 if (!normalizeToSequence) {
5045 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5047 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5050 // Otherwise see if we can optimize the "and" to a better pattern.
5051 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5052 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5056 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5057 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5058 SDValue N2_0 = N2->getOperand(0);
5059 SDValue N2_1 = N2->getOperand(1);
5060 SDValue N2_2 = N2->getOperand(2);
5061 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5062 // Create the actual or node if we can generate good code for it.
5063 if (!normalizeToSequence) {
5064 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5066 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5069 // Otherwise see if we can optimize to a better pattern.
5070 if (SDValue Combined = visitORLike(N0, N2_0, N))
5071 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5077 // fold selects based on a setcc into other things, such as min/max/abs
5078 if (N0.getOpcode() == ISD::SETCC) {
5079 // select x, y (fcmp lt x, y) -> fminnum x, y
5080 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5082 // This is OK if we don't care about what happens if either operand is a
5086 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5087 // no signed zeros as well as no nans.
5088 const TargetOptions &Options = DAG.getTarget().Options;
5089 if (Options.UnsafeFPMath &&
5090 VT.isFloatingPoint() && N0.hasOneUse() &&
5091 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5092 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5094 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5095 N0.getOperand(1), N1, N2, CC,
5100 if ((!LegalOperations &&
5101 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5102 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5103 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5104 N0.getOperand(0), N0.getOperand(1),
5105 N1, N2, N0.getOperand(2));
5106 return SimplifySelect(SDLoc(N), N0, N1, N2);
5113 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5116 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5118 // Split the inputs.
5119 SDValue Lo, Hi, LL, LH, RL, RH;
5120 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5121 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5123 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5124 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5126 return std::make_pair(Lo, Hi);
5129 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5130 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5131 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5133 SDValue Cond = N->getOperand(0);
5134 SDValue LHS = N->getOperand(1);
5135 SDValue RHS = N->getOperand(2);
5136 EVT VT = N->getValueType(0);
5137 int NumElems = VT.getVectorNumElements();
5138 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5139 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5140 Cond.getOpcode() == ISD::BUILD_VECTOR);
5142 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5143 // binary ones here.
5144 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5147 // We're sure we have an even number of elements due to the
5148 // concat_vectors we have as arguments to vselect.
5149 // Skip BV elements until we find one that's not an UNDEF
5150 // After we find an UNDEF element, keep looping until we get to half the
5151 // length of the BV and see if all the non-undef nodes are the same.
5152 ConstantSDNode *BottomHalf = nullptr;
5153 for (int i = 0; i < NumElems / 2; ++i) {
5154 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5157 if (BottomHalf == nullptr)
5158 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5159 else if (Cond->getOperand(i).getNode() != BottomHalf)
5163 // Do the same for the second half of the BuildVector
5164 ConstantSDNode *TopHalf = nullptr;
5165 for (int i = NumElems / 2; i < NumElems; ++i) {
5166 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5169 if (TopHalf == nullptr)
5170 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5171 else if (Cond->getOperand(i).getNode() != TopHalf)
5175 assert(TopHalf && BottomHalf &&
5176 "One half of the selector was all UNDEFs and the other was all the "
5177 "same value. This should have been addressed before this function.");
5179 ISD::CONCAT_VECTORS, dl, VT,
5180 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5181 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5184 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5186 if (Level >= AfterLegalizeTypes)
5189 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5190 SDValue Mask = MSC->getMask();
5191 SDValue Data = MSC->getValue();
5194 // If the MSCATTER data type requires splitting and the mask is provided by a
5195 // SETCC, then split both nodes and its operands before legalization. This
5196 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5197 // and enables future optimizations (e.g. min/max pattern matching on X86).
5198 if (Mask.getOpcode() != ISD::SETCC)
5201 // Check if any splitting is required.
5202 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5203 TargetLowering::TypeSplitVector)
5205 SDValue MaskLo, MaskHi, Lo, Hi;
5206 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5209 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5211 SDValue Chain = MSC->getChain();
5213 EVT MemoryVT = MSC->getMemoryVT();
5214 unsigned Alignment = MSC->getOriginalAlignment();
5216 EVT LoMemVT, HiMemVT;
5217 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5219 SDValue DataLo, DataHi;
5220 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5222 SDValue BasePtr = MSC->getBasePtr();
5223 SDValue IndexLo, IndexHi;
5224 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5226 MachineMemOperand *MMO = DAG.getMachineFunction().
5227 getMachineMemOperand(MSC->getPointerInfo(),
5228 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5229 Alignment, MSC->getAAInfo(), MSC->getRanges());
5231 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5232 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5235 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5236 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5239 AddToWorklist(Lo.getNode());
5240 AddToWorklist(Hi.getNode());
5242 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5245 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5247 if (Level >= AfterLegalizeTypes)
5250 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5251 SDValue Mask = MST->getMask();
5252 SDValue Data = MST->getValue();
5255 // If the MSTORE data type requires splitting and the mask is provided by a
5256 // SETCC, then split both nodes and its operands before legalization. This
5257 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5258 // and enables future optimizations (e.g. min/max pattern matching on X86).
5259 if (Mask.getOpcode() == ISD::SETCC) {
5261 // Check if any splitting is required.
5262 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5263 TargetLowering::TypeSplitVector)
5266 SDValue MaskLo, MaskHi, Lo, Hi;
5267 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5270 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5272 SDValue Chain = MST->getChain();
5273 SDValue Ptr = MST->getBasePtr();
5275 EVT MemoryVT = MST->getMemoryVT();
5276 unsigned Alignment = MST->getOriginalAlignment();
5278 // if Alignment is equal to the vector size,
5279 // take the half of it for the second part
5280 unsigned SecondHalfAlignment =
5281 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5282 Alignment/2 : Alignment;
5284 EVT LoMemVT, HiMemVT;
5285 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5287 SDValue DataLo, DataHi;
5288 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5290 MachineMemOperand *MMO = DAG.getMachineFunction().
5291 getMachineMemOperand(MST->getPointerInfo(),
5292 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5293 Alignment, MST->getAAInfo(), MST->getRanges());
5295 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5296 MST->isTruncatingStore());
5298 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5299 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5300 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5302 MMO = DAG.getMachineFunction().
5303 getMachineMemOperand(MST->getPointerInfo(),
5304 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5305 SecondHalfAlignment, MST->getAAInfo(),
5308 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5309 MST->isTruncatingStore());
5311 AddToWorklist(Lo.getNode());
5312 AddToWorklist(Hi.getNode());
5314 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5319 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5321 if (Level >= AfterLegalizeTypes)
5324 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5325 SDValue Mask = MGT->getMask();
5328 // If the MGATHER result requires splitting and the mask is provided by a
5329 // SETCC, then split both nodes and its operands before legalization. This
5330 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5331 // and enables future optimizations (e.g. min/max pattern matching on X86).
5333 if (Mask.getOpcode() != ISD::SETCC)
5336 EVT VT = N->getValueType(0);
5338 // Check if any splitting is required.
5339 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5340 TargetLowering::TypeSplitVector)
5343 SDValue MaskLo, MaskHi, Lo, Hi;
5344 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5346 SDValue Src0 = MGT->getValue();
5347 SDValue Src0Lo, Src0Hi;
5348 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5351 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5353 SDValue Chain = MGT->getChain();
5354 EVT MemoryVT = MGT->getMemoryVT();
5355 unsigned Alignment = MGT->getOriginalAlignment();
5357 EVT LoMemVT, HiMemVT;
5358 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5360 SDValue BasePtr = MGT->getBasePtr();
5361 SDValue Index = MGT->getIndex();
5362 SDValue IndexLo, IndexHi;
5363 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5365 MachineMemOperand *MMO = DAG.getMachineFunction().
5366 getMachineMemOperand(MGT->getPointerInfo(),
5367 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5368 Alignment, MGT->getAAInfo(), MGT->getRanges());
5370 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5371 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5374 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5375 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5378 AddToWorklist(Lo.getNode());
5379 AddToWorklist(Hi.getNode());
5381 // Build a factor node to remember that this load is independent of the
5383 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5386 // Legalized the chain result - switch anything that used the old chain to
5388 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5390 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5392 SDValue RetOps[] = { GatherRes, Chain };
5393 return DAG.getMergeValues(RetOps, DL);
5396 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5398 if (Level >= AfterLegalizeTypes)
5401 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5402 SDValue Mask = MLD->getMask();
5405 // If the MLOAD result requires splitting and the mask is provided by a
5406 // SETCC, then split both nodes and its operands before legalization. This
5407 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5408 // and enables future optimizations (e.g. min/max pattern matching on X86).
5410 if (Mask.getOpcode() == ISD::SETCC) {
5411 EVT VT = N->getValueType(0);
5413 // Check if any splitting is required.
5414 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5415 TargetLowering::TypeSplitVector)
5418 SDValue MaskLo, MaskHi, Lo, Hi;
5419 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5421 SDValue Src0 = MLD->getSrc0();
5422 SDValue Src0Lo, Src0Hi;
5423 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5426 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5428 SDValue Chain = MLD->getChain();
5429 SDValue Ptr = MLD->getBasePtr();
5430 EVT MemoryVT = MLD->getMemoryVT();
5431 unsigned Alignment = MLD->getOriginalAlignment();
5433 // if Alignment is equal to the vector size,
5434 // take the half of it for the second part
5435 unsigned SecondHalfAlignment =
5436 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5437 Alignment/2 : Alignment;
5439 EVT LoMemVT, HiMemVT;
5440 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5442 MachineMemOperand *MMO = DAG.getMachineFunction().
5443 getMachineMemOperand(MLD->getPointerInfo(),
5444 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5445 Alignment, MLD->getAAInfo(), MLD->getRanges());
5447 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5450 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5451 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5452 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5454 MMO = DAG.getMachineFunction().
5455 getMachineMemOperand(MLD->getPointerInfo(),
5456 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5457 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5459 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5462 AddToWorklist(Lo.getNode());
5463 AddToWorklist(Hi.getNode());
5465 // Build a factor node to remember that this load is independent of the
5467 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5470 // Legalized the chain result - switch anything that used the old chain to
5472 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5474 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5476 SDValue RetOps[] = { LoadRes, Chain };
5477 return DAG.getMergeValues(RetOps, DL);
5482 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5483 SDValue N0 = N->getOperand(0);
5484 SDValue N1 = N->getOperand(1);
5485 SDValue N2 = N->getOperand(2);
5488 // Canonicalize integer abs.
5489 // vselect (setg[te] X, 0), X, -X ->
5490 // vselect (setgt X, -1), X, -X ->
5491 // vselect (setl[te] X, 0), -X, X ->
5492 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5493 if (N0.getOpcode() == ISD::SETCC) {
5494 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5495 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5497 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5499 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5500 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5501 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5502 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5503 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5504 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5505 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5508 EVT VT = LHS.getValueType();
5509 SDValue Shift = DAG.getNode(
5510 ISD::SRA, DL, VT, LHS,
5511 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5512 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5513 AddToWorklist(Shift.getNode());
5514 AddToWorklist(Add.getNode());
5515 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5519 if (SimplifySelectOps(N, N1, N2))
5520 return SDValue(N, 0); // Don't revisit N.
5522 // If the VSELECT result requires splitting and the mask is provided by a
5523 // SETCC, then split both nodes and its operands before legalization. This
5524 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5525 // and enables future optimizations (e.g. min/max pattern matching on X86).
5526 if (N0.getOpcode() == ISD::SETCC) {
5527 EVT VT = N->getValueType(0);
5529 // Check if any splitting is required.
5530 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5531 TargetLowering::TypeSplitVector)
5534 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5535 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5536 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5537 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5539 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5540 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5542 // Add the new VSELECT nodes to the work list in case they need to be split
5544 AddToWorklist(Lo.getNode());
5545 AddToWorklist(Hi.getNode());
5547 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5550 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5551 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5553 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5554 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5557 // The ConvertSelectToConcatVector function is assuming both the above
5558 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5560 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5561 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5562 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5563 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5570 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5571 SDValue N0 = N->getOperand(0);
5572 SDValue N1 = N->getOperand(1);
5573 SDValue N2 = N->getOperand(2);
5574 SDValue N3 = N->getOperand(3);
5575 SDValue N4 = N->getOperand(4);
5576 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5578 // fold select_cc lhs, rhs, x, x, cc -> x
5582 // Determine if the condition we're dealing with is constant
5583 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5584 N0, N1, CC, SDLoc(N), false);
5585 if (SCC.getNode()) {
5586 AddToWorklist(SCC.getNode());
5588 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5589 if (!SCCC->isNullValue())
5590 return N2; // cond always true -> true val
5592 return N3; // cond always false -> false val
5593 } else if (SCC->getOpcode() == ISD::UNDEF) {
5594 // When the condition is UNDEF, just return the first operand. This is
5595 // coherent the DAG creation, no setcc node is created in this case
5597 } else if (SCC.getOpcode() == ISD::SETCC) {
5598 // Fold to a simpler select_cc
5599 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5600 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5605 // If we can fold this based on the true/false value, do so.
5606 if (SimplifySelectOps(N, N2, N3))
5607 return SDValue(N, 0); // Don't revisit N.
5609 // fold select_cc into other things, such as min/max/abs
5610 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5613 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5614 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5615 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5619 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5620 /// a build_vector of constants.
5621 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5622 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5623 /// Vector extends are not folded if operations are legal; this is to
5624 /// avoid introducing illegal build_vector dag nodes.
5625 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5626 SelectionDAG &DAG, bool LegalTypes,
5627 bool LegalOperations) {
5628 unsigned Opcode = N->getOpcode();
5629 SDValue N0 = N->getOperand(0);
5630 EVT VT = N->getValueType(0);
5632 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5633 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5634 && "Expected EXTEND dag node in input!");
5636 // fold (sext c1) -> c1
5637 // fold (zext c1) -> c1
5638 // fold (aext c1) -> c1
5639 if (isa<ConstantSDNode>(N0))
5640 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5642 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5643 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5644 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5645 EVT SVT = VT.getScalarType();
5646 if (!(VT.isVector() &&
5647 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5648 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5651 // We can fold this node into a build_vector.
5652 unsigned VTBits = SVT.getSizeInBits();
5653 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5654 SmallVector<SDValue, 8> Elts;
5655 unsigned NumElts = VT.getVectorNumElements();
5658 for (unsigned i=0; i != NumElts; ++i) {
5659 SDValue Op = N0->getOperand(i);
5660 if (Op->getOpcode() == ISD::UNDEF) {
5661 Elts.push_back(DAG.getUNDEF(SVT));
5666 // Get the constant value and if needed trunc it to the size of the type.
5667 // Nodes like build_vector might have constants wider than the scalar type.
5668 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5669 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5670 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5672 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5675 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5678 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5679 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5680 // transformation. Returns true if extension are possible and the above
5681 // mentioned transformation is profitable.
5682 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5684 SmallVectorImpl<SDNode *> &ExtendNodes,
5685 const TargetLowering &TLI) {
5686 bool HasCopyToRegUses = false;
5687 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5688 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5689 UE = N0.getNode()->use_end();
5694 if (UI.getUse().getResNo() != N0.getResNo())
5696 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5697 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5698 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5699 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5700 // Sign bits will be lost after a zext.
5703 for (unsigned i = 0; i != 2; ++i) {
5704 SDValue UseOp = User->getOperand(i);
5707 if (!isa<ConstantSDNode>(UseOp))
5712 ExtendNodes.push_back(User);
5715 // If truncates aren't free and there are users we can't
5716 // extend, it isn't worthwhile.
5719 // Remember if this value is live-out.
5720 if (User->getOpcode() == ISD::CopyToReg)
5721 HasCopyToRegUses = true;
5724 if (HasCopyToRegUses) {
5725 bool BothLiveOut = false;
5726 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5728 SDUse &Use = UI.getUse();
5729 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5735 // Both unextended and extended values are live out. There had better be
5736 // a good reason for the transformation.
5737 return ExtendNodes.size();
5742 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5743 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5744 ISD::NodeType ExtType) {
5745 // Extend SetCC uses if necessary.
5746 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5747 SDNode *SetCC = SetCCs[i];
5748 SmallVector<SDValue, 4> Ops;
5750 for (unsigned j = 0; j != 2; ++j) {
5751 SDValue SOp = SetCC->getOperand(j);
5753 Ops.push_back(ExtLoad);
5755 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5758 Ops.push_back(SetCC->getOperand(2));
5759 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5763 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5764 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5765 SDValue N0 = N->getOperand(0);
5766 EVT DstVT = N->getValueType(0);
5767 EVT SrcVT = N0.getValueType();
5769 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5770 N->getOpcode() == ISD::ZERO_EXTEND) &&
5771 "Unexpected node type (not an extend)!");
5773 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5774 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5775 // (v8i32 (sext (v8i16 (load x))))
5777 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5778 // (v4i32 (sextload (x + 16)))))
5779 // Where uses of the original load, i.e.:
5781 // are replaced with:
5783 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5784 // (v4i32 (sextload (x + 16)))))))
5786 // This combine is only applicable to illegal, but splittable, vectors.
5787 // All legal types, and illegal non-vector types, are handled elsewhere.
5788 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5790 if (N0->getOpcode() != ISD::LOAD)
5793 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5795 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5796 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5797 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5800 SmallVector<SDNode *, 4> SetCCs;
5801 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5804 ISD::LoadExtType ExtType =
5805 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5807 // Try to split the vector types to get down to legal types.
5808 EVT SplitSrcVT = SrcVT;
5809 EVT SplitDstVT = DstVT;
5810 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5811 SplitSrcVT.getVectorNumElements() > 1) {
5812 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5813 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5816 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5820 const unsigned NumSplits =
5821 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5822 const unsigned Stride = SplitSrcVT.getStoreSize();
5823 SmallVector<SDValue, 4> Loads;
5824 SmallVector<SDValue, 4> Chains;
5826 SDValue BasePtr = LN0->getBasePtr();
5827 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5828 const unsigned Offset = Idx * Stride;
5829 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5831 SDValue SplitLoad = DAG.getExtLoad(
5832 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5833 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5834 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5835 Align, LN0->getAAInfo());
5837 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5838 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5840 Loads.push_back(SplitLoad.getValue(0));
5841 Chains.push_back(SplitLoad.getValue(1));
5844 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5845 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5847 CombineTo(N, NewValue);
5849 // Replace uses of the original load (before extension)
5850 // with a truncate of the concatenated sextloaded vectors.
5852 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5853 CombineTo(N0.getNode(), Trunc, NewChain);
5854 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5855 (ISD::NodeType)N->getOpcode());
5856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5859 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5860 SDValue N0 = N->getOperand(0);
5861 EVT VT = N->getValueType(0);
5863 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5865 return SDValue(Res, 0);
5867 // fold (sext (sext x)) -> (sext x)
5868 // fold (sext (aext x)) -> (sext x)
5869 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5870 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5873 if (N0.getOpcode() == ISD::TRUNCATE) {
5874 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5875 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5876 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5877 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5878 if (NarrowLoad.getNode() != N0.getNode()) {
5879 CombineTo(N0.getNode(), NarrowLoad);
5880 // CombineTo deleted the truncate, if needed, but not what's under it.
5883 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5886 // See if the value being truncated is already sign extended. If so, just
5887 // eliminate the trunc/sext pair.
5888 SDValue Op = N0.getOperand(0);
5889 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5890 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5891 unsigned DestBits = VT.getScalarType().getSizeInBits();
5892 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5894 if (OpBits == DestBits) {
5895 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5896 // bits, it is already ready.
5897 if (NumSignBits > DestBits-MidBits)
5899 } else if (OpBits < DestBits) {
5900 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5901 // bits, just sext from i32.
5902 if (NumSignBits > OpBits-MidBits)
5903 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5905 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5906 // bits, just truncate to i32.
5907 if (NumSignBits > OpBits-MidBits)
5908 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5911 // fold (sext (truncate x)) -> (sextinreg x).
5912 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5913 N0.getValueType())) {
5914 if (OpBits < DestBits)
5915 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5916 else if (OpBits > DestBits)
5917 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5918 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5919 DAG.getValueType(N0.getValueType()));
5923 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5924 // Only generate vector extloads when 1) they're legal, and 2) they are
5925 // deemed desirable by the target.
5926 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5927 ((!LegalOperations && !VT.isVector() &&
5928 !cast<LoadSDNode>(N0)->isVolatile()) ||
5929 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5930 bool DoXform = true;
5931 SmallVector<SDNode*, 4> SetCCs;
5932 if (!N0.hasOneUse())
5933 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5935 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5938 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5940 LN0->getBasePtr(), N0.getValueType(),
5941 LN0->getMemOperand());
5942 CombineTo(N, ExtLoad);
5943 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5944 N0.getValueType(), ExtLoad);
5945 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5946 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5948 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5952 // fold (sext (load x)) to multiple smaller sextloads.
5953 // Only on illegal but splittable vectors.
5954 if (SDValue ExtLoad = CombineExtLoad(N))
5957 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5958 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5959 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5960 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5961 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5962 EVT MemVT = LN0->getMemoryVT();
5963 if ((!LegalOperations && !LN0->isVolatile()) ||
5964 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5965 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5967 LN0->getBasePtr(), MemVT,
5968 LN0->getMemOperand());
5969 CombineTo(N, ExtLoad);
5970 CombineTo(N0.getNode(),
5971 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5972 N0.getValueType(), ExtLoad),
5973 ExtLoad.getValue(1));
5974 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5978 // fold (sext (and/or/xor (load x), cst)) ->
5979 // (and/or/xor (sextload x), (sext cst))
5980 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5981 N0.getOpcode() == ISD::XOR) &&
5982 isa<LoadSDNode>(N0.getOperand(0)) &&
5983 N0.getOperand(1).getOpcode() == ISD::Constant &&
5984 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5985 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5986 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5987 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5988 bool DoXform = true;
5989 SmallVector<SDNode*, 4> SetCCs;
5990 if (!N0.hasOneUse())
5991 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5994 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5995 LN0->getChain(), LN0->getBasePtr(),
5997 LN0->getMemOperand());
5998 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5999 Mask = Mask.sext(VT.getSizeInBits());
6001 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6002 ExtLoad, DAG.getConstant(Mask, DL, VT));
6003 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6004 SDLoc(N0.getOperand(0)),
6005 N0.getOperand(0).getValueType(), ExtLoad);
6007 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6008 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6015 if (N0.getOpcode() == ISD::SETCC) {
6016 EVT N0VT = N0.getOperand(0).getValueType();
6017 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6018 // Only do this before legalize for now.
6019 if (VT.isVector() && !LegalOperations &&
6020 TLI.getBooleanContents(N0VT) ==
6021 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6022 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6023 // of the same size as the compared operands. Only optimize sext(setcc())
6024 // if this is the case.
6025 EVT SVT = getSetCCResultType(N0VT);
6027 // We know that the # elements of the results is the same as the
6028 // # elements of the compare (and the # elements of the compare result
6029 // for that matter). Check to see that they are the same size. If so,
6030 // we know that the element size of the sext'd result matches the
6031 // element size of the compare operands.
6032 if (VT.getSizeInBits() == SVT.getSizeInBits())
6033 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6035 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6037 // If the desired elements are smaller or larger than the source
6038 // elements we can use a matching integer vector type and then
6039 // truncate/sign extend
6040 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6041 if (SVT == MatchingVectorType) {
6042 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6043 N0.getOperand(0), N0.getOperand(1),
6044 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6045 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6049 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6050 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6053 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6055 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6056 NegOne, DAG.getConstant(0, DL, VT),
6057 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6058 if (SCC.getNode()) return SCC;
6060 if (!VT.isVector()) {
6061 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6062 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6064 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6065 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6066 N0.getOperand(0), N0.getOperand(1), CC);
6067 return DAG.getSelect(DL, VT, SetCC,
6068 NegOne, DAG.getConstant(0, DL, VT));
6073 // fold (sext x) -> (zext x) if the sign bit is known zero.
6074 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6075 DAG.SignBitIsZero(N0))
6076 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6081 // isTruncateOf - If N is a truncate of some other value, return true, record
6082 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6083 // This function computes KnownZero to avoid a duplicated call to
6084 // computeKnownBits in the caller.
6085 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6088 if (N->getOpcode() == ISD::TRUNCATE) {
6089 Op = N->getOperand(0);
6090 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6094 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6095 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6098 SDValue Op0 = N->getOperand(0);
6099 SDValue Op1 = N->getOperand(1);
6100 assert(Op0.getValueType() == Op1.getValueType());
6102 if (isNullConstant(Op0))
6104 else if (isNullConstant(Op1))
6109 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6111 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6117 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6118 SDValue N0 = N->getOperand(0);
6119 EVT VT = N->getValueType(0);
6121 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6123 return SDValue(Res, 0);
6125 // fold (zext (zext x)) -> (zext x)
6126 // fold (zext (aext x)) -> (zext x)
6127 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6128 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6131 // fold (zext (truncate x)) -> (zext x) or
6132 // (zext (truncate x)) -> (truncate x)
6133 // This is valid when the truncated bits of x are already zero.
6134 // FIXME: We should extend this to work for vectors too.
6137 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6138 APInt TruncatedBits =
6139 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6140 APInt(Op.getValueSizeInBits(), 0) :
6141 APInt::getBitsSet(Op.getValueSizeInBits(),
6142 N0.getValueSizeInBits(),
6143 std::min(Op.getValueSizeInBits(),
6144 VT.getSizeInBits()));
6145 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6146 if (VT.bitsGT(Op.getValueType()))
6147 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6148 if (VT.bitsLT(Op.getValueType()))
6149 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6155 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6156 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6157 if (N0.getOpcode() == ISD::TRUNCATE) {
6158 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6159 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6160 if (NarrowLoad.getNode() != N0.getNode()) {
6161 CombineTo(N0.getNode(), NarrowLoad);
6162 // CombineTo deleted the truncate, if needed, but not what's under it.
6165 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6169 // fold (zext (truncate x)) -> (and x, mask)
6170 if (N0.getOpcode() == ISD::TRUNCATE) {
6171 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6172 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6173 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6174 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6175 if (NarrowLoad.getNode() != N0.getNode()) {
6176 CombineTo(N0.getNode(), NarrowLoad);
6177 // CombineTo deleted the truncate, if needed, but not what's under it.
6180 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6183 EVT SrcVT = N0.getOperand(0).getValueType();
6184 EVT MinVT = N0.getValueType();
6186 // Try to mask before the extension to avoid having to generate a larger mask,
6187 // possibly over several sub-vectors.
6188 if (SrcVT.bitsLT(VT)) {
6189 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6190 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6191 SDValue Op = N0.getOperand(0);
6192 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6193 AddToWorklist(Op.getNode());
6194 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6198 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6199 SDValue Op = N0.getOperand(0);
6200 if (SrcVT.bitsLT(VT)) {
6201 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6202 AddToWorklist(Op.getNode());
6203 } else if (SrcVT.bitsGT(VT)) {
6204 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6205 AddToWorklist(Op.getNode());
6207 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6211 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6212 // if either of the casts is not free.
6213 if (N0.getOpcode() == ISD::AND &&
6214 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6215 N0.getOperand(1).getOpcode() == ISD::Constant &&
6216 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6217 N0.getValueType()) ||
6218 !TLI.isZExtFree(N0.getValueType(), VT))) {
6219 SDValue X = N0.getOperand(0).getOperand(0);
6220 if (X.getValueType().bitsLT(VT)) {
6221 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6222 } else if (X.getValueType().bitsGT(VT)) {
6223 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6225 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6226 Mask = Mask.zext(VT.getSizeInBits());
6228 return DAG.getNode(ISD::AND, DL, VT,
6229 X, DAG.getConstant(Mask, DL, VT));
6232 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6233 // Only generate vector extloads when 1) they're legal, and 2) they are
6234 // deemed desirable by the target.
6235 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6236 ((!LegalOperations && !VT.isVector() &&
6237 !cast<LoadSDNode>(N0)->isVolatile()) ||
6238 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6239 bool DoXform = true;
6240 SmallVector<SDNode*, 4> SetCCs;
6241 if (!N0.hasOneUse())
6242 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6244 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6246 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6247 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6249 LN0->getBasePtr(), N0.getValueType(),
6250 LN0->getMemOperand());
6251 CombineTo(N, ExtLoad);
6252 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6253 N0.getValueType(), ExtLoad);
6254 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6256 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6258 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6262 // fold (zext (load x)) to multiple smaller zextloads.
6263 // Only on illegal but splittable vectors.
6264 if (SDValue ExtLoad = CombineExtLoad(N))
6267 // fold (zext (and/or/xor (load x), cst)) ->
6268 // (and/or/xor (zextload x), (zext cst))
6269 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6270 N0.getOpcode() == ISD::XOR) &&
6271 isa<LoadSDNode>(N0.getOperand(0)) &&
6272 N0.getOperand(1).getOpcode() == ISD::Constant &&
6273 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6274 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6275 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6276 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6277 bool DoXform = true;
6278 SmallVector<SDNode*, 4> SetCCs;
6279 if (!N0.hasOneUse())
6280 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6283 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6284 LN0->getChain(), LN0->getBasePtr(),
6286 LN0->getMemOperand());
6287 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6288 Mask = Mask.zext(VT.getSizeInBits());
6290 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6291 ExtLoad, DAG.getConstant(Mask, DL, VT));
6292 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6293 SDLoc(N0.getOperand(0)),
6294 N0.getOperand(0).getValueType(), ExtLoad);
6296 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6297 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6299 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6304 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6305 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6306 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6307 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6308 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6309 EVT MemVT = LN0->getMemoryVT();
6310 if ((!LegalOperations && !LN0->isVolatile()) ||
6311 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6312 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6314 LN0->getBasePtr(), MemVT,
6315 LN0->getMemOperand());
6316 CombineTo(N, ExtLoad);
6317 CombineTo(N0.getNode(),
6318 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6320 ExtLoad.getValue(1));
6321 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6325 if (N0.getOpcode() == ISD::SETCC) {
6326 if (!LegalOperations && VT.isVector() &&
6327 N0.getValueType().getVectorElementType() == MVT::i1) {
6328 EVT N0VT = N0.getOperand(0).getValueType();
6329 if (getSetCCResultType(N0VT) == N0.getValueType())
6332 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6333 // Only do this before legalize for now.
6334 EVT EltVT = VT.getVectorElementType();
6336 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6337 DAG.getConstant(1, DL, EltVT));
6338 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6339 // We know that the # elements of the results is the same as the
6340 // # elements of the compare (and the # elements of the compare result
6341 // for that matter). Check to see that they are the same size. If so,
6342 // we know that the element size of the sext'd result matches the
6343 // element size of the compare operands.
6344 return DAG.getNode(ISD::AND, DL, VT,
6345 DAG.getSetCC(DL, VT, N0.getOperand(0),
6347 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6348 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6351 // If the desired elements are smaller or larger than the source
6352 // elements we can use a matching integer vector type and then
6353 // truncate/sign extend
6354 EVT MatchingElementType =
6355 EVT::getIntegerVT(*DAG.getContext(),
6356 N0VT.getScalarType().getSizeInBits());
6357 EVT MatchingVectorType =
6358 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6359 N0VT.getVectorNumElements());
6361 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6363 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6364 return DAG.getNode(ISD::AND, DL, VT,
6365 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6366 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6369 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6372 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6373 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6374 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6375 if (SCC.getNode()) return SCC;
6378 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6379 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6380 isa<ConstantSDNode>(N0.getOperand(1)) &&
6381 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6383 SDValue ShAmt = N0.getOperand(1);
6384 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6385 if (N0.getOpcode() == ISD::SHL) {
6386 SDValue InnerZExt = N0.getOperand(0);
6387 // If the original shl may be shifting out bits, do not perform this
6389 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6390 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6391 if (ShAmtVal > KnownZeroBits)
6397 // Ensure that the shift amount is wide enough for the shifted value.
6398 if (VT.getSizeInBits() >= 256)
6399 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6401 return DAG.getNode(N0.getOpcode(), DL, VT,
6402 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6409 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6410 SDValue N0 = N->getOperand(0);
6411 EVT VT = N->getValueType(0);
6413 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6415 return SDValue(Res, 0);
6417 // fold (aext (aext x)) -> (aext x)
6418 // fold (aext (zext x)) -> (zext x)
6419 // fold (aext (sext x)) -> (sext x)
6420 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6421 N0.getOpcode() == ISD::ZERO_EXTEND ||
6422 N0.getOpcode() == ISD::SIGN_EXTEND)
6423 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6425 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6426 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6427 if (N0.getOpcode() == ISD::TRUNCATE) {
6428 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6429 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6430 if (NarrowLoad.getNode() != N0.getNode()) {
6431 CombineTo(N0.getNode(), NarrowLoad);
6432 // CombineTo deleted the truncate, if needed, but not what's under it.
6435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6439 // fold (aext (truncate x))
6440 if (N0.getOpcode() == ISD::TRUNCATE) {
6441 SDValue TruncOp = N0.getOperand(0);
6442 if (TruncOp.getValueType() == VT)
6443 return TruncOp; // x iff x size == zext size.
6444 if (TruncOp.getValueType().bitsGT(VT))
6445 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6446 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6449 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6450 // if the trunc is not free.
6451 if (N0.getOpcode() == ISD::AND &&
6452 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6453 N0.getOperand(1).getOpcode() == ISD::Constant &&
6454 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6455 N0.getValueType())) {
6456 SDValue X = N0.getOperand(0).getOperand(0);
6457 if (X.getValueType().bitsLT(VT)) {
6458 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6459 } else if (X.getValueType().bitsGT(VT)) {
6460 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6462 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6463 Mask = Mask.zext(VT.getSizeInBits());
6465 return DAG.getNode(ISD::AND, DL, VT,
6466 X, DAG.getConstant(Mask, DL, VT));
6469 // fold (aext (load x)) -> (aext (truncate (extload x)))
6470 // None of the supported targets knows how to perform load and any_ext
6471 // on vectors in one instruction. We only perform this transformation on
6473 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6474 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6475 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6476 bool DoXform = true;
6477 SmallVector<SDNode*, 4> SetCCs;
6478 if (!N0.hasOneUse())
6479 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6481 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6482 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6484 LN0->getBasePtr(), N0.getValueType(),
6485 LN0->getMemOperand());
6486 CombineTo(N, ExtLoad);
6487 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6488 N0.getValueType(), ExtLoad);
6489 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6490 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6496 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6497 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6498 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6499 if (N0.getOpcode() == ISD::LOAD &&
6500 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6502 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6503 ISD::LoadExtType ExtType = LN0->getExtensionType();
6504 EVT MemVT = LN0->getMemoryVT();
6505 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6506 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6507 VT, LN0->getChain(), LN0->getBasePtr(),
6508 MemVT, LN0->getMemOperand());
6509 CombineTo(N, ExtLoad);
6510 CombineTo(N0.getNode(),
6511 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6512 N0.getValueType(), ExtLoad),
6513 ExtLoad.getValue(1));
6514 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6518 if (N0.getOpcode() == ISD::SETCC) {
6520 // aext(setcc) -> vsetcc
6521 // aext(setcc) -> truncate(vsetcc)
6522 // aext(setcc) -> aext(vsetcc)
6523 // Only do this before legalize for now.
6524 if (VT.isVector() && !LegalOperations) {
6525 EVT N0VT = N0.getOperand(0).getValueType();
6526 // We know that the # elements of the results is the same as the
6527 // # elements of the compare (and the # elements of the compare result
6528 // for that matter). Check to see that they are the same size. If so,
6529 // we know that the element size of the sext'd result matches the
6530 // element size of the compare operands.
6531 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6532 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6534 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6535 // If the desired elements are smaller or larger than the source
6536 // elements we can use a matching integer vector type and then
6537 // truncate/any extend
6539 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6541 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6543 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6544 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6548 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6551 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6552 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6553 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6561 /// See if the specified operand can be simplified with the knowledge that only
6562 /// the bits specified by Mask are used. If so, return the simpler operand,
6563 /// otherwise return a null SDValue.
6564 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6565 switch (V.getOpcode()) {
6567 case ISD::Constant: {
6568 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6569 assert(CV && "Const value should be ConstSDNode.");
6570 const APInt &CVal = CV->getAPIntValue();
6571 APInt NewVal = CVal & Mask;
6573 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6578 // If the LHS or RHS don't contribute bits to the or, drop them.
6579 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6580 return V.getOperand(1);
6581 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6582 return V.getOperand(0);
6585 // Only look at single-use SRLs.
6586 if (!V.getNode()->hasOneUse())
6588 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6589 // See if we can recursively simplify the LHS.
6590 unsigned Amt = RHSC->getZExtValue();
6592 // Watch out for shift count overflow though.
6593 if (Amt >= Mask.getBitWidth()) break;
6594 APInt NewMask = Mask << Amt;
6595 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6596 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6597 SimplifyLHS, V.getOperand(1));
6603 /// If the result of a wider load is shifted to right of N bits and then
6604 /// truncated to a narrower type and where N is a multiple of number of bits of
6605 /// the narrower type, transform it to a narrower load from address + N / num of
6606 /// bits of new type. If the result is to be extended, also fold the extension
6607 /// to form a extending load.
6608 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6609 unsigned Opc = N->getOpcode();
6611 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6612 SDValue N0 = N->getOperand(0);
6613 EVT VT = N->getValueType(0);
6616 // This transformation isn't valid for vector loads.
6620 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6622 if (Opc == ISD::SIGN_EXTEND_INREG) {
6623 ExtType = ISD::SEXTLOAD;
6624 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6625 } else if (Opc == ISD::SRL) {
6626 // Another special-case: SRL is basically zero-extending a narrower value.
6627 ExtType = ISD::ZEXTLOAD;
6629 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6630 if (!N01) return SDValue();
6631 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6632 VT.getSizeInBits() - N01->getZExtValue());
6634 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6637 unsigned EVTBits = ExtVT.getSizeInBits();
6639 // Do not generate loads of non-round integer types since these can
6640 // be expensive (and would be wrong if the type is not byte sized).
6641 if (!ExtVT.isRound())
6645 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6646 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6647 ShAmt = N01->getZExtValue();
6648 // Is the shift amount a multiple of size of VT?
6649 if ((ShAmt & (EVTBits-1)) == 0) {
6650 N0 = N0.getOperand(0);
6651 // Is the load width a multiple of size of VT?
6652 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6656 // At this point, we must have a load or else we can't do the transform.
6657 if (!isa<LoadSDNode>(N0)) return SDValue();
6659 // Because a SRL must be assumed to *need* to zero-extend the high bits
6660 // (as opposed to anyext the high bits), we can't combine the zextload
6661 // lowering of SRL and an sextload.
6662 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6665 // If the shift amount is larger than the input type then we're not
6666 // accessing any of the loaded bytes. If the load was a zextload/extload
6667 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6668 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6673 // If the load is shifted left (and the result isn't shifted back right),
6674 // we can fold the truncate through the shift.
6675 unsigned ShLeftAmt = 0;
6676 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6677 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6678 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6679 ShLeftAmt = N01->getZExtValue();
6680 N0 = N0.getOperand(0);
6684 // If we haven't found a load, we can't narrow it. Don't transform one with
6685 // multiple uses, this would require adding a new load.
6686 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6689 // Don't change the width of a volatile load.
6690 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6691 if (LN0->isVolatile())
6694 // Verify that we are actually reducing a load width here.
6695 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6698 // For the transform to be legal, the load must produce only two values
6699 // (the value loaded and the chain). Don't transform a pre-increment
6700 // load, for example, which produces an extra value. Otherwise the
6701 // transformation is not equivalent, and the downstream logic to replace
6702 // uses gets things wrong.
6703 if (LN0->getNumValues() > 2)
6706 // If the load that we're shrinking is an extload and we're not just
6707 // discarding the extension we can't simply shrink the load. Bail.
6708 // TODO: It would be possible to merge the extensions in some cases.
6709 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6710 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6713 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6716 EVT PtrType = N0.getOperand(1).getValueType();
6718 if (PtrType == MVT::Untyped || PtrType.isExtended())
6719 // It's not possible to generate a constant of extended or untyped type.
6722 // For big endian targets, we need to adjust the offset to the pointer to
6723 // load the correct bytes.
6724 if (DAG.getDataLayout().isBigEndian()) {
6725 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6726 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6727 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6730 uint64_t PtrOff = ShAmt / 8;
6731 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6733 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6734 PtrType, LN0->getBasePtr(),
6735 DAG.getConstant(PtrOff, DL, PtrType));
6736 AddToWorklist(NewPtr.getNode());
6739 if (ExtType == ISD::NON_EXTLOAD)
6740 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6741 LN0->getPointerInfo().getWithOffset(PtrOff),
6742 LN0->isVolatile(), LN0->isNonTemporal(),
6743 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6745 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6746 LN0->getPointerInfo().getWithOffset(PtrOff),
6747 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6748 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6750 // Replace the old load's chain with the new load's chain.
6751 WorklistRemover DeadNodes(*this);
6752 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6754 // Shift the result left, if we've swallowed a left shift.
6755 SDValue Result = Load;
6756 if (ShLeftAmt != 0) {
6757 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6758 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6760 // If the shift amount is as large as the result size (but, presumably,
6761 // no larger than the source) then the useful bits of the result are
6762 // zero; we can't simply return the shortened shift, because the result
6763 // of that operation is undefined.
6765 if (ShLeftAmt >= VT.getSizeInBits())
6766 Result = DAG.getConstant(0, DL, VT);
6768 Result = DAG.getNode(ISD::SHL, DL, VT,
6769 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6772 // Return the new loaded value.
6776 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6777 SDValue N0 = N->getOperand(0);
6778 SDValue N1 = N->getOperand(1);
6779 EVT VT = N->getValueType(0);
6780 EVT EVT = cast<VTSDNode>(N1)->getVT();
6781 unsigned VTBits = VT.getScalarType().getSizeInBits();
6782 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6784 // fold (sext_in_reg c1) -> c1
6785 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6786 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6788 // If the input is already sign extended, just drop the extension.
6789 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6792 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6793 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6794 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6795 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6796 N0.getOperand(0), N1);
6798 // fold (sext_in_reg (sext x)) -> (sext x)
6799 // fold (sext_in_reg (aext x)) -> (sext x)
6800 // if x is small enough.
6801 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6802 SDValue N00 = N0.getOperand(0);
6803 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6804 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6805 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6808 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6809 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6810 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6812 // fold operands of sext_in_reg based on knowledge that the top bits are not
6814 if (SimplifyDemandedBits(SDValue(N, 0)))
6815 return SDValue(N, 0);
6817 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6818 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6819 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6822 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6823 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6824 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6825 if (N0.getOpcode() == ISD::SRL) {
6826 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6827 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6828 // We can turn this into an SRA iff the input to the SRL is already sign
6830 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6831 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6832 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6833 N0.getOperand(0), N0.getOperand(1));
6837 // fold (sext_inreg (extload x)) -> (sextload x)
6838 if (ISD::isEXTLoad(N0.getNode()) &&
6839 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6840 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6841 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6842 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6844 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6846 LN0->getBasePtr(), EVT,
6847 LN0->getMemOperand());
6848 CombineTo(N, ExtLoad);
6849 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6850 AddToWorklist(ExtLoad.getNode());
6851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6853 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6854 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6856 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6857 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6858 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6859 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6860 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6862 LN0->getBasePtr(), EVT,
6863 LN0->getMemOperand());
6864 CombineTo(N, ExtLoad);
6865 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6869 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6870 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6871 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6872 N0.getOperand(1), false);
6873 if (BSwap.getNode())
6874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6878 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6879 // into a build_vector.
6880 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6881 SmallVector<SDValue, 8> Elts;
6882 unsigned NumElts = N0->getNumOperands();
6883 unsigned ShAmt = VTBits - EVTBits;
6885 for (unsigned i = 0; i != NumElts; ++i) {
6886 SDValue Op = N0->getOperand(i);
6887 if (Op->getOpcode() == ISD::UNDEF) {
6892 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6893 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6894 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6895 SDLoc(Op), Op.getValueType()));
6898 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6904 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6905 SDValue N0 = N->getOperand(0);
6906 EVT VT = N->getValueType(0);
6908 if (N0.getOpcode() == ISD::UNDEF)
6909 return DAG.getUNDEF(VT);
6911 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6913 return SDValue(Res, 0);
6918 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6919 SDValue N0 = N->getOperand(0);
6920 EVT VT = N->getValueType(0);
6921 bool isLE = DAG.getDataLayout().isLittleEndian();
6924 if (N0.getValueType() == N->getValueType(0))
6926 // fold (truncate c1) -> c1
6927 if (isConstantIntBuildVectorOrConstantInt(N0))
6928 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6929 // fold (truncate (truncate x)) -> (truncate x)
6930 if (N0.getOpcode() == ISD::TRUNCATE)
6931 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6932 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6933 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6934 N0.getOpcode() == ISD::SIGN_EXTEND ||
6935 N0.getOpcode() == ISD::ANY_EXTEND) {
6936 if (N0.getOperand(0).getValueType().bitsLT(VT))
6937 // if the source is smaller than the dest, we still need an extend
6938 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6940 if (N0.getOperand(0).getValueType().bitsGT(VT))
6941 // if the source is larger than the dest, than we just need the truncate
6942 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6943 // if the source and dest are the same type, we can drop both the extend
6944 // and the truncate.
6945 return N0.getOperand(0);
6948 // Fold extract-and-trunc into a narrow extract. For example:
6949 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6950 // i32 y = TRUNCATE(i64 x)
6952 // v16i8 b = BITCAST (v2i64 val)
6953 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6955 // Note: We only run this optimization after type legalization (which often
6956 // creates this pattern) and before operation legalization after which
6957 // we need to be more careful about the vector instructions that we generate.
6958 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6959 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6961 EVT VecTy = N0.getOperand(0).getValueType();
6962 EVT ExTy = N0.getValueType();
6963 EVT TrTy = N->getValueType(0);
6965 unsigned NumElem = VecTy.getVectorNumElements();
6966 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6968 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6969 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6971 SDValue EltNo = N0->getOperand(1);
6972 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6973 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6974 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6975 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6977 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6978 NVT, N0.getOperand(0));
6981 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6983 DAG.getConstant(Index, DL, IndexTy));
6987 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6988 if (N0.getOpcode() == ISD::SELECT) {
6989 EVT SrcVT = N0.getValueType();
6990 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6991 TLI.isTruncateFree(SrcVT, VT)) {
6993 SDValue Cond = N0.getOperand(0);
6994 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6995 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6996 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7000 // Fold a series of buildvector, bitcast, and truncate if possible.
7002 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7003 // (2xi32 (buildvector x, y)).
7004 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7005 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7006 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7007 N0.getOperand(0).hasOneUse()) {
7009 SDValue BuildVect = N0.getOperand(0);
7010 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7011 EVT TruncVecEltTy = VT.getVectorElementType();
7013 // Check that the element types match.
7014 if (BuildVectEltTy == TruncVecEltTy) {
7015 // Now we only need to compute the offset of the truncated elements.
7016 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7017 unsigned TruncVecNumElts = VT.getVectorNumElements();
7018 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7020 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7021 "Invalid number of elements");
7023 SmallVector<SDValue, 8> Opnds;
7024 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7025 Opnds.push_back(BuildVect.getOperand(i));
7027 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7031 // See if we can simplify the input to this truncate through knowledge that
7032 // only the low bits are being used.
7033 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7034 // Currently we only perform this optimization on scalars because vectors
7035 // may have different active low bits.
7036 if (!VT.isVector()) {
7038 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7039 VT.getSizeInBits()));
7040 if (Shorter.getNode())
7041 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7043 // fold (truncate (load x)) -> (smaller load x)
7044 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7045 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7046 if (SDValue Reduced = ReduceLoadWidth(N))
7049 // Handle the case where the load remains an extending load even
7050 // after truncation.
7051 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7052 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7053 if (!LN0->isVolatile() &&
7054 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7055 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7056 VT, LN0->getChain(), LN0->getBasePtr(),
7058 LN0->getMemOperand());
7059 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7064 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7065 // where ... are all 'undef'.
7066 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7067 SmallVector<EVT, 8> VTs;
7070 unsigned NumDefs = 0;
7072 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7073 SDValue X = N0.getOperand(i);
7074 if (X.getOpcode() != ISD::UNDEF) {
7079 // Stop if more than one members are non-undef.
7082 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7083 VT.getVectorElementType(),
7084 X.getValueType().getVectorNumElements()));
7088 return DAG.getUNDEF(VT);
7091 assert(V.getNode() && "The single defined operand is empty!");
7092 SmallVector<SDValue, 8> Opnds;
7093 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7095 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7098 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7099 AddToWorklist(NV.getNode());
7100 Opnds.push_back(NV);
7102 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7106 // Simplify the operands using demanded-bits information.
7107 if (!VT.isVector() &&
7108 SimplifyDemandedBits(SDValue(N, 0)))
7109 return SDValue(N, 0);
7114 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7115 SDValue Elt = N->getOperand(i);
7116 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7117 return Elt.getNode();
7118 return Elt.getOperand(Elt.getResNo()).getNode();
7121 /// build_pair (load, load) -> load
7122 /// if load locations are consecutive.
7123 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7124 assert(N->getOpcode() == ISD::BUILD_PAIR);
7126 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7127 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7128 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7129 LD1->getAddressSpace() != LD2->getAddressSpace())
7131 EVT LD1VT = LD1->getValueType(0);
7133 if (ISD::isNON_EXTLoad(LD2) &&
7135 // If both are volatile this would reduce the number of volatile loads.
7136 // If one is volatile it might be ok, but play conservative and bail out.
7137 !LD1->isVolatile() &&
7138 !LD2->isVolatile() &&
7139 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7140 unsigned Align = LD1->getAlignment();
7141 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7142 VT.getTypeForEVT(*DAG.getContext()));
7144 if (NewAlign <= Align &&
7145 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7146 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7147 LD1->getBasePtr(), LD1->getPointerInfo(),
7148 false, false, false, Align);
7154 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7155 SDValue N0 = N->getOperand(0);
7156 EVT VT = N->getValueType(0);
7158 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7159 // Only do this before legalize, since afterward the target may be depending
7160 // on the bitconvert.
7161 // First check to see if this is all constant.
7163 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7165 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7167 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7168 assert(!DestEltVT.isVector() &&
7169 "Element type of vector ValueType must not be vector!");
7171 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7174 // If the input is a constant, let getNode fold it.
7175 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7176 // If we can't allow illegal operations, we need to check that this is just
7177 // a fp -> int or int -> conversion and that the resulting operation will
7179 if (!LegalOperations ||
7180 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7181 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7182 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7183 TLI.isOperationLegal(ISD::Constant, VT)))
7184 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7187 // (conv (conv x, t1), t2) -> (conv x, t2)
7188 if (N0.getOpcode() == ISD::BITCAST)
7189 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7192 // fold (conv (load x)) -> (load (conv*)x)
7193 // If the resultant load doesn't need a higher alignment than the original!
7194 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7195 // Do not change the width of a volatile load.
7196 !cast<LoadSDNode>(N0)->isVolatile() &&
7197 // Do not remove the cast if the types differ in endian layout.
7198 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7199 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7200 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7201 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7202 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7203 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7204 VT.getTypeForEVT(*DAG.getContext()));
7205 unsigned OrigAlign = LN0->getAlignment();
7207 if (Align <= OrigAlign) {
7208 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7209 LN0->getBasePtr(), LN0->getPointerInfo(),
7210 LN0->isVolatile(), LN0->isNonTemporal(),
7211 LN0->isInvariant(), OrigAlign,
7213 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7218 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7219 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7220 // This often reduces constant pool loads.
7221 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7222 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7223 N0.getNode()->hasOneUse() && VT.isInteger() &&
7224 !VT.isVector() && !N0.getValueType().isVector()) {
7225 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7227 AddToWorklist(NewConv.getNode());
7230 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7231 if (N0.getOpcode() == ISD::FNEG)
7232 return DAG.getNode(ISD::XOR, DL, VT,
7233 NewConv, DAG.getConstant(SignBit, DL, VT));
7234 assert(N0.getOpcode() == ISD::FABS);
7235 return DAG.getNode(ISD::AND, DL, VT,
7236 NewConv, DAG.getConstant(~SignBit, DL, VT));
7239 // fold (bitconvert (fcopysign cst, x)) ->
7240 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7241 // Note that we don't handle (copysign x, cst) because this can always be
7242 // folded to an fneg or fabs.
7243 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7244 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7245 VT.isInteger() && !VT.isVector()) {
7246 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7247 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7248 if (isTypeLegal(IntXVT)) {
7249 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7250 IntXVT, N0.getOperand(1));
7251 AddToWorklist(X.getNode());
7253 // If X has a different width than the result/lhs, sext it or truncate it.
7254 unsigned VTWidth = VT.getSizeInBits();
7255 if (OrigXWidth < VTWidth) {
7256 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7257 AddToWorklist(X.getNode());
7258 } else if (OrigXWidth > VTWidth) {
7259 // To get the sign bit in the right place, we have to shift it right
7260 // before truncating.
7262 X = DAG.getNode(ISD::SRL, DL,
7263 X.getValueType(), X,
7264 DAG.getConstant(OrigXWidth-VTWidth, DL,
7266 AddToWorklist(X.getNode());
7267 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7268 AddToWorklist(X.getNode());
7271 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7272 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7273 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7274 AddToWorklist(X.getNode());
7276 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7277 VT, N0.getOperand(0));
7278 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7279 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7280 AddToWorklist(Cst.getNode());
7282 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7286 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7287 if (N0.getOpcode() == ISD::BUILD_PAIR)
7288 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7291 // Remove double bitcasts from shuffles - this is often a legacy of
7292 // XformToShuffleWithZero being used to combine bitmaskings (of
7293 // float vectors bitcast to integer vectors) into shuffles.
7294 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7295 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7296 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7297 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7298 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7299 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7301 // If operands are a bitcast, peek through if it casts the original VT.
7302 // If operands are a constant, just bitcast back to original VT.
7303 auto PeekThroughBitcast = [&](SDValue Op) {
7304 if (Op.getOpcode() == ISD::BITCAST &&
7305 Op.getOperand(0).getValueType() == VT)
7306 return SDValue(Op.getOperand(0));
7307 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7308 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7309 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7313 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7314 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7319 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7320 SmallVector<int, 8> NewMask;
7321 for (int M : SVN->getMask())
7322 for (int i = 0; i != MaskScale; ++i)
7323 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7325 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7327 std::swap(SV0, SV1);
7328 ShuffleVectorSDNode::commuteMask(NewMask);
7329 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7333 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7339 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7340 EVT VT = N->getValueType(0);
7341 return CombineConsecutiveLoads(N, VT);
7344 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7345 /// operands. DstEltVT indicates the destination element value type.
7346 SDValue DAGCombiner::
7347 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7348 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7350 // If this is already the right type, we're done.
7351 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7353 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7354 unsigned DstBitSize = DstEltVT.getSizeInBits();
7356 // If this is a conversion of N elements of one type to N elements of another
7357 // type, convert each element. This handles FP<->INT cases.
7358 if (SrcBitSize == DstBitSize) {
7359 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7360 BV->getValueType(0).getVectorNumElements());
7362 // Due to the FP element handling below calling this routine recursively,
7363 // we can end up with a scalar-to-vector node here.
7364 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7365 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7366 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7367 DstEltVT, BV->getOperand(0)));
7369 SmallVector<SDValue, 8> Ops;
7370 for (SDValue Op : BV->op_values()) {
7371 // If the vector element type is not legal, the BUILD_VECTOR operands
7372 // are promoted and implicitly truncated. Make that explicit here.
7373 if (Op.getValueType() != SrcEltVT)
7374 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7375 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7377 AddToWorklist(Ops.back().getNode());
7379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7382 // Otherwise, we're growing or shrinking the elements. To avoid having to
7383 // handle annoying details of growing/shrinking FP values, we convert them to
7385 if (SrcEltVT.isFloatingPoint()) {
7386 // Convert the input float vector to a int vector where the elements are the
7388 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7389 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7393 // Now we know the input is an integer vector. If the output is a FP type,
7394 // convert to integer first, then to FP of the right size.
7395 if (DstEltVT.isFloatingPoint()) {
7396 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7397 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7399 // Next, convert to FP elements of the same size.
7400 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7405 // Okay, we know the src/dst types are both integers of differing types.
7406 // Handling growing first.
7407 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7408 if (SrcBitSize < DstBitSize) {
7409 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7411 SmallVector<SDValue, 8> Ops;
7412 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7413 i += NumInputsPerOutput) {
7414 bool isLE = DAG.getDataLayout().isLittleEndian();
7415 APInt NewBits = APInt(DstBitSize, 0);
7416 bool EltIsUndef = true;
7417 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7418 // Shift the previously computed bits over.
7419 NewBits <<= SrcBitSize;
7420 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7421 if (Op.getOpcode() == ISD::UNDEF) continue;
7424 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7425 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7429 Ops.push_back(DAG.getUNDEF(DstEltVT));
7431 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7434 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7435 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7438 // Finally, this must be the case where we are shrinking elements: each input
7439 // turns into multiple outputs.
7440 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7441 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7442 NumOutputsPerInput*BV->getNumOperands());
7443 SmallVector<SDValue, 8> Ops;
7445 for (const SDValue &Op : BV->op_values()) {
7446 if (Op.getOpcode() == ISD::UNDEF) {
7447 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7451 APInt OpVal = cast<ConstantSDNode>(Op)->
7452 getAPIntValue().zextOrTrunc(SrcBitSize);
7454 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7455 APInt ThisVal = OpVal.trunc(DstBitSize);
7456 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7457 OpVal = OpVal.lshr(DstBitSize);
7460 // For big endian targets, swap the order of the pieces of each element.
7461 if (DAG.getDataLayout().isBigEndian())
7462 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7465 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7468 /// Try to perform FMA combining on a given FADD node.
7469 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7470 SDValue N0 = N->getOperand(0);
7471 SDValue N1 = N->getOperand(1);
7472 EVT VT = N->getValueType(0);
7475 const TargetOptions &Options = DAG.getTarget().Options;
7476 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7477 Options.UnsafeFPMath);
7479 // Floating-point multiply-add with intermediate rounding.
7480 bool HasFMAD = (LegalOperations &&
7481 TLI.isOperationLegal(ISD::FMAD, VT));
7483 // Floating-point multiply-add without intermediate rounding.
7484 bool HasFMA = ((!LegalOperations ||
7485 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7486 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7489 // No valid opcode, do not combine.
7490 if (!HasFMAD && !HasFMA)
7493 // Always prefer FMAD to FMA for precision.
7494 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7495 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7496 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7498 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7499 // prefer to fold the multiply with fewer uses.
7500 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7501 N1.getOpcode() == ISD::FMUL) {
7502 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7506 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7507 if (N0.getOpcode() == ISD::FMUL &&
7508 (Aggressive || N0->hasOneUse())) {
7509 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7510 N0.getOperand(0), N0.getOperand(1), N1);
7513 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7514 // Note: Commutes FADD operands.
7515 if (N1.getOpcode() == ISD::FMUL &&
7516 (Aggressive || N1->hasOneUse())) {
7517 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518 N1.getOperand(0), N1.getOperand(1), N0);
7521 // Look through FP_EXTEND nodes to do more combining.
7522 if (UnsafeFPMath && LookThroughFPExt) {
7523 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7524 if (N0.getOpcode() == ISD::FP_EXTEND) {
7525 SDValue N00 = N0.getOperand(0);
7526 if (N00.getOpcode() == ISD::FMUL)
7527 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7528 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7530 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7531 N00.getOperand(1)), N1);
7534 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7535 // Note: Commutes FADD operands.
7536 if (N1.getOpcode() == ISD::FP_EXTEND) {
7537 SDValue N10 = N1.getOperand(0);
7538 if (N10.getOpcode() == ISD::FMUL)
7539 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7540 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7542 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7543 N10.getOperand(1)), N0);
7547 // More folding opportunities when target permits.
7548 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7549 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7550 if (N0.getOpcode() == PreferredFusedOpcode &&
7551 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7552 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7553 N0.getOperand(0), N0.getOperand(1),
7554 DAG.getNode(PreferredFusedOpcode, SL, VT,
7555 N0.getOperand(2).getOperand(0),
7556 N0.getOperand(2).getOperand(1),
7560 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7561 if (N1->getOpcode() == PreferredFusedOpcode &&
7562 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7563 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7564 N1.getOperand(0), N1.getOperand(1),
7565 DAG.getNode(PreferredFusedOpcode, SL, VT,
7566 N1.getOperand(2).getOperand(0),
7567 N1.getOperand(2).getOperand(1),
7571 if (UnsafeFPMath && LookThroughFPExt) {
7572 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7573 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7574 auto FoldFAddFMAFPExtFMul = [&] (
7575 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7576 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7577 DAG.getNode(PreferredFusedOpcode, SL, VT,
7578 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7579 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7582 if (N0.getOpcode() == PreferredFusedOpcode) {
7583 SDValue N02 = N0.getOperand(2);
7584 if (N02.getOpcode() == ISD::FP_EXTEND) {
7585 SDValue N020 = N02.getOperand(0);
7586 if (N020.getOpcode() == ISD::FMUL)
7587 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7588 N020.getOperand(0), N020.getOperand(1),
7593 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7594 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7595 // FIXME: This turns two single-precision and one double-precision
7596 // operation into two double-precision operations, which might not be
7597 // interesting for all targets, especially GPUs.
7598 auto FoldFAddFPExtFMAFMul = [&] (
7599 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7600 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7601 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7602 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7603 DAG.getNode(PreferredFusedOpcode, SL, VT,
7604 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7605 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7608 if (N0.getOpcode() == ISD::FP_EXTEND) {
7609 SDValue N00 = N0.getOperand(0);
7610 if (N00.getOpcode() == PreferredFusedOpcode) {
7611 SDValue N002 = N00.getOperand(2);
7612 if (N002.getOpcode() == ISD::FMUL)
7613 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7614 N002.getOperand(0), N002.getOperand(1),
7619 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7620 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7621 if (N1.getOpcode() == PreferredFusedOpcode) {
7622 SDValue N12 = N1.getOperand(2);
7623 if (N12.getOpcode() == ISD::FP_EXTEND) {
7624 SDValue N120 = N12.getOperand(0);
7625 if (N120.getOpcode() == ISD::FMUL)
7626 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7627 N120.getOperand(0), N120.getOperand(1),
7632 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7633 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7634 // FIXME: This turns two single-precision and one double-precision
7635 // operation into two double-precision operations, which might not be
7636 // interesting for all targets, especially GPUs.
7637 if (N1.getOpcode() == ISD::FP_EXTEND) {
7638 SDValue N10 = N1.getOperand(0);
7639 if (N10.getOpcode() == PreferredFusedOpcode) {
7640 SDValue N102 = N10.getOperand(2);
7641 if (N102.getOpcode() == ISD::FMUL)
7642 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7643 N102.getOperand(0), N102.getOperand(1),
7653 /// Try to perform FMA combining on a given FSUB node.
7654 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7655 SDValue N0 = N->getOperand(0);
7656 SDValue N1 = N->getOperand(1);
7657 EVT VT = N->getValueType(0);
7660 const TargetOptions &Options = DAG.getTarget().Options;
7661 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7662 Options.UnsafeFPMath);
7664 // Floating-point multiply-add with intermediate rounding.
7665 bool HasFMAD = (LegalOperations &&
7666 TLI.isOperationLegal(ISD::FMAD, VT));
7668 // Floating-point multiply-add without intermediate rounding.
7669 bool HasFMA = ((!LegalOperations ||
7670 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7671 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7674 // No valid opcode, do not combine.
7675 if (!HasFMAD && !HasFMA)
7678 // Always prefer FMAD to FMA for precision.
7679 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7680 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7681 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7683 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7684 if (N0.getOpcode() == ISD::FMUL &&
7685 (Aggressive || N0->hasOneUse())) {
7686 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7687 N0.getOperand(0), N0.getOperand(1),
7688 DAG.getNode(ISD::FNEG, SL, VT, N1));
7691 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7692 // Note: Commutes FSUB operands.
7693 if (N1.getOpcode() == ISD::FMUL &&
7694 (Aggressive || N1->hasOneUse()))
7695 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7696 DAG.getNode(ISD::FNEG, SL, VT,
7698 N1.getOperand(1), N0);
7700 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7701 if (N0.getOpcode() == ISD::FNEG &&
7702 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7703 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7704 SDValue N00 = N0.getOperand(0).getOperand(0);
7705 SDValue N01 = N0.getOperand(0).getOperand(1);
7706 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7707 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7708 DAG.getNode(ISD::FNEG, SL, VT, N1));
7711 // Look through FP_EXTEND nodes to do more combining.
7712 if (UnsafeFPMath && LookThroughFPExt) {
7713 // fold (fsub (fpext (fmul x, y)), z)
7714 // -> (fma (fpext x), (fpext y), (fneg z))
7715 if (N0.getOpcode() == ISD::FP_EXTEND) {
7716 SDValue N00 = N0.getOperand(0);
7717 if (N00.getOpcode() == ISD::FMUL)
7718 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7719 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723 DAG.getNode(ISD::FNEG, SL, VT, N1));
7726 // fold (fsub x, (fpext (fmul y, z)))
7727 // -> (fma (fneg (fpext y)), (fpext z), x)
7728 // Note: Commutes FSUB operands.
7729 if (N1.getOpcode() == ISD::FP_EXTEND) {
7730 SDValue N10 = N1.getOperand(0);
7731 if (N10.getOpcode() == ISD::FMUL)
7732 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7733 DAG.getNode(ISD::FNEG, SL, VT,
7734 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7735 N10.getOperand(0))),
7736 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7741 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7742 // -> (fneg (fma (fpext x), (fpext y), z))
7743 // Note: This could be removed with appropriate canonicalization of the
7744 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7745 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7746 // from implementing the canonicalization in visitFSUB.
7747 if (N0.getOpcode() == ISD::FP_EXTEND) {
7748 SDValue N00 = N0.getOperand(0);
7749 if (N00.getOpcode() == ISD::FNEG) {
7750 SDValue N000 = N00.getOperand(0);
7751 if (N000.getOpcode() == ISD::FMUL) {
7752 return DAG.getNode(ISD::FNEG, SL, VT,
7753 DAG.getNode(PreferredFusedOpcode, SL, VT,
7754 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7755 N000.getOperand(0)),
7756 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7757 N000.getOperand(1)),
7763 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7764 // -> (fneg (fma (fpext x)), (fpext y), z)
7765 // Note: This could be removed with appropriate canonicalization of the
7766 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7767 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7768 // from implementing the canonicalization in visitFSUB.
7769 if (N0.getOpcode() == ISD::FNEG) {
7770 SDValue N00 = N0.getOperand(0);
7771 if (N00.getOpcode() == ISD::FP_EXTEND) {
7772 SDValue N000 = N00.getOperand(0);
7773 if (N000.getOpcode() == ISD::FMUL) {
7774 return DAG.getNode(ISD::FNEG, SL, VT,
7775 DAG.getNode(PreferredFusedOpcode, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777 N000.getOperand(0)),
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779 N000.getOperand(1)),
7787 // More folding opportunities when target permits.
7788 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7789 // fold (fsub (fma x, y, (fmul u, v)), z)
7790 // -> (fma x, y (fma u, v, (fneg z)))
7791 if (N0.getOpcode() == PreferredFusedOpcode &&
7792 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7793 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7794 N0.getOperand(0), N0.getOperand(1),
7795 DAG.getNode(PreferredFusedOpcode, SL, VT,
7796 N0.getOperand(2).getOperand(0),
7797 N0.getOperand(2).getOperand(1),
7798 DAG.getNode(ISD::FNEG, SL, VT,
7802 // fold (fsub x, (fma y, z, (fmul u, v)))
7803 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7804 if (N1.getOpcode() == PreferredFusedOpcode &&
7805 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7806 SDValue N20 = N1.getOperand(2).getOperand(0);
7807 SDValue N21 = N1.getOperand(2).getOperand(1);
7808 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7809 DAG.getNode(ISD::FNEG, SL, VT,
7812 DAG.getNode(PreferredFusedOpcode, SL, VT,
7813 DAG.getNode(ISD::FNEG, SL, VT, N20),
7818 if (UnsafeFPMath && LookThroughFPExt) {
7819 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7820 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7821 if (N0.getOpcode() == PreferredFusedOpcode) {
7822 SDValue N02 = N0.getOperand(2);
7823 if (N02.getOpcode() == ISD::FP_EXTEND) {
7824 SDValue N020 = N02.getOperand(0);
7825 if (N020.getOpcode() == ISD::FMUL)
7826 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7827 N0.getOperand(0), N0.getOperand(1),
7828 DAG.getNode(PreferredFusedOpcode, SL, VT,
7829 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7830 N020.getOperand(0)),
7831 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832 N020.getOperand(1)),
7833 DAG.getNode(ISD::FNEG, SL, VT,
7838 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7839 // -> (fma (fpext x), (fpext y),
7840 // (fma (fpext u), (fpext v), (fneg z)))
7841 // FIXME: This turns two single-precision and one double-precision
7842 // operation into two double-precision operations, which might not be
7843 // interesting for all targets, especially GPUs.
7844 if (N0.getOpcode() == ISD::FP_EXTEND) {
7845 SDValue N00 = N0.getOperand(0);
7846 if (N00.getOpcode() == PreferredFusedOpcode) {
7847 SDValue N002 = N00.getOperand(2);
7848 if (N002.getOpcode() == ISD::FMUL)
7849 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7850 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7852 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7854 DAG.getNode(PreferredFusedOpcode, SL, VT,
7855 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856 N002.getOperand(0)),
7857 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858 N002.getOperand(1)),
7859 DAG.getNode(ISD::FNEG, SL, VT,
7864 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7865 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7866 if (N1.getOpcode() == PreferredFusedOpcode &&
7867 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7868 SDValue N120 = N1.getOperand(2).getOperand(0);
7869 if (N120.getOpcode() == ISD::FMUL) {
7870 SDValue N1200 = N120.getOperand(0);
7871 SDValue N1201 = N120.getOperand(1);
7872 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7873 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7875 DAG.getNode(PreferredFusedOpcode, SL, VT,
7876 DAG.getNode(ISD::FNEG, SL, VT,
7877 DAG.getNode(ISD::FP_EXTEND, SL,
7879 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7885 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7886 // -> (fma (fneg (fpext y)), (fpext z),
7887 // (fma (fneg (fpext u)), (fpext v), x))
7888 // FIXME: This turns two single-precision and one double-precision
7889 // operation into two double-precision operations, which might not be
7890 // interesting for all targets, especially GPUs.
7891 if (N1.getOpcode() == ISD::FP_EXTEND &&
7892 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7893 SDValue N100 = N1.getOperand(0).getOperand(0);
7894 SDValue N101 = N1.getOperand(0).getOperand(1);
7895 SDValue N102 = N1.getOperand(0).getOperand(2);
7896 if (N102.getOpcode() == ISD::FMUL) {
7897 SDValue N1020 = N102.getOperand(0);
7898 SDValue N1021 = N102.getOperand(1);
7899 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7900 DAG.getNode(ISD::FNEG, SL, VT,
7901 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7903 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7904 DAG.getNode(PreferredFusedOpcode, SL, VT,
7905 DAG.getNode(ISD::FNEG, SL, VT,
7906 DAG.getNode(ISD::FP_EXTEND, SL,
7908 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7919 SDValue DAGCombiner::visitFADD(SDNode *N) {
7920 SDValue N0 = N->getOperand(0);
7921 SDValue N1 = N->getOperand(1);
7922 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7923 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7924 EVT VT = N->getValueType(0);
7926 const TargetOptions &Options = DAG.getTarget().Options;
7930 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7933 // fold (fadd c1, c2) -> c1 + c2
7935 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7937 // canonicalize constant to RHS
7938 if (N0CFP && !N1CFP)
7939 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7941 // fold (fadd A, (fneg B)) -> (fsub A, B)
7942 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7943 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7944 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7945 GetNegatedExpression(N1, DAG, LegalOperations));
7947 // fold (fadd (fneg A), B) -> (fsub B, A)
7948 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7949 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7950 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7951 GetNegatedExpression(N0, DAG, LegalOperations));
7953 // If 'unsafe math' is enabled, fold lots of things.
7954 if (Options.UnsafeFPMath) {
7955 // No FP constant should be created after legalization as Instruction
7956 // Selection pass has a hard time dealing with FP constants.
7957 bool AllowNewConst = (Level < AfterLegalizeDAG);
7959 // fold (fadd A, 0) -> A
7960 if (N1CFP && N1CFP->isZero())
7963 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7964 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7965 isa<ConstantFPSDNode>(N0.getOperand(1)))
7966 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7967 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7969 // If allowed, fold (fadd (fneg x), x) -> 0.0
7970 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7971 return DAG.getConstantFP(0.0, DL, VT);
7973 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7974 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7975 return DAG.getConstantFP(0.0, DL, VT);
7977 // We can fold chains of FADD's of the same value into multiplications.
7978 // This transform is not safe in general because we are reducing the number
7979 // of rounding steps.
7980 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7981 if (N0.getOpcode() == ISD::FMUL) {
7982 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7983 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7985 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7986 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7987 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7988 DAG.getConstantFP(1.0, DL, VT));
7989 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7992 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7993 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7994 N1.getOperand(0) == N1.getOperand(1) &&
7995 N0.getOperand(0) == N1.getOperand(0)) {
7996 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7997 DAG.getConstantFP(2.0, DL, VT));
7998 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
8002 if (N1.getOpcode() == ISD::FMUL) {
8003 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8004 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
8006 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8007 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8008 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8009 DAG.getConstantFP(1.0, DL, VT));
8010 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
8013 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8014 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8015 N0.getOperand(0) == N0.getOperand(1) &&
8016 N1.getOperand(0) == N0.getOperand(0)) {
8017 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
8018 DAG.getConstantFP(2.0, DL, VT));
8019 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
8023 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8024 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
8025 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8026 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
8027 (N0.getOperand(0) == N1)) {
8028 return DAG.getNode(ISD::FMUL, DL, VT,
8029 N1, DAG.getConstantFP(3.0, DL, VT));
8033 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8034 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
8035 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8036 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8037 N1.getOperand(0) == N0) {
8038 return DAG.getNode(ISD::FMUL, DL, VT,
8039 N0, DAG.getConstantFP(3.0, DL, VT));
8043 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8044 if (AllowNewConst &&
8045 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8046 N0.getOperand(0) == N0.getOperand(1) &&
8047 N1.getOperand(0) == N1.getOperand(1) &&
8048 N0.getOperand(0) == N1.getOperand(0)) {
8049 return DAG.getNode(ISD::FMUL, DL, VT,
8050 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8053 } // enable-unsafe-fp-math
8055 // FADD -> FMA combines:
8056 if (SDValue Fused = visitFADDForFMACombine(N)) {
8057 AddToWorklist(Fused.getNode());
8064 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8065 SDValue N0 = N->getOperand(0);
8066 SDValue N1 = N->getOperand(1);
8067 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8068 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8069 EVT VT = N->getValueType(0);
8071 const TargetOptions &Options = DAG.getTarget().Options;
8075 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8078 // fold (fsub c1, c2) -> c1-c2
8080 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8082 // fold (fsub A, (fneg B)) -> (fadd A, B)
8083 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8084 return DAG.getNode(ISD::FADD, dl, VT, N0,
8085 GetNegatedExpression(N1, DAG, LegalOperations));
8087 // If 'unsafe math' is enabled, fold lots of things.
8088 if (Options.UnsafeFPMath) {
8090 if (N1CFP && N1CFP->isZero())
8093 // (fsub 0, B) -> -B
8094 if (N0CFP && N0CFP->isZero()) {
8095 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8096 return GetNegatedExpression(N1, DAG, LegalOperations);
8097 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8098 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8101 // (fsub x, x) -> 0.0
8103 return DAG.getConstantFP(0.0f, dl, VT);
8105 // (fsub x, (fadd x, y)) -> (fneg y)
8106 // (fsub x, (fadd y, x)) -> (fneg y)
8107 if (N1.getOpcode() == ISD::FADD) {
8108 SDValue N10 = N1->getOperand(0);
8109 SDValue N11 = N1->getOperand(1);
8111 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8112 return GetNegatedExpression(N11, DAG, LegalOperations);
8114 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8115 return GetNegatedExpression(N10, DAG, LegalOperations);
8119 // FSUB -> FMA combines:
8120 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8121 AddToWorklist(Fused.getNode());
8128 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8129 SDValue N0 = N->getOperand(0);
8130 SDValue N1 = N->getOperand(1);
8131 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8132 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8133 EVT VT = N->getValueType(0);
8135 const TargetOptions &Options = DAG.getTarget().Options;
8138 if (VT.isVector()) {
8139 // This just handles C1 * C2 for vectors. Other vector folds are below.
8140 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8144 // fold (fmul c1, c2) -> c1*c2
8146 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8148 // canonicalize constant to RHS
8149 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8150 !isConstantFPBuildVectorOrConstantFP(N1))
8151 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8153 // fold (fmul A, 1.0) -> A
8154 if (N1CFP && N1CFP->isExactlyValue(1.0))
8157 if (Options.UnsafeFPMath) {
8158 // fold (fmul A, 0) -> 0
8159 if (N1CFP && N1CFP->isZero())
8162 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8163 if (N0.getOpcode() == ISD::FMUL) {
8164 // Fold scalars or any vector constants (not just splats).
8165 // This fold is done in general by InstCombine, but extra fmul insts
8166 // may have been generated during lowering.
8167 SDValue N00 = N0.getOperand(0);
8168 SDValue N01 = N0.getOperand(1);
8169 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8170 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8171 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8173 // Check 1: Make sure that the first operand of the inner multiply is NOT
8174 // a constant. Otherwise, we may induce infinite looping.
8175 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8176 // Check 2: Make sure that the second operand of the inner multiply and
8177 // the second operand of the outer multiply are constants.
8178 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8179 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8180 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8181 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8186 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8187 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8188 // during an early run of DAGCombiner can prevent folding with fmuls
8189 // inserted during lowering.
8190 if (N0.getOpcode() == ISD::FADD &&
8191 (N0.getOperand(0) == N0.getOperand(1)) &&
8193 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8194 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8195 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8199 // fold (fmul X, 2.0) -> (fadd X, X)
8200 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8201 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8203 // fold (fmul X, -1.0) -> (fneg X)
8204 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8205 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8206 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8208 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8209 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8210 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8211 // Both can be negated for free, check to see if at least one is cheaper
8213 if (LHSNeg == 2 || RHSNeg == 2)
8214 return DAG.getNode(ISD::FMUL, DL, VT,
8215 GetNegatedExpression(N0, DAG, LegalOperations),
8216 GetNegatedExpression(N1, DAG, LegalOperations));
8223 SDValue DAGCombiner::visitFMA(SDNode *N) {
8224 SDValue N0 = N->getOperand(0);
8225 SDValue N1 = N->getOperand(1);
8226 SDValue N2 = N->getOperand(2);
8227 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8228 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8229 EVT VT = N->getValueType(0);
8231 const TargetOptions &Options = DAG.getTarget().Options;
8233 // Constant fold FMA.
8234 if (isa<ConstantFPSDNode>(N0) &&
8235 isa<ConstantFPSDNode>(N1) &&
8236 isa<ConstantFPSDNode>(N2)) {
8237 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8240 if (Options.UnsafeFPMath) {
8241 if (N0CFP && N0CFP->isZero())
8243 if (N1CFP && N1CFP->isZero())
8246 if (N0CFP && N0CFP->isExactlyValue(1.0))
8247 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8248 if (N1CFP && N1CFP->isExactlyValue(1.0))
8249 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8251 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8252 if (N0CFP && !N1CFP)
8253 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8255 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8256 if (Options.UnsafeFPMath && N1CFP &&
8257 N2.getOpcode() == ISD::FMUL &&
8258 N0 == N2.getOperand(0) &&
8259 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8260 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8261 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8265 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8266 if (Options.UnsafeFPMath &&
8267 N0.getOpcode() == ISD::FMUL && N1CFP &&
8268 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8269 return DAG.getNode(ISD::FMA, dl, VT,
8271 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8275 // (fma x, 1, y) -> (fadd x, y)
8276 // (fma x, -1, y) -> (fadd (fneg x), y)
8278 if (N1CFP->isExactlyValue(1.0))
8279 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8281 if (N1CFP->isExactlyValue(-1.0) &&
8282 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8283 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8284 AddToWorklist(RHSNeg.getNode());
8285 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8289 // (fma x, c, x) -> (fmul x, (c+1))
8290 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8291 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8292 DAG.getNode(ISD::FADD, dl, VT,
8293 N1, DAG.getConstantFP(1.0, dl, VT)));
8295 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8296 if (Options.UnsafeFPMath && N1CFP &&
8297 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8298 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8299 DAG.getNode(ISD::FADD, dl, VT,
8300 N1, DAG.getConstantFP(-1.0, dl, VT)));
8306 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8308 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8309 // Notice that this is not always beneficial. One reason is different target
8310 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8311 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8312 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8313 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8314 if (!DAG.getTarget().Options.UnsafeFPMath)
8317 // Skip if current node is a reciprocal.
8318 SDValue N0 = N->getOperand(0);
8319 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8320 if (N0CFP && N0CFP->isExactlyValue(1.0))
8323 // Exit early if the target does not want this transform or if there can't
8324 // possibly be enough uses of the divisor to make the transform worthwhile.
8325 SDValue N1 = N->getOperand(1);
8326 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8327 if (!MinUses || N1->use_size() < MinUses)
8330 // Find all FDIV users of the same divisor.
8331 // Use a set because duplicates may be present in the user list.
8332 SetVector<SDNode *> Users;
8333 for (auto *U : N1->uses())
8334 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8337 // Now that we have the actual number of divisor uses, make sure it meets
8338 // the minimum threshold specified by the target.
8339 if (Users.size() < MinUses)
8342 EVT VT = N->getValueType(0);
8344 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8345 // FIXME: This optimization requires some level of fast-math, so the
8346 // created reciprocal node should at least have the 'allowReciprocal'
8347 // fast-math-flag set.
8348 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8350 // Dividend / Divisor -> Dividend * Reciprocal
8351 for (auto *U : Users) {
8352 SDValue Dividend = U->getOperand(0);
8353 if (Dividend != FPOne) {
8354 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8356 CombineTo(U, NewNode);
8357 } else if (U != Reciprocal.getNode()) {
8358 // In the absence of fast-math-flags, this user node is always the
8359 // same node as Reciprocal, but with FMF they may be different nodes.
8360 CombineTo(U, Reciprocal);
8363 return SDValue(N, 0); // N was replaced.
8366 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8367 SDValue N0 = N->getOperand(0);
8368 SDValue N1 = N->getOperand(1);
8369 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8370 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8371 EVT VT = N->getValueType(0);
8373 const TargetOptions &Options = DAG.getTarget().Options;
8377 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8380 // fold (fdiv c1, c2) -> c1/c2
8382 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8384 if (Options.UnsafeFPMath) {
8385 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8387 // Compute the reciprocal 1.0 / c2.
8388 APFloat N1APF = N1CFP->getValueAPF();
8389 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8390 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8391 // Only do the transform if the reciprocal is a legal fp immediate that
8392 // isn't too nasty (eg NaN, denormal, ...).
8393 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8394 (!LegalOperations ||
8395 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8396 // backend)... we should handle this gracefully after Legalize.
8397 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8398 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8399 TLI.isFPImmLegal(Recip, VT)))
8400 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8401 DAG.getConstantFP(Recip, DL, VT));
8404 // If this FDIV is part of a reciprocal square root, it may be folded
8405 // into a target-specific square root estimate instruction.
8406 if (N1.getOpcode() == ISD::FSQRT) {
8407 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8408 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8410 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8411 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8412 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8413 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8414 AddToWorklist(RV.getNode());
8415 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8417 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8418 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8419 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8420 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8421 AddToWorklist(RV.getNode());
8422 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8424 } else if (N1.getOpcode() == ISD::FMUL) {
8425 // Look through an FMUL. Even though this won't remove the FDIV directly,
8426 // it's still worthwhile to get rid of the FSQRT if possible.
8429 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8430 SqrtOp = N1.getOperand(0);
8431 OtherOp = N1.getOperand(1);
8432 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8433 SqrtOp = N1.getOperand(1);
8434 OtherOp = N1.getOperand(0);
8436 if (SqrtOp.getNode()) {
8437 // We found a FSQRT, so try to make this fold:
8438 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8439 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8440 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8441 AddToWorklist(RV.getNode());
8442 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8447 // Fold into a reciprocal estimate and multiply instead of a real divide.
8448 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8449 AddToWorklist(RV.getNode());
8450 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8454 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8455 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8456 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8457 // Both can be negated for free, check to see if at least one is cheaper
8459 if (LHSNeg == 2 || RHSNeg == 2)
8460 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8461 GetNegatedExpression(N0, DAG, LegalOperations),
8462 GetNegatedExpression(N1, DAG, LegalOperations));
8466 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8467 return CombineRepeatedDivisors;
8472 SDValue DAGCombiner::visitFREM(SDNode *N) {
8473 SDValue N0 = N->getOperand(0);
8474 SDValue N1 = N->getOperand(1);
8475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8476 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8477 EVT VT = N->getValueType(0);
8479 // fold (frem c1, c2) -> fmod(c1,c2)
8481 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8486 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8487 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8490 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8491 SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8495 EVT VT = RV.getValueType();
8497 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8498 AddToWorklist(RV.getNode());
8500 // Unfortunately, RV is now NaN if the input was exactly 0.
8501 // Select out this case and force the answer to 0.
8502 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8503 EVT CCVT = getSetCCResultType(VT);
8504 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8505 AddToWorklist(ZeroCmp.getNode());
8506 AddToWorklist(RV.getNode());
8508 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8512 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8513 SDValue N0 = N->getOperand(0);
8514 SDValue N1 = N->getOperand(1);
8515 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8516 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8517 EVT VT = N->getValueType(0);
8519 if (N0CFP && N1CFP) // Constant fold
8520 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8523 const APFloat& V = N1CFP->getValueAPF();
8524 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8525 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8526 if (!V.isNegative()) {
8527 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8528 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8530 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8531 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8532 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8536 // copysign(fabs(x), y) -> copysign(x, y)
8537 // copysign(fneg(x), y) -> copysign(x, y)
8538 // copysign(copysign(x,z), y) -> copysign(x, y)
8539 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8540 N0.getOpcode() == ISD::FCOPYSIGN)
8541 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8542 N0.getOperand(0), N1);
8544 // copysign(x, abs(y)) -> abs(x)
8545 if (N1.getOpcode() == ISD::FABS)
8546 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8548 // copysign(x, copysign(y,z)) -> copysign(x, z)
8549 if (N1.getOpcode() == ISD::FCOPYSIGN)
8550 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8551 N0, N1.getOperand(1));
8553 // copysign(x, fp_extend(y)) -> copysign(x, y)
8554 // copysign(x, fp_round(y)) -> copysign(x, y)
8555 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8556 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8557 N0, N1.getOperand(0));
8562 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8563 SDValue N0 = N->getOperand(0);
8564 EVT VT = N->getValueType(0);
8565 EVT OpVT = N0.getValueType();
8567 // fold (sint_to_fp c1) -> c1fp
8568 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8569 // ...but only if the target supports immediate floating-point values
8570 (!LegalOperations ||
8571 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8572 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8574 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8575 // but UINT_TO_FP is legal on this target, try to convert.
8576 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8577 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8578 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8579 if (DAG.SignBitIsZero(N0))
8580 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8583 // The next optimizations are desirable only if SELECT_CC can be lowered.
8584 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8585 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8586 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8588 (!LegalOperations ||
8589 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8592 { N0.getOperand(0), N0.getOperand(1),
8593 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8595 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8598 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8599 // (select_cc x, y, 1.0, 0.0,, cc)
8600 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8601 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8602 (!LegalOperations ||
8603 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8606 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8607 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8608 N0.getOperand(0).getOperand(2) };
8609 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8616 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8617 SDValue N0 = N->getOperand(0);
8618 EVT VT = N->getValueType(0);
8619 EVT OpVT = N0.getValueType();
8621 // fold (uint_to_fp c1) -> c1fp
8622 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8623 // ...but only if the target supports immediate floating-point values
8624 (!LegalOperations ||
8625 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8626 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8628 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8629 // but SINT_TO_FP is legal on this target, try to convert.
8630 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8631 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8632 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8633 if (DAG.SignBitIsZero(N0))
8634 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8637 // The next optimizations are desirable only if SELECT_CC can be lowered.
8638 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8639 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8641 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8642 (!LegalOperations ||
8643 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8646 { N0.getOperand(0), N0.getOperand(1),
8647 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8649 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8656 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8657 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8658 SDValue N0 = N->getOperand(0);
8659 EVT VT = N->getValueType(0);
8661 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8664 SDValue Src = N0.getOperand(0);
8665 EVT SrcVT = Src.getValueType();
8666 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8667 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8669 // We can safely assume the conversion won't overflow the output range,
8670 // because (for example) (uint8_t)18293.f is undefined behavior.
8672 // Since we can assume the conversion won't overflow, our decision as to
8673 // whether the input will fit in the float should depend on the minimum
8674 // of the input range and output range.
8676 // This means this is also safe for a signed input and unsigned output, since
8677 // a negative input would lead to undefined behavior.
8678 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8679 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8680 unsigned ActualSize = std::min(InputSize, OutputSize);
8681 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8683 // We can only fold away the float conversion if the input range can be
8684 // represented exactly in the float range.
8685 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8686 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8687 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8689 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8691 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8692 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8695 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8700 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8701 SDValue N0 = N->getOperand(0);
8702 EVT VT = N->getValueType(0);
8704 // fold (fp_to_sint c1fp) -> c1
8705 if (isConstantFPBuildVectorOrConstantFP(N0))
8706 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8708 return FoldIntToFPToInt(N, DAG);
8711 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8712 SDValue N0 = N->getOperand(0);
8713 EVT VT = N->getValueType(0);
8715 // fold (fp_to_uint c1fp) -> c1
8716 if (isConstantFPBuildVectorOrConstantFP(N0))
8717 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8719 return FoldIntToFPToInt(N, DAG);
8722 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8723 SDValue N0 = N->getOperand(0);
8724 SDValue N1 = N->getOperand(1);
8725 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8726 EVT VT = N->getValueType(0);
8728 // fold (fp_round c1fp) -> c1fp
8730 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8732 // fold (fp_round (fp_extend x)) -> x
8733 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8734 return N0.getOperand(0);
8736 // fold (fp_round (fp_round x)) -> (fp_round x)
8737 if (N0.getOpcode() == ISD::FP_ROUND) {
8738 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8739 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8740 // If the first fp_round isn't a value preserving truncation, it might
8741 // introduce a tie in the second fp_round, that wouldn't occur in the
8742 // single-step fp_round we want to fold to.
8743 // In other words, double rounding isn't the same as rounding.
8744 // Also, this is a value preserving truncation iff both fp_round's are.
8745 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8747 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8748 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8752 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8753 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8754 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8755 N0.getOperand(0), N1);
8756 AddToWorklist(Tmp.getNode());
8757 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8758 Tmp, N0.getOperand(1));
8764 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8765 SDValue N0 = N->getOperand(0);
8766 EVT VT = N->getValueType(0);
8767 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8768 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8770 // fold (fp_round_inreg c1fp) -> c1fp
8771 if (N0CFP && isTypeLegal(EVT)) {
8773 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8774 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8780 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8781 SDValue N0 = N->getOperand(0);
8782 EVT VT = N->getValueType(0);
8784 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8785 if (N->hasOneUse() &&
8786 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8789 // fold (fp_extend c1fp) -> c1fp
8790 if (isConstantFPBuildVectorOrConstantFP(N0))
8791 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8793 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8794 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8795 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8796 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8798 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8800 if (N0.getOpcode() == ISD::FP_ROUND
8801 && N0.getNode()->getConstantOperandVal(1) == 1) {
8802 SDValue In = N0.getOperand(0);
8803 if (In.getValueType() == VT) return In;
8804 if (VT.bitsLT(In.getValueType()))
8805 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8806 In, N0.getOperand(1));
8807 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8810 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8811 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8812 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8814 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8816 LN0->getBasePtr(), N0.getValueType(),
8817 LN0->getMemOperand());
8818 CombineTo(N, ExtLoad);
8819 CombineTo(N0.getNode(),
8820 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8821 N0.getValueType(), ExtLoad,
8822 DAG.getIntPtrConstant(1, SDLoc(N0))),
8823 ExtLoad.getValue(1));
8824 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8830 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8831 SDValue N0 = N->getOperand(0);
8832 EVT VT = N->getValueType(0);
8834 // fold (fceil c1) -> fceil(c1)
8835 if (isConstantFPBuildVectorOrConstantFP(N0))
8836 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8841 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8842 SDValue N0 = N->getOperand(0);
8843 EVT VT = N->getValueType(0);
8845 // fold (ftrunc c1) -> ftrunc(c1)
8846 if (isConstantFPBuildVectorOrConstantFP(N0))
8847 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8852 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8853 SDValue N0 = N->getOperand(0);
8854 EVT VT = N->getValueType(0);
8856 // fold (ffloor c1) -> ffloor(c1)
8857 if (isConstantFPBuildVectorOrConstantFP(N0))
8858 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8863 // FIXME: FNEG and FABS have a lot in common; refactor.
8864 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8865 SDValue N0 = N->getOperand(0);
8866 EVT VT = N->getValueType(0);
8868 // Constant fold FNEG.
8869 if (isConstantFPBuildVectorOrConstantFP(N0))
8870 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8872 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8873 &DAG.getTarget().Options))
8874 return GetNegatedExpression(N0, DAG, LegalOperations);
8876 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8877 // constant pool values.
8878 if (!TLI.isFNegFree(VT) &&
8879 N0.getOpcode() == ISD::BITCAST &&
8880 N0.getNode()->hasOneUse()) {
8881 SDValue Int = N0.getOperand(0);
8882 EVT IntVT = Int.getValueType();
8883 if (IntVT.isInteger() && !IntVT.isVector()) {
8885 if (N0.getValueType().isVector()) {
8886 // For a vector, get a mask such as 0x80... per scalar element
8888 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8889 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8891 // For a scalar, just generate 0x80...
8892 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8895 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8896 DAG.getConstant(SignMask, DL0, IntVT));
8897 AddToWorklist(Int.getNode());
8898 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8902 // (fneg (fmul c, x)) -> (fmul -c, x)
8903 if (N0.getOpcode() == ISD::FMUL &&
8904 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8905 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8907 APFloat CVal = CFP1->getValueAPF();
8909 if (Level >= AfterLegalizeDAG &&
8910 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8911 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8913 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8914 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8921 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8922 SDValue N0 = N->getOperand(0);
8923 SDValue N1 = N->getOperand(1);
8924 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8925 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8927 if (N0CFP && N1CFP) {
8928 const APFloat &C0 = N0CFP->getValueAPF();
8929 const APFloat &C1 = N1CFP->getValueAPF();
8930 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8934 EVT VT = N->getValueType(0);
8935 // Canonicalize to constant on RHS.
8936 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8942 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8943 SDValue N0 = N->getOperand(0);
8944 SDValue N1 = N->getOperand(1);
8945 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8946 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8948 if (N0CFP && N1CFP) {
8949 const APFloat &C0 = N0CFP->getValueAPF();
8950 const APFloat &C1 = N1CFP->getValueAPF();
8951 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8955 EVT VT = N->getValueType(0);
8956 // Canonicalize to constant on RHS.
8957 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8963 SDValue DAGCombiner::visitFABS(SDNode *N) {
8964 SDValue N0 = N->getOperand(0);
8965 EVT VT = N->getValueType(0);
8967 // fold (fabs c1) -> fabs(c1)
8968 if (isConstantFPBuildVectorOrConstantFP(N0))
8969 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8971 // fold (fabs (fabs x)) -> (fabs x)
8972 if (N0.getOpcode() == ISD::FABS)
8973 return N->getOperand(0);
8975 // fold (fabs (fneg x)) -> (fabs x)
8976 // fold (fabs (fcopysign x, y)) -> (fabs x)
8977 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8978 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8980 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8981 // constant pool values.
8982 if (!TLI.isFAbsFree(VT) &&
8983 N0.getOpcode() == ISD::BITCAST &&
8984 N0.getNode()->hasOneUse()) {
8985 SDValue Int = N0.getOperand(0);
8986 EVT IntVT = Int.getValueType();
8987 if (IntVT.isInteger() && !IntVT.isVector()) {
8989 if (N0.getValueType().isVector()) {
8990 // For a vector, get a mask such as 0x7f... per scalar element
8992 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8993 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8995 // For a scalar, just generate 0x7f...
8996 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8999 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9000 DAG.getConstant(SignMask, DL, IntVT));
9001 AddToWorklist(Int.getNode());
9002 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9009 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9010 SDValue Chain = N->getOperand(0);
9011 SDValue N1 = N->getOperand(1);
9012 SDValue N2 = N->getOperand(2);
9014 // If N is a constant we could fold this into a fallthrough or unconditional
9015 // branch. However that doesn't happen very often in normal code, because
9016 // Instcombine/SimplifyCFG should have handled the available opportunities.
9017 // If we did this folding here, it would be necessary to update the
9018 // MachineBasicBlock CFG, which is awkward.
9020 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9022 if (N1.getOpcode() == ISD::SETCC &&
9023 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9024 N1.getOperand(0).getValueType())) {
9025 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9026 Chain, N1.getOperand(2),
9027 N1.getOperand(0), N1.getOperand(1), N2);
9030 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9031 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9032 (N1.getOperand(0).hasOneUse() &&
9033 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9034 SDNode *Trunc = nullptr;
9035 if (N1.getOpcode() == ISD::TRUNCATE) {
9036 // Look pass the truncate.
9037 Trunc = N1.getNode();
9038 N1 = N1.getOperand(0);
9041 // Match this pattern so that we can generate simpler code:
9044 // %b = and i32 %a, 2
9045 // %c = srl i32 %b, 1
9046 // brcond i32 %c ...
9051 // %b = and i32 %a, 2
9052 // %c = setcc eq %b, 0
9055 // This applies only when the AND constant value has one bit set and the
9056 // SRL constant is equal to the log2 of the AND constant. The back-end is
9057 // smart enough to convert the result into a TEST/JMP sequence.
9058 SDValue Op0 = N1.getOperand(0);
9059 SDValue Op1 = N1.getOperand(1);
9061 if (Op0.getOpcode() == ISD::AND &&
9062 Op1.getOpcode() == ISD::Constant) {
9063 SDValue AndOp1 = Op0.getOperand(1);
9065 if (AndOp1.getOpcode() == ISD::Constant) {
9066 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9068 if (AndConst.isPowerOf2() &&
9069 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9073 getSetCCResultType(Op0.getValueType()),
9074 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9077 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9078 MVT::Other, Chain, SetCC, N2);
9079 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9080 // will convert it back to (X & C1) >> C2.
9081 CombineTo(N, NewBRCond, false);
9082 // Truncate is dead.
9084 deleteAndRecombine(Trunc);
9085 // Replace the uses of SRL with SETCC
9086 WorklistRemover DeadNodes(*this);
9087 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9088 deleteAndRecombine(N1.getNode());
9089 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9095 // Restore N1 if the above transformation doesn't match.
9096 N1 = N->getOperand(1);
9099 // Transform br(xor(x, y)) -> br(x != y)
9100 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9101 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9102 SDNode *TheXor = N1.getNode();
9103 SDValue Op0 = TheXor->getOperand(0);
9104 SDValue Op1 = TheXor->getOperand(1);
9105 if (Op0.getOpcode() == Op1.getOpcode()) {
9106 // Avoid missing important xor optimizations.
9107 if (SDValue Tmp = visitXOR(TheXor)) {
9108 if (Tmp.getNode() != TheXor) {
9109 DEBUG(dbgs() << "\nReplacing.8 ";
9111 dbgs() << "\nWith: ";
9112 Tmp.getNode()->dump(&DAG);
9114 WorklistRemover DeadNodes(*this);
9115 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9116 deleteAndRecombine(TheXor);
9117 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9118 MVT::Other, Chain, Tmp, N2);
9121 // visitXOR has changed XOR's operands or replaced the XOR completely,
9123 return SDValue(N, 0);
9127 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9129 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9130 Op0.getOpcode() == ISD::XOR) {
9131 TheXor = Op0.getNode();
9135 EVT SetCCVT = N1.getValueType();
9137 SetCCVT = getSetCCResultType(SetCCVT);
9138 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9141 Equal ? ISD::SETEQ : ISD::SETNE);
9142 // Replace the uses of XOR with SETCC
9143 WorklistRemover DeadNodes(*this);
9144 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9145 deleteAndRecombine(N1.getNode());
9146 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9147 MVT::Other, Chain, SetCC, N2);
9154 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9156 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9157 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9158 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9160 // If N is a constant we could fold this into a fallthrough or unconditional
9161 // branch. However that doesn't happen very often in normal code, because
9162 // Instcombine/SimplifyCFG should have handled the available opportunities.
9163 // If we did this folding here, it would be necessary to update the
9164 // MachineBasicBlock CFG, which is awkward.
9166 // Use SimplifySetCC to simplify SETCC's.
9167 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9168 CondLHS, CondRHS, CC->get(), SDLoc(N),
9170 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9172 // fold to a simpler setcc
9173 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9174 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9175 N->getOperand(0), Simp.getOperand(2),
9176 Simp.getOperand(0), Simp.getOperand(1),
9182 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9183 /// and that N may be folded in the load / store addressing mode.
9184 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9186 const TargetLowering &TLI) {
9190 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9191 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9193 VT = LD->getMemoryVT();
9194 AS = LD->getAddressSpace();
9195 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9196 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9198 VT = ST->getMemoryVT();
9199 AS = ST->getAddressSpace();
9203 TargetLowering::AddrMode AM;
9204 if (N->getOpcode() == ISD::ADD) {
9205 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9208 AM.BaseOffs = Offset->getSExtValue();
9212 } else if (N->getOpcode() == ISD::SUB) {
9213 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9216 AM.BaseOffs = -Offset->getSExtValue();
9223 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9224 VT.getTypeForEVT(*DAG.getContext()), AS);
9227 /// Try turning a load/store into a pre-indexed load/store when the base
9228 /// pointer is an add or subtract and it has other uses besides the load/store.
9229 /// After the transformation, the new indexed load/store has effectively folded
9230 /// the add/subtract in and all of its other uses are redirected to the
9232 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9233 if (Level < AfterLegalizeDAG)
9239 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9240 if (LD->isIndexed())
9242 VT = LD->getMemoryVT();
9243 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9244 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9246 Ptr = LD->getBasePtr();
9247 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9248 if (ST->isIndexed())
9250 VT = ST->getMemoryVT();
9251 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9252 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9254 Ptr = ST->getBasePtr();
9260 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9261 // out. There is no reason to make this a preinc/predec.
9262 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9263 Ptr.getNode()->hasOneUse())
9266 // Ask the target to do addressing mode selection.
9269 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9270 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9273 // Backends without true r+i pre-indexed forms may need to pass a
9274 // constant base with a variable offset so that constant coercion
9275 // will work with the patterns in canonical form.
9276 bool Swapped = false;
9277 if (isa<ConstantSDNode>(BasePtr)) {
9278 std::swap(BasePtr, Offset);
9282 // Don't create a indexed load / store with zero offset.
9283 if (isNullConstant(Offset))
9286 // Try turning it into a pre-indexed load / store except when:
9287 // 1) The new base ptr is a frame index.
9288 // 2) If N is a store and the new base ptr is either the same as or is a
9289 // predecessor of the value being stored.
9290 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9291 // that would create a cycle.
9292 // 4) All uses are load / store ops that use it as old base ptr.
9294 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9295 // (plus the implicit offset) to a register to preinc anyway.
9296 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9301 SDValue Val = cast<StoreSDNode>(N)->getValue();
9302 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9306 // If the offset is a constant, there may be other adds of constants that
9307 // can be folded with this one. We should do this to avoid having to keep
9308 // a copy of the original base pointer.
9309 SmallVector<SDNode *, 16> OtherUses;
9310 if (isa<ConstantSDNode>(Offset))
9311 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9312 UE = BasePtr.getNode()->use_end();
9314 SDUse &Use = UI.getUse();
9315 // Skip the use that is Ptr and uses of other results from BasePtr's
9316 // node (important for nodes that return multiple results).
9317 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9320 if (Use.getUser()->isPredecessorOf(N))
9323 if (Use.getUser()->getOpcode() != ISD::ADD &&
9324 Use.getUser()->getOpcode() != ISD::SUB) {
9329 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9330 if (!isa<ConstantSDNode>(Op1)) {
9335 // FIXME: In some cases, we can be smarter about this.
9336 if (Op1.getValueType() != Offset.getValueType()) {
9341 OtherUses.push_back(Use.getUser());
9345 std::swap(BasePtr, Offset);
9347 // Now check for #3 and #4.
9348 bool RealUse = false;
9350 // Caches for hasPredecessorHelper
9351 SmallPtrSet<const SDNode *, 32> Visited;
9352 SmallVector<const SDNode *, 16> Worklist;
9354 for (SDNode *Use : Ptr.getNode()->uses()) {
9357 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9360 // If Ptr may be folded in addressing mode of other use, then it's
9361 // not profitable to do this transformation.
9362 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9371 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9372 BasePtr, Offset, AM);
9374 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9375 BasePtr, Offset, AM);
9378 DEBUG(dbgs() << "\nReplacing.4 ";
9380 dbgs() << "\nWith: ";
9381 Result.getNode()->dump(&DAG);
9383 WorklistRemover DeadNodes(*this);
9385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9388 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9391 // Finally, since the node is now dead, remove it from the graph.
9392 deleteAndRecombine(N);
9395 std::swap(BasePtr, Offset);
9397 // Replace other uses of BasePtr that can be updated to use Ptr
9398 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9399 unsigned OffsetIdx = 1;
9400 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9402 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9403 BasePtr.getNode() && "Expected BasePtr operand");
9405 // We need to replace ptr0 in the following expression:
9406 // x0 * offset0 + y0 * ptr0 = t0
9408 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9410 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9411 // indexed load/store and the expresion that needs to be re-written.
9413 // Therefore, we have:
9414 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9416 ConstantSDNode *CN =
9417 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9419 APInt Offset0 = CN->getAPIntValue();
9420 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9422 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9423 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9424 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9425 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9427 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9429 APInt CNV = Offset0;
9430 if (X0 < 0) CNV = -CNV;
9431 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9432 else CNV = CNV - Offset1;
9434 SDLoc DL(OtherUses[i]);
9436 // We can now generate the new expression.
9437 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9438 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9440 SDValue NewUse = DAG.getNode(Opcode,
9442 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9443 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9444 deleteAndRecombine(OtherUses[i]);
9447 // Replace the uses of Ptr with uses of the updated base value.
9448 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9449 deleteAndRecombine(Ptr.getNode());
9454 /// Try to combine a load/store with a add/sub of the base pointer node into a
9455 /// post-indexed load/store. The transformation folded the add/subtract into the
9456 /// new indexed load/store effectively and all of its uses are redirected to the
9458 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9459 if (Level < AfterLegalizeDAG)
9465 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9466 if (LD->isIndexed())
9468 VT = LD->getMemoryVT();
9469 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9470 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9472 Ptr = LD->getBasePtr();
9473 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9474 if (ST->isIndexed())
9476 VT = ST->getMemoryVT();
9477 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9478 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9480 Ptr = ST->getBasePtr();
9486 if (Ptr.getNode()->hasOneUse())
9489 for (SDNode *Op : Ptr.getNode()->uses()) {
9491 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9496 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9497 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9498 // Don't create a indexed load / store with zero offset.
9499 if (isNullConstant(Offset))
9502 // Try turning it into a post-indexed load / store except when
9503 // 1) All uses are load / store ops that use it as base ptr (and
9504 // it may be folded as addressing mmode).
9505 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9506 // nor a successor of N. Otherwise, if Op is folded that would
9509 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9513 bool TryNext = false;
9514 for (SDNode *Use : BasePtr.getNode()->uses()) {
9515 if (Use == Ptr.getNode())
9518 // If all the uses are load / store addresses, then don't do the
9520 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9521 bool RealUse = false;
9522 for (SDNode *UseUse : Use->uses()) {
9523 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9538 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9539 SDValue Result = isLoad
9540 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9541 BasePtr, Offset, AM)
9542 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9543 BasePtr, Offset, AM);
9546 DEBUG(dbgs() << "\nReplacing.5 ";
9548 dbgs() << "\nWith: ";
9549 Result.getNode()->dump(&DAG);
9551 WorklistRemover DeadNodes(*this);
9553 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9554 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9556 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9559 // Finally, since the node is now dead, remove it from the graph.
9560 deleteAndRecombine(N);
9562 // Replace the uses of Use with uses of the updated base value.
9563 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9564 Result.getValue(isLoad ? 1 : 0));
9565 deleteAndRecombine(Op);
9574 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9575 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9576 ISD::MemIndexedMode AM = LD->getAddressingMode();
9577 assert(AM != ISD::UNINDEXED);
9578 SDValue BP = LD->getOperand(1);
9579 SDValue Inc = LD->getOperand(2);
9581 // Some backends use TargetConstants for load offsets, but don't expect
9582 // TargetConstants in general ADD nodes. We can convert these constants into
9583 // regular Constants (if the constant is not opaque).
9584 assert((Inc.getOpcode() != ISD::TargetConstant ||
9585 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9586 "Cannot split out indexing using opaque target constants");
9587 if (Inc.getOpcode() == ISD::TargetConstant) {
9588 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9589 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9590 ConstInc->getValueType(0));
9594 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9595 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9598 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9599 LoadSDNode *LD = cast<LoadSDNode>(N);
9600 SDValue Chain = LD->getChain();
9601 SDValue Ptr = LD->getBasePtr();
9603 // If load is not volatile and there are no uses of the loaded value (and
9604 // the updated indexed value in case of indexed loads), change uses of the
9605 // chain value into uses of the chain input (i.e. delete the dead load).
9606 if (!LD->isVolatile()) {
9607 if (N->getValueType(1) == MVT::Other) {
9609 if (!N->hasAnyUseOfValue(0)) {
9610 // It's not safe to use the two value CombineTo variant here. e.g.
9611 // v1, chain2 = load chain1, loc
9612 // v2, chain3 = load chain2, loc
9614 // Now we replace use of chain2 with chain1. This makes the second load
9615 // isomorphic to the one we are deleting, and thus makes this load live.
9616 DEBUG(dbgs() << "\nReplacing.6 ";
9618 dbgs() << "\nWith chain: ";
9619 Chain.getNode()->dump(&DAG);
9621 WorklistRemover DeadNodes(*this);
9622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9625 deleteAndRecombine(N);
9627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9631 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9633 // If this load has an opaque TargetConstant offset, then we cannot split
9634 // the indexing into an add/sub directly (that TargetConstant may not be
9635 // valid for a different type of node, and we cannot convert an opaque
9636 // target constant into a regular constant).
9637 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9638 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9640 if (!N->hasAnyUseOfValue(0) &&
9641 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9642 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9644 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9645 Index = SplitIndexingFromLoad(LD);
9646 // Try to fold the base pointer arithmetic into subsequent loads and
9648 AddUsersToWorklist(N);
9650 Index = DAG.getUNDEF(N->getValueType(1));
9651 DEBUG(dbgs() << "\nReplacing.7 ";
9653 dbgs() << "\nWith: ";
9654 Undef.getNode()->dump(&DAG);
9655 dbgs() << " and 2 other values\n");
9656 WorklistRemover DeadNodes(*this);
9657 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9658 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9659 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9660 deleteAndRecombine(N);
9661 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9666 // If this load is directly stored, replace the load value with the stored
9668 // TODO: Handle store large -> read small portion.
9669 // TODO: Handle TRUNCSTORE/LOADEXT
9670 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9671 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9672 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9673 if (PrevST->getBasePtr() == Ptr &&
9674 PrevST->getValue().getValueType() == N->getValueType(0))
9675 return CombineTo(N, Chain.getOperand(1), Chain);
9679 // Try to infer better alignment information than the load already has.
9680 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9681 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9682 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9684 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9685 LD->getValueType(0),
9686 Chain, Ptr, LD->getPointerInfo(),
9688 LD->isVolatile(), LD->isNonTemporal(),
9689 LD->isInvariant(), Align, LD->getAAInfo());
9690 if (NewLoad.getNode() != N)
9691 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9696 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9697 : DAG.getSubtarget().useAA();
9699 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9700 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9703 if (UseAA && LD->isUnindexed()) {
9704 // Walk up chain skipping non-aliasing memory nodes.
9705 SDValue BetterChain = FindBetterChain(N, Chain);
9707 // If there is a better chain.
9708 if (Chain != BetterChain) {
9711 // Replace the chain to void dependency.
9712 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9713 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9714 BetterChain, Ptr, LD->getMemOperand());
9716 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9717 LD->getValueType(0),
9718 BetterChain, Ptr, LD->getMemoryVT(),
9719 LD->getMemOperand());
9722 // Create token factor to keep old chain connected.
9723 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9724 MVT::Other, Chain, ReplLoad.getValue(1));
9726 // Make sure the new and old chains are cleaned up.
9727 AddToWorklist(Token.getNode());
9729 // Replace uses with load result and token factor. Don't add users
9731 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9735 // Try transforming N to an indexed load.
9736 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9737 return SDValue(N, 0);
9739 // Try to slice up N to more direct loads if the slices are mapped to
9740 // different register banks or pairing can take place.
9742 return SDValue(N, 0);
9748 /// \brief Helper structure used to slice a load in smaller loads.
9749 /// Basically a slice is obtained from the following sequence:
9750 /// Origin = load Ty1, Base
9751 /// Shift = srl Ty1 Origin, CstTy Amount
9752 /// Inst = trunc Shift to Ty2
9754 /// Then, it will be rewriten into:
9755 /// Slice = load SliceTy, Base + SliceOffset
9756 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9758 /// SliceTy is deduced from the number of bits that are actually used to
9760 struct LoadedSlice {
9761 /// \brief Helper structure used to compute the cost of a slice.
9763 /// Are we optimizing for code size.
9768 unsigned CrossRegisterBanksCopies;
9772 Cost(bool ForCodeSize = false)
9773 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9774 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9776 /// \brief Get the cost of one isolated slice.
9777 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9778 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9779 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9780 EVT TruncType = LS.Inst->getValueType(0);
9781 EVT LoadedType = LS.getLoadedType();
9782 if (TruncType != LoadedType &&
9783 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9787 /// \brief Account for slicing gain in the current cost.
9788 /// Slicing provide a few gains like removing a shift or a
9789 /// truncate. This method allows to grow the cost of the original
9790 /// load with the gain from this slice.
9791 void addSliceGain(const LoadedSlice &LS) {
9792 // Each slice saves a truncate.
9793 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9794 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9795 LS.Inst->getValueType(0)))
9797 // If there is a shift amount, this slice gets rid of it.
9800 // If this slice can merge a cross register bank copy, account for it.
9801 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9802 ++CrossRegisterBanksCopies;
9805 Cost &operator+=(const Cost &RHS) {
9807 Truncates += RHS.Truncates;
9808 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9814 bool operator==(const Cost &RHS) const {
9815 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9816 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9817 ZExts == RHS.ZExts && Shift == RHS.Shift;
9820 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9822 bool operator<(const Cost &RHS) const {
9823 // Assume cross register banks copies are as expensive as loads.
9824 // FIXME: Do we want some more target hooks?
9825 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9826 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9827 // Unless we are optimizing for code size, consider the
9828 // expensive operation first.
9829 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9830 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9831 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9832 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9835 bool operator>(const Cost &RHS) const { return RHS < *this; }
9837 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9839 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9841 // The last instruction that represent the slice. This should be a
9842 // truncate instruction.
9844 // The original load instruction.
9846 // The right shift amount in bits from the original load.
9848 // The DAG from which Origin came from.
9849 // This is used to get some contextual information about legal types, etc.
9852 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9853 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9854 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9856 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9857 /// \return Result is \p BitWidth and has used bits set to 1 and
9858 /// not used bits set to 0.
9859 APInt getUsedBits() const {
9860 // Reproduce the trunc(lshr) sequence:
9861 // - Start from the truncated value.
9862 // - Zero extend to the desired bit width.
9864 assert(Origin && "No original load to compare against.");
9865 unsigned BitWidth = Origin->getValueSizeInBits(0);
9866 assert(Inst && "This slice is not bound to an instruction");
9867 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9868 "Extracted slice is bigger than the whole type!");
9869 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9870 UsedBits.setAllBits();
9871 UsedBits = UsedBits.zext(BitWidth);
9876 /// \brief Get the size of the slice to be loaded in bytes.
9877 unsigned getLoadedSize() const {
9878 unsigned SliceSize = getUsedBits().countPopulation();
9879 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9880 return SliceSize / 8;
9883 /// \brief Get the type that will be loaded for this slice.
9884 /// Note: This may not be the final type for the slice.
9885 EVT getLoadedType() const {
9886 assert(DAG && "Missing context");
9887 LLVMContext &Ctxt = *DAG->getContext();
9888 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9891 /// \brief Get the alignment of the load used for this slice.
9892 unsigned getAlignment() const {
9893 unsigned Alignment = Origin->getAlignment();
9894 unsigned Offset = getOffsetFromBase();
9896 Alignment = MinAlign(Alignment, Alignment + Offset);
9900 /// \brief Check if this slice can be rewritten with legal operations.
9901 bool isLegal() const {
9902 // An invalid slice is not legal.
9903 if (!Origin || !Inst || !DAG)
9906 // Offsets are for indexed load only, we do not handle that.
9907 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9910 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9912 // Check that the type is legal.
9913 EVT SliceType = getLoadedType();
9914 if (!TLI.isTypeLegal(SliceType))
9917 // Check that the load is legal for this type.
9918 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9921 // Check that the offset can be computed.
9922 // 1. Check its type.
9923 EVT PtrType = Origin->getBasePtr().getValueType();
9924 if (PtrType == MVT::Untyped || PtrType.isExtended())
9927 // 2. Check that it fits in the immediate.
9928 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9931 // 3. Check that the computation is legal.
9932 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9935 // Check that the zext is legal if it needs one.
9936 EVT TruncateType = Inst->getValueType(0);
9937 if (TruncateType != SliceType &&
9938 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9944 /// \brief Get the offset in bytes of this slice in the original chunk of
9946 /// \pre DAG != nullptr.
9947 uint64_t getOffsetFromBase() const {
9948 assert(DAG && "Missing context.");
9949 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9950 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9951 uint64_t Offset = Shift / 8;
9952 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9953 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9954 "The size of the original loaded type is not a multiple of a"
9956 // If Offset is bigger than TySizeInBytes, it means we are loading all
9957 // zeros. This should have been optimized before in the process.
9958 assert(TySizeInBytes > Offset &&
9959 "Invalid shift amount for given loaded size");
9961 Offset = TySizeInBytes - Offset - getLoadedSize();
9965 /// \brief Generate the sequence of instructions to load the slice
9966 /// represented by this object and redirect the uses of this slice to
9967 /// this new sequence of instructions.
9968 /// \pre this->Inst && this->Origin are valid Instructions and this
9969 /// object passed the legal check: LoadedSlice::isLegal returned true.
9970 /// \return The last instruction of the sequence used to load the slice.
9971 SDValue loadSlice() const {
9972 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9973 const SDValue &OldBaseAddr = Origin->getBasePtr();
9974 SDValue BaseAddr = OldBaseAddr;
9975 // Get the offset in that chunk of bytes w.r.t. the endianess.
9976 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9977 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9979 // BaseAddr = BaseAddr + Offset.
9980 EVT ArithType = BaseAddr.getValueType();
9982 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9983 DAG->getConstant(Offset, DL, ArithType));
9986 // Create the type of the loaded slice according to its size.
9987 EVT SliceType = getLoadedType();
9989 // Create the load for the slice.
9990 SDValue LastInst = DAG->getLoad(
9991 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9992 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9993 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9994 // If the final type is not the same as the loaded type, this means that
9995 // we have to pad with zero. Create a zero extend for that.
9996 EVT FinalType = Inst->getValueType(0);
9997 if (SliceType != FinalType)
9999 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10003 /// \brief Check if this slice can be merged with an expensive cross register
10004 /// bank copy. E.g.,
10006 /// f = bitcast i32 i to float
10007 bool canMergeExpensiveCrossRegisterBankCopy() const {
10008 if (!Inst || !Inst->hasOneUse())
10010 SDNode *Use = *Inst->use_begin();
10011 if (Use->getOpcode() != ISD::BITCAST)
10013 assert(DAG && "Missing context");
10014 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10015 EVT ResVT = Use->getValueType(0);
10016 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10017 const TargetRegisterClass *ArgRC =
10018 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10019 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10022 // At this point, we know that we perform a cross-register-bank copy.
10023 // Check if it is expensive.
10024 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10025 // Assume bitcasts are cheap, unless both register classes do not
10026 // explicitly share a common sub class.
10027 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10030 // Check if it will be merged with the load.
10031 // 1. Check the alignment constraint.
10032 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10033 ResVT.getTypeForEVT(*DAG->getContext()));
10035 if (RequiredAlignment > getAlignment())
10038 // 2. Check that the load is a legal operation for that type.
10039 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10042 // 3. Check that we do not have a zext in the way.
10043 if (Inst->getValueType(0) != getLoadedType())
10051 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10052 /// \p UsedBits looks like 0..0 1..1 0..0.
10053 static bool areUsedBitsDense(const APInt &UsedBits) {
10054 // If all the bits are one, this is dense!
10055 if (UsedBits.isAllOnesValue())
10058 // Get rid of the unused bits on the right.
10059 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10060 // Get rid of the unused bits on the left.
10061 if (NarrowedUsedBits.countLeadingZeros())
10062 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10063 // Check that the chunk of bits is completely used.
10064 return NarrowedUsedBits.isAllOnesValue();
10067 /// \brief Check whether or not \p First and \p Second are next to each other
10068 /// in memory. This means that there is no hole between the bits loaded
10069 /// by \p First and the bits loaded by \p Second.
10070 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10071 const LoadedSlice &Second) {
10072 assert(First.Origin == Second.Origin && First.Origin &&
10073 "Unable to match different memory origins.");
10074 APInt UsedBits = First.getUsedBits();
10075 assert((UsedBits & Second.getUsedBits()) == 0 &&
10076 "Slices are not supposed to overlap.");
10077 UsedBits |= Second.getUsedBits();
10078 return areUsedBitsDense(UsedBits);
10081 /// \brief Adjust the \p GlobalLSCost according to the target
10082 /// paring capabilities and the layout of the slices.
10083 /// \pre \p GlobalLSCost should account for at least as many loads as
10084 /// there is in the slices in \p LoadedSlices.
10085 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10086 LoadedSlice::Cost &GlobalLSCost) {
10087 unsigned NumberOfSlices = LoadedSlices.size();
10088 // If there is less than 2 elements, no pairing is possible.
10089 if (NumberOfSlices < 2)
10092 // Sort the slices so that elements that are likely to be next to each
10093 // other in memory are next to each other in the list.
10094 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10095 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10096 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10097 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10099 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10100 // First (resp. Second) is the first (resp. Second) potentially candidate
10101 // to be placed in a paired load.
10102 const LoadedSlice *First = nullptr;
10103 const LoadedSlice *Second = nullptr;
10104 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10105 // Set the beginning of the pair.
10108 Second = &LoadedSlices[CurrSlice];
10110 // If First is NULL, it means we start a new pair.
10111 // Get to the next slice.
10115 EVT LoadedType = First->getLoadedType();
10117 // If the types of the slices are different, we cannot pair them.
10118 if (LoadedType != Second->getLoadedType())
10121 // Check if the target supplies paired loads for this type.
10122 unsigned RequiredAlignment = 0;
10123 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10124 // move to the next pair, this type is hopeless.
10128 // Check if we meet the alignment requirement.
10129 if (RequiredAlignment > First->getAlignment())
10132 // Check that both loads are next to each other in memory.
10133 if (!areSlicesNextToEachOther(*First, *Second))
10136 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10137 --GlobalLSCost.Loads;
10138 // Move to the next pair.
10143 /// \brief Check the profitability of all involved LoadedSlice.
10144 /// Currently, it is considered profitable if there is exactly two
10145 /// involved slices (1) which are (2) next to each other in memory, and
10146 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10148 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10149 /// the elements themselves.
10151 /// FIXME: When the cost model will be mature enough, we can relax
10152 /// constraints (1) and (2).
10153 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10154 const APInt &UsedBits, bool ForCodeSize) {
10155 unsigned NumberOfSlices = LoadedSlices.size();
10156 if (StressLoadSlicing)
10157 return NumberOfSlices > 1;
10160 if (NumberOfSlices != 2)
10164 if (!areUsedBitsDense(UsedBits))
10168 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10169 // The original code has one big load.
10170 OrigCost.Loads = 1;
10171 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10172 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10173 // Accumulate the cost of all the slices.
10174 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10175 GlobalSlicingCost += SliceCost;
10177 // Account as cost in the original configuration the gain obtained
10178 // with the current slices.
10179 OrigCost.addSliceGain(LS);
10182 // If the target supports paired load, adjust the cost accordingly.
10183 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10184 return OrigCost > GlobalSlicingCost;
10187 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10188 /// operations, split it in the various pieces being extracted.
10190 /// This sort of thing is introduced by SROA.
10191 /// This slicing takes care not to insert overlapping loads.
10192 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10193 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10194 if (Level < AfterLegalizeDAG)
10197 LoadSDNode *LD = cast<LoadSDNode>(N);
10198 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10199 !LD->getValueType(0).isInteger())
10202 // Keep track of already used bits to detect overlapping values.
10203 // In that case, we will just abort the transformation.
10204 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10206 SmallVector<LoadedSlice, 4> LoadedSlices;
10208 // Check if this load is used as several smaller chunks of bits.
10209 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10210 // of computation for each trunc.
10211 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10212 UI != UIEnd; ++UI) {
10213 // Skip the uses of the chain.
10214 if (UI.getUse().getResNo() != 0)
10217 SDNode *User = *UI;
10218 unsigned Shift = 0;
10220 // Check if this is a trunc(lshr).
10221 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10222 isa<ConstantSDNode>(User->getOperand(1))) {
10223 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10224 User = *User->use_begin();
10227 // At this point, User is a Truncate, iff we encountered, trunc or
10229 if (User->getOpcode() != ISD::TRUNCATE)
10232 // The width of the type must be a power of 2 and greater than 8-bits.
10233 // Otherwise the load cannot be represented in LLVM IR.
10234 // Moreover, if we shifted with a non-8-bits multiple, the slice
10235 // will be across several bytes. We do not support that.
10236 unsigned Width = User->getValueSizeInBits(0);
10237 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10240 // Build the slice for this chain of computations.
10241 LoadedSlice LS(User, LD, Shift, &DAG);
10242 APInt CurrentUsedBits = LS.getUsedBits();
10244 // Check if this slice overlaps with another.
10245 if ((CurrentUsedBits & UsedBits) != 0)
10247 // Update the bits used globally.
10248 UsedBits |= CurrentUsedBits;
10250 // Check if the new slice would be legal.
10254 // Record the slice.
10255 LoadedSlices.push_back(LS);
10258 // Abort slicing if it does not seem to be profitable.
10259 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10264 // Rewrite each chain to use an independent load.
10265 // By construction, each chain can be represented by a unique load.
10267 // Prepare the argument for the new token factor for all the slices.
10268 SmallVector<SDValue, 8> ArgChains;
10269 for (SmallVectorImpl<LoadedSlice>::const_iterator
10270 LSIt = LoadedSlices.begin(),
10271 LSItEnd = LoadedSlices.end();
10272 LSIt != LSItEnd; ++LSIt) {
10273 SDValue SliceInst = LSIt->loadSlice();
10274 CombineTo(LSIt->Inst, SliceInst, true);
10275 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10276 SliceInst = SliceInst.getOperand(0);
10277 assert(SliceInst->getOpcode() == ISD::LOAD &&
10278 "It takes more than a zext to get to the loaded slice!!");
10279 ArgChains.push_back(SliceInst.getValue(1));
10282 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10284 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10288 /// Check to see if V is (and load (ptr), imm), where the load is having
10289 /// specific bytes cleared out. If so, return the byte size being masked out
10290 /// and the shift amount.
10291 static std::pair<unsigned, unsigned>
10292 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10293 std::pair<unsigned, unsigned> Result(0, 0);
10295 // Check for the structure we're looking for.
10296 if (V->getOpcode() != ISD::AND ||
10297 !isa<ConstantSDNode>(V->getOperand(1)) ||
10298 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10301 // Check the chain and pointer.
10302 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10303 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10305 // The store should be chained directly to the load or be an operand of a
10307 if (LD == Chain.getNode())
10309 else if (Chain->getOpcode() != ISD::TokenFactor)
10310 return Result; // Fail.
10313 for (const SDValue &ChainOp : Chain->op_values())
10314 if (ChainOp.getNode() == LD) {
10318 if (!isOk) return Result;
10321 // This only handles simple types.
10322 if (V.getValueType() != MVT::i16 &&
10323 V.getValueType() != MVT::i32 &&
10324 V.getValueType() != MVT::i64)
10327 // Check the constant mask. Invert it so that the bits being masked out are
10328 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10329 // follow the sign bit for uniformity.
10330 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10331 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10332 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10333 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10334 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10335 if (NotMaskLZ == 64) return Result; // All zero mask.
10337 // See if we have a continuous run of bits. If so, we have 0*1+0*
10338 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10341 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10342 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10343 NotMaskLZ -= 64-V.getValueSizeInBits();
10345 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10346 switch (MaskedBytes) {
10350 default: return Result; // All one mask, or 5-byte mask.
10353 // Verify that the first bit starts at a multiple of mask so that the access
10354 // is aligned the same as the access width.
10355 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10357 Result.first = MaskedBytes;
10358 Result.second = NotMaskTZ/8;
10363 /// Check to see if IVal is something that provides a value as specified by
10364 /// MaskInfo. If so, replace the specified store with a narrower store of
10365 /// truncated IVal.
10367 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10368 SDValue IVal, StoreSDNode *St,
10370 unsigned NumBytes = MaskInfo.first;
10371 unsigned ByteShift = MaskInfo.second;
10372 SelectionDAG &DAG = DC->getDAG();
10374 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10375 // that uses this. If not, this is not a replacement.
10376 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10377 ByteShift*8, (ByteShift+NumBytes)*8);
10378 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10380 // Check that it is legal on the target to do this. It is legal if the new
10381 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10383 MVT VT = MVT::getIntegerVT(NumBytes*8);
10384 if (!DC->isTypeLegal(VT))
10387 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10388 // shifted by ByteShift and truncated down to NumBytes.
10391 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10392 DAG.getConstant(ByteShift*8, DL,
10393 DC->getShiftAmountTy(IVal.getValueType())));
10396 // Figure out the offset for the store and the alignment of the access.
10398 unsigned NewAlign = St->getAlignment();
10400 if (DAG.getDataLayout().isLittleEndian())
10401 StOffset = ByteShift;
10403 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10405 SDValue Ptr = St->getBasePtr();
10408 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10409 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10410 NewAlign = MinAlign(NewAlign, StOffset);
10413 // Truncate down to the new size.
10414 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10417 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10418 St->getPointerInfo().getWithOffset(StOffset),
10419 false, false, NewAlign).getNode();
10423 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10424 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10425 /// narrowing the load and store if it would end up being a win for performance
10427 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10428 StoreSDNode *ST = cast<StoreSDNode>(N);
10429 if (ST->isVolatile())
10432 SDValue Chain = ST->getChain();
10433 SDValue Value = ST->getValue();
10434 SDValue Ptr = ST->getBasePtr();
10435 EVT VT = Value.getValueType();
10437 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10440 unsigned Opc = Value.getOpcode();
10442 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10443 // is a byte mask indicating a consecutive number of bytes, check to see if
10444 // Y is known to provide just those bytes. If so, we try to replace the
10445 // load + replace + store sequence with a single (narrower) store, which makes
10447 if (Opc == ISD::OR) {
10448 std::pair<unsigned, unsigned> MaskedLoad;
10449 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10450 if (MaskedLoad.first)
10451 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10452 Value.getOperand(1), ST,this))
10453 return SDValue(NewST, 0);
10455 // Or is commutative, so try swapping X and Y.
10456 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10457 if (MaskedLoad.first)
10458 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10459 Value.getOperand(0), ST,this))
10460 return SDValue(NewST, 0);
10463 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10464 Value.getOperand(1).getOpcode() != ISD::Constant)
10467 SDValue N0 = Value.getOperand(0);
10468 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10469 Chain == SDValue(N0.getNode(), 1)) {
10470 LoadSDNode *LD = cast<LoadSDNode>(N0);
10471 if (LD->getBasePtr() != Ptr ||
10472 LD->getPointerInfo().getAddrSpace() !=
10473 ST->getPointerInfo().getAddrSpace())
10476 // Find the type to narrow it the load / op / store to.
10477 SDValue N1 = Value.getOperand(1);
10478 unsigned BitWidth = N1.getValueSizeInBits();
10479 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10480 if (Opc == ISD::AND)
10481 Imm ^= APInt::getAllOnesValue(BitWidth);
10482 if (Imm == 0 || Imm.isAllOnesValue())
10484 unsigned ShAmt = Imm.countTrailingZeros();
10485 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10486 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10487 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10488 // The narrowing should be profitable, the load/store operation should be
10489 // legal (or custom) and the store size should be equal to the NewVT width.
10490 while (NewBW < BitWidth &&
10491 (NewVT.getStoreSizeInBits() != NewBW ||
10492 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10493 !TLI.isNarrowingProfitable(VT, NewVT))) {
10494 NewBW = NextPowerOf2(NewBW);
10495 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10497 if (NewBW >= BitWidth)
10500 // If the lsb changed does not start at the type bitwidth boundary,
10501 // start at the previous one.
10503 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10504 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10505 std::min(BitWidth, ShAmt + NewBW));
10506 if ((Imm & Mask) == Imm) {
10507 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10508 if (Opc == ISD::AND)
10509 NewImm ^= APInt::getAllOnesValue(NewBW);
10510 uint64_t PtrOff = ShAmt / 8;
10511 // For big endian targets, we need to adjust the offset to the pointer to
10512 // load the correct bytes.
10513 if (DAG.getDataLayout().isBigEndian())
10514 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10516 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10517 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10518 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10521 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10522 Ptr.getValueType(), Ptr,
10523 DAG.getConstant(PtrOff, SDLoc(LD),
10524 Ptr.getValueType()));
10525 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10526 LD->getChain(), NewPtr,
10527 LD->getPointerInfo().getWithOffset(PtrOff),
10528 LD->isVolatile(), LD->isNonTemporal(),
10529 LD->isInvariant(), NewAlign,
10531 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10532 DAG.getConstant(NewImm, SDLoc(Value),
10534 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10536 ST->getPointerInfo().getWithOffset(PtrOff),
10537 false, false, NewAlign);
10539 AddToWorklist(NewPtr.getNode());
10540 AddToWorklist(NewLD.getNode());
10541 AddToWorklist(NewVal.getNode());
10542 WorklistRemover DeadNodes(*this);
10543 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10552 /// For a given floating point load / store pair, if the load value isn't used
10553 /// by any other operations, then consider transforming the pair to integer
10554 /// load / store operations if the target deems the transformation profitable.
10555 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10556 StoreSDNode *ST = cast<StoreSDNode>(N);
10557 SDValue Chain = ST->getChain();
10558 SDValue Value = ST->getValue();
10559 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10560 Value.hasOneUse() &&
10561 Chain == SDValue(Value.getNode(), 1)) {
10562 LoadSDNode *LD = cast<LoadSDNode>(Value);
10563 EVT VT = LD->getMemoryVT();
10564 if (!VT.isFloatingPoint() ||
10565 VT != ST->getMemoryVT() ||
10566 LD->isNonTemporal() ||
10567 ST->isNonTemporal() ||
10568 LD->getPointerInfo().getAddrSpace() != 0 ||
10569 ST->getPointerInfo().getAddrSpace() != 0)
10572 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10573 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10574 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10575 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10576 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10579 unsigned LDAlign = LD->getAlignment();
10580 unsigned STAlign = ST->getAlignment();
10581 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10582 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10583 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10586 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10587 LD->getChain(), LD->getBasePtr(),
10588 LD->getPointerInfo(),
10589 false, false, false, LDAlign);
10591 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10592 NewLD, ST->getBasePtr(),
10593 ST->getPointerInfo(),
10594 false, false, STAlign);
10596 AddToWorklist(NewLD.getNode());
10597 AddToWorklist(NewST.getNode());
10598 WorklistRemover DeadNodes(*this);
10599 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10608 /// Helper struct to parse and store a memory address as base + index + offset.
10609 /// We ignore sign extensions when it is safe to do so.
10610 /// The following two expressions are not equivalent. To differentiate we need
10611 /// to store whether there was a sign extension involved in the index
10613 /// (load (i64 add (i64 copyfromreg %c)
10614 /// (i64 signextend (add (i8 load %index)
10618 /// (load (i64 add (i64 copyfromreg %c)
10619 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10621 struct BaseIndexOffset {
10625 bool IsIndexSignExt;
10627 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10629 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10630 bool IsIndexSignExt) :
10631 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10633 bool equalBaseIndex(const BaseIndexOffset &Other) {
10634 return Other.Base == Base && Other.Index == Index &&
10635 Other.IsIndexSignExt == IsIndexSignExt;
10638 /// Parses tree in Ptr for base, index, offset addresses.
10639 static BaseIndexOffset match(SDValue Ptr) {
10640 bool IsIndexSignExt = false;
10642 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10643 // instruction, then it could be just the BASE or everything else we don't
10644 // know how to handle. Just use Ptr as BASE and give up.
10645 if (Ptr->getOpcode() != ISD::ADD)
10646 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10648 // We know that we have at least an ADD instruction. Try to pattern match
10649 // the simple case of BASE + OFFSET.
10650 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10651 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10652 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10656 // Inside a loop the current BASE pointer is calculated using an ADD and a
10657 // MUL instruction. In this case Ptr is the actual BASE pointer.
10658 // (i64 add (i64 %array_ptr)
10659 // (i64 mul (i64 %induction_var)
10660 // (i64 %element_size)))
10661 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10662 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10664 // Look at Base + Index + Offset cases.
10665 SDValue Base = Ptr->getOperand(0);
10666 SDValue IndexOffset = Ptr->getOperand(1);
10668 // Skip signextends.
10669 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10670 IndexOffset = IndexOffset->getOperand(0);
10671 IsIndexSignExt = true;
10674 // Either the case of Base + Index (no offset) or something else.
10675 if (IndexOffset->getOpcode() != ISD::ADD)
10676 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10678 // Now we have the case of Base + Index + offset.
10679 SDValue Index = IndexOffset->getOperand(0);
10680 SDValue Offset = IndexOffset->getOperand(1);
10682 if (!isa<ConstantSDNode>(Offset))
10683 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10685 // Ignore signextends.
10686 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10687 Index = Index->getOperand(0);
10688 IsIndexSignExt = true;
10689 } else IsIndexSignExt = false;
10691 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10692 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10697 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10699 ArrayRef<MemOpLink> Stores,
10701 SmallVector<SDValue, 8> BuildVector;
10703 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10704 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10706 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10709 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10710 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10711 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10712 // Make sure we have something to merge.
10716 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10717 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10718 unsigned LatestNodeUsed = 0;
10720 for (unsigned i=0; i < NumStores; ++i) {
10721 // Find a chain for the new wide-store operand. Notice that some
10722 // of the store nodes that we found may not be selected for inclusion
10723 // in the wide store. The chain we use needs to be the chain of the
10724 // latest store node which is *used* and replaced by the wide store.
10725 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10726 LatestNodeUsed = i;
10729 // The latest Node in the DAG.
10730 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10731 SDLoc DL(StoreNodes[0].MemNode);
10735 bool IsVec = MemVT.isVector();
10736 unsigned Elts = NumStores;
10738 // When merging vector stores, get the total number of elements.
10739 Elts *= MemVT.getVectorNumElements();
10741 // Get the type for the merged vector store.
10742 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10743 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10745 if (IsConstantSrc) {
10746 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10748 SmallVector<SDValue, 8> Ops;
10749 for (unsigned i = 0; i < NumStores; ++i) {
10750 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10751 SDValue Val = St->getValue();
10752 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10753 if (Val.getValueType() != MemVT)
10755 Ops.push_back(Val);
10758 // Build the extracted vector elements back into a vector.
10759 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10762 // We should always use a vector store when merging extracted vector
10763 // elements, so this path implies a store of constants.
10764 assert(IsConstantSrc && "Merged vector elements should use vector store");
10766 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10767 APInt StoreInt(SizeInBits, 0);
10769 // Construct a single integer constant which is made of the smaller
10770 // constant inputs.
10771 bool IsLE = DAG.getDataLayout().isLittleEndian();
10772 for (unsigned i = 0; i < NumStores; ++i) {
10773 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10774 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10775 SDValue Val = St->getValue();
10776 StoreInt <<= ElementSizeBytes * 8;
10777 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10778 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10779 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10780 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10782 llvm_unreachable("Invalid constant element type");
10786 // Create the new Load and Store operations.
10787 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10788 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10791 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10792 FirstInChain->getBasePtr(),
10793 FirstInChain->getPointerInfo(),
10795 FirstInChain->getAlignment());
10797 // Replace the last store with the new store
10798 CombineTo(LatestOp, NewStore);
10799 // Erase all other stores.
10800 for (unsigned i = 0; i < NumStores; ++i) {
10801 if (StoreNodes[i].MemNode == LatestOp)
10803 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10804 // ReplaceAllUsesWith will replace all uses that existed when it was
10805 // called, but graph optimizations may cause new ones to appear. For
10806 // example, the case in pr14333 looks like
10808 // St's chain -> St -> another store -> X
10810 // And the only difference from St to the other store is the chain.
10811 // When we change it's chain to be St's chain they become identical,
10812 // get CSEed and the net result is that X is now a use of St.
10813 // Since we know that St is redundant, just iterate.
10814 while (!St->use_empty())
10815 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10816 deleteAndRecombine(St);
10822 void DAGCombiner::getStoreMergeAndAliasCandidates(
10823 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10824 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10825 // This holds the base pointer, index, and the offset in bytes from the base
10827 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10829 // We must have a base and an offset.
10830 if (!BasePtr.Base.getNode())
10833 // Do not handle stores to undef base pointers.
10834 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10837 // Walk up the chain and look for nodes with offsets from the same
10838 // base pointer. Stop when reaching an instruction with a different kind
10839 // or instruction which has a different base pointer.
10840 EVT MemVT = St->getMemoryVT();
10842 StoreSDNode *Index = St;
10845 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10846 : DAG.getSubtarget().useAA();
10849 // Look at other users of the same chain. Stores on the same chain do not
10850 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
10851 // to be on the same chain, so don't bother looking at adjacent chains.
10853 SDValue Chain = St->getChain();
10854 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
10855 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
10857 if (OtherST->isVolatile() || OtherST->isIndexed())
10860 if (OtherST->getMemoryVT() != MemVT)
10863 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
10865 if (Ptr.equalBaseIndex(BasePtr))
10866 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
10874 // If the chain has more than one use, then we can't reorder the mem ops.
10875 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10878 // Find the base pointer and offset for this memory node.
10879 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10881 // Check that the base pointer is the same as the original one.
10882 if (!Ptr.equalBaseIndex(BasePtr))
10885 // The memory operands must not be volatile.
10886 if (Index->isVolatile() || Index->isIndexed())
10890 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10891 if (St->isTruncatingStore())
10894 // The stored memory type must be the same.
10895 if (Index->getMemoryVT() != MemVT)
10898 // We found a potential memory operand to merge.
10899 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10901 // Find the next memory operand in the chain. If the next operand in the
10902 // chain is a store then move up and continue the scan with the next
10903 // memory operand. If the next operand is a load save it and use alias
10904 // information to check if it interferes with anything.
10905 SDNode *NextInChain = Index->getChain().getNode();
10907 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10908 // We found a store node. Use it for the next iteration.
10911 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10912 if (Ldn->isVolatile()) {
10917 // Save the load node for later. Continue the scan.
10918 AliasLoadNodes.push_back(Ldn);
10919 NextInChain = Ldn->getChain().getNode();
10929 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10930 if (OptLevel == CodeGenOpt::None)
10933 EVT MemVT = St->getMemoryVT();
10934 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10935 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10936 Attribute::NoImplicitFloat);
10938 // This function cannot currently deal with non-byte-sized memory sizes.
10939 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10942 // Don't merge vectors into wider inputs.
10943 if (MemVT.isVector() || !MemVT.isSimple())
10946 // Perform an early exit check. Do not bother looking at stored values that
10947 // are not constants, loads, or extracted vector elements.
10948 SDValue StoredVal = St->getValue();
10949 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10950 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10951 isa<ConstantFPSDNode>(StoredVal);
10952 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10954 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10957 // Only look at ends of store sequences.
10958 SDValue Chain = SDValue(St, 0);
10959 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10962 // Save the LoadSDNodes that we find in the chain.
10963 // We need to make sure that these nodes do not interfere with
10964 // any of the store nodes.
10965 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10967 // Save the StoreSDNodes that we find in the chain.
10968 SmallVector<MemOpLink, 8> StoreNodes;
10970 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10972 // Check if there is anything to merge.
10973 if (StoreNodes.size() < 2)
10976 // Sort the memory operands according to their distance from the base pointer.
10977 std::sort(StoreNodes.begin(), StoreNodes.end(),
10978 [](MemOpLink LHS, MemOpLink RHS) {
10979 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10980 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10981 LHS.SequenceNum > RHS.SequenceNum);
10984 // Scan the memory operations on the chain and find the first non-consecutive
10985 // store memory address.
10986 unsigned LastConsecutiveStore = 0;
10987 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10988 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10990 // Check that the addresses are consecutive starting from the second
10991 // element in the list of stores.
10993 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10994 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10998 bool Alias = false;
10999 // Check if this store interferes with any of the loads that we found.
11000 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11001 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11005 // We found a load that alias with this store. Stop the sequence.
11009 // Mark this node as useful.
11010 LastConsecutiveStore = i;
11013 // The node with the lowest store address.
11014 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11015 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11016 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11017 LLVMContext &Context = *DAG.getContext();
11018 const DataLayout &DL = DAG.getDataLayout();
11020 // Store the constants into memory as one consecutive store.
11021 if (IsConstantSrc) {
11022 unsigned LastLegalType = 0;
11023 unsigned LastLegalVectorType = 0;
11024 bool NonZero = false;
11025 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11026 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11027 SDValue StoredVal = St->getValue();
11029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11030 NonZero |= !C->isNullValue();
11031 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11032 NonZero |= !C->getConstantFPValue()->isNullValue();
11038 // Find a legal type for the constant store.
11039 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11040 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11041 if (TLI.isTypeLegal(StoreTy) &&
11042 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11043 FirstStoreAlign)) {
11044 LastLegalType = i+1;
11045 // Or check whether a truncstore is legal.
11046 } else if (TLI.getTypeAction(Context, StoreTy) ==
11047 TargetLowering::TypePromoteInteger) {
11048 EVT LegalizedStoredValueTy =
11049 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11050 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11051 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11052 FirstStoreAS, FirstStoreAlign)) {
11053 LastLegalType = i + 1;
11057 // We only use vectors if the constant is known to be zero or the target
11058 // allows it and the function is not marked with the noimplicitfloat
11060 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11063 // Find a legal type for the vector store.
11064 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11065 if (TLI.isTypeLegal(Ty) &&
11066 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11068 LastLegalVectorType = i + 1;
11072 // Check if we found a legal integer type to store.
11073 if (LastLegalType == 0 && LastLegalVectorType == 0)
11076 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11077 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11079 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11083 // When extracting multiple vector elements, try to store them
11084 // in one vector store rather than a sequence of scalar stores.
11085 if (IsExtractVecEltSrc) {
11086 unsigned NumElem = 0;
11087 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11088 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11089 SDValue StoredVal = St->getValue();
11090 // This restriction could be loosened.
11091 // Bail out if any stored values are not elements extracted from a vector.
11092 // It should be possible to handle mixed sources, but load sources need
11093 // more careful handling (see the block of code below that handles
11094 // consecutive loads).
11095 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11098 // Find a legal type for the vector store.
11099 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11100 if (TLI.isTypeLegal(Ty) &&
11101 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11106 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11110 // Below we handle the case of multiple consecutive stores that
11111 // come from multiple consecutive loads. We merge them into a single
11112 // wide load and a single wide store.
11114 // Look for load nodes which are used by the stored values.
11115 SmallVector<MemOpLink, 8> LoadNodes;
11117 // Find acceptable loads. Loads need to have the same chain (token factor),
11118 // must not be zext, volatile, indexed, and they must be consecutive.
11119 BaseIndexOffset LdBasePtr;
11120 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11121 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11122 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11125 // Loads must only have one use.
11126 if (!Ld->hasNUsesOfValue(1, 0))
11129 // The memory operands must not be volatile.
11130 if (Ld->isVolatile() || Ld->isIndexed())
11133 // We do not accept ext loads.
11134 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11137 // The stored memory type must be the same.
11138 if (Ld->getMemoryVT() != MemVT)
11141 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11142 // If this is not the first ptr that we check.
11143 if (LdBasePtr.Base.getNode()) {
11144 // The base ptr must be the same.
11145 if (!LdPtr.equalBaseIndex(LdBasePtr))
11148 // Check that all other base pointers are the same as this one.
11152 // We found a potential memory operand to merge.
11153 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11156 if (LoadNodes.size() < 2)
11159 // If we have load/store pair instructions and we only have two values,
11161 unsigned RequiredAlignment;
11162 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11163 St->getAlignment() >= RequiredAlignment)
11166 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11167 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11168 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11170 // Scan the memory operations on the chain and find the first non-consecutive
11171 // load memory address. These variables hold the index in the store node
11173 unsigned LastConsecutiveLoad = 0;
11174 // This variable refers to the size and not index in the array.
11175 unsigned LastLegalVectorType = 0;
11176 unsigned LastLegalIntegerType = 0;
11177 StartAddress = LoadNodes[0].OffsetFromBase;
11178 SDValue FirstChain = FirstLoad->getChain();
11179 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11180 // All loads much share the same chain.
11181 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11184 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11185 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11187 LastConsecutiveLoad = i;
11189 // Find a legal type for the vector store.
11190 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11191 if (TLI.isTypeLegal(StoreTy) &&
11192 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11193 FirstStoreAlign) &&
11194 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11196 LastLegalVectorType = i + 1;
11199 // Find a legal type for the integer store.
11200 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11201 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11202 if (TLI.isTypeLegal(StoreTy) &&
11203 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11204 FirstStoreAlign) &&
11205 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11207 LastLegalIntegerType = i + 1;
11208 // Or check whether a truncstore and extload is legal.
11209 else if (TLI.getTypeAction(Context, StoreTy) ==
11210 TargetLowering::TypePromoteInteger) {
11211 EVT LegalizedStoredValueTy =
11212 TLI.getTypeToTransformTo(Context, StoreTy);
11213 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11214 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11215 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11216 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11217 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11218 FirstStoreAS, FirstStoreAlign) &&
11219 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11220 FirstLoadAS, FirstLoadAlign))
11221 LastLegalIntegerType = i+1;
11225 // Only use vector types if the vector type is larger than the integer type.
11226 // If they are the same, use integers.
11227 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11228 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11230 // We add +1 here because the LastXXX variables refer to location while
11231 // the NumElem refers to array/index size.
11232 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11233 NumElem = std::min(LastLegalType, NumElem);
11238 // The latest Node in the DAG.
11239 unsigned LatestNodeUsed = 0;
11240 for (unsigned i=1; i<NumElem; ++i) {
11241 // Find a chain for the new wide-store operand. Notice that some
11242 // of the store nodes that we found may not be selected for inclusion
11243 // in the wide store. The chain we use needs to be the chain of the
11244 // latest store node which is *used* and replaced by the wide store.
11245 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11246 LatestNodeUsed = i;
11249 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11251 // Find if it is better to use vectors or integers to load and store
11255 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11257 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11258 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11261 SDLoc LoadDL(LoadNodes[0].MemNode);
11262 SDLoc StoreDL(StoreNodes[0].MemNode);
11264 SDValue NewLoad = DAG.getLoad(
11265 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11266 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11268 SDValue NewStore = DAG.getStore(
11269 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11270 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11272 // Replace one of the loads with the new load.
11273 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11274 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11275 SDValue(NewLoad.getNode(), 1));
11277 // Remove the rest of the load chains.
11278 for (unsigned i = 1; i < NumElem ; ++i) {
11279 // Replace all chain users of the old load nodes with the chain of the new
11281 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11282 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11285 // Replace the last store with the new store.
11286 CombineTo(LatestOp, NewStore);
11287 // Erase all other stores.
11288 for (unsigned i = 0; i < NumElem ; ++i) {
11289 // Remove all Store nodes.
11290 if (StoreNodes[i].MemNode == LatestOp)
11292 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11293 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11294 deleteAndRecombine(St);
11300 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11304 // Replace the chain to avoid dependency.
11305 if (ST->isTruncatingStore()) {
11306 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11307 ST->getBasePtr(), ST->getMemoryVT(),
11308 ST->getMemOperand());
11310 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11311 ST->getMemOperand());
11314 // Create token to keep both nodes around.
11315 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11316 MVT::Other, ST->getChain(), ReplStore);
11318 // Make sure the new and old chains are cleaned up.
11319 AddToWorklist(Token.getNode());
11321 // Don't add users to work list.
11322 return CombineTo(ST, Token, false);
11325 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11326 StoreSDNode *ST = cast<StoreSDNode>(N);
11327 SDValue Chain = ST->getChain();
11328 SDValue Value = ST->getValue();
11329 SDValue Ptr = ST->getBasePtr();
11331 // If this is a store of a bit convert, store the input value if the
11332 // resultant store does not need a higher alignment than the original.
11333 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11334 ST->isUnindexed()) {
11335 unsigned OrigAlign = ST->getAlignment();
11336 EVT SVT = Value.getOperand(0).getValueType();
11337 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11338 SVT.getTypeForEVT(*DAG.getContext()));
11339 if (Align <= OrigAlign &&
11340 ((!LegalOperations && !ST->isVolatile()) ||
11341 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11342 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11343 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11344 ST->isNonTemporal(), OrigAlign,
11348 // Turn 'store undef, Ptr' -> nothing.
11349 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11352 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11353 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11354 // NOTE: If the original store is volatile, this transform must not increase
11355 // the number of stores. For example, on x86-32 an f64 can be stored in one
11356 // processor operation but an i64 (which is not legal) requires two. So the
11357 // transform should not be done in this case.
11358 if (Value.getOpcode() != ISD::TargetConstantFP) {
11360 switch (CFP->getSimpleValueType(0).SimpleTy) {
11361 default: llvm_unreachable("Unknown FP type");
11362 case MVT::f16: // We don't do this for these yet.
11368 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11369 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11371 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11372 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11374 return DAG.getStore(Chain, SDLoc(N), Tmp,
11375 Ptr, ST->getMemOperand());
11379 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11380 !ST->isVolatile()) ||
11381 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11383 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11384 getZExtValue(), SDLoc(CFP), MVT::i64);
11385 return DAG.getStore(Chain, SDLoc(N), Tmp,
11386 Ptr, ST->getMemOperand());
11389 if (!ST->isVolatile() &&
11390 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11391 // Many FP stores are not made apparent until after legalize, e.g. for
11392 // argument passing. Since this is so common, custom legalize the
11393 // 64-bit integer store into two 32-bit stores.
11394 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11395 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11396 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11397 if (DAG.getDataLayout().isBigEndian())
11400 unsigned Alignment = ST->getAlignment();
11401 bool isVolatile = ST->isVolatile();
11402 bool isNonTemporal = ST->isNonTemporal();
11403 AAMDNodes AAInfo = ST->getAAInfo();
11407 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11408 Ptr, ST->getPointerInfo(),
11409 isVolatile, isNonTemporal,
11410 ST->getAlignment(), AAInfo);
11411 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11412 DAG.getConstant(4, DL, Ptr.getValueType()));
11413 Alignment = MinAlign(Alignment, 4U);
11414 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11415 Ptr, ST->getPointerInfo().getWithOffset(4),
11416 isVolatile, isNonTemporal,
11417 Alignment, AAInfo);
11418 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11427 // Try to infer better alignment information than the store already has.
11428 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11429 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11430 if (Align > ST->getAlignment()) {
11432 DAG.getTruncStore(Chain, SDLoc(N), Value,
11433 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11434 ST->isVolatile(), ST->isNonTemporal(), Align,
11436 if (NewStore.getNode() != N)
11437 return CombineTo(ST, NewStore, true);
11442 // Try transforming a pair floating point load / store ops to integer
11443 // load / store ops.
11444 if (SDValue NewST = TransformFPLoadStorePair(N))
11447 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11448 : DAG.getSubtarget().useAA();
11450 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11451 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11454 if (UseAA && ST->isUnindexed()) {
11455 // FIXME: We should do this even without AA enabled. AA will just allow
11456 // FindBetterChain to work in more situations. The problem with this is that
11457 // any combine that expects memory operations to be on consecutive chains
11458 // first needs to be updated to look for users of the same chain.
11460 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11461 // adjacent stores.
11462 if (findBetterNeighborChains(ST)) {
11463 // replaceStoreChain uses CombineTo, which handled all of the worklist
11464 // manipulation. Return the original node to not do anything else.
11465 return SDValue(ST, 0);
11469 // Try transforming N to an indexed store.
11470 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11471 return SDValue(N, 0);
11473 // FIXME: is there such a thing as a truncating indexed store?
11474 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11475 Value.getValueType().isInteger()) {
11476 // See if we can simplify the input to this truncstore with knowledge that
11477 // only the low bits are being used. For example:
11478 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11480 GetDemandedBits(Value,
11481 APInt::getLowBitsSet(
11482 Value.getValueType().getScalarType().getSizeInBits(),
11483 ST->getMemoryVT().getScalarType().getSizeInBits()));
11484 AddToWorklist(Value.getNode());
11485 if (Shorter.getNode())
11486 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11487 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11489 // Otherwise, see if we can simplify the operation with
11490 // SimplifyDemandedBits, which only works if the value has a single use.
11491 if (SimplifyDemandedBits(Value,
11492 APInt::getLowBitsSet(
11493 Value.getValueType().getScalarType().getSizeInBits(),
11494 ST->getMemoryVT().getScalarType().getSizeInBits())))
11495 return SDValue(N, 0);
11498 // If this is a load followed by a store to the same location, then the store
11500 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11501 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11502 ST->isUnindexed() && !ST->isVolatile() &&
11503 // There can't be any side effects between the load and store, such as
11504 // a call or store.
11505 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11506 // The store is dead, remove it.
11511 // If this is a store followed by a store with the same value to the same
11512 // location, then the store is dead/noop.
11513 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11514 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11515 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11516 ST1->isUnindexed() && !ST1->isVolatile()) {
11517 // The store is dead, remove it.
11522 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11523 // truncating store. We can do this even if this is already a truncstore.
11524 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11525 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11526 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11527 ST->getMemoryVT())) {
11528 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11529 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11532 // Only perform this optimization before the types are legal, because we
11533 // don't want to perform this optimization on every DAGCombine invocation.
11535 bool EverChanged = false;
11538 // There can be multiple store sequences on the same chain.
11539 // Keep trying to merge store sequences until we are unable to do so
11540 // or until we merge the last store on the chain.
11541 bool Changed = MergeConsecutiveStores(ST);
11542 EverChanged |= Changed;
11543 if (!Changed) break;
11544 } while (ST->getOpcode() != ISD::DELETED_NODE);
11547 return SDValue(N, 0);
11550 return ReduceLoadOpStoreWidth(N);
11553 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11554 SDValue InVec = N->getOperand(0);
11555 SDValue InVal = N->getOperand(1);
11556 SDValue EltNo = N->getOperand(2);
11559 // If the inserted element is an UNDEF, just use the input vector.
11560 if (InVal.getOpcode() == ISD::UNDEF)
11563 EVT VT = InVec.getValueType();
11565 // If we can't generate a legal BUILD_VECTOR, exit
11566 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11569 // Check that we know which element is being inserted
11570 if (!isa<ConstantSDNode>(EltNo))
11572 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11574 // Canonicalize insert_vector_elt dag nodes.
11576 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11577 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11579 // Do this only if the child insert_vector node has one use; also
11580 // do this only if indices are both constants and Idx1 < Idx0.
11581 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11582 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11583 unsigned OtherElt =
11584 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11585 if (Elt < OtherElt) {
11587 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11588 InVec.getOperand(0), InVal, EltNo);
11589 AddToWorklist(NewOp.getNode());
11590 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11591 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11595 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11596 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11597 // vector elements.
11598 SmallVector<SDValue, 8> Ops;
11599 // Do not combine these two vectors if the output vector will not replace
11600 // the input vector.
11601 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11602 Ops.append(InVec.getNode()->op_begin(),
11603 InVec.getNode()->op_end());
11604 } else if (InVec.getOpcode() == ISD::UNDEF) {
11605 unsigned NElts = VT.getVectorNumElements();
11606 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11611 // Insert the element
11612 if (Elt < Ops.size()) {
11613 // All the operands of BUILD_VECTOR must have the same type;
11614 // we enforce that here.
11615 EVT OpVT = Ops[0].getValueType();
11616 if (InVal.getValueType() != OpVT)
11617 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11618 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11619 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11623 // Return the new vector
11624 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11627 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11628 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11629 EVT ResultVT = EVE->getValueType(0);
11630 EVT VecEltVT = InVecVT.getVectorElementType();
11631 unsigned Align = OriginalLoad->getAlignment();
11632 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11633 VecEltVT.getTypeForEVT(*DAG.getContext()));
11635 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11640 SDValue NewPtr = OriginalLoad->getBasePtr();
11642 EVT PtrType = NewPtr.getValueType();
11643 MachinePointerInfo MPI;
11645 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11646 int Elt = ConstEltNo->getZExtValue();
11647 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11648 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11649 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11651 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11652 Offset = DAG.getNode(
11653 ISD::MUL, DL, PtrType, Offset,
11654 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11655 MPI = OriginalLoad->getPointerInfo();
11657 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11659 // The replacement we need to do here is a little tricky: we need to
11660 // replace an extractelement of a load with a load.
11661 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11662 // Note that this replacement assumes that the extractvalue is the only
11663 // use of the load; that's okay because we don't want to perform this
11664 // transformation in other cases anyway.
11667 if (ResultVT.bitsGT(VecEltVT)) {
11668 // If the result type of vextract is wider than the load, then issue an
11669 // extending load instead.
11670 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11674 Load = DAG.getExtLoad(
11675 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11676 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11677 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11678 Chain = Load.getValue(1);
11680 Load = DAG.getLoad(
11681 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11682 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11683 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11684 Chain = Load.getValue(1);
11685 if (ResultVT.bitsLT(VecEltVT))
11686 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11688 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11690 WorklistRemover DeadNodes(*this);
11691 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11692 SDValue To[] = { Load, Chain };
11693 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11694 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11695 // worklist explicitly as well.
11696 AddToWorklist(Load.getNode());
11697 AddUsersToWorklist(Load.getNode()); // Add users too
11698 // Make sure to revisit this node to clean it up; it will usually be dead.
11699 AddToWorklist(EVE);
11701 return SDValue(EVE, 0);
11704 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11705 // (vextract (scalar_to_vector val, 0) -> val
11706 SDValue InVec = N->getOperand(0);
11707 EVT VT = InVec.getValueType();
11708 EVT NVT = N->getValueType(0);
11710 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11711 // Check if the result type doesn't match the inserted element type. A
11712 // SCALAR_TO_VECTOR may truncate the inserted element and the
11713 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11714 SDValue InOp = InVec.getOperand(0);
11715 if (InOp.getValueType() != NVT) {
11716 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11717 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11722 SDValue EltNo = N->getOperand(1);
11723 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11725 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11726 // We only perform this optimization before the op legalization phase because
11727 // we may introduce new vector instructions which are not backed by TD
11728 // patterns. For example on AVX, extracting elements from a wide vector
11729 // without using extract_subvector. However, if we can find an underlying
11730 // scalar value, then we can always use that.
11731 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11733 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11734 int NumElem = VT.getVectorNumElements();
11735 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11736 // Find the new index to extract from.
11737 int OrigElt = SVOp->getMaskElt(Elt);
11739 // Extracting an undef index is undef.
11741 return DAG.getUNDEF(NVT);
11743 // Select the right vector half to extract from.
11745 if (OrigElt < NumElem) {
11746 SVInVec = InVec->getOperand(0);
11748 SVInVec = InVec->getOperand(1);
11749 OrigElt -= NumElem;
11752 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11753 SDValue InOp = SVInVec.getOperand(OrigElt);
11754 if (InOp.getValueType() != NVT) {
11755 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11756 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11762 // FIXME: We should handle recursing on other vector shuffles and
11763 // scalar_to_vector here as well.
11765 if (!LegalOperations) {
11766 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11767 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11768 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11772 bool BCNumEltsChanged = false;
11773 EVT ExtVT = VT.getVectorElementType();
11776 // If the result of load has to be truncated, then it's not necessarily
11778 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11781 if (InVec.getOpcode() == ISD::BITCAST) {
11782 // Don't duplicate a load with other uses.
11783 if (!InVec.hasOneUse())
11786 EVT BCVT = InVec.getOperand(0).getValueType();
11787 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11789 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11790 BCNumEltsChanged = true;
11791 InVec = InVec.getOperand(0);
11792 ExtVT = BCVT.getVectorElementType();
11795 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11796 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11797 ISD::isNormalLoad(InVec.getNode()) &&
11798 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11799 SDValue Index = N->getOperand(1);
11800 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11801 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11805 // Perform only after legalization to ensure build_vector / vector_shuffle
11806 // optimizations have already been done.
11807 if (!LegalOperations) return SDValue();
11809 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11810 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11811 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11814 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11816 LoadSDNode *LN0 = nullptr;
11817 const ShuffleVectorSDNode *SVN = nullptr;
11818 if (ISD::isNormalLoad(InVec.getNode())) {
11819 LN0 = cast<LoadSDNode>(InVec);
11820 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11821 InVec.getOperand(0).getValueType() == ExtVT &&
11822 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11823 // Don't duplicate a load with other uses.
11824 if (!InVec.hasOneUse())
11827 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11828 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11829 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11831 // (load $addr+1*size)
11833 // Don't duplicate a load with other uses.
11834 if (!InVec.hasOneUse())
11837 // If the bit convert changed the number of elements, it is unsafe
11838 // to examine the mask.
11839 if (BCNumEltsChanged)
11842 // Select the input vector, guarding against out of range extract vector.
11843 unsigned NumElems = VT.getVectorNumElements();
11844 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11845 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11847 if (InVec.getOpcode() == ISD::BITCAST) {
11848 // Don't duplicate a load with other uses.
11849 if (!InVec.hasOneUse())
11852 InVec = InVec.getOperand(0);
11854 if (ISD::isNormalLoad(InVec.getNode())) {
11855 LN0 = cast<LoadSDNode>(InVec);
11856 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11857 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11861 // Make sure we found a non-volatile load and the extractelement is
11863 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11866 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11868 return DAG.getUNDEF(LVT);
11870 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11876 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11877 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11878 // We perform this optimization post type-legalization because
11879 // the type-legalizer often scalarizes integer-promoted vectors.
11880 // Performing this optimization before may create bit-casts which
11881 // will be type-legalized to complex code sequences.
11882 // We perform this optimization only before the operation legalizer because we
11883 // may introduce illegal operations.
11884 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11887 unsigned NumInScalars = N->getNumOperands();
11889 EVT VT = N->getValueType(0);
11891 // Check to see if this is a BUILD_VECTOR of a bunch of values
11892 // which come from any_extend or zero_extend nodes. If so, we can create
11893 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11894 // optimizations. We do not handle sign-extend because we can't fill the sign
11896 EVT SourceType = MVT::Other;
11897 bool AllAnyExt = true;
11899 for (unsigned i = 0; i != NumInScalars; ++i) {
11900 SDValue In = N->getOperand(i);
11901 // Ignore undef inputs.
11902 if (In.getOpcode() == ISD::UNDEF) continue;
11904 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11905 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11907 // Abort if the element is not an extension.
11908 if (!ZeroExt && !AnyExt) {
11909 SourceType = MVT::Other;
11913 // The input is a ZeroExt or AnyExt. Check the original type.
11914 EVT InTy = In.getOperand(0).getValueType();
11916 // Check that all of the widened source types are the same.
11917 if (SourceType == MVT::Other)
11920 else if (InTy != SourceType) {
11921 // Multiple income types. Abort.
11922 SourceType = MVT::Other;
11926 // Check if all of the extends are ANY_EXTENDs.
11927 AllAnyExt &= AnyExt;
11930 // In order to have valid types, all of the inputs must be extended from the
11931 // same source type and all of the inputs must be any or zero extend.
11932 // Scalar sizes must be a power of two.
11933 EVT OutScalarTy = VT.getScalarType();
11934 bool ValidTypes = SourceType != MVT::Other &&
11935 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11936 isPowerOf2_32(SourceType.getSizeInBits());
11938 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11939 // turn into a single shuffle instruction.
11943 bool isLE = DAG.getDataLayout().isLittleEndian();
11944 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11945 assert(ElemRatio > 1 && "Invalid element size ratio");
11946 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11947 DAG.getConstant(0, SDLoc(N), SourceType);
11949 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11950 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11952 // Populate the new build_vector
11953 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11954 SDValue Cast = N->getOperand(i);
11955 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11956 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11957 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11959 if (Cast.getOpcode() == ISD::UNDEF)
11960 In = DAG.getUNDEF(SourceType);
11962 In = Cast->getOperand(0);
11963 unsigned Index = isLE ? (i * ElemRatio) :
11964 (i * ElemRatio + (ElemRatio - 1));
11966 assert(Index < Ops.size() && "Invalid index");
11970 // The type of the new BUILD_VECTOR node.
11971 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11972 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11973 "Invalid vector size");
11974 // Check if the new vector type is legal.
11975 if (!isTypeLegal(VecVT)) return SDValue();
11977 // Make the new BUILD_VECTOR.
11978 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11980 // The new BUILD_VECTOR node has the potential to be further optimized.
11981 AddToWorklist(BV.getNode());
11982 // Bitcast to the desired type.
11983 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11986 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11987 EVT VT = N->getValueType(0);
11989 unsigned NumInScalars = N->getNumOperands();
11992 EVT SrcVT = MVT::Other;
11993 unsigned Opcode = ISD::DELETED_NODE;
11994 unsigned NumDefs = 0;
11996 for (unsigned i = 0; i != NumInScalars; ++i) {
11997 SDValue In = N->getOperand(i);
11998 unsigned Opc = In.getOpcode();
12000 if (Opc == ISD::UNDEF)
12003 // If all scalar values are floats and converted from integers.
12004 if (Opcode == ISD::DELETED_NODE &&
12005 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12012 EVT InVT = In.getOperand(0).getValueType();
12014 // If all scalar values are typed differently, bail out. It's chosen to
12015 // simplify BUILD_VECTOR of integer types.
12016 if (SrcVT == MVT::Other)
12023 // If the vector has just one element defined, it's not worth to fold it into
12024 // a vectorized one.
12028 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12029 && "Should only handle conversion from integer to float.");
12030 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12032 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12034 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12037 // Just because the floating-point vector type is legal does not necessarily
12038 // mean that the corresponding integer vector type is.
12039 if (!isTypeLegal(NVT))
12042 SmallVector<SDValue, 8> Opnds;
12043 for (unsigned i = 0; i != NumInScalars; ++i) {
12044 SDValue In = N->getOperand(i);
12046 if (In.getOpcode() == ISD::UNDEF)
12047 Opnds.push_back(DAG.getUNDEF(SrcVT));
12049 Opnds.push_back(In.getOperand(0));
12051 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12052 AddToWorklist(BV.getNode());
12054 return DAG.getNode(Opcode, dl, VT, BV);
12057 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12058 unsigned NumInScalars = N->getNumOperands();
12060 EVT VT = N->getValueType(0);
12062 // A vector built entirely of undefs is undef.
12063 if (ISD::allOperandsUndef(N))
12064 return DAG.getUNDEF(VT);
12066 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12069 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12072 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12073 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12074 // at most two distinct vectors, turn this into a shuffle node.
12076 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12077 if (!isTypeLegal(VT))
12080 // May only combine to shuffle after legalize if shuffle is legal.
12081 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12084 SDValue VecIn1, VecIn2;
12085 bool UsesZeroVector = false;
12086 for (unsigned i = 0; i != NumInScalars; ++i) {
12087 SDValue Op = N->getOperand(i);
12088 // Ignore undef inputs.
12089 if (Op.getOpcode() == ISD::UNDEF) continue;
12091 // See if we can combine this build_vector into a blend with a zero vector.
12092 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12093 UsesZeroVector = true;
12097 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12098 // constant index, bail out.
12099 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12100 !isa<ConstantSDNode>(Op.getOperand(1))) {
12101 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12105 // We allow up to two distinct input vectors.
12106 SDValue ExtractedFromVec = Op.getOperand(0);
12107 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12110 if (!VecIn1.getNode()) {
12111 VecIn1 = ExtractedFromVec;
12112 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12113 VecIn2 = ExtractedFromVec;
12115 // Too many inputs.
12116 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12121 // If everything is good, we can make a shuffle operation.
12122 if (VecIn1.getNode()) {
12123 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12124 SmallVector<int, 8> Mask;
12125 for (unsigned i = 0; i != NumInScalars; ++i) {
12126 unsigned Opcode = N->getOperand(i).getOpcode();
12127 if (Opcode == ISD::UNDEF) {
12128 Mask.push_back(-1);
12132 // Operands can also be zero.
12133 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12134 assert(UsesZeroVector &&
12135 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12136 "Unexpected node found!");
12137 Mask.push_back(NumInScalars+i);
12141 // If extracting from the first vector, just use the index directly.
12142 SDValue Extract = N->getOperand(i);
12143 SDValue ExtVal = Extract.getOperand(1);
12144 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12145 if (Extract.getOperand(0) == VecIn1) {
12146 Mask.push_back(ExtIndex);
12150 // Otherwise, use InIdx + InputVecSize
12151 Mask.push_back(InNumElements + ExtIndex);
12154 // Avoid introducing illegal shuffles with zero.
12155 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12158 // We can't generate a shuffle node with mismatched input and output types.
12159 // Attempt to transform a single input vector to the correct type.
12160 if ((VT != VecIn1.getValueType())) {
12161 // If the input vector type has a different base type to the output
12162 // vector type, bail out.
12163 EVT VTElemType = VT.getVectorElementType();
12164 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12165 (VecIn2.getNode() &&
12166 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12169 // If the input vector is too small, widen it.
12170 // We only support widening of vectors which are half the size of the
12171 // output registers. For example XMM->YMM widening on X86 with AVX.
12172 EVT VecInT = VecIn1.getValueType();
12173 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12174 // If we only have one small input, widen it by adding undef values.
12175 if (!VecIn2.getNode())
12176 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12177 DAG.getUNDEF(VecIn1.getValueType()));
12178 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12179 // If we have two small inputs of the same type, try to concat them.
12180 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12181 VecIn2 = SDValue(nullptr, 0);
12184 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12185 // If the input vector is too large, try to split it.
12186 // We don't support having two input vectors that are too large.
12187 // If the zero vector was used, we can not split the vector,
12188 // since we'd need 3 inputs.
12189 if (UsesZeroVector || VecIn2.getNode())
12192 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12195 // Try to replace VecIn1 with two extract_subvectors
12196 // No need to update the masks, they should still be correct.
12197 VecIn2 = DAG.getNode(
12198 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12199 DAG.getConstant(VT.getVectorNumElements(), dl,
12200 TLI.getVectorIdxTy(DAG.getDataLayout())));
12201 VecIn1 = DAG.getNode(
12202 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12203 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12208 if (UsesZeroVector)
12209 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12210 DAG.getConstantFP(0.0, dl, VT);
12212 // If VecIn2 is unused then change it to undef.
12213 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12215 // Check that we were able to transform all incoming values to the same
12217 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12218 VecIn1.getValueType() != VT)
12221 // Return the new VECTOR_SHUFFLE node.
12225 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12231 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12233 EVT OpVT = N->getOperand(0).getValueType();
12235 // If the operands are legal vectors, leave them alone.
12236 if (TLI.isTypeLegal(OpVT))
12240 EVT VT = N->getValueType(0);
12241 SmallVector<SDValue, 8> Ops;
12243 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12244 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12246 // Keep track of what we encounter.
12247 bool AnyInteger = false;
12248 bool AnyFP = false;
12249 for (const SDValue &Op : N->ops()) {
12250 if (ISD::BITCAST == Op.getOpcode() &&
12251 !Op.getOperand(0).getValueType().isVector())
12252 Ops.push_back(Op.getOperand(0));
12253 else if (ISD::UNDEF == Op.getOpcode())
12254 Ops.push_back(ScalarUndef);
12258 // Note whether we encounter an integer or floating point scalar.
12259 // If it's neither, bail out, it could be something weird like x86mmx.
12260 EVT LastOpVT = Ops.back().getValueType();
12261 if (LastOpVT.isFloatingPoint())
12263 else if (LastOpVT.isInteger())
12269 // If any of the operands is a floating point scalar bitcast to a vector,
12270 // use floating point types throughout, and bitcast everything.
12271 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12273 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12274 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12276 for (SDValue &Op : Ops) {
12277 if (Op.getValueType() == SVT)
12279 if (Op.getOpcode() == ISD::UNDEF)
12282 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12287 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12288 VT.getSizeInBits() / SVT.getSizeInBits());
12289 return DAG.getNode(ISD::BITCAST, DL, VT,
12290 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12293 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12294 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12295 // most two distinct vectors the same size as the result, attempt to turn this
12296 // into a legal shuffle.
12297 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12298 EVT VT = N->getValueType(0);
12299 EVT OpVT = N->getOperand(0).getValueType();
12300 int NumElts = VT.getVectorNumElements();
12301 int NumOpElts = OpVT.getVectorNumElements();
12303 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12304 SmallVector<int, 8> Mask;
12306 for (SDValue Op : N->ops()) {
12307 // Peek through any bitcast.
12308 while (Op.getOpcode() == ISD::BITCAST)
12309 Op = Op.getOperand(0);
12311 // UNDEF nodes convert to UNDEF shuffle mask values.
12312 if (Op.getOpcode() == ISD::UNDEF) {
12313 Mask.append((unsigned)NumOpElts, -1);
12317 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12320 // What vector are we extracting the subvector from and at what index?
12321 SDValue ExtVec = Op.getOperand(0);
12323 // We want the EVT of the original extraction to correctly scale the
12324 // extraction index.
12325 EVT ExtVT = ExtVec.getValueType();
12327 // Peek through any bitcast.
12328 while (ExtVec.getOpcode() == ISD::BITCAST)
12329 ExtVec = ExtVec.getOperand(0);
12331 // UNDEF nodes convert to UNDEF shuffle mask values.
12332 if (ExtVec.getOpcode() == ISD::UNDEF) {
12333 Mask.append((unsigned)NumOpElts, -1);
12337 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12339 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12341 // Ensure that we are extracting a subvector from a vector the same
12342 // size as the result.
12343 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12346 // Scale the subvector index to account for any bitcast.
12347 int NumExtElts = ExtVT.getVectorNumElements();
12348 if (0 == (NumExtElts % NumElts))
12349 ExtIdx /= (NumExtElts / NumElts);
12350 else if (0 == (NumElts % NumExtElts))
12351 ExtIdx *= (NumElts / NumExtElts);
12355 // At most we can reference 2 inputs in the final shuffle.
12356 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12358 for (int i = 0; i != NumOpElts; ++i)
12359 Mask.push_back(i + ExtIdx);
12360 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12362 for (int i = 0; i != NumOpElts; ++i)
12363 Mask.push_back(i + ExtIdx + NumElts);
12369 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12372 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12373 DAG.getBitcast(VT, SV1), Mask);
12376 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12377 // If we only have one input vector, we don't need to do any concatenation.
12378 if (N->getNumOperands() == 1)
12379 return N->getOperand(0);
12381 // Check if all of the operands are undefs.
12382 EVT VT = N->getValueType(0);
12383 if (ISD::allOperandsUndef(N))
12384 return DAG.getUNDEF(VT);
12386 // Optimize concat_vectors where all but the first of the vectors are undef.
12387 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12388 return Op.getOpcode() == ISD::UNDEF;
12390 SDValue In = N->getOperand(0);
12391 assert(In.getValueType().isVector() && "Must concat vectors");
12393 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12394 if (In->getOpcode() == ISD::BITCAST &&
12395 !In->getOperand(0)->getValueType(0).isVector()) {
12396 SDValue Scalar = In->getOperand(0);
12398 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12399 // look through the trunc so we can still do the transform:
12400 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12401 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12402 !TLI.isTypeLegal(Scalar.getValueType()) &&
12403 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12404 Scalar = Scalar->getOperand(0);
12406 EVT SclTy = Scalar->getValueType(0);
12408 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12411 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12412 VT.getSizeInBits() / SclTy.getSizeInBits());
12413 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12416 SDLoc dl = SDLoc(N);
12417 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12418 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12422 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12423 // We have already tested above for an UNDEF only concatenation.
12424 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12425 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12426 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12427 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12429 bool AllBuildVectorsOrUndefs =
12430 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12431 if (AllBuildVectorsOrUndefs) {
12432 SmallVector<SDValue, 8> Opnds;
12433 EVT SVT = VT.getScalarType();
12436 if (!SVT.isFloatingPoint()) {
12437 // If BUILD_VECTOR are from built from integer, they may have different
12438 // operand types. Get the smallest type and truncate all operands to it.
12439 bool FoundMinVT = false;
12440 for (const SDValue &Op : N->ops())
12441 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12442 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12443 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12446 assert(FoundMinVT && "Concat vector type mismatch");
12449 for (const SDValue &Op : N->ops()) {
12450 EVT OpVT = Op.getValueType();
12451 unsigned NumElts = OpVT.getVectorNumElements();
12453 if (ISD::UNDEF == Op.getOpcode())
12454 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12456 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12457 if (SVT.isFloatingPoint()) {
12458 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12459 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12461 for (unsigned i = 0; i != NumElts; ++i)
12463 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12468 assert(VT.getVectorNumElements() == Opnds.size() &&
12469 "Concat vector type mismatch");
12470 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12473 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12474 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12477 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12478 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12479 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12482 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12483 // nodes often generate nop CONCAT_VECTOR nodes.
12484 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12485 // place the incoming vectors at the exact same location.
12486 SDValue SingleSource = SDValue();
12487 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12489 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12490 SDValue Op = N->getOperand(i);
12492 if (Op.getOpcode() == ISD::UNDEF)
12495 // Check if this is the identity extract:
12496 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12499 // Find the single incoming vector for the extract_subvector.
12500 if (SingleSource.getNode()) {
12501 if (Op.getOperand(0) != SingleSource)
12504 SingleSource = Op.getOperand(0);
12506 // Check the source type is the same as the type of the result.
12507 // If not, this concat may extend the vector, so we can not
12508 // optimize it away.
12509 if (SingleSource.getValueType() != N->getValueType(0))
12513 unsigned IdentityIndex = i * PartNumElem;
12514 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12515 // The extract index must be constant.
12519 // Check that we are reading from the identity index.
12520 if (CS->getZExtValue() != IdentityIndex)
12524 if (SingleSource.getNode())
12525 return SingleSource;
12530 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12531 EVT NVT = N->getValueType(0);
12532 SDValue V = N->getOperand(0);
12534 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12536 // (extract_subvec (concat V1, V2, ...), i)
12539 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12541 if (V->getOperand(0).getValueType() != NVT)
12543 unsigned Idx = N->getConstantOperandVal(1);
12544 unsigned NumElems = NVT.getVectorNumElements();
12545 assert((Idx % NumElems) == 0 &&
12546 "IDX in concat is not a multiple of the result vector length.");
12547 return V->getOperand(Idx / NumElems);
12551 if (V->getOpcode() == ISD::BITCAST)
12552 V = V.getOperand(0);
12554 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12556 // Handle only simple case where vector being inserted and vector
12557 // being extracted are of same type, and are half size of larger vectors.
12558 EVT BigVT = V->getOperand(0).getValueType();
12559 EVT SmallVT = V->getOperand(1).getValueType();
12560 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12563 // Only handle cases where both indexes are constants with the same type.
12564 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12565 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12567 if (InsIdx && ExtIdx &&
12568 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12569 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12571 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12573 // indices are equal or bit offsets are equal => V1
12574 // otherwise => (extract_subvec V1, ExtIdx)
12575 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12576 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12577 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12578 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12579 DAG.getNode(ISD::BITCAST, dl,
12580 N->getOperand(0).getValueType(),
12581 V->getOperand(0)), N->getOperand(1));
12588 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12589 SDValue V, SelectionDAG &DAG) {
12591 EVT VT = V.getValueType();
12593 switch (V.getOpcode()) {
12597 case ISD::CONCAT_VECTORS: {
12598 EVT OpVT = V->getOperand(0).getValueType();
12599 int OpSize = OpVT.getVectorNumElements();
12600 SmallBitVector OpUsedElements(OpSize, false);
12601 bool FoundSimplification = false;
12602 SmallVector<SDValue, 4> NewOps;
12603 NewOps.reserve(V->getNumOperands());
12604 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12605 SDValue Op = V->getOperand(i);
12606 bool OpUsed = false;
12607 for (int j = 0; j < OpSize; ++j)
12608 if (UsedElements[i * OpSize + j]) {
12609 OpUsedElements[j] = true;
12613 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12614 : DAG.getUNDEF(OpVT));
12615 FoundSimplification |= Op == NewOps.back();
12616 OpUsedElements.reset();
12618 if (FoundSimplification)
12619 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12623 case ISD::INSERT_SUBVECTOR: {
12624 SDValue BaseV = V->getOperand(0);
12625 SDValue SubV = V->getOperand(1);
12626 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12630 int SubSize = SubV.getValueType().getVectorNumElements();
12631 int Idx = IdxN->getZExtValue();
12632 bool SubVectorUsed = false;
12633 SmallBitVector SubUsedElements(SubSize, false);
12634 for (int i = 0; i < SubSize; ++i)
12635 if (UsedElements[i + Idx]) {
12636 SubVectorUsed = true;
12637 SubUsedElements[i] = true;
12638 UsedElements[i + Idx] = false;
12641 // Now recurse on both the base and sub vectors.
12642 SDValue SimplifiedSubV =
12644 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12645 : DAG.getUNDEF(SubV.getValueType());
12646 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12647 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12648 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12649 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12655 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12656 SDValue N1, SelectionDAG &DAG) {
12657 EVT VT = SVN->getValueType(0);
12658 int NumElts = VT.getVectorNumElements();
12659 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12660 for (int M : SVN->getMask())
12661 if (M >= 0 && M < NumElts)
12662 N0UsedElements[M] = true;
12663 else if (M >= NumElts)
12664 N1UsedElements[M - NumElts] = true;
12666 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12667 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12668 if (S0 == N0 && S1 == N1)
12671 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12674 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12675 // or turn a shuffle of a single concat into simpler shuffle then concat.
12676 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12677 EVT VT = N->getValueType(0);
12678 unsigned NumElts = VT.getVectorNumElements();
12680 SDValue N0 = N->getOperand(0);
12681 SDValue N1 = N->getOperand(1);
12682 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12684 SmallVector<SDValue, 4> Ops;
12685 EVT ConcatVT = N0.getOperand(0).getValueType();
12686 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12687 unsigned NumConcats = NumElts / NumElemsPerConcat;
12689 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12690 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12691 // half vector elements.
12692 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12693 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12694 SVN->getMask().end(), [](int i) { return i == -1; })) {
12695 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12696 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12697 N1 = DAG.getUNDEF(ConcatVT);
12698 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12701 // Look at every vector that's inserted. We're looking for exact
12702 // subvector-sized copies from a concatenated vector
12703 for (unsigned I = 0; I != NumConcats; ++I) {
12704 // Make sure we're dealing with a copy.
12705 unsigned Begin = I * NumElemsPerConcat;
12706 bool AllUndef = true, NoUndef = true;
12707 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12708 if (SVN->getMaskElt(J) >= 0)
12715 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12718 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12719 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12722 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12723 if (FirstElt < N0.getNumOperands())
12724 Ops.push_back(N0.getOperand(FirstElt));
12726 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12728 } else if (AllUndef) {
12729 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12730 } else { // Mixed with general masks and undefs, can't do optimization.
12735 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12738 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12739 EVT VT = N->getValueType(0);
12740 unsigned NumElts = VT.getVectorNumElements();
12742 SDValue N0 = N->getOperand(0);
12743 SDValue N1 = N->getOperand(1);
12745 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12747 // Canonicalize shuffle undef, undef -> undef
12748 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12749 return DAG.getUNDEF(VT);
12751 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12753 // Canonicalize shuffle v, v -> v, undef
12755 SmallVector<int, 8> NewMask;
12756 for (unsigned i = 0; i != NumElts; ++i) {
12757 int Idx = SVN->getMaskElt(i);
12758 if (Idx >= (int)NumElts) Idx -= NumElts;
12759 NewMask.push_back(Idx);
12761 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12765 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12766 if (N0.getOpcode() == ISD::UNDEF) {
12767 SmallVector<int, 8> NewMask;
12768 for (unsigned i = 0; i != NumElts; ++i) {
12769 int Idx = SVN->getMaskElt(i);
12771 if (Idx >= (int)NumElts)
12774 Idx = -1; // remove reference to lhs
12776 NewMask.push_back(Idx);
12778 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12782 // Remove references to rhs if it is undef
12783 if (N1.getOpcode() == ISD::UNDEF) {
12784 bool Changed = false;
12785 SmallVector<int, 8> NewMask;
12786 for (unsigned i = 0; i != NumElts; ++i) {
12787 int Idx = SVN->getMaskElt(i);
12788 if (Idx >= (int)NumElts) {
12792 NewMask.push_back(Idx);
12795 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12798 // If it is a splat, check if the argument vector is another splat or a
12800 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12801 SDNode *V = N0.getNode();
12803 // If this is a bit convert that changes the element type of the vector but
12804 // not the number of vector elements, look through it. Be careful not to
12805 // look though conversions that change things like v4f32 to v2f64.
12806 if (V->getOpcode() == ISD::BITCAST) {
12807 SDValue ConvInput = V->getOperand(0);
12808 if (ConvInput.getValueType().isVector() &&
12809 ConvInput.getValueType().getVectorNumElements() == NumElts)
12810 V = ConvInput.getNode();
12813 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12814 assert(V->getNumOperands() == NumElts &&
12815 "BUILD_VECTOR has wrong number of operands");
12817 bool AllSame = true;
12818 for (unsigned i = 0; i != NumElts; ++i) {
12819 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12820 Base = V->getOperand(i);
12824 // Splat of <u, u, u, u>, return <u, u, u, u>
12825 if (!Base.getNode())
12827 for (unsigned i = 0; i != NumElts; ++i) {
12828 if (V->getOperand(i) != Base) {
12833 // Splat of <x, x, x, x>, return <x, x, x, x>
12837 // Canonicalize any other splat as a build_vector.
12838 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12839 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12840 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12841 V->getValueType(0), Ops);
12843 // We may have jumped through bitcasts, so the type of the
12844 // BUILD_VECTOR may not match the type of the shuffle.
12845 if (V->getValueType(0) != VT)
12846 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12851 // There are various patterns used to build up a vector from smaller vectors,
12852 // subvectors, or elements. Scan chains of these and replace unused insertions
12853 // or components with undef.
12854 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12857 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12858 Level < AfterLegalizeVectorOps &&
12859 (N1.getOpcode() == ISD::UNDEF ||
12860 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12861 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12862 SDValue V = partitionShuffleOfConcats(N, DAG);
12868 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12869 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12870 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12871 SmallVector<SDValue, 8> Ops;
12872 for (int M : SVN->getMask()) {
12873 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12875 int Idx = M % NumElts;
12876 SDValue &S = (M < (int)NumElts ? N0 : N1);
12877 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12878 Op = S.getOperand(Idx);
12879 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12881 Op = S.getOperand(0);
12883 // Operand can't be combined - bail out.
12889 if (Ops.size() == VT.getVectorNumElements()) {
12890 // BUILD_VECTOR requires all inputs to be of the same type, find the
12891 // maximum type and extend them all.
12892 EVT SVT = VT.getScalarType();
12893 if (SVT.isInteger())
12894 for (SDValue &Op : Ops)
12895 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12896 if (SVT != VT.getScalarType())
12897 for (SDValue &Op : Ops)
12898 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12899 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12900 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12901 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12905 // If this shuffle only has a single input that is a bitcasted shuffle,
12906 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12907 // back to their original types.
12908 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12909 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12910 TLI.isTypeLegal(VT)) {
12912 // Peek through the bitcast only if there is one user.
12914 while (BC0.getOpcode() == ISD::BITCAST) {
12915 if (!BC0.hasOneUse())
12917 BC0 = BC0.getOperand(0);
12920 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12922 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12924 SmallVector<int, 8> NewMask;
12926 for (int s = 0; s != Scale; ++s)
12927 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12931 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12932 EVT SVT = VT.getScalarType();
12933 EVT InnerVT = BC0->getValueType(0);
12934 EVT InnerSVT = InnerVT.getScalarType();
12936 // Determine which shuffle works with the smaller scalar type.
12937 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12938 EVT ScaleSVT = ScaleVT.getScalarType();
12940 if (TLI.isTypeLegal(ScaleVT) &&
12941 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12942 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12944 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12945 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12947 // Scale the shuffle masks to the smaller scalar type.
12948 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12949 SmallVector<int, 8> InnerMask =
12950 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12951 SmallVector<int, 8> OuterMask =
12952 ScaleShuffleMask(SVN->getMask(), OuterScale);
12954 // Merge the shuffle masks.
12955 SmallVector<int, 8> NewMask;
12956 for (int M : OuterMask)
12957 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12959 // Test for shuffle mask legality over both commutations.
12960 SDValue SV0 = BC0->getOperand(0);
12961 SDValue SV1 = BC0->getOperand(1);
12962 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12964 std::swap(SV0, SV1);
12965 ShuffleVectorSDNode::commuteMask(NewMask);
12966 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12970 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12971 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12972 return DAG.getNode(
12973 ISD::BITCAST, SDLoc(N), VT,
12974 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12980 // Canonicalize shuffles according to rules:
12981 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12982 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12983 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12984 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12985 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12986 TLI.isTypeLegal(VT)) {
12987 // The incoming shuffle must be of the same type as the result of the
12988 // current shuffle.
12989 assert(N1->getOperand(0).getValueType() == VT &&
12990 "Shuffle types don't match");
12992 SDValue SV0 = N1->getOperand(0);
12993 SDValue SV1 = N1->getOperand(1);
12994 bool HasSameOp0 = N0 == SV0;
12995 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12996 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12997 // Commute the operands of this shuffle so that next rule
12999 return DAG.getCommutedVectorShuffle(*SVN);
13002 // Try to fold according to rules:
13003 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13004 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13005 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13006 // Don't try to fold shuffles with illegal type.
13007 // Only fold if this shuffle is the only user of the other shuffle.
13008 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13009 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13010 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13012 // The incoming shuffle must be of the same type as the result of the
13013 // current shuffle.
13014 assert(OtherSV->getOperand(0).getValueType() == VT &&
13015 "Shuffle types don't match");
13018 SmallVector<int, 4> Mask;
13019 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13020 // operand, and SV1 as the second operand.
13021 for (unsigned i = 0; i != NumElts; ++i) {
13022 int Idx = SVN->getMaskElt(i);
13024 // Propagate Undef.
13025 Mask.push_back(Idx);
13029 SDValue CurrentVec;
13030 if (Idx < (int)NumElts) {
13031 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13032 // shuffle mask to identify which vector is actually referenced.
13033 Idx = OtherSV->getMaskElt(Idx);
13035 // Propagate Undef.
13036 Mask.push_back(Idx);
13040 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13041 : OtherSV->getOperand(1);
13043 // This shuffle index references an element within N1.
13047 // Simple case where 'CurrentVec' is UNDEF.
13048 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13049 Mask.push_back(-1);
13053 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13054 // will be the first or second operand of the combined shuffle.
13055 Idx = Idx % NumElts;
13056 if (!SV0.getNode() || SV0 == CurrentVec) {
13057 // Ok. CurrentVec is the left hand side.
13058 // Update the mask accordingly.
13060 Mask.push_back(Idx);
13064 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13065 if (SV1.getNode() && SV1 != CurrentVec)
13068 // Ok. CurrentVec is the right hand side.
13069 // Update the mask accordingly.
13071 Mask.push_back(Idx + NumElts);
13074 // Check if all indices in Mask are Undef. In case, propagate Undef.
13075 bool isUndefMask = true;
13076 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13077 isUndefMask &= Mask[i] < 0;
13080 return DAG.getUNDEF(VT);
13082 if (!SV0.getNode())
13083 SV0 = DAG.getUNDEF(VT);
13084 if (!SV1.getNode())
13085 SV1 = DAG.getUNDEF(VT);
13087 // Avoid introducing shuffles with illegal mask.
13088 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13089 ShuffleVectorSDNode::commuteMask(Mask);
13091 if (!TLI.isShuffleMaskLegal(Mask, VT))
13094 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13095 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13096 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13097 std::swap(SV0, SV1);
13100 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13101 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13102 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13103 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13109 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13110 SDValue InVal = N->getOperand(0);
13111 EVT VT = N->getValueType(0);
13113 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13114 // with a VECTOR_SHUFFLE.
13115 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13116 SDValue InVec = InVal->getOperand(0);
13117 SDValue EltNo = InVal->getOperand(1);
13119 // FIXME: We could support implicit truncation if the shuffle can be
13120 // scaled to a smaller vector scalar type.
13121 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13122 if (C0 && VT == InVec.getValueType() &&
13123 VT.getScalarType() == InVal.getValueType()) {
13124 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13125 int Elt = C0->getZExtValue();
13128 if (TLI.isShuffleMaskLegal(NewMask, VT))
13129 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13137 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13138 SDValue N0 = N->getOperand(0);
13139 SDValue N2 = N->getOperand(2);
13141 // If the input vector is a concatenation, and the insert replaces
13142 // one of the halves, we can optimize into a single concat_vectors.
13143 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13144 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13145 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13146 EVT VT = N->getValueType(0);
13148 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13149 // (concat_vectors Z, Y)
13151 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13152 N->getOperand(1), N0.getOperand(1));
13154 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13155 // (concat_vectors X, Z)
13156 if (InsIdx == VT.getVectorNumElements()/2)
13157 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13158 N0.getOperand(0), N->getOperand(1));
13164 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13165 SDValue N0 = N->getOperand(0);
13167 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13168 if (N0->getOpcode() == ISD::FP16_TO_FP)
13169 return N0->getOperand(0);
13174 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13175 SDValue N0 = N->getOperand(0);
13177 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13178 if (N0->getOpcode() == ISD::AND) {
13179 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13180 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13181 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13189 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13190 /// with the destination vector and a zero vector.
13191 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13192 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13193 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13194 EVT VT = N->getValueType(0);
13195 SDValue LHS = N->getOperand(0);
13196 SDValue RHS = N->getOperand(1);
13199 // Make sure we're not running after operation legalization where it
13200 // may have custom lowered the vector shuffles.
13201 if (LegalOperations)
13204 if (N->getOpcode() != ISD::AND)
13207 if (RHS.getOpcode() == ISD::BITCAST)
13208 RHS = RHS.getOperand(0);
13210 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13213 EVT RVT = RHS.getValueType();
13214 unsigned NumElts = RHS.getNumOperands();
13216 // Attempt to create a valid clear mask, splitting the mask into
13217 // sub elements and checking to see if each is
13218 // all zeros or all ones - suitable for shuffle masking.
13219 auto BuildClearMask = [&](int Split) {
13220 int NumSubElts = NumElts * Split;
13221 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13223 SmallVector<int, 8> Indices;
13224 for (int i = 0; i != NumSubElts; ++i) {
13225 int EltIdx = i / Split;
13226 int SubIdx = i % Split;
13227 SDValue Elt = RHS.getOperand(EltIdx);
13228 if (Elt.getOpcode() == ISD::UNDEF) {
13229 Indices.push_back(-1);
13234 if (isa<ConstantSDNode>(Elt))
13235 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13236 else if (isa<ConstantFPSDNode>(Elt))
13237 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13241 // Extract the sub element from the constant bit mask.
13242 if (DAG.getDataLayout().isBigEndian()) {
13243 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13245 Bits = Bits.lshr(SubIdx * NumSubBits);
13249 Bits = Bits.trunc(NumSubBits);
13251 if (Bits.isAllOnesValue())
13252 Indices.push_back(i);
13253 else if (Bits == 0)
13254 Indices.push_back(i + NumSubElts);
13259 // Let's see if the target supports this vector_shuffle.
13260 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13261 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13262 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13265 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13266 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13267 DAG.getBitcast(ClearVT, LHS),
13268 Zero, &Indices[0]));
13271 // Determine maximum split level (byte level masking).
13273 if (RVT.getScalarSizeInBits() % 8 == 0)
13274 MaxSplit = RVT.getScalarSizeInBits() / 8;
13276 for (int Split = 1; Split <= MaxSplit; ++Split)
13277 if (RVT.getScalarSizeInBits() % Split == 0)
13278 if (SDValue S = BuildClearMask(Split))
13284 /// Visit a binary vector operation, like ADD.
13285 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13286 assert(N->getValueType(0).isVector() &&
13287 "SimplifyVBinOp only works on vectors!");
13289 SDValue LHS = N->getOperand(0);
13290 SDValue RHS = N->getOperand(1);
13292 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13294 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13295 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13296 // Check if both vectors are constants. If not bail out.
13297 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13298 cast<BuildVectorSDNode>(RHS)->isConstant()))
13301 SmallVector<SDValue, 8> Ops;
13302 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13303 SDValue LHSOp = LHS.getOperand(i);
13304 SDValue RHSOp = RHS.getOperand(i);
13306 // Can't fold divide by zero.
13307 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13308 N->getOpcode() == ISD::FDIV) {
13309 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13310 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13314 EVT VT = LHSOp.getValueType();
13315 EVT RVT = RHSOp.getValueType();
13317 // Integer BUILD_VECTOR operands may have types larger than the element
13318 // size (e.g., when the element type is not legal). Prior to type
13319 // legalization, the types may not match between the two BUILD_VECTORS.
13320 // Truncate one of the operands to make them match.
13321 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13322 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13324 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13328 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13330 if (FoldOp.getOpcode() != ISD::UNDEF &&
13331 FoldOp.getOpcode() != ISD::Constant &&
13332 FoldOp.getOpcode() != ISD::ConstantFP)
13334 Ops.push_back(FoldOp);
13335 AddToWorklist(FoldOp.getNode());
13338 if (Ops.size() == LHS.getNumOperands())
13339 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13342 // Try to convert a constant mask AND into a shuffle clear mask.
13343 if (SDValue Shuffle = XformToShuffleWithZero(N))
13346 // Type legalization might introduce new shuffles in the DAG.
13347 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13348 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13349 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13350 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13351 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13352 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13353 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13354 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13356 if (SVN0->getMask().equals(SVN1->getMask())) {
13357 EVT VT = N->getValueType(0);
13358 SDValue UndefVector = LHS.getOperand(1);
13359 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13360 LHS.getOperand(0), RHS.getOperand(0));
13361 AddUsersToWorklist(N);
13362 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13363 &SVN0->getMask()[0]);
13370 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13371 SDValue N1, SDValue N2){
13372 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13374 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13375 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13377 // If we got a simplified select_cc node back from SimplifySelectCC, then
13378 // break it down into a new SETCC node, and a new SELECT node, and then return
13379 // the SELECT node, since we were called with a SELECT node.
13380 if (SCC.getNode()) {
13381 // Check to see if we got a select_cc back (to turn into setcc/select).
13382 // Otherwise, just return whatever node we got back, like fabs.
13383 if (SCC.getOpcode() == ISD::SELECT_CC) {
13384 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13386 SCC.getOperand(0), SCC.getOperand(1),
13387 SCC.getOperand(4));
13388 AddToWorklist(SETCC.getNode());
13389 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13390 SCC.getOperand(2), SCC.getOperand(3));
13398 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13399 /// being selected between, see if we can simplify the select. Callers of this
13400 /// should assume that TheSelect is deleted if this returns true. As such, they
13401 /// should return the appropriate thing (e.g. the node) back to the top-level of
13402 /// the DAG combiner loop to avoid it being looked at.
13403 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13406 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13407 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13408 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13409 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13410 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13411 SDValue Sqrt = RHS;
13414 const ConstantFPSDNode *NegZero = nullptr;
13416 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13417 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13418 CmpLHS = TheSelect->getOperand(0);
13419 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13421 // SELECT or VSELECT
13422 SDValue Cmp = TheSelect->getOperand(0);
13423 if (Cmp.getOpcode() == ISD::SETCC) {
13424 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13425 CmpLHS = Cmp.getOperand(0);
13426 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13429 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13430 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13431 CC == ISD::SETULT || CC == ISD::SETLT)) {
13432 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13433 CombineTo(TheSelect, Sqrt);
13438 // Cannot simplify select with vector condition
13439 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13441 // If this is a select from two identical things, try to pull the operation
13442 // through the select.
13443 if (LHS.getOpcode() != RHS.getOpcode() ||
13444 !LHS.hasOneUse() || !RHS.hasOneUse())
13447 // If this is a load and the token chain is identical, replace the select
13448 // of two loads with a load through a select of the address to load from.
13449 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13450 // constants have been dropped into the constant pool.
13451 if (LHS.getOpcode() == ISD::LOAD) {
13452 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13453 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13455 // Token chains must be identical.
13456 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13457 // Do not let this transformation reduce the number of volatile loads.
13458 LLD->isVolatile() || RLD->isVolatile() ||
13459 // FIXME: If either is a pre/post inc/dec load,
13460 // we'd need to split out the address adjustment.
13461 LLD->isIndexed() || RLD->isIndexed() ||
13462 // If this is an EXTLOAD, the VT's must match.
13463 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13464 // If this is an EXTLOAD, the kind of extension must match.
13465 (LLD->getExtensionType() != RLD->getExtensionType() &&
13466 // The only exception is if one of the extensions is anyext.
13467 LLD->getExtensionType() != ISD::EXTLOAD &&
13468 RLD->getExtensionType() != ISD::EXTLOAD) ||
13469 // FIXME: this discards src value information. This is
13470 // over-conservative. It would be beneficial to be able to remember
13471 // both potential memory locations. Since we are discarding
13472 // src value info, don't do the transformation if the memory
13473 // locations are not in the default address space.
13474 LLD->getPointerInfo().getAddrSpace() != 0 ||
13475 RLD->getPointerInfo().getAddrSpace() != 0 ||
13476 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13477 LLD->getBasePtr().getValueType()))
13480 // Check that the select condition doesn't reach either load. If so,
13481 // folding this will induce a cycle into the DAG. If not, this is safe to
13482 // xform, so create a select of the addresses.
13484 if (TheSelect->getOpcode() == ISD::SELECT) {
13485 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13486 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13487 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13489 // The loads must not depend on one another.
13490 if (LLD->isPredecessorOf(RLD) ||
13491 RLD->isPredecessorOf(LLD))
13493 Addr = DAG.getSelect(SDLoc(TheSelect),
13494 LLD->getBasePtr().getValueType(),
13495 TheSelect->getOperand(0), LLD->getBasePtr(),
13496 RLD->getBasePtr());
13497 } else { // Otherwise SELECT_CC
13498 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13499 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13501 if ((LLD->hasAnyUseOfValue(1) &&
13502 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13503 (RLD->hasAnyUseOfValue(1) &&
13504 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13507 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13508 LLD->getBasePtr().getValueType(),
13509 TheSelect->getOperand(0),
13510 TheSelect->getOperand(1),
13511 LLD->getBasePtr(), RLD->getBasePtr(),
13512 TheSelect->getOperand(4));
13516 // It is safe to replace the two loads if they have different alignments,
13517 // but the new load must be the minimum (most restrictive) alignment of the
13519 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13520 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13521 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13522 Load = DAG.getLoad(TheSelect->getValueType(0),
13524 // FIXME: Discards pointer and AA info.
13525 LLD->getChain(), Addr, MachinePointerInfo(),
13526 LLD->isVolatile(), LLD->isNonTemporal(),
13527 isInvariant, Alignment);
13529 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13530 RLD->getExtensionType() : LLD->getExtensionType(),
13532 TheSelect->getValueType(0),
13533 // FIXME: Discards pointer and AA info.
13534 LLD->getChain(), Addr, MachinePointerInfo(),
13535 LLD->getMemoryVT(), LLD->isVolatile(),
13536 LLD->isNonTemporal(), isInvariant, Alignment);
13539 // Users of the select now use the result of the load.
13540 CombineTo(TheSelect, Load);
13542 // Users of the old loads now use the new load's chain. We know the
13543 // old-load value is dead now.
13544 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13545 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13552 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13553 /// where 'cond' is the comparison specified by CC.
13554 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13555 SDValue N2, SDValue N3,
13556 ISD::CondCode CC, bool NotExtCompare) {
13557 // (x ? y : y) -> y.
13558 if (N2 == N3) return N2;
13560 EVT VT = N2.getValueType();
13561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13562 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13564 // Determine if the condition we're dealing with is constant
13565 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13566 N0, N1, CC, DL, false);
13567 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13569 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13570 // fold select_cc true, x, y -> x
13571 // fold select_cc false, x, y -> y
13572 return !SCCC->isNullValue() ? N2 : N3;
13575 // Check to see if we can simplify the select into an fabs node
13576 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13577 // Allow either -0.0 or 0.0
13578 if (CFP->isZero()) {
13579 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13580 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13581 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13582 N2 == N3.getOperand(0))
13583 return DAG.getNode(ISD::FABS, DL, VT, N0);
13585 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13586 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13587 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13588 N2.getOperand(0) == N3)
13589 return DAG.getNode(ISD::FABS, DL, VT, N3);
13593 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13594 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13595 // in it. This is a win when the constant is not otherwise available because
13596 // it replaces two constant pool loads with one. We only do this if the FP
13597 // type is known to be legal, because if it isn't, then we are before legalize
13598 // types an we want the other legalization to happen first (e.g. to avoid
13599 // messing with soft float) and if the ConstantFP is not legal, because if
13600 // it is legal, we may not need to store the FP constant in a constant pool.
13601 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13602 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13603 if (TLI.isTypeLegal(N2.getValueType()) &&
13604 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13605 TargetLowering::Legal &&
13606 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13607 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13608 // If both constants have multiple uses, then we won't need to do an
13609 // extra load, they are likely around in registers for other users.
13610 (TV->hasOneUse() || FV->hasOneUse())) {
13611 Constant *Elts[] = {
13612 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13613 const_cast<ConstantFP*>(TV->getConstantFPValue())
13615 Type *FPTy = Elts[0]->getType();
13616 const DataLayout &TD = DAG.getDataLayout();
13618 // Create a ConstantArray of the two constants.
13619 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13621 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13622 TD.getPrefTypeAlignment(FPTy));
13623 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13625 // Get the offsets to the 0 and 1 element of the array so that we can
13626 // select between them.
13627 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13628 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13629 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13631 SDValue Cond = DAG.getSetCC(DL,
13632 getSetCCResultType(N0.getValueType()),
13634 AddToWorklist(Cond.getNode());
13635 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13637 AddToWorklist(CstOffset.getNode());
13638 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13640 AddToWorklist(CPIdx.getNode());
13641 return DAG.getLoad(
13642 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13643 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13644 false, false, false, Alignment);
13648 // Check to see if we can perform the "gzip trick", transforming
13649 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13650 if (isNullConstant(N3) && CC == ISD::SETLT &&
13651 (isNullConstant(N1) || // (a < 0) ? b : 0
13652 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13653 EVT XType = N0.getValueType();
13654 EVT AType = N2.getValueType();
13655 if (XType.bitsGE(AType)) {
13656 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13657 // single-bit constant.
13658 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13659 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13660 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13661 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13662 getShiftAmountTy(N0.getValueType()));
13663 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13665 AddToWorklist(Shift.getNode());
13667 if (XType.bitsGT(AType)) {
13668 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13669 AddToWorklist(Shift.getNode());
13672 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13675 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13677 DAG.getConstant(XType.getSizeInBits() - 1,
13679 getShiftAmountTy(N0.getValueType())));
13680 AddToWorklist(Shift.getNode());
13682 if (XType.bitsGT(AType)) {
13683 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13684 AddToWorklist(Shift.getNode());
13687 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13691 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13692 // where y is has a single bit set.
13693 // A plaintext description would be, we can turn the SELECT_CC into an AND
13694 // when the condition can be materialized as an all-ones register. Any
13695 // single bit-test can be materialized as an all-ones register with
13696 // shift-left and shift-right-arith.
13697 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13698 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13699 SDValue AndLHS = N0->getOperand(0);
13700 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13701 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13702 // Shift the tested bit over the sign bit.
13703 APInt AndMask = ConstAndRHS->getAPIntValue();
13705 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13706 getShiftAmountTy(AndLHS.getValueType()));
13707 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13709 // Now arithmetic right shift it all the way over, so the result is either
13710 // all-ones, or zero.
13712 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13713 getShiftAmountTy(Shl.getValueType()));
13714 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13716 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13720 // fold select C, 16, 0 -> shl C, 4
13721 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13722 TLI.getBooleanContents(N0.getValueType()) ==
13723 TargetLowering::ZeroOrOneBooleanContent) {
13725 // If the caller doesn't want us to simplify this into a zext of a compare,
13727 if (NotExtCompare && N2C->isOne())
13730 // Get a SetCC of the condition
13731 // NOTE: Don't create a SETCC if it's not legal on this target.
13732 if (!LegalOperations ||
13733 TLI.isOperationLegal(ISD::SETCC,
13734 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13736 // cast from setcc result type to select result type
13738 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13740 if (N2.getValueType().bitsLT(SCC.getValueType()))
13741 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13742 N2.getValueType());
13744 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13745 N2.getValueType(), SCC);
13747 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13748 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13749 N2.getValueType(), SCC);
13752 AddToWorklist(SCC.getNode());
13753 AddToWorklist(Temp.getNode());
13758 // shl setcc result by log2 n2c
13759 return DAG.getNode(
13760 ISD::SHL, DL, N2.getValueType(), Temp,
13761 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13762 getShiftAmountTy(Temp.getValueType())));
13766 // Check to see if this is an integer abs.
13767 // select_cc setg[te] X, 0, X, -X ->
13768 // select_cc setgt X, -1, X, -X ->
13769 // select_cc setl[te] X, 0, -X, X ->
13770 // select_cc setlt X, 1, -X, X ->
13771 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13773 ConstantSDNode *SubC = nullptr;
13774 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13775 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13776 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13777 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13778 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13779 (N1C->isOne() && CC == ISD::SETLT)) &&
13780 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13781 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13783 EVT XType = N0.getValueType();
13784 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13786 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13788 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13789 getShiftAmountTy(N0.getValueType())));
13790 SDValue Add = DAG.getNode(ISD::ADD, DL,
13792 AddToWorklist(Shift.getNode());
13793 AddToWorklist(Add.getNode());
13794 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13801 /// This is a stub for TargetLowering::SimplifySetCC.
13802 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13803 SDValue N1, ISD::CondCode Cond,
13804 SDLoc DL, bool foldBooleans) {
13805 TargetLowering::DAGCombinerInfo
13806 DagCombineInfo(DAG, Level, false, this);
13807 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13810 /// Given an ISD::SDIV node expressing a divide by constant, return
13811 /// a DAG expression to select that will generate the same value by multiplying
13812 /// by a magic number.
13813 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13814 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13815 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13819 // Avoid division by zero.
13820 if (C->isNullValue())
13823 std::vector<SDNode*> Built;
13825 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13827 for (SDNode *N : Built)
13832 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13833 /// DAG expression that will generate the same value by right shifting.
13834 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13835 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13839 // Avoid division by zero.
13840 if (C->isNullValue())
13843 std::vector<SDNode *> Built;
13844 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13846 for (SDNode *N : Built)
13851 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13852 /// expression that will generate the same value by multiplying by a magic
13854 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13855 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13856 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13860 // Avoid division by zero.
13861 if (C->isNullValue())
13864 std::vector<SDNode*> Built;
13866 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13868 for (SDNode *N : Built)
13873 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13874 if (Level >= AfterLegalizeDAG)
13877 // Expose the DAG combiner to the target combiner implementations.
13878 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13880 unsigned Iterations = 0;
13881 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13883 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13884 // For the reciprocal, we need to find the zero of the function:
13885 // F(X) = A X - 1 [which has a zero at X = 1/A]
13887 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13888 // does not require additional intermediate precision]
13889 EVT VT = Op.getValueType();
13891 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13893 AddToWorklist(Est.getNode());
13895 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13896 for (unsigned i = 0; i < Iterations; ++i) {
13897 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13898 AddToWorklist(NewEst.getNode());
13900 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13901 AddToWorklist(NewEst.getNode());
13903 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13904 AddToWorklist(NewEst.getNode());
13906 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13907 AddToWorklist(Est.getNode());
13916 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13917 /// For the reciprocal sqrt, we need to find the zero of the function:
13918 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13920 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13921 /// As a result, we precompute A/2 prior to the iteration loop.
13922 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13923 unsigned Iterations) {
13924 EVT VT = Arg.getValueType();
13926 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13928 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13929 // this entire sequence requires only one FP constant.
13930 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13931 AddToWorklist(HalfArg.getNode());
13933 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13934 AddToWorklist(HalfArg.getNode());
13936 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13937 for (unsigned i = 0; i < Iterations; ++i) {
13938 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13939 AddToWorklist(NewEst.getNode());
13941 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13942 AddToWorklist(NewEst.getNode());
13944 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13945 AddToWorklist(NewEst.getNode());
13947 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13948 AddToWorklist(Est.getNode());
13953 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13954 /// For the reciprocal sqrt, we need to find the zero of the function:
13955 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13957 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13958 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13959 unsigned Iterations) {
13960 EVT VT = Arg.getValueType();
13962 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13963 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13965 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13966 for (unsigned i = 0; i < Iterations; ++i) {
13967 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13968 AddToWorklist(HalfEst.getNode());
13970 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13971 AddToWorklist(Est.getNode());
13973 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13974 AddToWorklist(Est.getNode());
13976 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13977 AddToWorklist(Est.getNode());
13979 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13980 AddToWorklist(Est.getNode());
13985 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13986 if (Level >= AfterLegalizeDAG)
13989 // Expose the DAG combiner to the target combiner implementations.
13990 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13991 unsigned Iterations = 0;
13992 bool UseOneConstNR = false;
13993 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13994 AddToWorklist(Est.getNode());
13996 Est = UseOneConstNR ?
13997 BuildRsqrtNROneConst(Op, Est, Iterations) :
13998 BuildRsqrtNRTwoConst(Op, Est, Iterations);
14006 /// Return true if base is a frame index, which is known not to alias with
14007 /// anything but itself. Provides base object and offset as results.
14008 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14009 const GlobalValue *&GV, const void *&CV) {
14010 // Assume it is a primitive operation.
14011 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14013 // If it's an adding a simple constant then integrate the offset.
14014 if (Base.getOpcode() == ISD::ADD) {
14015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14016 Base = Base.getOperand(0);
14017 Offset += C->getZExtValue();
14021 // Return the underlying GlobalValue, and update the Offset. Return false
14022 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14023 // by multiple nodes with different offsets.
14024 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14025 GV = G->getGlobal();
14026 Offset += G->getOffset();
14030 // Return the underlying Constant value, and update the Offset. Return false
14031 // for ConstantSDNodes since the same constant pool entry may be represented
14032 // by multiple nodes with different offsets.
14033 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14034 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14035 : (const void *)C->getConstVal();
14036 Offset += C->getOffset();
14039 // If it's any of the following then it can't alias with anything but itself.
14040 return isa<FrameIndexSDNode>(Base);
14043 /// Return true if there is any possibility that the two addresses overlap.
14044 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14045 // If they are the same then they must be aliases.
14046 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14048 // If they are both volatile then they cannot be reordered.
14049 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14051 // If one operation reads from invariant memory, and the other may store, they
14052 // cannot alias. These should really be checking the equivalent of mayWrite,
14053 // but it only matters for memory nodes other than load /store.
14054 if (Op0->isInvariant() && Op1->writeMem())
14057 if (Op1->isInvariant() && Op0->writeMem())
14060 // Gather base node and offset information.
14061 SDValue Base1, Base2;
14062 int64_t Offset1, Offset2;
14063 const GlobalValue *GV1, *GV2;
14064 const void *CV1, *CV2;
14065 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14066 Base1, Offset1, GV1, CV1);
14067 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14068 Base2, Offset2, GV2, CV2);
14070 // If they have a same base address then check to see if they overlap.
14071 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14072 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14073 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14075 // It is possible for different frame indices to alias each other, mostly
14076 // when tail call optimization reuses return address slots for arguments.
14077 // To catch this case, look up the actual index of frame indices to compute
14078 // the real alias relationship.
14079 if (isFrameIndex1 && isFrameIndex2) {
14080 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14081 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14082 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14083 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14084 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14087 // Otherwise, if we know what the bases are, and they aren't identical, then
14088 // we know they cannot alias.
14089 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14092 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14093 // compared to the size and offset of the access, we may be able to prove they
14094 // do not alias. This check is conservative for now to catch cases created by
14095 // splitting vector types.
14096 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14097 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14098 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14099 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14100 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14101 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14102 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14104 // There is no overlap between these relatively aligned accesses of similar
14105 // size, return no alias.
14106 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14107 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14111 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14113 : DAG.getSubtarget().useAA();
14115 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14116 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14120 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14121 // Use alias analysis information.
14122 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14123 Op1->getSrcValueOffset());
14124 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14125 Op0->getSrcValueOffset() - MinOffset;
14126 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14127 Op1->getSrcValueOffset() - MinOffset;
14128 AliasResult AAResult =
14129 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14130 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14131 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14132 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14133 if (AAResult == NoAlias)
14137 // Otherwise we have to assume they alias.
14141 /// Walk up chain skipping non-aliasing memory nodes,
14142 /// looking for aliasing nodes and adding them to the Aliases vector.
14143 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14144 SmallVectorImpl<SDValue> &Aliases) {
14145 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14146 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14148 // Get alias information for node.
14149 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14152 Chains.push_back(OriginalChain);
14153 unsigned Depth = 0;
14155 // Look at each chain and determine if it is an alias. If so, add it to the
14156 // aliases list. If not, then continue up the chain looking for the next
14158 while (!Chains.empty()) {
14159 SDValue Chain = Chains.pop_back_val();
14161 // For TokenFactor nodes, look at each operand and only continue up the
14162 // chain until we find two aliases. If we've seen two aliases, assume we'll
14163 // find more and revert to original chain since the xform is unlikely to be
14166 // FIXME: The depth check could be made to return the last non-aliasing
14167 // chain we found before we hit a tokenfactor rather than the original
14169 if (Depth > 6 || Aliases.size() == 2) {
14171 Aliases.push_back(OriginalChain);
14175 // Don't bother if we've been before.
14176 if (!Visited.insert(Chain.getNode()).second)
14179 switch (Chain.getOpcode()) {
14180 case ISD::EntryToken:
14181 // Entry token is ideal chain operand, but handled in FindBetterChain.
14186 // Get alias information for Chain.
14187 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14188 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14190 // If chain is alias then stop here.
14191 if (!(IsLoad && IsOpLoad) &&
14192 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14193 Aliases.push_back(Chain);
14195 // Look further up the chain.
14196 Chains.push_back(Chain.getOperand(0));
14202 case ISD::TokenFactor:
14203 // We have to check each of the operands of the token factor for "small"
14204 // token factors, so we queue them up. Adding the operands to the queue
14205 // (stack) in reverse order maintains the original order and increases the
14206 // likelihood that getNode will find a matching token factor (CSE.)
14207 if (Chain.getNumOperands() > 16) {
14208 Aliases.push_back(Chain);
14211 for (unsigned n = Chain.getNumOperands(); n;)
14212 Chains.push_back(Chain.getOperand(--n));
14217 // For all other instructions we will just have to take what we can get.
14218 Aliases.push_back(Chain);
14223 // We need to be careful here to also search for aliases through the
14224 // value operand of a store, etc. Consider the following situation:
14226 // L1 = load Token1, %52
14227 // S1 = store Token1, L1, %51
14228 // L2 = load Token1, %52+8
14229 // S2 = store Token1, L2, %51+8
14230 // Token2 = Token(S1, S2)
14231 // L3 = load Token2, %53
14232 // S3 = store Token2, L3, %52
14233 // L4 = load Token2, %53+8
14234 // S4 = store Token2, L4, %52+8
14235 // If we search for aliases of S3 (which loads address %52), and we look
14236 // only through the chain, then we'll miss the trivial dependence on L1
14237 // (which also loads from %52). We then might change all loads and
14238 // stores to use Token1 as their chain operand, which could result in
14239 // copying %53 into %52 before copying %52 into %51 (which should
14242 // The problem is, however, that searching for such data dependencies
14243 // can become expensive, and the cost is not directly related to the
14244 // chain depth. Instead, we'll rule out such configurations here by
14245 // insisting that we've visited all chain users (except for users
14246 // of the original chain, which is not necessary). When doing this,
14247 // we need to look through nodes we don't care about (otherwise, things
14248 // like register copies will interfere with trivial cases).
14250 SmallVector<const SDNode *, 16> Worklist;
14251 for (const SDNode *N : Visited)
14252 if (N != OriginalChain.getNode())
14253 Worklist.push_back(N);
14255 while (!Worklist.empty()) {
14256 const SDNode *M = Worklist.pop_back_val();
14258 // We have already visited M, and want to make sure we've visited any uses
14259 // of M that we care about. For uses that we've not visisted, and don't
14260 // care about, queue them to the worklist.
14262 for (SDNode::use_iterator UI = M->use_begin(),
14263 UIE = M->use_end(); UI != UIE; ++UI)
14264 if (UI.getUse().getValueType() == MVT::Other &&
14265 Visited.insert(*UI).second) {
14266 if (isa<MemSDNode>(*UI)) {
14267 // We've not visited this use, and we care about it (it could have an
14268 // ordering dependency with the original node).
14270 Aliases.push_back(OriginalChain);
14274 // We've not visited this use, but we don't care about it. Mark it as
14275 // visited and enqueue it to the worklist.
14276 Worklist.push_back(*UI);
14281 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14282 /// (aliasing node.)
14283 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14284 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14286 // Accumulate all the aliases to this node.
14287 GatherAllAliases(N, OldChain, Aliases);
14289 // If no operands then chain to entry token.
14290 if (Aliases.size() == 0)
14291 return DAG.getEntryNode();
14293 // If a single operand then chain to it. We don't need to revisit it.
14294 if (Aliases.size() == 1)
14297 // Construct a custom tailored token factor.
14298 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14301 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14302 // This holds the base pointer, index, and the offset in bytes from the base
14304 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14306 // We must have a base and an offset.
14307 if (!BasePtr.Base.getNode())
14310 // Do not handle stores to undef base pointers.
14311 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14314 SmallVector<StoreSDNode *, 8> ChainedStores;
14315 ChainedStores.push_back(St);
14317 // Walk up the chain and look for nodes with offsets from the same
14318 // base pointer. Stop when reaching an instruction with a different kind
14319 // or instruction which has a different base pointer.
14320 StoreSDNode *Index = St;
14322 // If the chain has more than one use, then we can't reorder the mem ops.
14323 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14326 // Find the base pointer and offset for this memory node.
14327 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14329 // Check that the base pointer is the same as the original one.
14330 if (!Ptr.equalBaseIndex(BasePtr))
14333 if (Index->isVolatile() || Index->isIndexed())
14336 // Find the next memory operand in the chain. If the next operand in the
14337 // chain is a store then move up and continue the scan with the next
14338 // memory operand. If the next operand is a load save it and use alias
14339 // information to check if it interferes with anything.
14340 SDNode *NextInChain = Index->getChain().getNode();
14342 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14343 // We found a store node. Use it for the next iteration.
14344 ChainedStores.push_back(STn);
14347 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14348 NextInChain = Ldn->getChain().getNode();
14357 bool MadeChange = false;
14358 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14360 for (StoreSDNode *ChainedStore : ChainedStores) {
14361 SDValue Chain = ChainedStore->getChain();
14362 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14364 if (Chain != BetterChain) {
14366 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14370 // Do all replacements after finding the replacements to make to avoid making
14371 // the chains more complicated by introducing new TokenFactors.
14372 for (auto Replacement : BetterChains)
14373 replaceStoreChain(Replacement.first, Replacement.second);
14378 /// This is the entry point for the file.
14379 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14380 CodeGenOpt::Level OptLevel) {
14381 /// This is the main entry point to this class.
14382 DAGCombiner(*this, AA, OptLevel).Run(Level);