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 /// Replaces all uses of the results of one DAG node with new values.
160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
163 /// Replaces all uses of the results of one DAG node with new values.
164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165 return CombineTo(N, &Res, 1, AddTo);
168 /// Replaces all uses of the results of one DAG node with new values.
169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
171 SDValue To[] = { Res0, Res1 };
172 return CombineTo(N, To, 2, AddTo);
175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
179 /// Check the specified integer node value to see if it can be simplified or
180 /// if things it uses can be simplified by bit propagation.
181 /// If so, return true.
182 bool SimplifyDemandedBits(SDValue Op) {
183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184 APInt Demanded = APInt::getAllOnesValue(BitWidth);
185 return SimplifyDemandedBits(Op, Demanded);
188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
190 bool CombineToPreIndexedLoadStore(SDNode *N);
191 bool CombineToPostIndexedLoadStore(SDNode *N);
192 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193 bool SliceUpLoad(SDNode *N);
195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200 /// \param EltNo index of the vector element to load.
201 /// \param OriginalLoad load that EVE came from to be replaced.
202 /// \returns EVE on success SDValue() on failure.
203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209 SDValue PromoteIntBinOp(SDValue Op);
210 SDValue PromoteIntShiftOp(SDValue Op);
211 SDValue PromoteExtend(SDValue Op);
212 bool PromoteLoad(SDValue Op);
214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216 ISD::NodeType ExtType);
218 /// Call the node-specific routine that knows how to fold each
219 /// particular type of node. If that doesn't do anything, try the
220 /// target-specific DAG combines.
221 SDValue combine(SDNode *N);
223 // Visitation implementation - Implement dag node combining for different
224 // node types. The semantics are as follows:
226 // SDValue.getNode() == 0 - No change was made
227 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
228 // otherwise - N should be replaced by the returned Operand.
230 SDValue visitTokenFactor(SDNode *N);
231 SDValue visitMERGE_VALUES(SDNode *N);
232 SDValue visitADD(SDNode *N);
233 SDValue visitSUB(SDNode *N);
234 SDValue visitADDC(SDNode *N);
235 SDValue visitSUBC(SDNode *N);
236 SDValue visitADDE(SDNode *N);
237 SDValue visitSUBE(SDNode *N);
238 SDValue visitMUL(SDNode *N);
239 SDValue useDivRem(SDNode *N);
240 SDValue visitSDIV(SDNode *N);
241 SDValue visitUDIV(SDNode *N);
242 SDValue visitREM(SDNode *N);
243 SDValue visitMULHU(SDNode *N);
244 SDValue visitMULHS(SDNode *N);
245 SDValue visitSMUL_LOHI(SDNode *N);
246 SDValue visitUMUL_LOHI(SDNode *N);
247 SDValue visitSMULO(SDNode *N);
248 SDValue visitUMULO(SDNode *N);
249 SDValue visitIMINMAX(SDNode *N);
250 SDValue visitAND(SDNode *N);
251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitOR(SDNode *N);
253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254 SDValue visitXOR(SDNode *N);
255 SDValue SimplifyVBinOp(SDNode *N);
256 SDValue visitSHL(SDNode *N);
257 SDValue visitSRA(SDNode *N);
258 SDValue visitSRL(SDNode *N);
259 SDValue visitRotate(SDNode *N);
260 SDValue visitBSWAP(SDNode *N);
261 SDValue visitCTLZ(SDNode *N);
262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTTZ(SDNode *N);
264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265 SDValue visitCTPOP(SDNode *N);
266 SDValue visitSELECT(SDNode *N);
267 SDValue visitVSELECT(SDNode *N);
268 SDValue visitSELECT_CC(SDNode *N);
269 SDValue visitSETCC(SDNode *N);
270 SDValue visitSIGN_EXTEND(SDNode *N);
271 SDValue visitZERO_EXTEND(SDNode *N);
272 SDValue visitANY_EXTEND(SDNode *N);
273 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275 SDValue visitTRUNCATE(SDNode *N);
276 SDValue visitBITCAST(SDNode *N);
277 SDValue visitBUILD_PAIR(SDNode *N);
278 SDValue visitFADD(SDNode *N);
279 SDValue visitFSUB(SDNode *N);
280 SDValue visitFMUL(SDNode *N);
281 SDValue visitFMA(SDNode *N);
282 SDValue visitFDIV(SDNode *N);
283 SDValue visitFREM(SDNode *N);
284 SDValue visitFSQRT(SDNode *N);
285 SDValue visitFCOPYSIGN(SDNode *N);
286 SDValue visitSINT_TO_FP(SDNode *N);
287 SDValue visitUINT_TO_FP(SDNode *N);
288 SDValue visitFP_TO_SINT(SDNode *N);
289 SDValue visitFP_TO_UINT(SDNode *N);
290 SDValue visitFP_ROUND(SDNode *N);
291 SDValue visitFP_ROUND_INREG(SDNode *N);
292 SDValue visitFP_EXTEND(SDNode *N);
293 SDValue visitFNEG(SDNode *N);
294 SDValue visitFABS(SDNode *N);
295 SDValue visitFCEIL(SDNode *N);
296 SDValue visitFTRUNC(SDNode *N);
297 SDValue visitFFLOOR(SDNode *N);
298 SDValue visitFMINNUM(SDNode *N);
299 SDValue visitFMAXNUM(SDNode *N);
300 SDValue visitBRCOND(SDNode *N);
301 SDValue visitBR_CC(SDNode *N);
302 SDValue visitLOAD(SDNode *N);
304 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305 SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
307 SDValue visitSTORE(SDNode *N);
308 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310 SDValue visitBUILD_VECTOR(SDNode *N);
311 SDValue visitCONCAT_VECTORS(SDNode *N);
312 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313 SDValue visitVECTOR_SHUFFLE(SDNode *N);
314 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315 SDValue visitINSERT_SUBVECTOR(SDNode *N);
316 SDValue visitMLOAD(SDNode *N);
317 SDValue visitMSTORE(SDNode *N);
318 SDValue visitMGATHER(SDNode *N);
319 SDValue visitMSCATTER(SDNode *N);
320 SDValue visitFP_TO_FP16(SDNode *N);
321 SDValue visitFP16_TO_FP(SDNode *N);
323 SDValue visitFADDForFMACombine(SDNode *N);
324 SDValue visitFSUBForFMACombine(SDNode *N);
325 SDValue visitFMULForFMACombine(SDNode *N);
327 SDValue XformToShuffleWithZero(SDNode *N);
328 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
330 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
332 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336 SDValue N3, ISD::CondCode CC,
337 bool NotExtCompare = false);
338 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339 SDLoc DL, bool foldBooleans = true);
341 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
343 bool isOneUseSetCC(SDValue N) const;
345 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
347 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348 SDValue CombineExtLoad(SDNode *N);
349 SDValue combineRepeatedFPDivisors(SDNode *N);
350 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351 SDValue BuildSDIV(SDNode *N);
352 SDValue BuildSDIVPow2(SDNode *N);
353 SDValue BuildUDIV(SDNode *N);
354 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
358 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
360 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361 bool DemandHighBits = true);
362 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364 SDValue InnerPos, SDValue InnerNeg,
365 unsigned PosOpcode, unsigned NegOpcode,
367 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368 SDValue ReduceLoadWidth(SDNode *N);
369 SDValue ReduceLoadOpStoreWidth(SDNode *N);
370 SDValue TransformFPLoadStorePair(SDNode *N);
371 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
374 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
376 /// Walk up chain skipping non-aliasing memory nodes,
377 /// looking for aliasing nodes and adding them to the Aliases vector.
378 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379 SmallVectorImpl<SDValue> &Aliases);
381 /// Return true if there is any possibility that the two addresses overlap.
382 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
384 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385 /// chain (aliasing node.)
386 SDValue FindBetterChain(SDNode *N, SDValue Chain);
388 /// Do FindBetterChain for a store and any possibly adjacent stores on
389 /// consecutive chains.
390 bool findBetterNeighborChains(StoreSDNode *St);
392 /// Holds a pointer to an LSBaseSDNode as well as information on where it
393 /// is located in a sequence of memory operations connected by a chain.
395 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397 // Ptr to the mem node.
398 LSBaseSDNode *MemNode;
399 // Offset from the base ptr.
400 int64_t OffsetFromBase;
401 // What is the sequence number of this mem node.
402 // Lowest mem operand in the DAG starts at zero.
403 unsigned SequenceNum;
406 /// This is a helper function for visitMUL to check the profitability
407 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
408 /// MulNode is the original multiply, AddNode is (add x, c1),
409 /// and ConstNode is c2.
410 bool isMulAddWithConstProfitable(SDNode *MulNode,
414 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
415 /// constant build_vector of the stored constant values in Stores.
416 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
418 ArrayRef<MemOpLink> Stores,
419 SmallVectorImpl<SDValue> &Chains,
422 /// This is a helper function for MergeConsecutiveStores. When the source
423 /// elements of the consecutive stores are all constants or all extracted
424 /// vector elements, try to merge them into one larger store.
425 /// \return True if a merged store was created.
426 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
427 EVT MemVT, unsigned NumStores,
428 bool IsConstantSrc, bool UseVector);
430 /// This is a helper function for MergeConsecutiveStores.
431 /// Stores that may be merged are placed in StoreNodes.
432 /// Loads that may alias with those stores are placed in AliasLoadNodes.
433 void getStoreMergeAndAliasCandidates(
434 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
435 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
437 /// Merge consecutive store operations into a wide store.
438 /// This optimization uses wide integers or vectors when possible.
439 /// \return True if some memory operations were changed.
440 bool MergeConsecutiveStores(StoreSDNode *N);
442 /// \brief Try to transform a truncation where C is a constant:
443 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
445 /// \p N needs to be a truncation and its first operand an AND. Other
446 /// requirements are checked by the function (e.g. that trunc is
447 /// single-use) and if missed an empty SDValue is returned.
448 SDValue distributeTruncateThroughAnd(SDNode *N);
451 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
452 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
453 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
454 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
457 /// Runs the dag combiner on all nodes in the work list
458 void Run(CombineLevel AtLevel);
460 SelectionDAG &getDAG() const { return DAG; }
462 /// Returns a type large enough to hold any valid shift amount - before type
463 /// legalization these can be huge.
464 EVT getShiftAmountTy(EVT LHSTy) {
465 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
466 if (LHSTy.isVector())
468 auto &DL = DAG.getDataLayout();
469 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
470 : TLI.getPointerTy(DL);
473 /// This method returns true if we are running before type legalization or
474 /// if the specified VT is legal.
475 bool isTypeLegal(const EVT &VT) {
476 if (!LegalTypes) return true;
477 return TLI.isTypeLegal(VT);
480 /// Convenience wrapper around TargetLowering::getSetCCResultType
481 EVT getSetCCResultType(EVT VT) const {
482 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
489 /// This class is a DAGUpdateListener that removes any deleted
490 /// nodes from the worklist.
491 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
494 explicit WorklistRemover(DAGCombiner &dc)
495 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
497 void NodeDeleted(SDNode *N, SDNode *E) override {
498 DC.removeFromWorklist(N);
503 //===----------------------------------------------------------------------===//
504 // TargetLowering::DAGCombinerInfo implementation
505 //===----------------------------------------------------------------------===//
507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
508 ((DAGCombiner*)DC)->AddToWorklist(N);
511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
512 ((DAGCombiner*)DC)->removeFromWorklist(N);
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
517 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
520 SDValue TargetLowering::DAGCombinerInfo::
521 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
522 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
526 SDValue TargetLowering::DAGCombinerInfo::
527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
528 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
531 void TargetLowering::DAGCombinerInfo::
532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
533 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
540 void DAGCombiner::deleteAndRecombine(SDNode *N) {
541 removeFromWorklist(N);
543 // If the operands of this node are only used by the node, they will now be
544 // dead. Make sure to re-visit them and recursively delete dead nodes.
545 for (const SDValue &Op : N->ops())
546 // For an operand generating multiple values, one of the values may
547 // become dead allowing further simplification (e.g. split index
548 // arithmetic from an indexed load).
549 if (Op->hasOneUse() || Op->getNumValues() > 1)
550 AddToWorklist(Op.getNode());
555 /// Return 1 if we can compute the negated form of the specified expression for
556 /// the same cost as the expression itself, or 2 if we can compute the negated
557 /// form more cheaply than the expression itself.
558 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
559 const TargetLowering &TLI,
560 const TargetOptions *Options,
561 unsigned Depth = 0) {
562 // fneg is removable even if it has multiple uses.
563 if (Op.getOpcode() == ISD::FNEG) return 2;
565 // Don't allow anything with multiple uses.
566 if (!Op.hasOneUse()) return 0;
568 // Don't recurse exponentially.
569 if (Depth > 6) return 0;
571 switch (Op.getOpcode()) {
572 default: return false;
573 case ISD::ConstantFP:
574 // Don't invert constant FP values after legalize. The negated constant
575 // isn't necessarily legal.
576 return LegalOperations ? 0 : 1;
578 // FIXME: determine better conditions for this xform.
579 if (!Options->UnsafeFPMath) return 0;
581 // After operation legalization, it might not be legal to create new FSUBs.
582 if (LegalOperations &&
583 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
586 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
587 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
590 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
591 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
594 // We can't turn -(A-B) into B-A when we honor signed zeros.
595 if (!Options->UnsafeFPMath) return 0;
597 // fold (fneg (fsub A, B)) -> (fsub B, A)
602 if (Options->HonorSignDependentRoundingFPMath()) return 0;
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
605 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
609 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
615 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
620 /// If isNegatibleForFree returns true, return the newly negated expression.
621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
622 bool LegalOperations, unsigned Depth = 0) {
623 const TargetOptions &Options = DAG.getTarget().Options;
624 // fneg is removable even if it has multiple uses.
625 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
627 // Don't allow anything with multiple uses.
628 assert(Op.hasOneUse() && "Unknown reuse!");
630 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
632 const SDNodeFlags *Flags = Op.getNode()->getFlags();
634 switch (Op.getOpcode()) {
635 default: llvm_unreachable("Unknown code");
636 case ISD::ConstantFP: {
637 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
639 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
642 // FIXME: determine better conditions for this xform.
643 assert(Options.UnsafeFPMath);
645 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
646 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
647 DAG.getTargetLoweringInfo(), &Options, Depth+1))
648 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
649 GetNegatedExpression(Op.getOperand(0), DAG,
650 LegalOperations, Depth+1),
651 Op.getOperand(1), Flags);
652 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
654 GetNegatedExpression(Op.getOperand(1), DAG,
655 LegalOperations, Depth+1),
656 Op.getOperand(0), Flags);
658 // We can't turn -(A-B) into B-A when we honor signed zeros.
659 assert(Options.UnsafeFPMath);
661 // fold (fneg (fsub 0, B)) -> B
662 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
664 return Op.getOperand(1);
666 // fold (fneg (fsub A, B)) -> (fsub B, A)
667 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
668 Op.getOperand(1), Op.getOperand(0), Flags);
672 assert(!Options.HonorSignDependentRoundingFPMath());
674 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
675 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
676 DAG.getTargetLoweringInfo(), &Options, Depth+1))
677 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678 GetNegatedExpression(Op.getOperand(0), DAG,
679 LegalOperations, Depth+1),
680 Op.getOperand(1), Flags);
682 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
683 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
685 GetNegatedExpression(Op.getOperand(1), DAG,
686 LegalOperations, Depth+1), Flags);
690 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691 GetNegatedExpression(Op.getOperand(0), DAG,
692 LegalOperations, Depth+1));
694 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
695 GetNegatedExpression(Op.getOperand(0), DAG,
696 LegalOperations, Depth+1),
701 // Return true if this node is a setcc, or is a select_cc
702 // that selects between the target values used for true and false, making it
703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
704 // the appropriate nodes based on the type of node we are checking. This
705 // simplifies life a bit for the callers.
706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
708 if (N.getOpcode() == ISD::SETCC) {
709 LHS = N.getOperand(0);
710 RHS = N.getOperand(1);
711 CC = N.getOperand(2);
715 if (N.getOpcode() != ISD::SELECT_CC ||
716 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
717 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
720 if (TLI.getBooleanContents(N.getValueType()) ==
721 TargetLowering::UndefinedBooleanContent)
724 LHS = N.getOperand(0);
725 RHS = N.getOperand(1);
726 CC = N.getOperand(4);
730 /// Return true if this is a SetCC-equivalent operation with only one use.
731 /// If this is true, it allows the users to invert the operation for free when
732 /// it is profitable to do so.
733 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
735 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
740 /// Returns true if N is a BUILD_VECTOR node whose
741 /// elements are all the same constant or undefined.
742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
743 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
748 unsigned SplatBitSize;
750 EVT EltVT = N->getValueType(0).getVectorElementType();
751 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
753 EltVT.getSizeInBits() >= SplatBitSize);
756 // \brief Returns the SDNode if it is a constant integer BuildVector
757 // or constant integer.
758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
759 if (isa<ConstantSDNode>(N))
761 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
766 // \brief Returns the SDNode if it is a constant float BuildVector
767 // or constant float.
768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
769 if (isa<ConstantFPSDNode>(N))
771 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
778 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
779 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
782 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
783 BitVector UndefElements;
784 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
786 // BuildVectors can truncate their operands. Ignore that case here.
787 // FIXME: We blindly ignore splats which include undef which is overly
789 if (CN && UndefElements.none() &&
790 CN->getValueType(0) == N.getValueType().getScalarType())
797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
800 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
803 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
804 BitVector UndefElements;
805 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
807 if (CN && UndefElements.none())
814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
815 SDValue N0, SDValue N1) {
816 EVT VT = N0.getValueType();
817 if (N0.getOpcode() == Opc) {
818 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
819 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
820 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
821 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
822 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
825 if (N0.hasOneUse()) {
826 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
828 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
829 if (!OpNode.getNode())
831 AddToWorklist(OpNode.getNode());
832 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
837 if (N1.getOpcode() == Opc) {
838 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
839 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
840 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
841 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
842 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
845 if (N1.hasOneUse()) {
846 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
848 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
849 if (!OpNode.getNode())
851 AddToWorklist(OpNode.getNode());
852 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
862 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
864 DEBUG(dbgs() << "\nReplacing.1 ";
866 dbgs() << "\nWith: ";
867 To[0].getNode()->dump(&DAG);
868 dbgs() << " and " << NumTo-1 << " other values\n");
869 for (unsigned i = 0, e = NumTo; i != e; ++i)
870 assert((!To[i].getNode() ||
871 N->getValueType(i) == To[i].getValueType()) &&
872 "Cannot combine value to value of different type!");
874 WorklistRemover DeadNodes(*this);
875 DAG.ReplaceAllUsesWith(N, To);
877 // Push the new nodes and any users onto the worklist
878 for (unsigned i = 0, e = NumTo; i != e; ++i) {
879 if (To[i].getNode()) {
880 AddToWorklist(To[i].getNode());
881 AddUsersToWorklist(To[i].getNode());
886 // Finally, if the node is now dead, remove it from the graph. The node
887 // may not be dead if the replacement process recursively simplified to
888 // something else needing this node.
890 deleteAndRecombine(N);
891 return SDValue(N, 0);
895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
896 // Replace all uses. If any nodes become isomorphic to other nodes and
897 // are deleted, make sure to remove them from our worklist.
898 WorklistRemover DeadNodes(*this);
899 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
901 // Push the new node and any (possibly new) users onto the worklist.
902 AddToWorklist(TLO.New.getNode());
903 AddUsersToWorklist(TLO.New.getNode());
905 // Finally, if the node is now dead, remove it from the graph. The node
906 // may not be dead if the replacement process recursively simplified to
907 // something else needing this node.
908 if (TLO.Old.getNode()->use_empty())
909 deleteAndRecombine(TLO.Old.getNode());
912 /// Check the specified integer node value to see if it can be simplified or if
913 /// things it uses can be simplified by bit propagation. If so, return true.
914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
915 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
916 APInt KnownZero, KnownOne;
917 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
921 AddToWorklist(Op.getNode());
923 // Replace the old value with the new one.
925 DEBUG(dbgs() << "\nReplacing.2 ";
926 TLO.Old.getNode()->dump(&DAG);
927 dbgs() << "\nWith: ";
928 TLO.New.getNode()->dump(&DAG);
931 CommitTargetLoweringOpt(TLO);
935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
937 EVT VT = Load->getValueType(0);
938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
940 DEBUG(dbgs() << "\nReplacing.9 ";
942 dbgs() << "\nWith: ";
943 Trunc.getNode()->dump(&DAG);
945 WorklistRemover DeadNodes(*this);
946 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
947 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
948 deleteAndRecombine(Load);
949 AddToWorklist(Trunc.getNode());
952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
955 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
956 EVT MemVT = LD->getMemoryVT();
957 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
958 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
960 : LD->getExtensionType();
962 return DAG.getExtLoad(ExtType, dl, PVT,
963 LD->getChain(), LD->getBasePtr(),
964 MemVT, LD->getMemOperand());
967 unsigned Opc = Op.getOpcode();
970 case ISD::AssertSext:
971 return DAG.getNode(ISD::AssertSext, dl, PVT,
972 SExtPromoteOperand(Op.getOperand(0), PVT),
974 case ISD::AssertZext:
975 return DAG.getNode(ISD::AssertZext, dl, PVT,
976 ZExtPromoteOperand(Op.getOperand(0), PVT),
978 case ISD::Constant: {
980 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
981 return DAG.getNode(ExtOpc, dl, PVT, Op);
985 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
987 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
991 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
993 EVT OldVT = Op.getValueType();
995 bool Replace = false;
996 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
997 if (!NewOp.getNode())
999 AddToWorklist(NewOp.getNode());
1002 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1004 DAG.getValueType(OldVT));
1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1008 EVT OldVT = Op.getValueType();
1010 bool Replace = false;
1011 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012 if (!NewOp.getNode())
1014 AddToWorklist(NewOp.getNode());
1017 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1021 /// Promote the specified integer binary operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1025 if (!LegalOperations)
1028 EVT VT = Op.getValueType();
1029 if (VT.isVector() || !VT.isInteger())
1032 // If operation type is 'undesirable', e.g. i16 on x86, consider
1034 unsigned Opc = Op.getOpcode();
1035 if (TLI.isTypeDesirableForOp(Opc, VT))
1039 // Consult target whether it is a good idea to promote this operation and
1040 // what's the right type to promote it to.
1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042 assert(PVT != VT && "Don't know what type to promote to!");
1044 bool Replace0 = false;
1045 SDValue N0 = Op.getOperand(0);
1046 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1050 bool Replace1 = false;
1051 SDValue N1 = Op.getOperand(1);
1056 NN1 = PromoteOperand(N1, PVT, Replace1);
1061 AddToWorklist(NN0.getNode());
1063 AddToWorklist(NN1.getNode());
1066 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1068 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1070 DEBUG(dbgs() << "\nPromoting ";
1071 Op.getNode()->dump(&DAG));
1073 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1074 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1079 /// Promote the specified integer shift operation if the target indicates it is
1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1081 /// i32 since i16 instructions are longer.
1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1083 if (!LegalOperations)
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1102 bool Replace = false;
1103 SDValue N0 = Op.getOperand(0);
1104 if (Opc == ISD::SRA)
1105 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1106 else if (Opc == ISD::SRL)
1107 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1109 N0 = PromoteOperand(N0, PVT, Replace);
1113 AddToWorklist(N0.getNode());
1115 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1117 DEBUG(dbgs() << "\nPromoting ";
1118 Op.getNode()->dump(&DAG));
1120 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1121 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1127 if (!LegalOperations)
1130 EVT VT = Op.getValueType();
1131 if (VT.isVector() || !VT.isInteger())
1134 // If operation type is 'undesirable', e.g. i16 on x86, consider
1136 unsigned Opc = Op.getOpcode();
1137 if (TLI.isTypeDesirableForOp(Opc, VT))
1141 // Consult target whether it is a good idea to promote this operation and
1142 // what's the right type to promote it to.
1143 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1144 assert(PVT != VT && "Don't know what type to promote to!");
1145 // fold (aext (aext x)) -> (aext x)
1146 // fold (aext (zext x)) -> (zext x)
1147 // fold (aext (sext x)) -> (sext x)
1148 DEBUG(dbgs() << "\nPromoting ";
1149 Op.getNode()->dump(&DAG));
1150 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1155 bool DAGCombiner::PromoteLoad(SDValue Op) {
1156 if (!LegalOperations)
1159 EVT VT = Op.getValueType();
1160 if (VT.isVector() || !VT.isInteger())
1163 // If operation type is 'undesirable', e.g. i16 on x86, consider
1165 unsigned Opc = Op.getOpcode();
1166 if (TLI.isTypeDesirableForOp(Opc, VT))
1170 // Consult target whether it is a good idea to promote this operation and
1171 // what's the right type to promote it to.
1172 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1173 assert(PVT != VT && "Don't know what type to promote to!");
1176 SDNode *N = Op.getNode();
1177 LoadSDNode *LD = cast<LoadSDNode>(N);
1178 EVT MemVT = LD->getMemoryVT();
1179 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1180 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1182 : LD->getExtensionType();
1183 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1184 LD->getChain(), LD->getBasePtr(),
1185 MemVT, LD->getMemOperand());
1186 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1188 DEBUG(dbgs() << "\nPromoting ";
1191 Result.getNode()->dump(&DAG);
1193 WorklistRemover DeadNodes(*this);
1194 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1195 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1196 deleteAndRecombine(N);
1197 AddToWorklist(Result.getNode());
1203 /// \brief Recursively delete a node which has no uses and any operands for
1204 /// which it is the only use.
1206 /// Note that this both deletes the nodes and removes them from the worklist.
1207 /// It also adds any nodes who have had a user deleted to the worklist as they
1208 /// may now have only one use and subject to other combines.
1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1210 if (!N->use_empty())
1213 SmallSetVector<SDNode *, 16> Nodes;
1216 N = Nodes.pop_back_val();
1220 if (N->use_empty()) {
1221 for (const SDValue &ChildN : N->op_values())
1222 Nodes.insert(ChildN.getNode());
1224 removeFromWorklist(N);
1229 } while (!Nodes.empty());
1233 //===----------------------------------------------------------------------===//
1234 // Main DAG Combiner implementation
1235 //===----------------------------------------------------------------------===//
1237 void DAGCombiner::Run(CombineLevel AtLevel) {
1238 // set the instance variables, so that the various visit routines may use it.
1240 LegalOperations = Level >= AfterLegalizeVectorOps;
1241 LegalTypes = Level >= AfterLegalizeTypes;
1243 // Add all the dag nodes to the worklist.
1244 for (SDNode &Node : DAG.allnodes())
1245 AddToWorklist(&Node);
1247 // Create a dummy node (which is not added to allnodes), that adds a reference
1248 // to the root node, preventing it from being deleted, and tracking any
1249 // changes of the root.
1250 HandleSDNode Dummy(DAG.getRoot());
1252 // while the worklist isn't empty, find a node and
1253 // try and combine it.
1254 while (!WorklistMap.empty()) {
1256 // The Worklist holds the SDNodes in order, but it may contain null entries.
1258 N = Worklist.pop_back_val();
1261 bool GoodWorklistEntry = WorklistMap.erase(N);
1262 (void)GoodWorklistEntry;
1263 assert(GoodWorklistEntry &&
1264 "Found a worklist entry without a corresponding map entry!");
1266 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1267 // N is deleted from the DAG, since they too may now be dead or may have a
1268 // reduced number of uses, allowing other xforms.
1269 if (recursivelyDeleteUnusedNodes(N))
1272 WorklistRemover DeadNodes(*this);
1274 // If this combine is running after legalizing the DAG, re-legalize any
1275 // nodes pulled off the worklist.
1276 if (Level == AfterLegalizeDAG) {
1277 SmallSetVector<SDNode *, 16> UpdatedNodes;
1278 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1280 for (SDNode *LN : UpdatedNodes) {
1282 AddUsersToWorklist(LN);
1288 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1290 // Add any operands of the new node which have not yet been combined to the
1291 // worklist as well. Because the worklist uniques things already, this
1292 // won't repeatedly process the same operand.
1293 CombinedNodes.insert(N);
1294 for (const SDValue &ChildN : N->op_values())
1295 if (!CombinedNodes.count(ChildN.getNode()))
1296 AddToWorklist(ChildN.getNode());
1298 SDValue RV = combine(N);
1305 // If we get back the same node we passed in, rather than a new node or
1306 // zero, we know that the node must have defined multiple values and
1307 // CombineTo was used. Since CombineTo takes care of the worklist
1308 // mechanics for us, we have no work to do in this case.
1309 if (RV.getNode() == N)
1312 assert(N->getOpcode() != ISD::DELETED_NODE &&
1313 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1314 "Node was deleted but visit returned new node!");
1316 DEBUG(dbgs() << " ... into: ";
1317 RV.getNode()->dump(&DAG));
1319 // Transfer debug value.
1320 DAG.TransferDbgValues(SDValue(N, 0), RV);
1321 if (N->getNumValues() == RV.getNode()->getNumValues())
1322 DAG.ReplaceAllUsesWith(N, RV.getNode());
1324 assert(N->getValueType(0) == RV.getValueType() &&
1325 N->getNumValues() == 1 && "Type mismatch");
1327 DAG.ReplaceAllUsesWith(N, &OpV);
1330 // Push the new node and any users onto the worklist
1331 AddToWorklist(RV.getNode());
1332 AddUsersToWorklist(RV.getNode());
1334 // Finally, if the node is now dead, remove it from the graph. The node
1335 // may not be dead if the replacement process recursively simplified to
1336 // something else needing this node. This will also take care of adding any
1337 // operands which have lost a user to the worklist.
1338 recursivelyDeleteUnusedNodes(N);
1341 // If the root changed (e.g. it was a dead load, update the root).
1342 DAG.setRoot(Dummy.getValue());
1343 DAG.RemoveDeadNodes();
1346 SDValue DAGCombiner::visit(SDNode *N) {
1347 switch (N->getOpcode()) {
1349 case ISD::TokenFactor: return visitTokenFactor(N);
1350 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1351 case ISD::ADD: return visitADD(N);
1352 case ISD::SUB: return visitSUB(N);
1353 case ISD::ADDC: return visitADDC(N);
1354 case ISD::SUBC: return visitSUBC(N);
1355 case ISD::ADDE: return visitADDE(N);
1356 case ISD::SUBE: return visitSUBE(N);
1357 case ISD::MUL: return visitMUL(N);
1358 case ISD::SDIV: return visitSDIV(N);
1359 case ISD::UDIV: return visitUDIV(N);
1361 case ISD::UREM: return visitREM(N);
1362 case ISD::MULHU: return visitMULHU(N);
1363 case ISD::MULHS: return visitMULHS(N);
1364 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1365 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1366 case ISD::SMULO: return visitSMULO(N);
1367 case ISD::UMULO: return visitUMULO(N);
1371 case ISD::UMAX: return visitIMINMAX(N);
1372 case ISD::AND: return visitAND(N);
1373 case ISD::OR: return visitOR(N);
1374 case ISD::XOR: return visitXOR(N);
1375 case ISD::SHL: return visitSHL(N);
1376 case ISD::SRA: return visitSRA(N);
1377 case ISD::SRL: return visitSRL(N);
1379 case ISD::ROTL: return visitRotate(N);
1380 case ISD::BSWAP: return visitBSWAP(N);
1381 case ISD::CTLZ: return visitCTLZ(N);
1382 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1383 case ISD::CTTZ: return visitCTTZ(N);
1384 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1385 case ISD::CTPOP: return visitCTPOP(N);
1386 case ISD::SELECT: return visitSELECT(N);
1387 case ISD::VSELECT: return visitVSELECT(N);
1388 case ISD::SELECT_CC: return visitSELECT_CC(N);
1389 case ISD::SETCC: return visitSETCC(N);
1390 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1391 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1392 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1393 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1394 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1395 case ISD::TRUNCATE: return visitTRUNCATE(N);
1396 case ISD::BITCAST: return visitBITCAST(N);
1397 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1398 case ISD::FADD: return visitFADD(N);
1399 case ISD::FSUB: return visitFSUB(N);
1400 case ISD::FMUL: return visitFMUL(N);
1401 case ISD::FMA: return visitFMA(N);
1402 case ISD::FDIV: return visitFDIV(N);
1403 case ISD::FREM: return visitFREM(N);
1404 case ISD::FSQRT: return visitFSQRT(N);
1405 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1406 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1407 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1408 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1409 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1410 case ISD::FP_ROUND: return visitFP_ROUND(N);
1411 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1412 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1413 case ISD::FNEG: return visitFNEG(N);
1414 case ISD::FABS: return visitFABS(N);
1415 case ISD::FFLOOR: return visitFFLOOR(N);
1416 case ISD::FMINNUM: return visitFMINNUM(N);
1417 case ISD::FMAXNUM: return visitFMAXNUM(N);
1418 case ISD::FCEIL: return visitFCEIL(N);
1419 case ISD::FTRUNC: return visitFTRUNC(N);
1420 case ISD::BRCOND: return visitBRCOND(N);
1421 case ISD::BR_CC: return visitBR_CC(N);
1422 case ISD::LOAD: return visitLOAD(N);
1423 case ISD::STORE: return visitSTORE(N);
1424 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1425 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1426 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1427 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1428 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1429 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1430 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1431 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1432 case ISD::MGATHER: return visitMGATHER(N);
1433 case ISD::MLOAD: return visitMLOAD(N);
1434 case ISD::MSCATTER: return visitMSCATTER(N);
1435 case ISD::MSTORE: return visitMSTORE(N);
1436 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1437 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
1442 SDValue DAGCombiner::combine(SDNode *N) {
1443 SDValue RV = visit(N);
1445 // If nothing happened, try a target-specific DAG combine.
1446 if (!RV.getNode()) {
1447 assert(N->getOpcode() != ISD::DELETED_NODE &&
1448 "Node was deleted but visit returned NULL!");
1450 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1451 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1453 // Expose the DAG combiner to the target combiner impls.
1454 TargetLowering::DAGCombinerInfo
1455 DagCombineInfo(DAG, Level, false, this);
1457 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1461 // If nothing happened still, try promoting the operation.
1462 if (!RV.getNode()) {
1463 switch (N->getOpcode()) {
1471 RV = PromoteIntBinOp(SDValue(N, 0));
1476 RV = PromoteIntShiftOp(SDValue(N, 0));
1478 case ISD::SIGN_EXTEND:
1479 case ISD::ZERO_EXTEND:
1480 case ISD::ANY_EXTEND:
1481 RV = PromoteExtend(SDValue(N, 0));
1484 if (PromoteLoad(SDValue(N, 0)))
1490 // If N is a commutative binary node, try commuting it to enable more
1492 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1493 N->getNumValues() == 1) {
1494 SDValue N0 = N->getOperand(0);
1495 SDValue N1 = N->getOperand(1);
1497 // Constant operands are canonicalized to RHS.
1498 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1499 SDValue Ops[] = {N1, N0};
1500 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1503 return SDValue(CSENode, 0);
1510 /// Given a node, return its input chain if it has one, otherwise return a null
1512 static SDValue getInputChainForNode(SDNode *N) {
1513 if (unsigned NumOps = N->getNumOperands()) {
1514 if (N->getOperand(0).getValueType() == MVT::Other)
1515 return N->getOperand(0);
1516 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1517 return N->getOperand(NumOps-1);
1518 for (unsigned i = 1; i < NumOps-1; ++i)
1519 if (N->getOperand(i).getValueType() == MVT::Other)
1520 return N->getOperand(i);
1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1526 // If N has two operands, where one has an input chain equal to the other,
1527 // the 'other' chain is redundant.
1528 if (N->getNumOperands() == 2) {
1529 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1530 return N->getOperand(0);
1531 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1532 return N->getOperand(1);
1535 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1536 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1537 SmallPtrSet<SDNode*, 16> SeenOps;
1538 bool Changed = false; // If we should replace this token factor.
1540 // Start out with this token factor.
1543 // Iterate through token factors. The TFs grows when new token factors are
1545 for (unsigned i = 0; i < TFs.size(); ++i) {
1546 SDNode *TF = TFs[i];
1548 // Check each of the operands.
1549 for (const SDValue &Op : TF->op_values()) {
1551 switch (Op.getOpcode()) {
1552 case ISD::EntryToken:
1553 // Entry tokens don't need to be added to the list. They are
1558 case ISD::TokenFactor:
1559 if (Op.hasOneUse() &&
1560 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1561 // Queue up for processing.
1562 TFs.push_back(Op.getNode());
1563 // Clean up in case the token factor is removed.
1564 AddToWorklist(Op.getNode());
1571 // Only add if it isn't already in the list.
1572 if (SeenOps.insert(Op.getNode()).second)
1583 // If we've changed things around then replace token factor.
1586 // The entry token is the only possible outcome.
1587 Result = DAG.getEntryNode();
1589 // New and improved token factor.
1590 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1593 // Add users to worklist if AA is enabled, since it may introduce
1594 // a lot of new chained token factors while removing memory deps.
1595 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1596 : DAG.getSubtarget().useAA();
1597 return CombineTo(N, Result, UseAA /*add to worklist*/);
1603 /// MERGE_VALUES can always be eliminated.
1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1605 WorklistRemover DeadNodes(*this);
1606 // Replacing results may cause a different MERGE_VALUES to suddenly
1607 // be CSE'd with N, and carry its uses with it. Iterate until no
1608 // uses remain, to ensure that the node can be safely deleted.
1609 // First add the users of this node to the work list so that they
1610 // can be tried again once they have new operands.
1611 AddUsersToWorklist(N);
1613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1615 } while (!N->use_empty());
1616 deleteAndRecombine(N);
1617 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1620 static bool isNullConstant(SDValue V) {
1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622 return Const != nullptr && Const->isNullValue();
1625 static bool isNullFPConstant(SDValue V) {
1626 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1627 return Const != nullptr && Const->isZero() && !Const->isNegative();
1630 static bool isAllOnesConstant(SDValue V) {
1631 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632 return Const != nullptr && Const->isAllOnesValue();
1635 static bool isOneConstant(SDValue V) {
1636 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1637 return Const != nullptr && Const->isOne();
1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1641 /// ContantSDNode pointer else nullptr.
1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1643 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1644 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1647 SDValue DAGCombiner::visitADD(SDNode *N) {
1648 SDValue N0 = N->getOperand(0);
1649 SDValue N1 = N->getOperand(1);
1650 EVT VT = N0.getValueType();
1653 if (VT.isVector()) {
1654 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1657 // fold (add x, 0) -> x, vector edition
1658 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1660 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1664 // fold (add x, undef) -> undef
1665 if (N0.getOpcode() == ISD::UNDEF)
1667 if (N1.getOpcode() == ISD::UNDEF)
1669 // fold (add c1, c2) -> c1+c2
1670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1671 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1673 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1674 // canonicalize constant to RHS
1675 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1676 !isConstantIntBuildVectorOrConstantInt(N1))
1677 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1678 // fold (add x, 0) -> x
1679 if (isNullConstant(N1))
1681 // fold (add Sym, c) -> Sym+c
1682 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1683 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1684 GA->getOpcode() == ISD::GlobalAddress)
1685 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1687 (uint64_t)N1C->getSExtValue());
1688 // fold ((c1-A)+c2) -> (c1+c2)-A
1689 if (N1C && N0.getOpcode() == ISD::SUB)
1690 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1692 return DAG.getNode(ISD::SUB, DL, VT,
1693 DAG.getConstant(N1C->getAPIntValue()+
1694 N0C->getAPIntValue(), DL, VT),
1698 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1700 // fold ((0-A) + B) -> B-A
1701 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1703 // fold (A + (0-B)) -> A-B
1704 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1706 // fold (A+(B-A)) -> B
1707 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1708 return N1.getOperand(0);
1709 // fold ((B-A)+A) -> B
1710 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1711 return N0.getOperand(0);
1712 // fold (A+(B-(A+C))) to (B-C)
1713 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714 N0 == N1.getOperand(1).getOperand(0))
1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716 N1.getOperand(1).getOperand(1));
1717 // fold (A+(B-(C+A))) to (B-C)
1718 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1719 N0 == N1.getOperand(1).getOperand(1))
1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1721 N1.getOperand(1).getOperand(0));
1722 // fold (A+((B-A)+or-C)) to (B+or-C)
1723 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1724 N1.getOperand(0).getOpcode() == ISD::SUB &&
1725 N0 == N1.getOperand(0).getOperand(1))
1726 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1727 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1729 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1730 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1731 SDValue N00 = N0.getOperand(0);
1732 SDValue N01 = N0.getOperand(1);
1733 SDValue N10 = N1.getOperand(0);
1734 SDValue N11 = N1.getOperand(1);
1736 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1737 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1738 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1739 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1742 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1743 return SDValue(N, 0);
1745 // fold (a+b) -> (a|b) iff a and b share no bits.
1746 if (VT.isInteger() && !VT.isVector()) {
1747 APInt LHSZero, LHSOne;
1748 APInt RHSZero, RHSOne;
1749 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1751 if (LHSZero.getBoolValue()) {
1752 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1754 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1755 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1756 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1757 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1763 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1764 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1765 isNullConstant(N1.getOperand(0).getOperand(0)))
1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1767 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1768 N1.getOperand(0).getOperand(1),
1770 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1771 isNullConstant(N0.getOperand(0).getOperand(0)))
1772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1773 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1774 N0.getOperand(0).getOperand(1),
1777 if (N1.getOpcode() == ISD::AND) {
1778 SDValue AndOp0 = N1.getOperand(0);
1779 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1780 unsigned DestBits = VT.getScalarType().getSizeInBits();
1782 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1783 // and similar xforms where the inner op is either ~0 or 0.
1784 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1786 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1790 // add (sext i1), X -> sub X, (zext i1)
1791 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1792 N0.getOperand(0).getValueType() == MVT::i1 &&
1793 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1795 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1796 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1799 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1800 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1801 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1802 if (TN->getVT() == MVT::i1) {
1804 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1805 DAG.getConstant(1, DL, VT));
1806 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1813 SDValue DAGCombiner::visitADDC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 EVT VT = N0.getValueType();
1818 // If the flag result is dead, turn this into an ADD.
1819 if (!N->hasAnyUseOfValue(1))
1820 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1821 DAG.getNode(ISD::CARRY_FALSE,
1822 SDLoc(N), MVT::Glue));
1824 // canonicalize constant to RHS.
1825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1828 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1830 // fold (addc x, 0) -> x + no carry out
1831 if (isNullConstant(N1))
1832 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1833 SDLoc(N), MVT::Glue));
1835 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1836 APInt LHSZero, LHSOne;
1837 APInt RHSZero, RHSOne;
1838 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1840 if (LHSZero.getBoolValue()) {
1841 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1843 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1844 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1845 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1846 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1847 DAG.getNode(ISD::CARRY_FALSE,
1848 SDLoc(N), MVT::Glue));
1854 SDValue DAGCombiner::visitADDE(SDNode *N) {
1855 SDValue N0 = N->getOperand(0);
1856 SDValue N1 = N->getOperand(1);
1857 SDValue CarryIn = N->getOperand(2);
1859 // canonicalize constant to RHS
1860 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1861 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1863 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1866 // fold (adde x, y, false) -> (addc x, y)
1867 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1868 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1873 // Since it may not be valid to emit a fold to zero for vector initializers
1874 // check if we can before folding.
1875 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1877 bool LegalOperations, bool LegalTypes) {
1879 return DAG.getConstant(0, DL, VT);
1880 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1881 return DAG.getConstant(0, DL, VT);
1885 SDValue DAGCombiner::visitSUB(SDNode *N) {
1886 SDValue N0 = N->getOperand(0);
1887 SDValue N1 = N->getOperand(1);
1888 EVT VT = N0.getValueType();
1891 if (VT.isVector()) {
1892 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1895 // fold (sub x, 0) -> x, vector edition
1896 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1900 // fold (sub x, x) -> 0
1901 // FIXME: Refactor this and xor and other similar operations together.
1903 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1904 // fold (sub c1, c2) -> c1-c2
1905 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1906 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1908 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1909 // fold (sub x, c) -> (add x, -c)
1912 return DAG.getNode(ISD::ADD, DL, VT, N0,
1913 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1915 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1916 if (isAllOnesConstant(N0))
1917 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1918 // fold A-(A-B) -> B
1919 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1920 return N1.getOperand(1);
1921 // fold (A+B)-A -> B
1922 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1923 return N0.getOperand(1);
1924 // fold (A+B)-B -> A
1925 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1926 return N0.getOperand(0);
1927 // fold C2-(A+C1) -> (C2-C1)-A
1928 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1929 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1930 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1932 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1934 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1937 // fold ((A+(B+or-C))-B) -> A+or-C
1938 if (N0.getOpcode() == ISD::ADD &&
1939 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1940 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1941 N0.getOperand(1).getOperand(0) == N1)
1942 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1943 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1944 // fold ((A+(C+B))-B) -> A+C
1945 if (N0.getOpcode() == ISD::ADD &&
1946 N0.getOperand(1).getOpcode() == ISD::ADD &&
1947 N0.getOperand(1).getOperand(1) == N1)
1948 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1950 // fold ((A-(B-C))-C) -> A-B
1951 if (N0.getOpcode() == ISD::SUB &&
1952 N0.getOperand(1).getOpcode() == ISD::SUB &&
1953 N0.getOperand(1).getOperand(1) == N1)
1954 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1955 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1957 // If either operand of a sub is undef, the result is undef
1958 if (N0.getOpcode() == ISD::UNDEF)
1960 if (N1.getOpcode() == ISD::UNDEF)
1963 // If the relocation model supports it, consider symbol offsets.
1964 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1965 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1966 // fold (sub Sym, c) -> Sym-c
1967 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1968 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1970 (uint64_t)N1C->getSExtValue());
1971 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1972 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1973 if (GA->getGlobal() == GB->getGlobal())
1974 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1978 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1979 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1980 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1981 if (TN->getVT() == MVT::i1) {
1983 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1984 DAG.getConstant(1, DL, VT));
1985 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1992 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1993 SDValue N0 = N->getOperand(0);
1994 SDValue N1 = N->getOperand(1);
1995 EVT VT = N0.getValueType();
1998 // If the flag result is dead, turn this into an SUB.
1999 if (!N->hasAnyUseOfValue(1))
2000 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2001 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003 // fold (subc x, x) -> 0 + no borrow
2005 return CombineTo(N, DAG.getConstant(0, DL, VT),
2006 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2008 // fold (subc x, 0) -> x + no borrow
2009 if (isNullConstant(N1))
2010 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2012 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2013 if (isAllOnesConstant(N0))
2014 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2015 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2020 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2021 SDValue N0 = N->getOperand(0);
2022 SDValue N1 = N->getOperand(1);
2023 SDValue CarryIn = N->getOperand(2);
2025 // fold (sube x, y, false) -> (subc x, y)
2026 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2027 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2032 SDValue DAGCombiner::visitMUL(SDNode *N) {
2033 SDValue N0 = N->getOperand(0);
2034 SDValue N1 = N->getOperand(1);
2035 EVT VT = N0.getValueType();
2037 // fold (mul x, undef) -> 0
2038 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2039 return DAG.getConstant(0, SDLoc(N), VT);
2041 bool N0IsConst = false;
2042 bool N1IsConst = false;
2043 bool N1IsOpaqueConst = false;
2044 bool N0IsOpaqueConst = false;
2045 APInt ConstValue0, ConstValue1;
2047 if (VT.isVector()) {
2048 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2051 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2052 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2054 N0IsConst = isa<ConstantSDNode>(N0);
2056 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2057 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2059 N1IsConst = isa<ConstantSDNode>(N1);
2061 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2062 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2066 // fold (mul c1, c2) -> c1*c2
2067 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2068 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2069 N0.getNode(), N1.getNode());
2071 // canonicalize constant to RHS (vector doesn't have to splat)
2072 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2073 !isConstantIntBuildVectorOrConstantInt(N1))
2074 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2075 // fold (mul x, 0) -> 0
2076 if (N1IsConst && ConstValue1 == 0)
2078 // We require a splat of the entire scalar bit width for non-contiguous
2081 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2082 // fold (mul x, 1) -> x
2083 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2085 // fold (mul x, -1) -> 0-x
2086 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2088 return DAG.getNode(ISD::SUB, DL, VT,
2089 DAG.getConstant(0, DL, VT), N0);
2091 // fold (mul x, (1 << c)) -> x << c
2092 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2095 return DAG.getNode(ISD::SHL, DL, VT, N0,
2096 DAG.getConstant(ConstValue1.logBase2(), DL,
2097 getShiftAmountTy(N0.getValueType())));
2099 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2100 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2102 unsigned Log2Val = (-ConstValue1).logBase2();
2104 // FIXME: If the input is something that is easily negated (e.g. a
2105 // single-use add), we should put the negate there.
2106 return DAG.getNode(ISD::SUB, DL, VT,
2107 DAG.getConstant(0, DL, VT),
2108 DAG.getNode(ISD::SHL, DL, VT, N0,
2109 DAG.getConstant(Log2Val, DL,
2110 getShiftAmountTy(N0.getValueType()))));
2114 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2115 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2116 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2117 isa<ConstantSDNode>(N0.getOperand(1)))) {
2118 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2119 N1, N0.getOperand(1));
2120 AddToWorklist(C3.getNode());
2121 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2122 N0.getOperand(0), C3);
2125 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2128 SDValue Sh(nullptr,0), Y(nullptr,0);
2129 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2130 if (N0.getOpcode() == ISD::SHL &&
2131 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2132 isa<ConstantSDNode>(N0.getOperand(1))) &&
2133 N0.getNode()->hasOneUse()) {
2135 } else if (N1.getOpcode() == ISD::SHL &&
2136 isa<ConstantSDNode>(N1.getOperand(1)) &&
2137 N1.getNode()->hasOneUse()) {
2142 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143 Sh.getOperand(0), Y);
2144 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2145 Mul, Sh.getOperand(1));
2149 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2150 if (isConstantIntBuildVectorOrConstantInt(N1) &&
2151 N0.getOpcode() == ISD::ADD &&
2152 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2153 isMulAddWithConstProfitable(N, N0, N1))
2154 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2155 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2156 N0.getOperand(0), N1),
2157 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2158 N0.getOperand(1), N1));
2161 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2167 /// Return true if divmod libcall is available.
2168 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2169 const TargetLowering &TLI) {
2171 switch (Node->getSimpleValueType(0).SimpleTy) {
2172 default: return false; // No libcall for vector types.
2173 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2174 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2175 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2176 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2177 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2180 return TLI.getLibcallName(LC) != nullptr;
2183 /// Issue divrem if both quotient and remainder are needed.
2184 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2185 if (Node->use_empty())
2186 return SDValue(); // This is a dead node, leave it alone.
2188 EVT VT = Node->getValueType(0);
2189 if (!TLI.isTypeLegal(VT))
2192 unsigned Opcode = Node->getOpcode();
2193 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2195 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2196 // If DIVREM is going to get expanded into a libcall,
2197 // but there is no libcall available, then don't combine.
2198 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2199 !isDivRemLibcallAvailable(Node, isSigned, TLI))
2202 // If div is legal, it's better to do the normal expansion
2203 unsigned OtherOpcode = 0;
2204 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2205 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2206 if (TLI.isOperationLegalOrCustom(Opcode, VT))
2209 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2210 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2214 SDValue Op0 = Node->getOperand(0);
2215 SDValue Op1 = Node->getOperand(1);
2217 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2218 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2220 if (User == Node || User->use_empty())
2222 // Convert the other matching node(s), too;
2223 // otherwise, the DIVREM may get target-legalized into something
2224 // target-specific that we won't be able to recognize.
2225 unsigned UserOpc = User->getOpcode();
2226 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2227 User->getOperand(0) == Op0 &&
2228 User->getOperand(1) == Op1) {
2230 if (UserOpc == OtherOpcode) {
2231 SDVTList VTs = DAG.getVTList(VT, VT);
2232 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2233 } else if (UserOpc == DivRemOpc) {
2234 combined = SDValue(User, 0);
2236 assert(UserOpc == Opcode);
2240 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2241 CombineTo(User, combined);
2242 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2243 CombineTo(User, combined.getValue(1));
2249 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2250 SDValue N0 = N->getOperand(0);
2251 SDValue N1 = N->getOperand(1);
2252 EVT VT = N->getValueType(0);
2256 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2261 // fold (sdiv c1, c2) -> c1/c2
2262 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2263 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2264 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2265 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2266 // fold (sdiv X, 1) -> X
2267 if (N1C && N1C->isOne())
2269 // fold (sdiv X, -1) -> 0-X
2270 if (N1C && N1C->isAllOnesValue())
2271 return DAG.getNode(ISD::SUB, DL, VT,
2272 DAG.getConstant(0, DL, VT), N0);
2274 // If we know the sign bits of both operands are zero, strength reduce to a
2275 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2276 if (!VT.isVector()) {
2277 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2278 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2281 // fold (sdiv X, pow2) -> simple ops after legalize
2282 // FIXME: We check for the exact bit here because the generic lowering gives
2283 // better results in that case. The target-specific lowering should learn how
2284 // to handle exact sdivs efficiently.
2285 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2286 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2287 (N1C->getAPIntValue().isPowerOf2() ||
2288 (-N1C->getAPIntValue()).isPowerOf2())) {
2289 // Target-specific implementation of sdiv x, pow2.
2290 if (SDValue Res = BuildSDIVPow2(N))
2293 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2295 // Splat the sign bit into the register
2297 DAG.getNode(ISD::SRA, DL, VT, N0,
2298 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2299 getShiftAmountTy(N0.getValueType())));
2300 AddToWorklist(SGN.getNode());
2302 // Add (N0 < 0) ? abs2 - 1 : 0;
2304 DAG.getNode(ISD::SRL, DL, VT, SGN,
2305 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2306 getShiftAmountTy(SGN.getValueType())));
2307 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2308 AddToWorklist(SRL.getNode());
2309 AddToWorklist(ADD.getNode()); // Divide by pow2
2310 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2311 DAG.getConstant(lg2, DL,
2312 getShiftAmountTy(ADD.getValueType())));
2314 // If we're dividing by a positive value, we're done. Otherwise, we must
2315 // negate the result.
2316 if (N1C->getAPIntValue().isNonNegative())
2319 AddToWorklist(SRA.getNode());
2320 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2323 // If integer divide is expensive and we satisfy the requirements, emit an
2324 // alternate sequence. Targets may check function attributes for size/speed
2326 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2327 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2328 if (SDValue Op = BuildSDIV(N))
2331 // sdiv, srem -> sdivrem
2332 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2333 // Otherwise, we break the simplification logic in visitREM().
2334 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2335 if (SDValue DivRem = useDivRem(N))
2339 if (N0.getOpcode() == ISD::UNDEF)
2340 return DAG.getConstant(0, DL, VT);
2341 // X / undef -> undef
2342 if (N1.getOpcode() == ISD::UNDEF)
2348 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2349 SDValue N0 = N->getOperand(0);
2350 SDValue N1 = N->getOperand(1);
2351 EVT VT = N->getValueType(0);
2355 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2360 // fold (udiv c1, c2) -> c1/c2
2361 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2364 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2367 // fold (udiv x, (1 << c)) -> x >>u c
2368 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2369 return DAG.getNode(ISD::SRL, DL, VT, N0,
2370 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2371 getShiftAmountTy(N0.getValueType())));
2373 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2374 if (N1.getOpcode() == ISD::SHL) {
2375 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2376 if (SHC->getAPIntValue().isPowerOf2()) {
2377 EVT ADDVT = N1.getOperand(1).getValueType();
2378 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2380 DAG.getConstant(SHC->getAPIntValue()
2383 AddToWorklist(Add.getNode());
2384 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2389 // fold (udiv x, c) -> alternate
2390 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2391 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2392 if (SDValue Op = BuildUDIV(N))
2395 // sdiv, srem -> sdivrem
2396 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2397 // Otherwise, we break the simplification logic in visitREM().
2398 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2399 if (SDValue DivRem = useDivRem(N))
2403 if (N0.getOpcode() == ISD::UNDEF)
2404 return DAG.getConstant(0, DL, VT);
2405 // X / undef -> undef
2406 if (N1.getOpcode() == ISD::UNDEF)
2412 // handles ISD::SREM and ISD::UREM
2413 SDValue DAGCombiner::visitREM(SDNode *N) {
2414 unsigned Opcode = N->getOpcode();
2415 SDValue N0 = N->getOperand(0);
2416 SDValue N1 = N->getOperand(1);
2417 EVT VT = N->getValueType(0);
2418 bool isSigned = (Opcode == ISD::SREM);
2421 // fold (rem c1, c2) -> c1%c2
2422 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2423 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2425 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2429 // If we know the sign bits of both operands are zero, strength reduce to a
2430 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2431 if (!VT.isVector()) {
2432 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2433 return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2436 // fold (urem x, pow2) -> (and x, pow2-1)
2437 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2438 N1C->getAPIntValue().isPowerOf2()) {
2439 return DAG.getNode(ISD::AND, DL, VT, N0,
2440 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2442 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2443 if (N1.getOpcode() == ISD::SHL) {
2444 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2445 if (SHC->getAPIntValue().isPowerOf2()) {
2447 DAG.getNode(ISD::ADD, DL, VT, N1,
2448 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2450 AddToWorklist(Add.getNode());
2451 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2457 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2459 // If X/C can be simplified by the division-by-constant logic, lower
2460 // X%C to the equivalent of X-X/C*C.
2461 // To avoid mangling nodes, this simplification requires that the combine()
2462 // call for the speculative DIV must not cause a DIVREM conversion. We guard
2463 // against this by skipping the simplification if isIntDivCheap(). When
2464 // div is not cheap, combine will not return a DIVREM. Regardless,
2465 // checking cheapness here makes sense since the simplification results in
2467 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2468 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2469 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2470 AddToWorklist(Div.getNode());
2471 SDValue OptimizedDiv = combine(Div.getNode());
2472 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2473 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2474 (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2475 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2476 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2477 AddToWorklist(Mul.getNode());
2482 // sdiv, srem -> sdivrem
2483 if (SDValue DivRem = useDivRem(N))
2484 return DivRem.getValue(1);
2487 if (N0.getOpcode() == ISD::UNDEF)
2488 return DAG.getConstant(0, DL, VT);
2489 // X % undef -> undef
2490 if (N1.getOpcode() == ISD::UNDEF)
2496 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2497 SDValue N0 = N->getOperand(0);
2498 SDValue N1 = N->getOperand(1);
2499 EVT VT = N->getValueType(0);
2502 // fold (mulhs x, 0) -> 0
2503 if (isNullConstant(N1))
2505 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2506 if (isOneConstant(N1)) {
2508 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2509 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2511 getShiftAmountTy(N0.getValueType())));
2513 // fold (mulhs x, undef) -> 0
2514 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2515 return DAG.getConstant(0, SDLoc(N), VT);
2517 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2519 if (VT.isSimple() && !VT.isVector()) {
2520 MVT Simple = VT.getSimpleVT();
2521 unsigned SimpleSize = Simple.getSizeInBits();
2522 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2523 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2524 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2525 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2526 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2527 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2528 DAG.getConstant(SimpleSize, DL,
2529 getShiftAmountTy(N1.getValueType())));
2530 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2537 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2538 SDValue N0 = N->getOperand(0);
2539 SDValue N1 = N->getOperand(1);
2540 EVT VT = N->getValueType(0);
2543 // fold (mulhu x, 0) -> 0
2544 if (isNullConstant(N1))
2546 // fold (mulhu x, 1) -> 0
2547 if (isOneConstant(N1))
2548 return DAG.getConstant(0, DL, N0.getValueType());
2549 // fold (mulhu x, undef) -> 0
2550 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2551 return DAG.getConstant(0, DL, VT);
2553 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2555 if (VT.isSimple() && !VT.isVector()) {
2556 MVT Simple = VT.getSimpleVT();
2557 unsigned SimpleSize = Simple.getSizeInBits();
2558 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2559 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2560 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2561 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2562 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2563 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2564 DAG.getConstant(SimpleSize, DL,
2565 getShiftAmountTy(N1.getValueType())));
2566 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2573 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2574 /// give the opcodes for the two computations that are being performed. Return
2575 /// true if a simplification was made.
2576 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2578 // If the high half is not needed, just compute the low half.
2579 bool HiExists = N->hasAnyUseOfValue(1);
2581 (!LegalOperations ||
2582 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2583 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2584 return CombineTo(N, Res, Res);
2587 // If the low half is not needed, just compute the high half.
2588 bool LoExists = N->hasAnyUseOfValue(0);
2590 (!LegalOperations ||
2591 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2592 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2593 return CombineTo(N, Res, Res);
2596 // If both halves are used, return as it is.
2597 if (LoExists && HiExists)
2600 // If the two computed results can be simplified separately, separate them.
2602 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2603 AddToWorklist(Lo.getNode());
2604 SDValue LoOpt = combine(Lo.getNode());
2605 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2606 (!LegalOperations ||
2607 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2608 return CombineTo(N, LoOpt, LoOpt);
2612 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2613 AddToWorklist(Hi.getNode());
2614 SDValue HiOpt = combine(Hi.getNode());
2615 if (HiOpt.getNode() && HiOpt != Hi &&
2616 (!LegalOperations ||
2617 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2618 return CombineTo(N, HiOpt, HiOpt);
2624 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2628 EVT VT = N->getValueType(0);
2631 // If the type is twice as wide is legal, transform the mulhu to a wider
2632 // multiply plus a shift.
2633 if (VT.isSimple() && !VT.isVector()) {
2634 MVT Simple = VT.getSimpleVT();
2635 unsigned SimpleSize = Simple.getSizeInBits();
2636 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2637 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2638 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2639 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2640 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2641 // Compute the high part as N1.
2642 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2643 DAG.getConstant(SimpleSize, DL,
2644 getShiftAmountTy(Lo.getValueType())));
2645 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2646 // Compute the low part as N0.
2647 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2648 return CombineTo(N, Lo, Hi);
2655 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2656 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2659 EVT VT = N->getValueType(0);
2662 // If the type is twice as wide is legal, transform the mulhu to a wider
2663 // multiply plus a shift.
2664 if (VT.isSimple() && !VT.isVector()) {
2665 MVT Simple = VT.getSimpleVT();
2666 unsigned SimpleSize = Simple.getSizeInBits();
2667 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2668 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2669 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2670 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2671 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2672 // Compute the high part as N1.
2673 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2674 DAG.getConstant(SimpleSize, DL,
2675 getShiftAmountTy(Lo.getValueType())));
2676 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2677 // Compute the low part as N0.
2678 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2679 return CombineTo(N, Lo, Hi);
2686 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2687 // (smulo x, 2) -> (saddo x, x)
2688 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2689 if (C2->getAPIntValue() == 2)
2690 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2691 N->getOperand(0), N->getOperand(0));
2696 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2697 // (umulo x, 2) -> (uaddo x, x)
2698 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2699 if (C2->getAPIntValue() == 2)
2700 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2701 N->getOperand(0), N->getOperand(0));
2706 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2707 SDValue N0 = N->getOperand(0);
2708 SDValue N1 = N->getOperand(1);
2709 EVT VT = N0.getValueType();
2713 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2716 // fold (add c1, c2) -> c1+c2
2717 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2718 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2720 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2722 // canonicalize constant to RHS
2723 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2724 !isConstantIntBuildVectorOrConstantInt(N1))
2725 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2730 /// If this is a binary operator with two operands of the same opcode, try to
2732 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2733 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2734 EVT VT = N0.getValueType();
2735 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2737 // Bail early if none of these transforms apply.
2738 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2740 // For each of OP in AND/OR/XOR:
2741 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2742 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2743 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2744 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2745 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2747 // do not sink logical op inside of a vector extend, since it may combine
2749 EVT Op0VT = N0.getOperand(0).getValueType();
2750 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2751 N0.getOpcode() == ISD::SIGN_EXTEND ||
2752 N0.getOpcode() == ISD::BSWAP ||
2753 // Avoid infinite looping with PromoteIntBinOp.
2754 (N0.getOpcode() == ISD::ANY_EXTEND &&
2755 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2756 (N0.getOpcode() == ISD::TRUNCATE &&
2757 (!TLI.isZExtFree(VT, Op0VT) ||
2758 !TLI.isTruncateFree(Op0VT, VT)) &&
2759 TLI.isTypeLegal(Op0VT))) &&
2761 Op0VT == N1.getOperand(0).getValueType() &&
2762 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2763 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2764 N0.getOperand(0).getValueType(),
2765 N0.getOperand(0), N1.getOperand(0));
2766 AddToWorklist(ORNode.getNode());
2767 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2770 // For each of OP in SHL/SRL/SRA/AND...
2771 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2772 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2773 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2774 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2775 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2776 N0.getOperand(1) == N1.getOperand(1)) {
2777 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2778 N0.getOperand(0).getValueType(),
2779 N0.getOperand(0), N1.getOperand(0));
2780 AddToWorklist(ORNode.getNode());
2781 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2782 ORNode, N0.getOperand(1));
2785 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2786 // Only perform this optimization after type legalization and before
2787 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2788 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2789 // we don't want to undo this promotion.
2790 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2792 if ((N0.getOpcode() == ISD::BITCAST ||
2793 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2794 Level == AfterLegalizeTypes) {
2795 SDValue In0 = N0.getOperand(0);
2796 SDValue In1 = N1.getOperand(0);
2797 EVT In0Ty = In0.getValueType();
2798 EVT In1Ty = In1.getValueType();
2800 // If both incoming values are integers, and the original types are the
2802 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2803 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2804 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2805 AddToWorklist(Op.getNode());
2810 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2811 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2812 // If both shuffles use the same mask, and both shuffle within a single
2813 // vector, then it is worthwhile to move the swizzle after the operation.
2814 // The type-legalizer generates this pattern when loading illegal
2815 // vector types from memory. In many cases this allows additional shuffle
2817 // There are other cases where moving the shuffle after the xor/and/or
2818 // is profitable even if shuffles don't perform a swizzle.
2819 // If both shuffles use the same mask, and both shuffles have the same first
2820 // or second operand, then it might still be profitable to move the shuffle
2821 // after the xor/and/or operation.
2822 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2823 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2824 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2826 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2827 "Inputs to shuffles are not the same type");
2829 // Check that both shuffles use the same mask. The masks are known to be of
2830 // the same length because the result vector type is the same.
2831 // Check also that shuffles have only one use to avoid introducing extra
2833 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2834 SVN0->getMask().equals(SVN1->getMask())) {
2835 SDValue ShOp = N0->getOperand(1);
2837 // Don't try to fold this node if it requires introducing a
2838 // build vector of all zeros that might be illegal at this stage.
2839 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2841 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2846 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2847 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2848 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2849 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2850 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2851 N0->getOperand(0), N1->getOperand(0));
2852 AddToWorklist(NewNode.getNode());
2853 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2854 &SVN0->getMask()[0]);
2857 // Don't try to fold this node if it requires introducing a
2858 // build vector of all zeros that might be illegal at this stage.
2859 ShOp = N0->getOperand(0);
2860 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2862 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2867 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2868 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2869 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2870 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2871 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2872 N0->getOperand(1), N1->getOperand(1));
2873 AddToWorklist(NewNode.getNode());
2874 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2875 &SVN0->getMask()[0]);
2883 /// This contains all DAGCombine rules which reduce two values combined by
2884 /// an And operation to a single value. This makes them reusable in the context
2885 /// of visitSELECT(). Rules involving constants are not included as
2886 /// visitSELECT() already handles those cases.
2887 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2888 SDNode *LocReference) {
2889 EVT VT = N1.getValueType();
2891 // fold (and x, undef) -> 0
2892 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2893 return DAG.getConstant(0, SDLoc(LocReference), VT);
2894 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2895 SDValue LL, LR, RL, RR, CC0, CC1;
2896 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2897 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2898 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2900 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2901 LL.getValueType().isInteger()) {
2902 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2903 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2904 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2905 LR.getValueType(), LL, RL);
2906 AddToWorklist(ORNode.getNode());
2907 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2909 if (isAllOnesConstant(LR)) {
2910 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2911 if (Op1 == ISD::SETEQ) {
2912 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2913 LR.getValueType(), LL, RL);
2914 AddToWorklist(ANDNode.getNode());
2915 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2917 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2918 if (Op1 == ISD::SETGT) {
2919 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2920 LR.getValueType(), LL, RL);
2921 AddToWorklist(ORNode.getNode());
2922 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2926 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2927 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2928 Op0 == Op1 && LL.getValueType().isInteger() &&
2929 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2930 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2932 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2933 LL, DAG.getConstant(1, DL,
2934 LL.getValueType()));
2935 AddToWorklist(ADDNode.getNode());
2936 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2937 DAG.getConstant(2, DL, LL.getValueType()),
2940 // canonicalize equivalent to ll == rl
2941 if (LL == RR && LR == RL) {
2942 Op1 = ISD::getSetCCSwappedOperands(Op1);
2945 if (LL == RL && LR == RR) {
2946 bool isInteger = LL.getValueType().isInteger();
2947 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2948 if (Result != ISD::SETCC_INVALID &&
2949 (!LegalOperations ||
2950 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2951 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2952 EVT CCVT = getSetCCResultType(LL.getValueType());
2953 if (N0.getValueType() == CCVT ||
2954 (!LegalOperations && N0.getValueType() == MVT::i1))
2955 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2961 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2962 VT.getSizeInBits() <= 64) {
2963 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2964 APInt ADDC = ADDI->getAPIntValue();
2965 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2966 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2967 // immediate for an add, but it is legal if its top c2 bits are set,
2968 // transform the ADD so the immediate doesn't need to be materialized
2970 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2971 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2972 SRLI->getZExtValue());
2973 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2975 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2978 DAG.getNode(ISD::ADD, DL, VT,
2979 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2980 CombineTo(N0.getNode(), NewAdd);
2981 // Return N so it doesn't get rechecked!
2982 return SDValue(LocReference, 0);
2993 SDValue DAGCombiner::visitAND(SDNode *N) {
2994 SDValue N0 = N->getOperand(0);
2995 SDValue N1 = N->getOperand(1);
2996 EVT VT = N1.getValueType();
2999 if (VT.isVector()) {
3000 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3003 // fold (and x, 0) -> 0, vector edition
3004 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3005 // do not return N0, because undef node may exist in N0
3006 return DAG.getConstant(
3007 APInt::getNullValue(
3008 N0.getValueType().getScalarType().getSizeInBits()),
3009 SDLoc(N), N0.getValueType());
3010 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3011 // do not return N1, because undef node may exist in N1
3012 return DAG.getConstant(
3013 APInt::getNullValue(
3014 N1.getValueType().getScalarType().getSizeInBits()),
3015 SDLoc(N), N1.getValueType());
3017 // fold (and x, -1) -> x, vector edition
3018 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3020 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3024 // fold (and c1, c2) -> c1&c2
3025 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3026 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3027 if (N0C && N1C && !N1C->isOpaque())
3028 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3029 // canonicalize constant to RHS
3030 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3031 !isConstantIntBuildVectorOrConstantInt(N1))
3032 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3033 // fold (and x, -1) -> x
3034 if (isAllOnesConstant(N1))
3036 // if (and x, c) is known to be zero, return 0
3037 unsigned BitWidth = VT.getScalarType().getSizeInBits();
3038 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3039 APInt::getAllOnesValue(BitWidth)))
3040 return DAG.getConstant(0, SDLoc(N), VT);
3042 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3044 // fold (and (or x, C), D) -> D if (C & D) == D
3045 if (N1C && N0.getOpcode() == ISD::OR)
3046 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3047 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3049 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3050 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3051 SDValue N0Op0 = N0.getOperand(0);
3052 APInt Mask = ~N1C->getAPIntValue();
3053 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3054 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3055 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3056 N0.getValueType(), N0Op0);
3058 // Replace uses of the AND with uses of the Zero extend node.
3061 // We actually want to replace all uses of the any_extend with the
3062 // zero_extend, to avoid duplicating things. This will later cause this
3063 // AND to be folded.
3064 CombineTo(N0.getNode(), Zext);
3065 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3068 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3069 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3070 // already be zero by virtue of the width of the base type of the load.
3072 // the 'X' node here can either be nothing or an extract_vector_elt to catch
3074 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3075 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3076 N0.getOpcode() == ISD::LOAD) {
3077 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3078 N0 : N0.getOperand(0) );
3080 // Get the constant (if applicable) the zero'th operand is being ANDed with.
3081 // This can be a pure constant or a vector splat, in which case we treat the
3082 // vector as a scalar and use the splat value.
3083 APInt Constant = APInt::getNullValue(1);
3084 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3085 Constant = C->getAPIntValue();
3086 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3087 APInt SplatValue, SplatUndef;
3088 unsigned SplatBitSize;
3090 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3091 SplatBitSize, HasAnyUndefs);
3093 // Undef bits can contribute to a possible optimisation if set, so
3095 SplatValue |= SplatUndef;
3097 // The splat value may be something like "0x00FFFFFF", which means 0 for
3098 // the first vector value and FF for the rest, repeating. We need a mask
3099 // that will apply equally to all members of the vector, so AND all the
3100 // lanes of the constant together.
3101 EVT VT = Vector->getValueType(0);
3102 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3104 // If the splat value has been compressed to a bitlength lower
3105 // than the size of the vector lane, we need to re-expand it to
3107 if (BitWidth > SplatBitSize)
3108 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3109 SplatBitSize < BitWidth;
3110 SplatBitSize = SplatBitSize * 2)
3111 SplatValue |= SplatValue.shl(SplatBitSize);
3113 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3114 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3115 if (SplatBitSize % BitWidth == 0) {
3116 Constant = APInt::getAllOnesValue(BitWidth);
3117 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3118 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3123 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3124 // actually legal and isn't going to get expanded, else this is a false
3126 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3127 Load->getValueType(0),
3128 Load->getMemoryVT());
3130 // Resize the constant to the same size as the original memory access before
3131 // extension. If it is still the AllOnesValue then this AND is completely
3134 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3137 switch (Load->getExtensionType()) {
3138 default: B = false; break;
3139 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3141 case ISD::NON_EXTLOAD: B = true; break;
3144 if (B && Constant.isAllOnesValue()) {
3145 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3146 // preserve semantics once we get rid of the AND.
3147 SDValue NewLoad(Load, 0);
3148 if (Load->getExtensionType() == ISD::EXTLOAD) {
3149 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3150 Load->getValueType(0), SDLoc(Load),
3151 Load->getChain(), Load->getBasePtr(),
3152 Load->getOffset(), Load->getMemoryVT(),
3153 Load->getMemOperand());
3154 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3155 if (Load->getNumValues() == 3) {
3156 // PRE/POST_INC loads have 3 values.
3157 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3158 NewLoad.getValue(2) };
3159 CombineTo(Load, To, 3, true);
3161 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3165 // Fold the AND away, taking care not to fold to the old load node if we
3167 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3169 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3173 // fold (and (load x), 255) -> (zextload x, i8)
3174 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3175 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3176 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3177 (N0.getOpcode() == ISD::ANY_EXTEND &&
3178 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3179 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3180 LoadSDNode *LN0 = HasAnyExt
3181 ? cast<LoadSDNode>(N0.getOperand(0))
3182 : cast<LoadSDNode>(N0);
3183 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3184 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3185 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3186 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3187 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3188 EVT LoadedVT = LN0->getMemoryVT();
3189 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3191 if (ExtVT == LoadedVT &&
3192 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3196 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3197 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3198 LN0->getMemOperand());
3200 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3201 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3204 // Do not change the width of a volatile load.
3205 // Do not generate loads of non-round integer types since these can
3206 // be expensive (and would be wrong if the type is not byte sized).
3207 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3208 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3210 TLI.shouldReduceLoadWidth(LN0, ISD::ZEXTLOAD, ExtVT)) {
3211 EVT PtrType = LN0->getOperand(1).getValueType();
3213 unsigned Alignment = LN0->getAlignment();
3214 SDValue NewPtr = LN0->getBasePtr();
3216 // For big endian targets, we need to add an offset to the pointer
3217 // to load the correct bytes. For little endian systems, we merely
3218 // need to read fewer bytes from the same pointer.
3219 if (DAG.getDataLayout().isBigEndian()) {
3220 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3221 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3222 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3224 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3225 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3226 Alignment = MinAlign(Alignment, PtrOff);
3229 AddToWorklist(NewPtr.getNode());
3232 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3233 LN0->getChain(), NewPtr,
3234 LN0->getPointerInfo(),
3235 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3236 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3238 CombineTo(LN0, Load, Load.getValue(1));
3239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3245 if (SDValue Combined = visitANDLike(N0, N1, N))
3248 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3249 if (N0.getOpcode() == N1.getOpcode())
3250 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3253 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3254 // fold (and (sra)) -> (and (srl)) when possible.
3255 if (!VT.isVector() &&
3256 SimplifyDemandedBits(SDValue(N, 0)))
3257 return SDValue(N, 0);
3259 // fold (zext_inreg (extload x)) -> (zextload x)
3260 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3261 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3262 EVT MemVT = LN0->getMemoryVT();
3263 // If we zero all the possible extended bits, then we can turn this into
3264 // a zextload if we are running before legalize or the operation is legal.
3265 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3266 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3267 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3268 ((!LegalOperations && !LN0->isVolatile()) ||
3269 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3270 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3271 LN0->getChain(), LN0->getBasePtr(),
3272 MemVT, LN0->getMemOperand());
3274 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3275 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3278 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3279 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3281 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3282 EVT MemVT = LN0->getMemoryVT();
3283 // If we zero all the possible extended bits, then we can turn this into
3284 // a zextload if we are running before legalize or the operation is legal.
3285 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3286 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3287 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3288 ((!LegalOperations && !LN0->isVolatile()) ||
3289 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3290 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3291 LN0->getChain(), LN0->getBasePtr(),
3292 MemVT, LN0->getMemOperand());
3294 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3295 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3298 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3299 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3300 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3301 N0.getOperand(1), false);
3302 if (BSwap.getNode())
3309 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3310 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3311 bool DemandHighBits) {
3312 if (!LegalOperations)
3315 EVT VT = N->getValueType(0);
3316 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3318 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3321 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3322 bool LookPassAnd0 = false;
3323 bool LookPassAnd1 = false;
3324 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3326 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3328 if (N0.getOpcode() == ISD::AND) {
3329 if (!N0.getNode()->hasOneUse())
3331 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3332 if (!N01C || N01C->getZExtValue() != 0xFF00)
3334 N0 = N0.getOperand(0);
3335 LookPassAnd0 = true;
3338 if (N1.getOpcode() == ISD::AND) {
3339 if (!N1.getNode()->hasOneUse())
3341 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3342 if (!N11C || N11C->getZExtValue() != 0xFF)
3344 N1 = N1.getOperand(0);
3345 LookPassAnd1 = true;
3348 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3350 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3352 if (!N0.getNode()->hasOneUse() ||
3353 !N1.getNode()->hasOneUse())
3356 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3357 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3360 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3363 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3364 SDValue N00 = N0->getOperand(0);
3365 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3366 if (!N00.getNode()->hasOneUse())
3368 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3369 if (!N001C || N001C->getZExtValue() != 0xFF)
3371 N00 = N00.getOperand(0);
3372 LookPassAnd0 = true;
3375 SDValue N10 = N1->getOperand(0);
3376 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3377 if (!N10.getNode()->hasOneUse())
3379 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3380 if (!N101C || N101C->getZExtValue() != 0xFF00)
3382 N10 = N10.getOperand(0);
3383 LookPassAnd1 = true;
3389 // Make sure everything beyond the low halfword gets set to zero since the SRL
3390 // 16 will clear the top bits.
3391 unsigned OpSizeInBits = VT.getSizeInBits();
3392 if (DemandHighBits && OpSizeInBits > 16) {
3393 // If the left-shift isn't masked out then the only way this is a bswap is
3394 // if all bits beyond the low 8 are 0. In that case the entire pattern
3395 // reduces to a left shift anyway: leave it for other parts of the combiner.
3399 // However, if the right shift isn't masked out then it might be because
3400 // it's not needed. See if we can spot that too.
3401 if (!LookPassAnd1 &&
3402 !DAG.MaskedValueIsZero(
3403 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3407 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3408 if (OpSizeInBits > 16) {
3410 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3411 DAG.getConstant(OpSizeInBits - 16, DL,
3412 getShiftAmountTy(VT)));
3417 /// Return true if the specified node is an element that makes up a 32-bit
3418 /// packed halfword byteswap.
3419 /// ((x & 0x000000ff) << 8) |
3420 /// ((x & 0x0000ff00) >> 8) |
3421 /// ((x & 0x00ff0000) << 8) |
3422 /// ((x & 0xff000000) >> 8)
3423 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3424 if (!N.getNode()->hasOneUse())
3427 unsigned Opc = N.getOpcode();
3428 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3431 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3436 switch (N1C->getZExtValue()) {
3439 case 0xFF: Num = 0; break;
3440 case 0xFF00: Num = 1; break;
3441 case 0xFF0000: Num = 2; break;
3442 case 0xFF000000: Num = 3; break;
3445 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3446 SDValue N0 = N.getOperand(0);
3447 if (Opc == ISD::AND) {
3448 if (Num == 0 || Num == 2) {
3450 // (x >> 8) & 0xff0000
3451 if (N0.getOpcode() != ISD::SRL)
3453 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3454 if (!C || C->getZExtValue() != 8)
3457 // (x << 8) & 0xff00
3458 // (x << 8) & 0xff000000
3459 if (N0.getOpcode() != ISD::SHL)
3461 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3462 if (!C || C->getZExtValue() != 8)
3465 } else if (Opc == ISD::SHL) {
3467 // (x & 0xff0000) << 8
3468 if (Num != 0 && Num != 2)
3470 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3471 if (!C || C->getZExtValue() != 8)
3473 } else { // Opc == ISD::SRL
3474 // (x & 0xff00) >> 8
3475 // (x & 0xff000000) >> 8
3476 if (Num != 1 && Num != 3)
3478 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3479 if (!C || C->getZExtValue() != 8)
3486 Parts[Num] = N0.getOperand(0).getNode();
3490 /// Match a 32-bit packed halfword bswap. That is
3491 /// ((x & 0x000000ff) << 8) |
3492 /// ((x & 0x0000ff00) >> 8) |
3493 /// ((x & 0x00ff0000) << 8) |
3494 /// ((x & 0xff000000) >> 8)
3495 /// => (rotl (bswap x), 16)
3496 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3497 if (!LegalOperations)
3500 EVT VT = N->getValueType(0);
3503 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3507 // (or (or (and), (and)), (or (and), (and)))
3508 // (or (or (or (and), (and)), (and)), (and))
3509 if (N0.getOpcode() != ISD::OR)
3511 SDValue N00 = N0.getOperand(0);
3512 SDValue N01 = N0.getOperand(1);
3513 SDNode *Parts[4] = {};
3515 if (N1.getOpcode() == ISD::OR &&
3516 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3517 // (or (or (and), (and)), (or (and), (and)))
3518 SDValue N000 = N00.getOperand(0);
3519 if (!isBSwapHWordElement(N000, Parts))
3522 SDValue N001 = N00.getOperand(1);
3523 if (!isBSwapHWordElement(N001, Parts))
3525 SDValue N010 = N01.getOperand(0);
3526 if (!isBSwapHWordElement(N010, Parts))
3528 SDValue N011 = N01.getOperand(1);
3529 if (!isBSwapHWordElement(N011, Parts))
3532 // (or (or (or (and), (and)), (and)), (and))
3533 if (!isBSwapHWordElement(N1, Parts))
3535 if (!isBSwapHWordElement(N01, Parts))
3537 if (N00.getOpcode() != ISD::OR)
3539 SDValue N000 = N00.getOperand(0);
3540 if (!isBSwapHWordElement(N000, Parts))
3542 SDValue N001 = N00.getOperand(1);
3543 if (!isBSwapHWordElement(N001, Parts))
3547 // Make sure the parts are all coming from the same node.
3548 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3552 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3553 SDValue(Parts[0], 0));
3555 // Result of the bswap should be rotated by 16. If it's not legal, then
3556 // do (x << 16) | (x >> 16).
3557 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3558 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3559 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3560 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3561 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3562 return DAG.getNode(ISD::OR, DL, VT,
3563 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3564 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3567 /// This contains all DAGCombine rules which reduce two values combined by
3568 /// an Or operation to a single value \see visitANDLike().
3569 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3570 EVT VT = N1.getValueType();
3571 // fold (or x, undef) -> -1
3572 if (!LegalOperations &&
3573 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3574 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3575 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3576 SDLoc(LocReference), VT);
3578 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3579 SDValue LL, LR, RL, RR, CC0, CC1;
3580 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3581 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3582 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3584 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3585 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3586 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3587 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3588 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3589 LR.getValueType(), LL, RL);
3590 AddToWorklist(ORNode.getNode());
3591 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3593 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3594 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3595 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3596 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3597 LR.getValueType(), LL, RL);
3598 AddToWorklist(ANDNode.getNode());
3599 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3602 // canonicalize equivalent to ll == rl
3603 if (LL == RR && LR == RL) {
3604 Op1 = ISD::getSetCCSwappedOperands(Op1);
3607 if (LL == RL && LR == RR) {
3608 bool isInteger = LL.getValueType().isInteger();
3609 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3610 if (Result != ISD::SETCC_INVALID &&
3611 (!LegalOperations ||
3612 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3613 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3614 EVT CCVT = getSetCCResultType(LL.getValueType());
3615 if (N0.getValueType() == CCVT ||
3616 (!LegalOperations && N0.getValueType() == MVT::i1))
3617 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3623 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3624 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3625 // Don't increase # computations.
3626 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3627 // We can only do this xform if we know that bits from X that are set in C2
3628 // but not in C1 are already zero. Likewise for Y.
3629 if (const ConstantSDNode *N0O1C =
3630 getAsNonOpaqueConstant(N0.getOperand(1))) {
3631 if (const ConstantSDNode *N1O1C =
3632 getAsNonOpaqueConstant(N1.getOperand(1))) {
3633 // We can only do this xform if we know that bits from X that are set in
3634 // C2 but not in C1 are already zero. Likewise for Y.
3635 const APInt &LHSMask = N0O1C->getAPIntValue();
3636 const APInt &RHSMask = N1O1C->getAPIntValue();
3638 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3639 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3640 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3641 N0.getOperand(0), N1.getOperand(0));
3642 SDLoc DL(LocReference);
3643 return DAG.getNode(ISD::AND, DL, VT, X,
3644 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3650 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3651 if (N0.getOpcode() == ISD::AND &&
3652 N1.getOpcode() == ISD::AND &&
3653 N0.getOperand(0) == N1.getOperand(0) &&
3654 // Don't increase # computations.
3655 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3656 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3657 N0.getOperand(1), N1.getOperand(1));
3658 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3664 SDValue DAGCombiner::visitOR(SDNode *N) {
3665 SDValue N0 = N->getOperand(0);
3666 SDValue N1 = N->getOperand(1);
3667 EVT VT = N1.getValueType();
3670 if (VT.isVector()) {
3671 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3674 // fold (or x, 0) -> x, vector edition
3675 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3677 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3680 // fold (or x, -1) -> -1, vector edition
3681 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3682 // do not return N0, because undef node may exist in N0
3683 return DAG.getConstant(
3684 APInt::getAllOnesValue(
3685 N0.getValueType().getScalarType().getSizeInBits()),
3686 SDLoc(N), N0.getValueType());
3687 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3688 // do not return N1, because undef node may exist in N1
3689 return DAG.getConstant(
3690 APInt::getAllOnesValue(
3691 N1.getValueType().getScalarType().getSizeInBits()),
3692 SDLoc(N), N1.getValueType());
3694 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3695 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3696 // Do this only if the resulting shuffle is legal.
3697 if (isa<ShuffleVectorSDNode>(N0) &&
3698 isa<ShuffleVectorSDNode>(N1) &&
3699 // Avoid folding a node with illegal type.
3700 TLI.isTypeLegal(VT) &&
3701 N0->getOperand(1) == N1->getOperand(1) &&
3702 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3703 bool CanFold = true;
3704 unsigned NumElts = VT.getVectorNumElements();
3705 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3706 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3707 // We construct two shuffle masks:
3708 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3709 // and N1 as the second operand.
3710 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3711 // and N0 as the second operand.
3712 // We do this because OR is commutable and therefore there might be
3713 // two ways to fold this node into a shuffle.
3714 SmallVector<int,4> Mask1;
3715 SmallVector<int,4> Mask2;
3717 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3718 int M0 = SV0->getMaskElt(i);
3719 int M1 = SV1->getMaskElt(i);
3721 // Both shuffle indexes are undef. Propagate Undef.
3722 if (M0 < 0 && M1 < 0) {
3723 Mask1.push_back(M0);
3724 Mask2.push_back(M0);
3728 if (M0 < 0 || M1 < 0 ||
3729 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3730 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3735 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3736 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3740 // Fold this sequence only if the resulting shuffle is 'legal'.
3741 if (TLI.isShuffleMaskLegal(Mask1, VT))
3742 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3743 N1->getOperand(0), &Mask1[0]);
3744 if (TLI.isShuffleMaskLegal(Mask2, VT))
3745 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3746 N0->getOperand(0), &Mask2[0]);
3751 // fold (or c1, c2) -> c1|c2
3752 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3754 if (N0C && N1C && !N1C->isOpaque())
3755 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3756 // canonicalize constant to RHS
3757 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3758 !isConstantIntBuildVectorOrConstantInt(N1))
3759 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3760 // fold (or x, 0) -> x
3761 if (isNullConstant(N1))
3763 // fold (or x, -1) -> -1
3764 if (isAllOnesConstant(N1))
3766 // fold (or x, c) -> c iff (x & ~c) == 0
3767 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3770 if (SDValue Combined = visitORLike(N0, N1, N))
3773 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3774 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3776 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3780 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3782 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3783 // iff (c1 & c2) == 0.
3784 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3785 isa<ConstantSDNode>(N0.getOperand(1))) {
3786 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3787 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3788 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3791 ISD::AND, SDLoc(N), VT,
3792 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3796 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3797 if (N0.getOpcode() == N1.getOpcode())
3798 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3801 // See if this is some rotate idiom.
3802 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3803 return SDValue(Rot, 0);
3805 // Simplify the operands using demanded-bits information.
3806 if (!VT.isVector() &&
3807 SimplifyDemandedBits(SDValue(N, 0)))
3808 return SDValue(N, 0);
3813 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3814 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3815 if (Op.getOpcode() == ISD::AND) {
3816 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3817 Mask = Op.getOperand(1);
3818 Op = Op.getOperand(0);
3824 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3832 // Return true if we can prove that, whenever Neg and Pos are both in the
3833 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
3834 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3836 // (or (shift1 X, Neg), (shift2 X, Pos))
3838 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3839 // in direction shift1 by Neg. The range [0, EltSize) means that we only need
3840 // to consider shift amounts with defined behavior.
3841 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3842 // If EltSize is a power of 2 then:
3844 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3845 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3847 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3848 // for the stronger condition:
3850 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
3852 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3853 // we can just replace Neg with Neg' for the rest of the function.
3855 // In other cases we check for the even stronger condition:
3857 // Neg == EltSize - Pos [B]
3859 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3860 // behavior if Pos == 0 (and consequently Neg == EltSize).
3862 // We could actually use [A] whenever EltSize is a power of 2, but the
3863 // only extra cases that it would match are those uninteresting ones
3864 // where Neg and Pos are never in range at the same time. E.g. for
3865 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3866 // as well as (sub 32, Pos), but:
3868 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3870 // always invokes undefined behavior for 32-bit X.
3872 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3873 unsigned MaskLoBits = 0;
3874 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3875 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3876 if (NegC->getAPIntValue() == EltSize - 1) {
3877 Neg = Neg.getOperand(0);
3878 MaskLoBits = Log2_64(EltSize);
3883 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3884 if (Neg.getOpcode() != ISD::SUB)
3886 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3889 SDValue NegOp1 = Neg.getOperand(1);
3891 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3892 // Pos'. The truncation is redundant for the purpose of the equality.
3893 if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3894 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3895 if (PosC->getAPIntValue() == EltSize - 1)
3896 Pos = Pos.getOperand(0);
3898 // The condition we need is now:
3900 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3902 // If NegOp1 == Pos then we need:
3904 // EltSize & Mask == NegC & Mask
3906 // (because "x & Mask" is a truncation and distributes through subtraction).
3909 Width = NegC->getAPIntValue();
3911 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3912 // Then the condition we want to prove becomes:
3914 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3916 // which, again because "x & Mask" is a truncation, becomes:
3918 // NegC & Mask == (EltSize - PosC) & Mask
3919 // EltSize & Mask == (NegC + PosC) & Mask
3920 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3921 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3922 Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3928 // Now we just need to check that EltSize & Mask == Width & Mask.
3930 // EltSize & Mask is 0 since Mask is EltSize - 1.
3931 return Width.getLoBits(MaskLoBits) == 0;
3932 return Width == EltSize;
3935 // A subroutine of MatchRotate used once we have found an OR of two opposite
3936 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3937 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3938 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3939 // Neg with outer conversions stripped away.
3940 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3941 SDValue Neg, SDValue InnerPos,
3942 SDValue InnerNeg, unsigned PosOpcode,
3943 unsigned NegOpcode, SDLoc DL) {
3944 // fold (or (shl x, (*ext y)),
3945 // (srl x, (*ext (sub 32, y)))) ->
3946 // (rotl x, y) or (rotr x, (sub 32, y))
3948 // fold (or (shl x, (*ext (sub 32, y))),
3949 // (srl x, (*ext y))) ->
3950 // (rotr x, y) or (rotl x, (sub 32, y))
3951 EVT VT = Shifted.getValueType();
3952 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3953 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3954 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3955 HasPos ? Pos : Neg).getNode();
3961 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3962 // idioms for rotate, and if the target supports rotation instructions, generate
3964 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3965 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3966 EVT VT = LHS.getValueType();
3967 if (!TLI.isTypeLegal(VT)) return nullptr;
3969 // The target must have at least one rotate flavor.
3970 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3971 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3972 if (!HasROTL && !HasROTR) return nullptr;
3974 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3975 SDValue LHSShift; // The shift.
3976 SDValue LHSMask; // AND value if any.
3977 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3978 return nullptr; // Not part of a rotate.
3980 SDValue RHSShift; // The shift.
3981 SDValue RHSMask; // AND value if any.
3982 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3983 return nullptr; // Not part of a rotate.
3985 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3986 return nullptr; // Not shifting the same value.
3988 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3989 return nullptr; // Shifts must disagree.
3991 // Canonicalize shl to left side in a shl/srl pair.
3992 if (RHSShift.getOpcode() == ISD::SHL) {
3993 std::swap(LHS, RHS);
3994 std::swap(LHSShift, RHSShift);
3995 std::swap(LHSMask, RHSMask);
3998 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3999 SDValue LHSShiftArg = LHSShift.getOperand(0);
4000 SDValue LHSShiftAmt = LHSShift.getOperand(1);
4001 SDValue RHSShiftArg = RHSShift.getOperand(0);
4002 SDValue RHSShiftAmt = RHSShift.getOperand(1);
4004 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4005 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4006 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4007 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4008 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4009 if ((LShVal + RShVal) != EltSizeInBits)
4012 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4013 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4015 // If there is an AND of either shifted operand, apply it to the result.
4016 if (LHSMask.getNode() || RHSMask.getNode()) {
4017 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4018 SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4020 if (LHSMask.getNode()) {
4021 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4022 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4023 DAG.getNode(ISD::OR, DL, VT, LHSMask,
4024 DAG.getConstant(RHSBits, DL, VT)));
4026 if (RHSMask.getNode()) {
4027 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4028 Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4029 DAG.getNode(ISD::OR, DL, VT, RHSMask,
4030 DAG.getConstant(LHSBits, DL, VT)));
4033 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4036 return Rot.getNode();
4039 // If there is a mask here, and we have a variable shift, we can't be sure
4040 // that we're masking out the right stuff.
4041 if (LHSMask.getNode() || RHSMask.getNode())
4044 // If the shift amount is sign/zext/any-extended just peel it off.
4045 SDValue LExtOp0 = LHSShiftAmt;
4046 SDValue RExtOp0 = RHSShiftAmt;
4047 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4048 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4049 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4050 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4051 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4052 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4053 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4054 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4055 LExtOp0 = LHSShiftAmt.getOperand(0);
4056 RExtOp0 = RHSShiftAmt.getOperand(0);
4059 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4060 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4064 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4065 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4072 SDValue DAGCombiner::visitXOR(SDNode *N) {
4073 SDValue N0 = N->getOperand(0);
4074 SDValue N1 = N->getOperand(1);
4075 EVT VT = N0.getValueType();
4078 if (VT.isVector()) {
4079 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4082 // fold (xor x, 0) -> x, vector edition
4083 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4085 if (ISD::isBuildVectorAllZeros(N1.getNode()))
4089 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4090 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4091 return DAG.getConstant(0, SDLoc(N), VT);
4092 // fold (xor x, undef) -> undef
4093 if (N0.getOpcode() == ISD::UNDEF)
4095 if (N1.getOpcode() == ISD::UNDEF)
4097 // fold (xor c1, c2) -> c1^c2
4098 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4099 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4101 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4102 // canonicalize constant to RHS
4103 if (isConstantIntBuildVectorOrConstantInt(N0) &&
4104 !isConstantIntBuildVectorOrConstantInt(N1))
4105 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4106 // fold (xor x, 0) -> x
4107 if (isNullConstant(N1))
4110 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4113 // fold !(x cc y) -> (x !cc y)
4114 SDValue LHS, RHS, CC;
4115 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4116 bool isInt = LHS.getValueType().isInteger();
4117 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4120 if (!LegalOperations ||
4121 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4122 switch (N0.getOpcode()) {
4124 llvm_unreachable("Unhandled SetCC Equivalent!");
4126 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4127 case ISD::SELECT_CC:
4128 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4129 N0.getOperand(3), NotCC);
4134 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4135 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4136 N0.getNode()->hasOneUse() &&
4137 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4138 SDValue V = N0.getOperand(0);
4140 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4141 DAG.getConstant(1, DL, V.getValueType()));
4142 AddToWorklist(V.getNode());
4143 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4146 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4147 if (isOneConstant(N1) && VT == MVT::i1 &&
4148 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4149 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4150 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4151 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4152 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4153 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4154 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4155 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4158 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4159 if (isAllOnesConstant(N1) &&
4160 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4161 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4162 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4163 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4164 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4165 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4166 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4167 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4170 // fold (xor (and x, y), y) -> (and (not x), y)
4171 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4172 N0->getOperand(1) == N1) {
4173 SDValue X = N0->getOperand(0);
4174 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4175 AddToWorklist(NotX.getNode());
4176 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4178 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4179 if (N1C && N0.getOpcode() == ISD::XOR) {
4180 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4182 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4183 DAG.getConstant(N1C->getAPIntValue() ^
4184 N00C->getAPIntValue(), DL, VT));
4186 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4188 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4189 DAG.getConstant(N1C->getAPIntValue() ^
4190 N01C->getAPIntValue(), DL, VT));
4193 // fold (xor x, x) -> 0
4195 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4197 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4198 // Here is a concrete example of this equivalence:
4200 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4201 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4205 // i16 ~1 == 0b1111111111111110
4206 // i16 rol(~1, 14) == 0b1011111111111111
4208 // Some additional tips to help conceptualize this transform:
4209 // - Try to see the operation as placing a single zero in a value of all ones.
4210 // - There exists no value for x which would allow the result to contain zero.
4211 // - Values of x larger than the bitwidth are undefined and do not require a
4212 // consistent result.
4213 // - Pushing the zero left requires shifting one bits in from the right.
4214 // A rotate left of ~1 is a nice way of achieving the desired result.
4215 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4216 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4218 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4222 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4223 if (N0.getOpcode() == N1.getOpcode())
4224 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4227 // Simplify the expression using non-local knowledge.
4228 if (!VT.isVector() &&
4229 SimplifyDemandedBits(SDValue(N, 0)))
4230 return SDValue(N, 0);
4235 /// Handle transforms common to the three shifts, when the shift amount is a
4237 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4238 SDNode *LHS = N->getOperand(0).getNode();
4239 if (!LHS->hasOneUse()) return SDValue();
4241 // We want to pull some binops through shifts, so that we have (and (shift))
4242 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4243 // thing happens with address calculations, so it's important to canonicalize
4245 bool HighBitSet = false; // Can we transform this if the high bit is set?
4247 switch (LHS->getOpcode()) {
4248 default: return SDValue();
4251 HighBitSet = false; // We can only transform sra if the high bit is clear.
4254 HighBitSet = true; // We can only transform sra if the high bit is set.
4257 if (N->getOpcode() != ISD::SHL)
4258 return SDValue(); // only shl(add) not sr[al](add).
4259 HighBitSet = false; // We can only transform sra if the high bit is clear.
4263 // We require the RHS of the binop to be a constant and not opaque as well.
4264 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4265 if (!BinOpCst) return SDValue();
4267 // FIXME: disable this unless the input to the binop is a shift by a constant.
4268 // If it is not a shift, it pessimizes some common cases like:
4270 // void foo(int *X, int i) { X[i & 1235] = 1; }
4271 // int bar(int *X, int i) { return X[i & 255]; }
4272 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4273 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4274 BinOpLHSVal->getOpcode() != ISD::SRA &&
4275 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4276 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4279 EVT VT = N->getValueType(0);
4281 // If this is a signed shift right, and the high bit is modified by the
4282 // logical operation, do not perform the transformation. The highBitSet
4283 // boolean indicates the value of the high bit of the constant which would
4284 // cause it to be modified for this operation.
4285 if (N->getOpcode() == ISD::SRA) {
4286 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4287 if (BinOpRHSSignSet != HighBitSet)
4291 if (!TLI.isDesirableToCommuteWithShift(LHS))
4294 // Fold the constants, shifting the binop RHS by the shift amount.
4295 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4297 LHS->getOperand(1), N->getOperand(1));
4298 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4300 // Create the new shift.
4301 SDValue NewShift = DAG.getNode(N->getOpcode(),
4302 SDLoc(LHS->getOperand(0)),
4303 VT, LHS->getOperand(0), N->getOperand(1));
4305 // Create the new binop.
4306 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4309 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4310 assert(N->getOpcode() == ISD::TRUNCATE);
4311 assert(N->getOperand(0).getOpcode() == ISD::AND);
4313 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4314 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4315 SDValue N01 = N->getOperand(0).getOperand(1);
4317 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4318 if (!N01C->isOpaque()) {
4319 EVT TruncVT = N->getValueType(0);
4320 SDValue N00 = N->getOperand(0).getOperand(0);
4321 APInt TruncC = N01C->getAPIntValue();
4322 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4325 return DAG.getNode(ISD::AND, DL, TruncVT,
4326 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4327 DAG.getConstant(TruncC, DL, TruncVT));
4335 SDValue DAGCombiner::visitRotate(SDNode *N) {
4336 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4337 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4338 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4339 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4340 if (NewOp1.getNode())
4341 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4342 N->getOperand(0), NewOp1);
4347 SDValue DAGCombiner::visitSHL(SDNode *N) {
4348 SDValue N0 = N->getOperand(0);
4349 SDValue N1 = N->getOperand(1);
4350 EVT VT = N0.getValueType();
4351 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4355 if (VT.isVector()) {
4356 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4359 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4360 // If setcc produces all-one true value then:
4361 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4362 if (N1CV && N1CV->isConstant()) {
4363 if (N0.getOpcode() == ISD::AND) {
4364 SDValue N00 = N0->getOperand(0);
4365 SDValue N01 = N0->getOperand(1);
4366 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4368 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4369 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4370 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4371 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4373 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4376 N1C = isConstOrConstSplat(N1);
4381 // fold (shl c1, c2) -> c1<<c2
4382 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4383 if (N0C && N1C && !N1C->isOpaque())
4384 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4385 // fold (shl 0, x) -> 0
4386 if (isNullConstant(N0))
4388 // fold (shl x, c >= size(x)) -> undef
4389 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4390 return DAG.getUNDEF(VT);
4391 // fold (shl x, 0) -> x
4392 if (N1C && N1C->isNullValue())
4394 // fold (shl undef, x) -> 0
4395 if (N0.getOpcode() == ISD::UNDEF)
4396 return DAG.getConstant(0, SDLoc(N), VT);
4397 // if (shl x, c) is known to be zero, return 0
4398 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4399 APInt::getAllOnesValue(OpSizeInBits)))
4400 return DAG.getConstant(0, SDLoc(N), VT);
4401 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4402 if (N1.getOpcode() == ISD::TRUNCATE &&
4403 N1.getOperand(0).getOpcode() == ISD::AND) {
4404 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4405 if (NewOp1.getNode())
4406 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4409 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4410 return SDValue(N, 0);
4412 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4413 if (N1C && N0.getOpcode() == ISD::SHL) {
4414 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4415 uint64_t c1 = N0C1->getZExtValue();
4416 uint64_t c2 = N1C->getZExtValue();
4418 if (c1 + c2 >= OpSizeInBits)
4419 return DAG.getConstant(0, DL, VT);
4420 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4421 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4425 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4426 // For this to be valid, the second form must not preserve any of the bits
4427 // that are shifted out by the inner shift in the first form. This means
4428 // the outer shift size must be >= the number of bits added by the ext.
4429 // As a corollary, we don't care what kind of ext it is.
4430 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4431 N0.getOpcode() == ISD::ANY_EXTEND ||
4432 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4433 N0.getOperand(0).getOpcode() == ISD::SHL) {
4434 SDValue N0Op0 = N0.getOperand(0);
4435 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4436 uint64_t c1 = N0Op0C1->getZExtValue();
4437 uint64_t c2 = N1C->getZExtValue();
4438 EVT InnerShiftVT = N0Op0.getValueType();
4439 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4440 if (c2 >= OpSizeInBits - InnerShiftSize) {
4442 if (c1 + c2 >= OpSizeInBits)
4443 return DAG.getConstant(0, DL, VT);
4444 return DAG.getNode(ISD::SHL, DL, VT,
4445 DAG.getNode(N0.getOpcode(), DL, VT,
4446 N0Op0->getOperand(0)),
4447 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4452 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4453 // Only fold this if the inner zext has no other uses to avoid increasing
4454 // the total number of instructions.
4455 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4456 N0.getOperand(0).getOpcode() == ISD::SRL) {
4457 SDValue N0Op0 = N0.getOperand(0);
4458 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4459 uint64_t c1 = N0Op0C1->getZExtValue();
4460 if (c1 < VT.getScalarSizeInBits()) {
4461 uint64_t c2 = N1C->getZExtValue();
4463 SDValue NewOp0 = N0.getOperand(0);
4464 EVT CountVT = NewOp0.getOperand(1).getValueType();
4466 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4468 DAG.getConstant(c2, DL, CountVT));
4469 AddToWorklist(NewSHL.getNode());
4470 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4476 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4477 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4478 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4479 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4480 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4481 uint64_t C1 = N0C1->getZExtValue();
4482 uint64_t C2 = N1C->getZExtValue();
4485 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4486 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4487 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4488 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4492 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4493 // (and (srl x, (sub c1, c2), MASK)
4494 // Only fold this if the inner shift has no other uses -- if it does, folding
4495 // this will increase the total number of instructions.
4496 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4497 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4498 uint64_t c1 = N0C1->getZExtValue();
4499 if (c1 < OpSizeInBits) {
4500 uint64_t c2 = N1C->getZExtValue();
4501 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4504 Mask = Mask.shl(c2 - c1);
4506 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4507 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4509 Mask = Mask.lshr(c1 - c2);
4511 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4512 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4515 return DAG.getNode(ISD::AND, DL, VT, Shift,
4516 DAG.getConstant(Mask, DL, VT));
4520 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4521 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4522 unsigned BitSize = VT.getScalarSizeInBits();
4524 SDValue HiBitsMask =
4525 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4526 BitSize - N1C->getZExtValue()),
4528 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4532 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4533 // Variant of version done on multiply, except mul by a power of 2 is turned
4536 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4537 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4538 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4539 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4540 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4541 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4544 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4545 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4546 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4547 if (SDValue Folded =
4548 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4549 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4553 if (N1C && !N1C->isOpaque())
4554 if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4560 SDValue DAGCombiner::visitSRA(SDNode *N) {
4561 SDValue N0 = N->getOperand(0);
4562 SDValue N1 = N->getOperand(1);
4563 EVT VT = N0.getValueType();
4564 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4567 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4568 if (VT.isVector()) {
4569 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4572 N1C = isConstOrConstSplat(N1);
4575 // fold (sra c1, c2) -> (sra c1, c2)
4576 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4577 if (N0C && N1C && !N1C->isOpaque())
4578 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4579 // fold (sra 0, x) -> 0
4580 if (isNullConstant(N0))
4582 // fold (sra -1, x) -> -1
4583 if (isAllOnesConstant(N0))
4585 // fold (sra x, (setge c, size(x))) -> undef
4586 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4587 return DAG.getUNDEF(VT);
4588 // fold (sra x, 0) -> x
4589 if (N1C && N1C->isNullValue())
4591 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4593 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4594 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4595 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4597 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4598 ExtVT, VT.getVectorNumElements());
4599 if ((!LegalOperations ||
4600 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4601 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4602 N0.getOperand(0), DAG.getValueType(ExtVT));
4605 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4606 if (N1C && N0.getOpcode() == ISD::SRA) {
4607 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4608 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4609 if (Sum >= OpSizeInBits)
4610 Sum = OpSizeInBits - 1;
4612 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4613 DAG.getConstant(Sum, DL, N1.getValueType()));
4617 // fold (sra (shl X, m), (sub result_size, n))
4618 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4619 // result_size - n != m.
4620 // If truncate is free for the target sext(shl) is likely to result in better
4622 if (N0.getOpcode() == ISD::SHL && N1C) {
4623 // Get the two constanst of the shifts, CN0 = m, CN = n.
4624 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4626 LLVMContext &Ctx = *DAG.getContext();
4627 // Determine what the truncate's result bitsize and type would be.
4628 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4631 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4633 // Determine the residual right-shift amount.
4634 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4636 // If the shift is not a no-op (in which case this should be just a sign
4637 // extend already), the truncated to type is legal, sign_extend is legal
4638 // on that type, and the truncate to that type is both legal and free,
4639 // perform the transform.
4640 if ((ShiftAmt > 0) &&
4641 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4642 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4643 TLI.isTruncateFree(VT, TruncVT)) {
4646 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4647 getShiftAmountTy(N0.getOperand(0).getValueType()));
4648 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4649 N0.getOperand(0), Amt);
4650 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4652 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4653 N->getValueType(0), Trunc);
4658 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4659 if (N1.getOpcode() == ISD::TRUNCATE &&
4660 N1.getOperand(0).getOpcode() == ISD::AND) {
4661 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4662 if (NewOp1.getNode())
4663 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4666 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4667 // if c1 is equal to the number of bits the trunc removes
4668 if (N0.getOpcode() == ISD::TRUNCATE &&
4669 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4670 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4671 N0.getOperand(0).hasOneUse() &&
4672 N0.getOperand(0).getOperand(1).hasOneUse() &&
4674 SDValue N0Op0 = N0.getOperand(0);
4675 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4676 unsigned LargeShiftVal = LargeShift->getZExtValue();
4677 EVT LargeVT = N0Op0.getValueType();
4679 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4682 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4683 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4684 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4685 N0Op0.getOperand(0), Amt);
4686 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4691 // Simplify, based on bits shifted out of the LHS.
4692 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693 return SDValue(N, 0);
4696 // If the sign bit is known to be zero, switch this to a SRL.
4697 if (DAG.SignBitIsZero(N0))
4698 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4700 if (N1C && !N1C->isOpaque())
4701 if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4707 SDValue DAGCombiner::visitSRL(SDNode *N) {
4708 SDValue N0 = N->getOperand(0);
4709 SDValue N1 = N->getOperand(1);
4710 EVT VT = N0.getValueType();
4711 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4715 if (VT.isVector()) {
4716 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4719 N1C = isConstOrConstSplat(N1);
4722 // fold (srl c1, c2) -> c1 >>u c2
4723 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4724 if (N0C && N1C && !N1C->isOpaque())
4725 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4726 // fold (srl 0, x) -> 0
4727 if (isNullConstant(N0))
4729 // fold (srl x, c >= size(x)) -> undef
4730 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4731 return DAG.getUNDEF(VT);
4732 // fold (srl x, 0) -> x
4733 if (N1C && N1C->isNullValue())
4735 // if (srl x, c) is known to be zero, return 0
4736 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4737 APInt::getAllOnesValue(OpSizeInBits)))
4738 return DAG.getConstant(0, SDLoc(N), VT);
4740 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4741 if (N1C && N0.getOpcode() == ISD::SRL) {
4742 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4743 uint64_t c1 = N01C->getZExtValue();
4744 uint64_t c2 = N1C->getZExtValue();
4746 if (c1 + c2 >= OpSizeInBits)
4747 return DAG.getConstant(0, DL, VT);
4748 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4749 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4753 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4754 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4755 N0.getOperand(0).getOpcode() == ISD::SRL &&
4756 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4758 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4759 uint64_t c2 = N1C->getZExtValue();
4760 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4761 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4762 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4763 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4764 if (c1 + OpSizeInBits == InnerShiftSize) {
4766 if (c1 + c2 >= InnerShiftSize)
4767 return DAG.getConstant(0, DL, VT);
4768 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4769 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4770 N0.getOperand(0)->getOperand(0),
4771 DAG.getConstant(c1 + c2, DL,
4776 // fold (srl (shl x, c), c) -> (and x, cst2)
4777 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4778 unsigned BitSize = N0.getScalarValueSizeInBits();
4779 if (BitSize <= 64) {
4780 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4782 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4783 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4787 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4788 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4789 // Shifting in all undef bits?
4790 EVT SmallVT = N0.getOperand(0).getValueType();
4791 unsigned BitSize = SmallVT.getScalarSizeInBits();
4792 if (N1C->getZExtValue() >= BitSize)
4793 return DAG.getUNDEF(VT);
4795 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4796 uint64_t ShiftAmt = N1C->getZExtValue();
4798 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4800 DAG.getConstant(ShiftAmt, DL0,
4801 getShiftAmountTy(SmallVT)));
4802 AddToWorklist(SmallShift.getNode());
4803 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4805 return DAG.getNode(ISD::AND, DL, VT,
4806 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4807 DAG.getConstant(Mask, DL, VT));
4811 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4812 // bit, which is unmodified by sra.
4813 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4814 if (N0.getOpcode() == ISD::SRA)
4815 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4818 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4819 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4820 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4821 APInt KnownZero, KnownOne;
4822 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4824 // If any of the input bits are KnownOne, then the input couldn't be all
4825 // zeros, thus the result of the srl will always be zero.
4826 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4828 // If all of the bits input the to ctlz node are known to be zero, then
4829 // the result of the ctlz is "32" and the result of the shift is one.
4830 APInt UnknownBits = ~KnownZero;
4831 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4833 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4834 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4835 // Okay, we know that only that the single bit specified by UnknownBits
4836 // could be set on input to the CTLZ node. If this bit is set, the SRL
4837 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4838 // to an SRL/XOR pair, which is likely to simplify more.
4839 unsigned ShAmt = UnknownBits.countTrailingZeros();
4840 SDValue Op = N0.getOperand(0);
4844 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4845 DAG.getConstant(ShAmt, DL,
4846 getShiftAmountTy(Op.getValueType())));
4847 AddToWorklist(Op.getNode());
4851 return DAG.getNode(ISD::XOR, DL, VT,
4852 Op, DAG.getConstant(1, DL, VT));
4856 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4857 if (N1.getOpcode() == ISD::TRUNCATE &&
4858 N1.getOperand(0).getOpcode() == ISD::AND) {
4859 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4860 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4863 // fold operands of srl based on knowledge that the low bits are not
4865 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4866 return SDValue(N, 0);
4868 if (N1C && !N1C->isOpaque())
4869 if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4872 // Attempt to convert a srl of a load into a narrower zero-extending load.
4873 if (SDValue NarrowLoad = ReduceLoadWidth(N))
4876 // Here is a common situation. We want to optimize:
4879 // %b = and i32 %a, 2
4880 // %c = srl i32 %b, 1
4881 // brcond i32 %c ...
4887 // %c = setcc eq %b, 0
4890 // However when after the source operand of SRL is optimized into AND, the SRL
4891 // itself may not be optimized further. Look for it and add the BRCOND into
4893 if (N->hasOneUse()) {
4894 SDNode *Use = *N->use_begin();
4895 if (Use->getOpcode() == ISD::BRCOND)
4897 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4898 // Also look pass the truncate.
4899 Use = *Use->use_begin();
4900 if (Use->getOpcode() == ISD::BRCOND)
4908 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4909 SDValue N0 = N->getOperand(0);
4910 EVT VT = N->getValueType(0);
4912 // fold (bswap c1) -> c2
4913 if (isConstantIntBuildVectorOrConstantInt(N0))
4914 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4915 // fold (bswap (bswap x)) -> x
4916 if (N0.getOpcode() == ISD::BSWAP)
4917 return N0->getOperand(0);
4921 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4922 SDValue N0 = N->getOperand(0);
4923 EVT VT = N->getValueType(0);
4925 // fold (ctlz c1) -> c2
4926 if (isConstantIntBuildVectorOrConstantInt(N0))
4927 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4931 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4932 SDValue N0 = N->getOperand(0);
4933 EVT VT = N->getValueType(0);
4935 // fold (ctlz_zero_undef c1) -> c2
4936 if (isConstantIntBuildVectorOrConstantInt(N0))
4937 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4941 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4942 SDValue N0 = N->getOperand(0);
4943 EVT VT = N->getValueType(0);
4945 // fold (cttz c1) -> c2
4946 if (isConstantIntBuildVectorOrConstantInt(N0))
4947 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4951 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4952 SDValue N0 = N->getOperand(0);
4953 EVT VT = N->getValueType(0);
4955 // fold (cttz_zero_undef c1) -> c2
4956 if (isConstantIntBuildVectorOrConstantInt(N0))
4957 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4961 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4962 SDValue N0 = N->getOperand(0);
4963 EVT VT = N->getValueType(0);
4965 // fold (ctpop c1) -> c2
4966 if (isConstantIntBuildVectorOrConstantInt(N0))
4967 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4972 /// \brief Generate Min/Max node
4973 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4974 SDValue True, SDValue False,
4975 ISD::CondCode CC, const TargetLowering &TLI,
4976 SelectionDAG &DAG) {
4977 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4987 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4988 if (TLI.isOperationLegal(Opcode, VT))
4989 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4998 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4999 if (TLI.isOperationLegal(Opcode, VT))
5000 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5008 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5009 SDValue N0 = N->getOperand(0);
5010 SDValue N1 = N->getOperand(1);
5011 SDValue N2 = N->getOperand(2);
5012 EVT VT = N->getValueType(0);
5013 EVT VT0 = N0.getValueType();
5015 // fold (select C, X, X) -> X
5018 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5019 // fold (select true, X, Y) -> X
5020 // fold (select false, X, Y) -> Y
5021 return !N0C->isNullValue() ? N1 : N2;
5023 // fold (select C, 1, X) -> (or C, X)
5024 if (VT == MVT::i1 && isOneConstant(N1))
5025 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5026 // fold (select C, 0, 1) -> (xor C, 1)
5027 // We can't do this reliably if integer based booleans have different contents
5028 // to floating point based booleans. This is because we can't tell whether we
5029 // have an integer-based boolean or a floating-point-based boolean unless we
5030 // can find the SETCC that produced it and inspect its operands. This is
5031 // fairly easy if C is the SETCC node, but it can potentially be
5032 // undiscoverable (or not reasonably discoverable). For example, it could be
5033 // in another basic block or it could require searching a complicated
5035 if (VT.isInteger() &&
5036 (VT0 == MVT::i1 || (VT0.isInteger() &&
5037 TLI.getBooleanContents(false, false) ==
5038 TLI.getBooleanContents(false, true) &&
5039 TLI.getBooleanContents(false, false) ==
5040 TargetLowering::ZeroOrOneBooleanContent)) &&
5041 isNullConstant(N1) && isOneConstant(N2)) {
5045 return DAG.getNode(ISD::XOR, DL, VT0,
5046 N0, DAG.getConstant(1, DL, VT0));
5049 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5050 N0, DAG.getConstant(1, DL0, VT0));
5051 AddToWorklist(XORNode.getNode());
5053 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5054 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5056 // fold (select C, 0, X) -> (and (not C), X)
5057 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5058 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5059 AddToWorklist(NOTNode.getNode());
5060 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5062 // fold (select C, X, 1) -> (or (not C), X)
5063 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5064 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5065 AddToWorklist(NOTNode.getNode());
5066 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5068 // fold (select C, X, 0) -> (and C, X)
5069 if (VT == MVT::i1 && isNullConstant(N2))
5070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5071 // fold (select X, X, Y) -> (or X, Y)
5072 // fold (select X, 1, Y) -> (or X, Y)
5073 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5074 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5075 // fold (select X, Y, X) -> (and X, Y)
5076 // fold (select X, Y, 0) -> (and X, Y)
5077 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5078 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5080 // If we can fold this based on the true/false value, do so.
5081 if (SimplifySelectOps(N, N1, N2))
5082 return SDValue(N, 0); // Don't revisit N.
5084 if (VT0 == MVT::i1) {
5085 // The code in this block deals with the following 2 equivalences:
5086 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5087 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5088 // The target can specify its prefered form with the
5089 // shouldNormalizeToSelectSequence() callback. However we always transform
5090 // to the right anyway if we find the inner select exists in the DAG anyway
5091 // and we always transform to the left side if we know that we can further
5092 // optimize the combination of the conditions.
5093 bool normalizeToSequence
5094 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5095 // select (and Cond0, Cond1), X, Y
5096 // -> select Cond0, (select Cond1, X, Y), Y
5097 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5098 SDValue Cond0 = N0->getOperand(0);
5099 SDValue Cond1 = N0->getOperand(1);
5100 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5101 N1.getValueType(), Cond1, N1, N2);
5102 if (normalizeToSequence || !InnerSelect.use_empty())
5103 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5106 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5107 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5108 SDValue Cond0 = N0->getOperand(0);
5109 SDValue Cond1 = N0->getOperand(1);
5110 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5111 N1.getValueType(), Cond1, N1, N2);
5112 if (normalizeToSequence || !InnerSelect.use_empty())
5113 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5117 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5118 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5119 SDValue N1_0 = N1->getOperand(0);
5120 SDValue N1_1 = N1->getOperand(1);
5121 SDValue N1_2 = N1->getOperand(2);
5122 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5123 // Create the actual and node if we can generate good code for it.
5124 if (!normalizeToSequence) {
5125 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5127 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5130 // Otherwise see if we can optimize the "and" to a better pattern.
5131 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5132 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5136 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5137 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5138 SDValue N2_0 = N2->getOperand(0);
5139 SDValue N2_1 = N2->getOperand(1);
5140 SDValue N2_2 = N2->getOperand(2);
5141 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5142 // Create the actual or node if we can generate good code for it.
5143 if (!normalizeToSequence) {
5144 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5146 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5149 // Otherwise see if we can optimize to a better pattern.
5150 if (SDValue Combined = visitORLike(N0, N2_0, N))
5151 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5157 // fold selects based on a setcc into other things, such as min/max/abs
5158 if (N0.getOpcode() == ISD::SETCC) {
5159 // select x, y (fcmp lt x, y) -> fminnum x, y
5160 // select x, y (fcmp gt x, y) -> fmaxnum x, y
5162 // This is OK if we don't care about what happens if either operand is a
5166 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5167 // no signed zeros as well as no nans.
5168 const TargetOptions &Options = DAG.getTarget().Options;
5169 if (Options.UnsafeFPMath &&
5170 VT.isFloatingPoint() && N0.hasOneUse() &&
5171 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5172 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5174 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5175 N0.getOperand(1), N1, N2, CC,
5180 if ((!LegalOperations &&
5181 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5182 TLI.isOperationLegal(ISD::SELECT_CC, VT))
5183 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5184 N0.getOperand(0), N0.getOperand(1),
5185 N1, N2, N0.getOperand(2));
5186 return SimplifySelect(SDLoc(N), N0, N1, N2);
5193 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5196 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5198 // Split the inputs.
5199 SDValue Lo, Hi, LL, LH, RL, RH;
5200 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5201 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5203 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5204 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5206 return std::make_pair(Lo, Hi);
5209 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5210 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5211 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5213 SDValue Cond = N->getOperand(0);
5214 SDValue LHS = N->getOperand(1);
5215 SDValue RHS = N->getOperand(2);
5216 EVT VT = N->getValueType(0);
5217 int NumElems = VT.getVectorNumElements();
5218 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5219 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5220 Cond.getOpcode() == ISD::BUILD_VECTOR);
5222 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5223 // binary ones here.
5224 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5227 // We're sure we have an even number of elements due to the
5228 // concat_vectors we have as arguments to vselect.
5229 // Skip BV elements until we find one that's not an UNDEF
5230 // After we find an UNDEF element, keep looping until we get to half the
5231 // length of the BV and see if all the non-undef nodes are the same.
5232 ConstantSDNode *BottomHalf = nullptr;
5233 for (int i = 0; i < NumElems / 2; ++i) {
5234 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5237 if (BottomHalf == nullptr)
5238 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5239 else if (Cond->getOperand(i).getNode() != BottomHalf)
5243 // Do the same for the second half of the BuildVector
5244 ConstantSDNode *TopHalf = nullptr;
5245 for (int i = NumElems / 2; i < NumElems; ++i) {
5246 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5249 if (TopHalf == nullptr)
5250 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5251 else if (Cond->getOperand(i).getNode() != TopHalf)
5255 assert(TopHalf && BottomHalf &&
5256 "One half of the selector was all UNDEFs and the other was all the "
5257 "same value. This should have been addressed before this function.");
5259 ISD::CONCAT_VECTORS, dl, VT,
5260 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5261 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5264 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5266 if (Level >= AfterLegalizeTypes)
5269 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5270 SDValue Mask = MSC->getMask();
5271 SDValue Data = MSC->getValue();
5274 // If the MSCATTER data type requires splitting and the mask is provided by a
5275 // SETCC, then split both nodes and its operands before legalization. This
5276 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5277 // and enables future optimizations (e.g. min/max pattern matching on X86).
5278 if (Mask.getOpcode() != ISD::SETCC)
5281 // Check if any splitting is required.
5282 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5283 TargetLowering::TypeSplitVector)
5285 SDValue MaskLo, MaskHi, Lo, Hi;
5286 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5289 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5291 SDValue Chain = MSC->getChain();
5293 EVT MemoryVT = MSC->getMemoryVT();
5294 unsigned Alignment = MSC->getOriginalAlignment();
5296 EVT LoMemVT, HiMemVT;
5297 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5299 SDValue DataLo, DataHi;
5300 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5302 SDValue BasePtr = MSC->getBasePtr();
5303 SDValue IndexLo, IndexHi;
5304 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5306 MachineMemOperand *MMO = DAG.getMachineFunction().
5307 getMachineMemOperand(MSC->getPointerInfo(),
5308 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5309 Alignment, MSC->getAAInfo(), MSC->getRanges());
5311 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5312 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5315 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5316 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5319 AddToWorklist(Lo.getNode());
5320 AddToWorklist(Hi.getNode());
5322 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5325 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5327 if (Level >= AfterLegalizeTypes)
5330 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5331 SDValue Mask = MST->getMask();
5332 SDValue Data = MST->getValue();
5335 // If the MSTORE data type requires splitting and the mask is provided by a
5336 // SETCC, then split both nodes and its operands before legalization. This
5337 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5338 // and enables future optimizations (e.g. min/max pattern matching on X86).
5339 if (Mask.getOpcode() == ISD::SETCC) {
5341 // Check if any splitting is required.
5342 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5343 TargetLowering::TypeSplitVector)
5346 SDValue MaskLo, MaskHi, Lo, Hi;
5347 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5350 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5352 SDValue Chain = MST->getChain();
5353 SDValue Ptr = MST->getBasePtr();
5355 EVT MemoryVT = MST->getMemoryVT();
5356 unsigned Alignment = MST->getOriginalAlignment();
5358 // if Alignment is equal to the vector size,
5359 // take the half of it for the second part
5360 unsigned SecondHalfAlignment =
5361 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5362 Alignment/2 : Alignment;
5364 EVT LoMemVT, HiMemVT;
5365 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5367 SDValue DataLo, DataHi;
5368 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5370 MachineMemOperand *MMO = DAG.getMachineFunction().
5371 getMachineMemOperand(MST->getPointerInfo(),
5372 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5373 Alignment, MST->getAAInfo(), MST->getRanges());
5375 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5376 MST->isTruncatingStore());
5378 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5379 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5380 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5382 MMO = DAG.getMachineFunction().
5383 getMachineMemOperand(MST->getPointerInfo(),
5384 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5385 SecondHalfAlignment, MST->getAAInfo(),
5388 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5389 MST->isTruncatingStore());
5391 AddToWorklist(Lo.getNode());
5392 AddToWorklist(Hi.getNode());
5394 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5399 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5401 if (Level >= AfterLegalizeTypes)
5404 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5405 SDValue Mask = MGT->getMask();
5408 // If the MGATHER result requires splitting and the mask is provided by a
5409 // SETCC, then split both nodes and its operands before legalization. This
5410 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5411 // and enables future optimizations (e.g. min/max pattern matching on X86).
5413 if (Mask.getOpcode() != ISD::SETCC)
5416 EVT VT = N->getValueType(0);
5418 // Check if any splitting is required.
5419 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5420 TargetLowering::TypeSplitVector)
5423 SDValue MaskLo, MaskHi, Lo, Hi;
5424 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5426 SDValue Src0 = MGT->getValue();
5427 SDValue Src0Lo, Src0Hi;
5428 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5431 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5433 SDValue Chain = MGT->getChain();
5434 EVT MemoryVT = MGT->getMemoryVT();
5435 unsigned Alignment = MGT->getOriginalAlignment();
5437 EVT LoMemVT, HiMemVT;
5438 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5440 SDValue BasePtr = MGT->getBasePtr();
5441 SDValue Index = MGT->getIndex();
5442 SDValue IndexLo, IndexHi;
5443 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5445 MachineMemOperand *MMO = DAG.getMachineFunction().
5446 getMachineMemOperand(MGT->getPointerInfo(),
5447 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5448 Alignment, MGT->getAAInfo(), MGT->getRanges());
5450 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5451 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5454 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5455 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5458 AddToWorklist(Lo.getNode());
5459 AddToWorklist(Hi.getNode());
5461 // Build a factor node to remember that this load is independent of the
5463 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5466 // Legalized the chain result - switch anything that used the old chain to
5468 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5470 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5472 SDValue RetOps[] = { GatherRes, Chain };
5473 return DAG.getMergeValues(RetOps, DL);
5476 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5478 if (Level >= AfterLegalizeTypes)
5481 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5482 SDValue Mask = MLD->getMask();
5485 // If the MLOAD result requires splitting and the mask is provided by a
5486 // SETCC, then split both nodes and its operands before legalization. This
5487 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5488 // and enables future optimizations (e.g. min/max pattern matching on X86).
5490 if (Mask.getOpcode() == ISD::SETCC) {
5491 EVT VT = N->getValueType(0);
5493 // Check if any splitting is required.
5494 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5495 TargetLowering::TypeSplitVector)
5498 SDValue MaskLo, MaskHi, Lo, Hi;
5499 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5501 SDValue Src0 = MLD->getSrc0();
5502 SDValue Src0Lo, Src0Hi;
5503 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5506 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5508 SDValue Chain = MLD->getChain();
5509 SDValue Ptr = MLD->getBasePtr();
5510 EVT MemoryVT = MLD->getMemoryVT();
5511 unsigned Alignment = MLD->getOriginalAlignment();
5513 // if Alignment is equal to the vector size,
5514 // take the half of it for the second part
5515 unsigned SecondHalfAlignment =
5516 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5517 Alignment/2 : Alignment;
5519 EVT LoMemVT, HiMemVT;
5520 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5522 MachineMemOperand *MMO = DAG.getMachineFunction().
5523 getMachineMemOperand(MLD->getPointerInfo(),
5524 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5525 Alignment, MLD->getAAInfo(), MLD->getRanges());
5527 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5530 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5531 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5532 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5534 MMO = DAG.getMachineFunction().
5535 getMachineMemOperand(MLD->getPointerInfo(),
5536 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5537 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5539 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5542 AddToWorklist(Lo.getNode());
5543 AddToWorklist(Hi.getNode());
5545 // Build a factor node to remember that this load is independent of the
5547 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5550 // Legalized the chain result - switch anything that used the old chain to
5552 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5554 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5556 SDValue RetOps[] = { LoadRes, Chain };
5557 return DAG.getMergeValues(RetOps, DL);
5562 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5563 SDValue N0 = N->getOperand(0);
5564 SDValue N1 = N->getOperand(1);
5565 SDValue N2 = N->getOperand(2);
5568 // Canonicalize integer abs.
5569 // vselect (setg[te] X, 0), X, -X ->
5570 // vselect (setgt X, -1), X, -X ->
5571 // vselect (setl[te] X, 0), -X, X ->
5572 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5573 if (N0.getOpcode() == ISD::SETCC) {
5574 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5575 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5577 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5579 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5580 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5581 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5582 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5583 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5584 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5585 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5588 EVT VT = LHS.getValueType();
5589 SDValue Shift = DAG.getNode(
5590 ISD::SRA, DL, VT, LHS,
5591 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5592 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5593 AddToWorklist(Shift.getNode());
5594 AddToWorklist(Add.getNode());
5595 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5599 if (SimplifySelectOps(N, N1, N2))
5600 return SDValue(N, 0); // Don't revisit N.
5602 // If the VSELECT result requires splitting and the mask is provided by a
5603 // SETCC, then split both nodes and its operands before legalization. This
5604 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5605 // and enables future optimizations (e.g. min/max pattern matching on X86).
5606 if (N0.getOpcode() == ISD::SETCC) {
5607 EVT VT = N->getValueType(0);
5609 // Check if any splitting is required.
5610 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5611 TargetLowering::TypeSplitVector)
5614 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5615 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5616 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5617 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5619 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5620 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5622 // Add the new VSELECT nodes to the work list in case they need to be split
5624 AddToWorklist(Lo.getNode());
5625 AddToWorklist(Hi.getNode());
5627 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5630 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5631 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5633 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5634 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5637 // The ConvertSelectToConcatVector function is assuming both the above
5638 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5640 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5641 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5642 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5643 if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5650 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5651 SDValue N0 = N->getOperand(0);
5652 SDValue N1 = N->getOperand(1);
5653 SDValue N2 = N->getOperand(2);
5654 SDValue N3 = N->getOperand(3);
5655 SDValue N4 = N->getOperand(4);
5656 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5658 // fold select_cc lhs, rhs, x, x, cc -> x
5662 // Determine if the condition we're dealing with is constant
5663 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5664 N0, N1, CC, SDLoc(N), false);
5665 if (SCC.getNode()) {
5666 AddToWorklist(SCC.getNode());
5668 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5669 if (!SCCC->isNullValue())
5670 return N2; // cond always true -> true val
5672 return N3; // cond always false -> false val
5673 } else if (SCC->getOpcode() == ISD::UNDEF) {
5674 // When the condition is UNDEF, just return the first operand. This is
5675 // coherent the DAG creation, no setcc node is created in this case
5677 } else if (SCC.getOpcode() == ISD::SETCC) {
5678 // Fold to a simpler select_cc
5679 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5680 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5685 // If we can fold this based on the true/false value, do so.
5686 if (SimplifySelectOps(N, N2, N3))
5687 return SDValue(N, 0); // Don't revisit N.
5689 // fold select_cc into other things, such as min/max/abs
5690 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5693 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5694 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5695 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5699 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5700 /// a build_vector of constants.
5701 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5702 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5703 /// Vector extends are not folded if operations are legal; this is to
5704 /// avoid introducing illegal build_vector dag nodes.
5705 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5706 SelectionDAG &DAG, bool LegalTypes,
5707 bool LegalOperations) {
5708 unsigned Opcode = N->getOpcode();
5709 SDValue N0 = N->getOperand(0);
5710 EVT VT = N->getValueType(0);
5712 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5713 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5714 && "Expected EXTEND dag node in input!");
5716 // fold (sext c1) -> c1
5717 // fold (zext c1) -> c1
5718 // fold (aext c1) -> c1
5719 if (isa<ConstantSDNode>(N0))
5720 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5722 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5723 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5724 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5725 EVT SVT = VT.getScalarType();
5726 if (!(VT.isVector() &&
5727 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5728 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5731 // We can fold this node into a build_vector.
5732 unsigned VTBits = SVT.getSizeInBits();
5733 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5734 SmallVector<SDValue, 8> Elts;
5735 unsigned NumElts = VT.getVectorNumElements();
5738 for (unsigned i=0; i != NumElts; ++i) {
5739 SDValue Op = N0->getOperand(i);
5740 if (Op->getOpcode() == ISD::UNDEF) {
5741 Elts.push_back(DAG.getUNDEF(SVT));
5746 // Get the constant value and if needed trunc it to the size of the type.
5747 // Nodes like build_vector might have constants wider than the scalar type.
5748 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5749 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5750 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5752 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5755 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5758 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5759 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5760 // transformation. Returns true if extension are possible and the above
5761 // mentioned transformation is profitable.
5762 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5764 SmallVectorImpl<SDNode *> &ExtendNodes,
5765 const TargetLowering &TLI) {
5766 bool HasCopyToRegUses = false;
5767 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5768 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5769 UE = N0.getNode()->use_end();
5774 if (UI.getUse().getResNo() != N0.getResNo())
5776 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5777 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5778 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5779 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5780 // Sign bits will be lost after a zext.
5783 for (unsigned i = 0; i != 2; ++i) {
5784 SDValue UseOp = User->getOperand(i);
5787 if (!isa<ConstantSDNode>(UseOp))
5792 ExtendNodes.push_back(User);
5795 // If truncates aren't free and there are users we can't
5796 // extend, it isn't worthwhile.
5799 // Remember if this value is live-out.
5800 if (User->getOpcode() == ISD::CopyToReg)
5801 HasCopyToRegUses = true;
5804 if (HasCopyToRegUses) {
5805 bool BothLiveOut = false;
5806 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5808 SDUse &Use = UI.getUse();
5809 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5815 // Both unextended and extended values are live out. There had better be
5816 // a good reason for the transformation.
5817 return ExtendNodes.size();
5822 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5823 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5824 ISD::NodeType ExtType) {
5825 // Extend SetCC uses if necessary.
5826 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5827 SDNode *SetCC = SetCCs[i];
5828 SmallVector<SDValue, 4> Ops;
5830 for (unsigned j = 0; j != 2; ++j) {
5831 SDValue SOp = SetCC->getOperand(j);
5833 Ops.push_back(ExtLoad);
5835 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5838 Ops.push_back(SetCC->getOperand(2));
5839 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5843 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5844 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5845 SDValue N0 = N->getOperand(0);
5846 EVT DstVT = N->getValueType(0);
5847 EVT SrcVT = N0.getValueType();
5849 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5850 N->getOpcode() == ISD::ZERO_EXTEND) &&
5851 "Unexpected node type (not an extend)!");
5853 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5854 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5855 // (v8i32 (sext (v8i16 (load x))))
5857 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5858 // (v4i32 (sextload (x + 16)))))
5859 // Where uses of the original load, i.e.:
5861 // are replaced with:
5863 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5864 // (v4i32 (sextload (x + 16)))))))
5866 // This combine is only applicable to illegal, but splittable, vectors.
5867 // All legal types, and illegal non-vector types, are handled elsewhere.
5868 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5870 if (N0->getOpcode() != ISD::LOAD)
5873 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5875 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5876 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5877 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5880 SmallVector<SDNode *, 4> SetCCs;
5881 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5884 ISD::LoadExtType ExtType =
5885 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5887 // Try to split the vector types to get down to legal types.
5888 EVT SplitSrcVT = SrcVT;
5889 EVT SplitDstVT = DstVT;
5890 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5891 SplitSrcVT.getVectorNumElements() > 1) {
5892 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5893 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5896 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5900 const unsigned NumSplits =
5901 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5902 const unsigned Stride = SplitSrcVT.getStoreSize();
5903 SmallVector<SDValue, 4> Loads;
5904 SmallVector<SDValue, 4> Chains;
5906 SDValue BasePtr = LN0->getBasePtr();
5907 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5908 const unsigned Offset = Idx * Stride;
5909 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5911 SDValue SplitLoad = DAG.getExtLoad(
5912 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5913 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5914 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5915 Align, LN0->getAAInfo());
5917 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5918 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5920 Loads.push_back(SplitLoad.getValue(0));
5921 Chains.push_back(SplitLoad.getValue(1));
5924 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5925 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5927 CombineTo(N, NewValue);
5929 // Replace uses of the original load (before extension)
5930 // with a truncate of the concatenated sextloaded vectors.
5932 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5933 CombineTo(N0.getNode(), Trunc, NewChain);
5934 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5935 (ISD::NodeType)N->getOpcode());
5936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5939 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5940 SDValue N0 = N->getOperand(0);
5941 EVT VT = N->getValueType(0);
5943 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5945 return SDValue(Res, 0);
5947 // fold (sext (sext x)) -> (sext x)
5948 // fold (sext (aext x)) -> (sext x)
5949 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5950 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5953 if (N0.getOpcode() == ISD::TRUNCATE) {
5954 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5955 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5956 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5957 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5958 if (NarrowLoad.getNode() != N0.getNode()) {
5959 CombineTo(N0.getNode(), NarrowLoad);
5960 // CombineTo deleted the truncate, if needed, but not what's under it.
5963 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5966 // See if the value being truncated is already sign extended. If so, just
5967 // eliminate the trunc/sext pair.
5968 SDValue Op = N0.getOperand(0);
5969 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5970 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5971 unsigned DestBits = VT.getScalarType().getSizeInBits();
5972 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5974 if (OpBits == DestBits) {
5975 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5976 // bits, it is already ready.
5977 if (NumSignBits > DestBits-MidBits)
5979 } else if (OpBits < DestBits) {
5980 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5981 // bits, just sext from i32.
5982 if (NumSignBits > OpBits-MidBits)
5983 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5985 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5986 // bits, just truncate to i32.
5987 if (NumSignBits > OpBits-MidBits)
5988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5991 // fold (sext (truncate x)) -> (sextinreg x).
5992 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5993 N0.getValueType())) {
5994 if (OpBits < DestBits)
5995 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5996 else if (OpBits > DestBits)
5997 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5998 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5999 DAG.getValueType(N0.getValueType()));
6003 // fold (sext (load x)) -> (sext (truncate (sextload x)))
6004 // Only generate vector extloads when 1) they're legal, and 2) they are
6005 // deemed desirable by the target.
6006 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6007 ((!LegalOperations && !VT.isVector() &&
6008 !cast<LoadSDNode>(N0)->isVolatile()) ||
6009 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6010 bool DoXform = true;
6011 SmallVector<SDNode*, 4> SetCCs;
6012 if (!N0.hasOneUse())
6013 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6015 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6017 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6018 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6020 LN0->getBasePtr(), N0.getValueType(),
6021 LN0->getMemOperand());
6022 CombineTo(N, ExtLoad);
6023 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6024 N0.getValueType(), ExtLoad);
6025 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6026 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6028 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6032 // fold (sext (load x)) to multiple smaller sextloads.
6033 // Only on illegal but splittable vectors.
6034 if (SDValue ExtLoad = CombineExtLoad(N))
6037 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6038 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6039 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6040 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6041 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6042 EVT MemVT = LN0->getMemoryVT();
6043 if ((!LegalOperations && !LN0->isVolatile()) ||
6044 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6045 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6047 LN0->getBasePtr(), MemVT,
6048 LN0->getMemOperand());
6049 CombineTo(N, ExtLoad);
6050 CombineTo(N0.getNode(),
6051 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6052 N0.getValueType(), ExtLoad),
6053 ExtLoad.getValue(1));
6054 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6058 // fold (sext (and/or/xor (load x), cst)) ->
6059 // (and/or/xor (sextload x), (sext cst))
6060 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6061 N0.getOpcode() == ISD::XOR) &&
6062 isa<LoadSDNode>(N0.getOperand(0)) &&
6063 N0.getOperand(1).getOpcode() == ISD::Constant &&
6064 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6065 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6066 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6067 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6068 bool DoXform = true;
6069 SmallVector<SDNode*, 4> SetCCs;
6070 if (!N0.hasOneUse())
6071 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6074 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6075 LN0->getChain(), LN0->getBasePtr(),
6077 LN0->getMemOperand());
6078 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6079 Mask = Mask.sext(VT.getSizeInBits());
6081 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6082 ExtLoad, DAG.getConstant(Mask, DL, VT));
6083 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6084 SDLoc(N0.getOperand(0)),
6085 N0.getOperand(0).getValueType(), ExtLoad);
6087 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6088 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6090 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6095 if (N0.getOpcode() == ISD::SETCC) {
6096 EVT N0VT = N0.getOperand(0).getValueType();
6097 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6098 // Only do this before legalize for now.
6099 if (VT.isVector() && !LegalOperations &&
6100 TLI.getBooleanContents(N0VT) ==
6101 TargetLowering::ZeroOrNegativeOneBooleanContent) {
6102 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6103 // of the same size as the compared operands. Only optimize sext(setcc())
6104 // if this is the case.
6105 EVT SVT = getSetCCResultType(N0VT);
6107 // We know that the # elements of the results is the same as the
6108 // # elements of the compare (and the # elements of the compare result
6109 // for that matter). Check to see that they are the same size. If so,
6110 // we know that the element size of the sext'd result matches the
6111 // element size of the compare operands.
6112 if (VT.getSizeInBits() == SVT.getSizeInBits())
6113 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6115 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6117 // If the desired elements are smaller or larger than the source
6118 // elements we can use a matching integer vector type and then
6119 // truncate/sign extend
6120 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6121 if (SVT == MatchingVectorType) {
6122 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6123 N0.getOperand(0), N0.getOperand(1),
6124 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6125 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6129 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6130 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6133 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6135 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6136 NegOne, DAG.getConstant(0, DL, VT),
6137 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6138 if (SCC.getNode()) return SCC;
6140 if (!VT.isVector()) {
6141 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6142 if (!LegalOperations ||
6143 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6145 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6146 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6147 N0.getOperand(0), N0.getOperand(1), CC);
6148 return DAG.getSelect(DL, VT, SetCC,
6149 NegOne, DAG.getConstant(0, DL, VT));
6154 // fold (sext x) -> (zext x) if the sign bit is known zero.
6155 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6156 DAG.SignBitIsZero(N0))
6157 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6162 // isTruncateOf - If N is a truncate of some other value, return true, record
6163 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6164 // This function computes KnownZero to avoid a duplicated call to
6165 // computeKnownBits in the caller.
6166 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6169 if (N->getOpcode() == ISD::TRUNCATE) {
6170 Op = N->getOperand(0);
6171 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6175 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6176 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6179 SDValue Op0 = N->getOperand(0);
6180 SDValue Op1 = N->getOperand(1);
6181 assert(Op0.getValueType() == Op1.getValueType());
6183 if (isNullConstant(Op0))
6185 else if (isNullConstant(Op1))
6190 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6192 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6198 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6199 SDValue N0 = N->getOperand(0);
6200 EVT VT = N->getValueType(0);
6202 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6204 return SDValue(Res, 0);
6206 // fold (zext (zext x)) -> (zext x)
6207 // fold (zext (aext x)) -> (zext x)
6208 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6209 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6212 // fold (zext (truncate x)) -> (zext x) or
6213 // (zext (truncate x)) -> (truncate x)
6214 // This is valid when the truncated bits of x are already zero.
6215 // FIXME: We should extend this to work for vectors too.
6218 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6219 APInt TruncatedBits =
6220 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6221 APInt(Op.getValueSizeInBits(), 0) :
6222 APInt::getBitsSet(Op.getValueSizeInBits(),
6223 N0.getValueSizeInBits(),
6224 std::min(Op.getValueSizeInBits(),
6225 VT.getSizeInBits()));
6226 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6227 if (VT.bitsGT(Op.getValueType()))
6228 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6229 if (VT.bitsLT(Op.getValueType()))
6230 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6236 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6237 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6238 if (N0.getOpcode() == ISD::TRUNCATE) {
6239 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6240 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6241 if (NarrowLoad.getNode() != N0.getNode()) {
6242 CombineTo(N0.getNode(), NarrowLoad);
6243 // CombineTo deleted the truncate, if needed, but not what's under it.
6246 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6250 // fold (zext (truncate x)) -> (and x, mask)
6251 if (N0.getOpcode() == ISD::TRUNCATE) {
6252 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6253 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6254 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6255 SDNode *oye = N0.getNode()->getOperand(0).getNode();
6256 if (NarrowLoad.getNode() != N0.getNode()) {
6257 CombineTo(N0.getNode(), NarrowLoad);
6258 // CombineTo deleted the truncate, if needed, but not what's under it.
6261 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6264 EVT SrcVT = N0.getOperand(0).getValueType();
6265 EVT MinVT = N0.getValueType();
6267 // Try to mask before the extension to avoid having to generate a larger mask,
6268 // possibly over several sub-vectors.
6269 if (SrcVT.bitsLT(VT)) {
6270 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6271 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6272 SDValue Op = N0.getOperand(0);
6273 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6274 AddToWorklist(Op.getNode());
6275 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6279 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6280 SDValue Op = N0.getOperand(0);
6281 if (SrcVT.bitsLT(VT)) {
6282 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6283 AddToWorklist(Op.getNode());
6284 } else if (SrcVT.bitsGT(VT)) {
6285 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6286 AddToWorklist(Op.getNode());
6288 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6292 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6293 // if either of the casts is not free.
6294 if (N0.getOpcode() == ISD::AND &&
6295 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6296 N0.getOperand(1).getOpcode() == ISD::Constant &&
6297 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6298 N0.getValueType()) ||
6299 !TLI.isZExtFree(N0.getValueType(), VT))) {
6300 SDValue X = N0.getOperand(0).getOperand(0);
6301 if (X.getValueType().bitsLT(VT)) {
6302 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6303 } else if (X.getValueType().bitsGT(VT)) {
6304 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6306 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6307 Mask = Mask.zext(VT.getSizeInBits());
6309 return DAG.getNode(ISD::AND, DL, VT,
6310 X, DAG.getConstant(Mask, DL, VT));
6313 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6314 // Only generate vector extloads when 1) they're legal, and 2) they are
6315 // deemed desirable by the target.
6316 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6317 ((!LegalOperations && !VT.isVector() &&
6318 !cast<LoadSDNode>(N0)->isVolatile()) ||
6319 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6320 bool DoXform = true;
6321 SmallVector<SDNode*, 4> SetCCs;
6322 if (!N0.hasOneUse())
6323 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6325 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6327 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6328 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6330 LN0->getBasePtr(), N0.getValueType(),
6331 LN0->getMemOperand());
6332 CombineTo(N, ExtLoad);
6333 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6334 N0.getValueType(), ExtLoad);
6335 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6337 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6339 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6343 // fold (zext (load x)) to multiple smaller zextloads.
6344 // Only on illegal but splittable vectors.
6345 if (SDValue ExtLoad = CombineExtLoad(N))
6348 // fold (zext (and/or/xor (load x), cst)) ->
6349 // (and/or/xor (zextload x), (zext cst))
6350 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6351 N0.getOpcode() == ISD::XOR) &&
6352 isa<LoadSDNode>(N0.getOperand(0)) &&
6353 N0.getOperand(1).getOpcode() == ISD::Constant &&
6354 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6355 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6356 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6357 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6358 bool DoXform = true;
6359 SmallVector<SDNode*, 4> SetCCs;
6360 if (!N0.hasOneUse())
6361 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6364 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6365 LN0->getChain(), LN0->getBasePtr(),
6367 LN0->getMemOperand());
6368 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6369 Mask = Mask.zext(VT.getSizeInBits());
6371 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6372 ExtLoad, DAG.getConstant(Mask, DL, VT));
6373 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6374 SDLoc(N0.getOperand(0)),
6375 N0.getOperand(0).getValueType(), ExtLoad);
6377 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6378 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6380 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6385 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6386 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6387 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6388 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6389 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6390 EVT MemVT = LN0->getMemoryVT();
6391 if ((!LegalOperations && !LN0->isVolatile()) ||
6392 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6393 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6395 LN0->getBasePtr(), MemVT,
6396 LN0->getMemOperand());
6397 CombineTo(N, ExtLoad);
6398 CombineTo(N0.getNode(),
6399 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6401 ExtLoad.getValue(1));
6402 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6406 if (N0.getOpcode() == ISD::SETCC) {
6407 if (!LegalOperations && VT.isVector() &&
6408 N0.getValueType().getVectorElementType() == MVT::i1) {
6409 EVT N0VT = N0.getOperand(0).getValueType();
6410 if (getSetCCResultType(N0VT) == N0.getValueType())
6413 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6414 // Only do this before legalize for now.
6415 EVT EltVT = VT.getVectorElementType();
6417 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6418 DAG.getConstant(1, DL, EltVT));
6419 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6420 // We know that the # elements of the results is the same as the
6421 // # elements of the compare (and the # elements of the compare result
6422 // for that matter). Check to see that they are the same size. If so,
6423 // we know that the element size of the sext'd result matches the
6424 // element size of the compare operands.
6425 return DAG.getNode(ISD::AND, DL, VT,
6426 DAG.getSetCC(DL, VT, N0.getOperand(0),
6428 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6429 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6432 // If the desired elements are smaller or larger than the source
6433 // elements we can use a matching integer vector type and then
6434 // truncate/sign extend
6435 EVT MatchingElementType =
6436 EVT::getIntegerVT(*DAG.getContext(),
6437 N0VT.getScalarType().getSizeInBits());
6438 EVT MatchingVectorType =
6439 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6440 N0VT.getVectorNumElements());
6442 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6444 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6445 return DAG.getNode(ISD::AND, DL, VT,
6446 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6447 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6450 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6453 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6454 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6455 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6456 if (SCC.getNode()) return SCC;
6459 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6460 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6461 isa<ConstantSDNode>(N0.getOperand(1)) &&
6462 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6464 SDValue ShAmt = N0.getOperand(1);
6465 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6466 if (N0.getOpcode() == ISD::SHL) {
6467 SDValue InnerZExt = N0.getOperand(0);
6468 // If the original shl may be shifting out bits, do not perform this
6470 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6471 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6472 if (ShAmtVal > KnownZeroBits)
6478 // Ensure that the shift amount is wide enough for the shifted value.
6479 if (VT.getSizeInBits() >= 256)
6480 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6482 return DAG.getNode(N0.getOpcode(), DL, VT,
6483 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6490 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6491 SDValue N0 = N->getOperand(0);
6492 EVT VT = N->getValueType(0);
6494 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6496 return SDValue(Res, 0);
6498 // fold (aext (aext x)) -> (aext x)
6499 // fold (aext (zext x)) -> (zext x)
6500 // fold (aext (sext x)) -> (sext x)
6501 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6502 N0.getOpcode() == ISD::ZERO_EXTEND ||
6503 N0.getOpcode() == ISD::SIGN_EXTEND)
6504 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6506 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6507 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6508 if (N0.getOpcode() == ISD::TRUNCATE) {
6509 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6510 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6511 if (NarrowLoad.getNode() != N0.getNode()) {
6512 CombineTo(N0.getNode(), NarrowLoad);
6513 // CombineTo deleted the truncate, if needed, but not what's under it.
6516 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6520 // fold (aext (truncate x))
6521 if (N0.getOpcode() == ISD::TRUNCATE) {
6522 SDValue TruncOp = N0.getOperand(0);
6523 if (TruncOp.getValueType() == VT)
6524 return TruncOp; // x iff x size == zext size.
6525 if (TruncOp.getValueType().bitsGT(VT))
6526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6527 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6530 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6531 // if the trunc is not free.
6532 if (N0.getOpcode() == ISD::AND &&
6533 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6534 N0.getOperand(1).getOpcode() == ISD::Constant &&
6535 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6536 N0.getValueType())) {
6537 SDValue X = N0.getOperand(0).getOperand(0);
6538 if (X.getValueType().bitsLT(VT)) {
6539 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6540 } else if (X.getValueType().bitsGT(VT)) {
6541 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6543 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6544 Mask = Mask.zext(VT.getSizeInBits());
6546 return DAG.getNode(ISD::AND, DL, VT,
6547 X, DAG.getConstant(Mask, DL, VT));
6550 // fold (aext (load x)) -> (aext (truncate (extload x)))
6551 // None of the supported targets knows how to perform load and any_ext
6552 // on vectors in one instruction. We only perform this transformation on
6554 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6555 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6556 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6557 bool DoXform = true;
6558 SmallVector<SDNode*, 4> SetCCs;
6559 if (!N0.hasOneUse())
6560 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6562 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6563 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6565 LN0->getBasePtr(), N0.getValueType(),
6566 LN0->getMemOperand());
6567 CombineTo(N, ExtLoad);
6568 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6569 N0.getValueType(), ExtLoad);
6570 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6571 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6573 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6577 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6578 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6579 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6580 if (N0.getOpcode() == ISD::LOAD &&
6581 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6583 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6584 ISD::LoadExtType ExtType = LN0->getExtensionType();
6585 EVT MemVT = LN0->getMemoryVT();
6586 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6587 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6588 VT, LN0->getChain(), LN0->getBasePtr(),
6589 MemVT, LN0->getMemOperand());
6590 CombineTo(N, ExtLoad);
6591 CombineTo(N0.getNode(),
6592 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6593 N0.getValueType(), ExtLoad),
6594 ExtLoad.getValue(1));
6595 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6599 if (N0.getOpcode() == ISD::SETCC) {
6601 // aext(setcc) -> vsetcc
6602 // aext(setcc) -> truncate(vsetcc)
6603 // aext(setcc) -> aext(vsetcc)
6604 // Only do this before legalize for now.
6605 if (VT.isVector() && !LegalOperations) {
6606 EVT N0VT = N0.getOperand(0).getValueType();
6607 // We know that the # elements of the results is the same as the
6608 // # elements of the compare (and the # elements of the compare result
6609 // for that matter). Check to see that they are the same size. If so,
6610 // we know that the element size of the sext'd result matches the
6611 // element size of the compare operands.
6612 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6613 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6615 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6616 // If the desired elements are smaller or larger than the source
6617 // elements we can use a matching integer vector type and then
6618 // truncate/any extend
6620 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6622 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6624 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6625 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6629 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6632 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6633 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6634 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6642 /// See if the specified operand can be simplified with the knowledge that only
6643 /// the bits specified by Mask are used. If so, return the simpler operand,
6644 /// otherwise return a null SDValue.
6645 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6646 switch (V.getOpcode()) {
6648 case ISD::Constant: {
6649 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6650 assert(CV && "Const value should be ConstSDNode.");
6651 const APInt &CVal = CV->getAPIntValue();
6652 APInt NewVal = CVal & Mask;
6654 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6659 // If the LHS or RHS don't contribute bits to the or, drop them.
6660 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6661 return V.getOperand(1);
6662 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6663 return V.getOperand(0);
6666 // Only look at single-use SRLs.
6667 if (!V.getNode()->hasOneUse())
6669 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6670 // See if we can recursively simplify the LHS.
6671 unsigned Amt = RHSC->getZExtValue();
6673 // Watch out for shift count overflow though.
6674 if (Amt >= Mask.getBitWidth()) break;
6675 APInt NewMask = Mask << Amt;
6676 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6677 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6678 SimplifyLHS, V.getOperand(1));
6684 /// If the result of a wider load is shifted to right of N bits and then
6685 /// truncated to a narrower type and where N is a multiple of number of bits of
6686 /// the narrower type, transform it to a narrower load from address + N / num of
6687 /// bits of new type. If the result is to be extended, also fold the extension
6688 /// to form a extending load.
6689 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6690 unsigned Opc = N->getOpcode();
6692 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6693 SDValue N0 = N->getOperand(0);
6694 EVT VT = N->getValueType(0);
6697 // This transformation isn't valid for vector loads.
6701 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6703 if (Opc == ISD::SIGN_EXTEND_INREG) {
6704 ExtType = ISD::SEXTLOAD;
6705 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6706 } else if (Opc == ISD::SRL) {
6707 // Another special-case: SRL is basically zero-extending a narrower value.
6708 ExtType = ISD::ZEXTLOAD;
6710 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6711 if (!N01) return SDValue();
6712 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6713 VT.getSizeInBits() - N01->getZExtValue());
6715 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6718 unsigned EVTBits = ExtVT.getSizeInBits();
6720 // Do not generate loads of non-round integer types since these can
6721 // be expensive (and would be wrong if the type is not byte sized).
6722 if (!ExtVT.isRound())
6726 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6727 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6728 ShAmt = N01->getZExtValue();
6729 // Is the shift amount a multiple of size of VT?
6730 if ((ShAmt & (EVTBits-1)) == 0) {
6731 N0 = N0.getOperand(0);
6732 // Is the load width a multiple of size of VT?
6733 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6737 // At this point, we must have a load or else we can't do the transform.
6738 if (!isa<LoadSDNode>(N0)) return SDValue();
6740 // Because a SRL must be assumed to *need* to zero-extend the high bits
6741 // (as opposed to anyext the high bits), we can't combine the zextload
6742 // lowering of SRL and an sextload.
6743 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6746 // If the shift amount is larger than the input type then we're not
6747 // accessing any of the loaded bytes. If the load was a zextload/extload
6748 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6749 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6754 // If the load is shifted left (and the result isn't shifted back right),
6755 // we can fold the truncate through the shift.
6756 unsigned ShLeftAmt = 0;
6757 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6758 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6759 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6760 ShLeftAmt = N01->getZExtValue();
6761 N0 = N0.getOperand(0);
6765 // If we haven't found a load, we can't narrow it. Don't transform one with
6766 // multiple uses, this would require adding a new load.
6767 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6770 // Don't change the width of a volatile load.
6771 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6772 if (LN0->isVolatile())
6775 // Verify that we are actually reducing a load width here.
6776 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6779 // For the transform to be legal, the load must produce only two values
6780 // (the value loaded and the chain). Don't transform a pre-increment
6781 // load, for example, which produces an extra value. Otherwise the
6782 // transformation is not equivalent, and the downstream logic to replace
6783 // uses gets things wrong.
6784 if (LN0->getNumValues() > 2)
6787 // If the load that we're shrinking is an extload and we're not just
6788 // discarding the extension we can't simply shrink the load. Bail.
6789 // TODO: It would be possible to merge the extensions in some cases.
6790 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6791 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6794 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6797 EVT PtrType = N0.getOperand(1).getValueType();
6799 if (PtrType == MVT::Untyped || PtrType.isExtended())
6800 // It's not possible to generate a constant of extended or untyped type.
6803 // For big endian targets, we need to adjust the offset to the pointer to
6804 // load the correct bytes.
6805 if (DAG.getDataLayout().isBigEndian()) {
6806 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6807 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6808 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6811 uint64_t PtrOff = ShAmt / 8;
6812 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6814 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6815 PtrType, LN0->getBasePtr(),
6816 DAG.getConstant(PtrOff, DL, PtrType));
6817 AddToWorklist(NewPtr.getNode());
6820 if (ExtType == ISD::NON_EXTLOAD)
6821 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6822 LN0->getPointerInfo().getWithOffset(PtrOff),
6823 LN0->isVolatile(), LN0->isNonTemporal(),
6824 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6826 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6827 LN0->getPointerInfo().getWithOffset(PtrOff),
6828 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6829 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6831 // Replace the old load's chain with the new load's chain.
6832 WorklistRemover DeadNodes(*this);
6833 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6835 // Shift the result left, if we've swallowed a left shift.
6836 SDValue Result = Load;
6837 if (ShLeftAmt != 0) {
6838 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6839 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6841 // If the shift amount is as large as the result size (but, presumably,
6842 // no larger than the source) then the useful bits of the result are
6843 // zero; we can't simply return the shortened shift, because the result
6844 // of that operation is undefined.
6846 if (ShLeftAmt >= VT.getSizeInBits())
6847 Result = DAG.getConstant(0, DL, VT);
6849 Result = DAG.getNode(ISD::SHL, DL, VT,
6850 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6853 // Return the new loaded value.
6857 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6858 SDValue N0 = N->getOperand(0);
6859 SDValue N1 = N->getOperand(1);
6860 EVT VT = N->getValueType(0);
6861 EVT EVT = cast<VTSDNode>(N1)->getVT();
6862 unsigned VTBits = VT.getScalarType().getSizeInBits();
6863 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6866 return DAG.getUNDEF(VT);
6868 // fold (sext_in_reg c1) -> c1
6869 if (isConstantIntBuildVectorOrConstantInt(N0))
6870 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6872 // If the input is already sign extended, just drop the extension.
6873 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6876 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6877 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6878 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6880 N0.getOperand(0), N1);
6882 // fold (sext_in_reg (sext x)) -> (sext x)
6883 // fold (sext_in_reg (aext x)) -> (sext x)
6884 // if x is small enough.
6885 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6886 SDValue N00 = N0.getOperand(0);
6887 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6888 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6889 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6892 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6893 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6894 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6896 // fold operands of sext_in_reg based on knowledge that the top bits are not
6898 if (SimplifyDemandedBits(SDValue(N, 0)))
6899 return SDValue(N, 0);
6901 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6902 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6903 if (SDValue NarrowLoad = ReduceLoadWidth(N))
6906 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6907 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6908 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6909 if (N0.getOpcode() == ISD::SRL) {
6910 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6911 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6912 // We can turn this into an SRA iff the input to the SRL is already sign
6914 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6915 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6916 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6917 N0.getOperand(0), N0.getOperand(1));
6921 // fold (sext_inreg (extload x)) -> (sextload x)
6922 if (ISD::isEXTLoad(N0.getNode()) &&
6923 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6924 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6925 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6926 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6927 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6928 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6930 LN0->getBasePtr(), EVT,
6931 LN0->getMemOperand());
6932 CombineTo(N, ExtLoad);
6933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6934 AddToWorklist(ExtLoad.getNode());
6935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6937 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6938 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6940 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6941 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6942 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6943 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6944 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6946 LN0->getBasePtr(), EVT,
6947 LN0->getMemOperand());
6948 CombineTo(N, ExtLoad);
6949 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6953 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6954 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6955 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6956 N0.getOperand(1), false);
6957 if (BSwap.getNode())
6958 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6965 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6966 SDValue N0 = N->getOperand(0);
6967 EVT VT = N->getValueType(0);
6969 if (N0.getOpcode() == ISD::UNDEF)
6970 return DAG.getUNDEF(VT);
6972 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6974 return SDValue(Res, 0);
6979 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6980 SDValue N0 = N->getOperand(0);
6981 EVT VT = N->getValueType(0);
6982 bool isLE = DAG.getDataLayout().isLittleEndian();
6985 if (N0.getValueType() == N->getValueType(0))
6987 // fold (truncate c1) -> c1
6988 if (isConstantIntBuildVectorOrConstantInt(N0))
6989 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6990 // fold (truncate (truncate x)) -> (truncate x)
6991 if (N0.getOpcode() == ISD::TRUNCATE)
6992 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6993 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6994 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6995 N0.getOpcode() == ISD::SIGN_EXTEND ||
6996 N0.getOpcode() == ISD::ANY_EXTEND) {
6997 if (N0.getOperand(0).getValueType().bitsLT(VT))
6998 // if the source is smaller than the dest, we still need an extend
6999 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
7001 if (N0.getOperand(0).getValueType().bitsGT(VT))
7002 // if the source is larger than the dest, than we just need the truncate
7003 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7004 // if the source and dest are the same type, we can drop both the extend
7005 // and the truncate.
7006 return N0.getOperand(0);
7009 // Fold extract-and-trunc into a narrow extract. For example:
7010 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7011 // i32 y = TRUNCATE(i64 x)
7013 // v16i8 b = BITCAST (v2i64 val)
7014 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7016 // Note: We only run this optimization after type legalization (which often
7017 // creates this pattern) and before operation legalization after which
7018 // we need to be more careful about the vector instructions that we generate.
7019 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7020 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7022 EVT VecTy = N0.getOperand(0).getValueType();
7023 EVT ExTy = N0.getValueType();
7024 EVT TrTy = N->getValueType(0);
7026 unsigned NumElem = VecTy.getVectorNumElements();
7027 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7029 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7030 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7032 SDValue EltNo = N0->getOperand(1);
7033 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7034 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7035 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7036 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7038 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7039 NVT, N0.getOperand(0));
7042 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7044 DAG.getConstant(Index, DL, IndexTy));
7048 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7049 if (N0.getOpcode() == ISD::SELECT) {
7050 EVT SrcVT = N0.getValueType();
7051 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7052 TLI.isTruncateFree(SrcVT, VT)) {
7054 SDValue Cond = N0.getOperand(0);
7055 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7056 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7057 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7061 // Fold a series of buildvector, bitcast, and truncate if possible.
7063 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7064 // (2xi32 (buildvector x, y)).
7065 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7066 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7067 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7068 N0.getOperand(0).hasOneUse()) {
7070 SDValue BuildVect = N0.getOperand(0);
7071 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7072 EVT TruncVecEltTy = VT.getVectorElementType();
7074 // Check that the element types match.
7075 if (BuildVectEltTy == TruncVecEltTy) {
7076 // Now we only need to compute the offset of the truncated elements.
7077 unsigned BuildVecNumElts = BuildVect.getNumOperands();
7078 unsigned TruncVecNumElts = VT.getVectorNumElements();
7079 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7081 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7082 "Invalid number of elements");
7084 SmallVector<SDValue, 8> Opnds;
7085 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7086 Opnds.push_back(BuildVect.getOperand(i));
7088 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7092 // See if we can simplify the input to this truncate through knowledge that
7093 // only the low bits are being used.
7094 // For example "trunc (or (shl x, 8), y)" // -> trunc y
7095 // Currently we only perform this optimization on scalars because vectors
7096 // may have different active low bits.
7097 if (!VT.isVector()) {
7099 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7100 VT.getSizeInBits()));
7101 if (Shorter.getNode())
7102 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7104 // fold (truncate (load x)) -> (smaller load x)
7105 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7106 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7107 if (SDValue Reduced = ReduceLoadWidth(N))
7110 // Handle the case where the load remains an extending load even
7111 // after truncation.
7112 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7113 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7114 if (!LN0->isVolatile() &&
7115 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7116 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7117 VT, LN0->getChain(), LN0->getBasePtr(),
7119 LN0->getMemOperand());
7120 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7125 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7126 // where ... are all 'undef'.
7127 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7128 SmallVector<EVT, 8> VTs;
7131 unsigned NumDefs = 0;
7133 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7134 SDValue X = N0.getOperand(i);
7135 if (X.getOpcode() != ISD::UNDEF) {
7140 // Stop if more than one members are non-undef.
7143 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7144 VT.getVectorElementType(),
7145 X.getValueType().getVectorNumElements()));
7149 return DAG.getUNDEF(VT);
7152 assert(V.getNode() && "The single defined operand is empty!");
7153 SmallVector<SDValue, 8> Opnds;
7154 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7156 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7159 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7160 AddToWorklist(NV.getNode());
7161 Opnds.push_back(NV);
7163 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7167 // Simplify the operands using demanded-bits information.
7168 if (!VT.isVector() &&
7169 SimplifyDemandedBits(SDValue(N, 0)))
7170 return SDValue(N, 0);
7175 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7176 SDValue Elt = N->getOperand(i);
7177 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7178 return Elt.getNode();
7179 return Elt.getOperand(Elt.getResNo()).getNode();
7182 /// build_pair (load, load) -> load
7183 /// if load locations are consecutive.
7184 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7185 assert(N->getOpcode() == ISD::BUILD_PAIR);
7187 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7188 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7189 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7190 LD1->getAddressSpace() != LD2->getAddressSpace())
7192 EVT LD1VT = LD1->getValueType(0);
7194 if (ISD::isNON_EXTLoad(LD2) &&
7196 // If both are volatile this would reduce the number of volatile loads.
7197 // If one is volatile it might be ok, but play conservative and bail out.
7198 !LD1->isVolatile() &&
7199 !LD2->isVolatile() &&
7200 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7201 unsigned Align = LD1->getAlignment();
7202 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7203 VT.getTypeForEVT(*DAG.getContext()));
7205 if (NewAlign <= Align &&
7206 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7207 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7208 LD1->getBasePtr(), LD1->getPointerInfo(),
7209 false, false, false, Align);
7215 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7216 SDValue N0 = N->getOperand(0);
7217 EVT VT = N->getValueType(0);
7219 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7220 // Only do this before legalize, since afterward the target may be depending
7221 // on the bitconvert.
7222 // First check to see if this is all constant.
7224 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7226 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7228 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7229 assert(!DestEltVT.isVector() &&
7230 "Element type of vector ValueType must not be vector!");
7232 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7235 // If the input is a constant, let getNode fold it.
7236 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7237 // If we can't allow illegal operations, we need to check that this is just
7238 // a fp -> int or int -> conversion and that the resulting operation will
7240 if (!LegalOperations ||
7241 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7242 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7243 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7244 TLI.isOperationLegal(ISD::Constant, VT)))
7245 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7248 // (conv (conv x, t1), t2) -> (conv x, t2)
7249 if (N0.getOpcode() == ISD::BITCAST)
7250 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7253 // fold (conv (load x)) -> (load (conv*)x)
7254 // If the resultant load doesn't need a higher alignment than the original!
7255 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7256 // Do not change the width of a volatile load.
7257 !cast<LoadSDNode>(N0)->isVolatile() &&
7258 // Do not remove the cast if the types differ in endian layout.
7259 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7260 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7261 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7262 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7263 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7264 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7265 VT.getTypeForEVT(*DAG.getContext()));
7266 unsigned OrigAlign = LN0->getAlignment();
7268 if (Align <= OrigAlign) {
7269 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7270 LN0->getBasePtr(), LN0->getPointerInfo(),
7271 LN0->isVolatile(), LN0->isNonTemporal(),
7272 LN0->isInvariant(), OrigAlign,
7274 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7279 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7280 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7281 // This often reduces constant pool loads.
7282 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7283 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7284 N0.getNode()->hasOneUse() && VT.isInteger() &&
7285 !VT.isVector() && !N0.getValueType().isVector()) {
7286 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7288 AddToWorklist(NewConv.getNode());
7291 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7292 if (N0.getOpcode() == ISD::FNEG)
7293 return DAG.getNode(ISD::XOR, DL, VT,
7294 NewConv, DAG.getConstant(SignBit, DL, VT));
7295 assert(N0.getOpcode() == ISD::FABS);
7296 return DAG.getNode(ISD::AND, DL, VT,
7297 NewConv, DAG.getConstant(~SignBit, DL, VT));
7300 // fold (bitconvert (fcopysign cst, x)) ->
7301 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7302 // Note that we don't handle (copysign x, cst) because this can always be
7303 // folded to an fneg or fabs.
7304 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7305 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7306 VT.isInteger() && !VT.isVector()) {
7307 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7308 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7309 if (isTypeLegal(IntXVT)) {
7310 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7311 IntXVT, N0.getOperand(1));
7312 AddToWorklist(X.getNode());
7314 // If X has a different width than the result/lhs, sext it or truncate it.
7315 unsigned VTWidth = VT.getSizeInBits();
7316 if (OrigXWidth < VTWidth) {
7317 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7318 AddToWorklist(X.getNode());
7319 } else if (OrigXWidth > VTWidth) {
7320 // To get the sign bit in the right place, we have to shift it right
7321 // before truncating.
7323 X = DAG.getNode(ISD::SRL, DL,
7324 X.getValueType(), X,
7325 DAG.getConstant(OrigXWidth-VTWidth, DL,
7327 AddToWorklist(X.getNode());
7328 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7329 AddToWorklist(X.getNode());
7332 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7333 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7334 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7335 AddToWorklist(X.getNode());
7337 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7338 VT, N0.getOperand(0));
7339 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7340 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7341 AddToWorklist(Cst.getNode());
7343 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7347 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7348 if (N0.getOpcode() == ISD::BUILD_PAIR)
7349 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7352 // Remove double bitcasts from shuffles - this is often a legacy of
7353 // XformToShuffleWithZero being used to combine bitmaskings (of
7354 // float vectors bitcast to integer vectors) into shuffles.
7355 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7356 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7357 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7358 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7359 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7360 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7362 // If operands are a bitcast, peek through if it casts the original VT.
7363 // If operands are a constant, just bitcast back to original VT.
7364 auto PeekThroughBitcast = [&](SDValue Op) {
7365 if (Op.getOpcode() == ISD::BITCAST &&
7366 Op.getOperand(0).getValueType() == VT)
7367 return SDValue(Op.getOperand(0));
7368 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7369 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7370 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7374 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7375 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7380 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7381 SmallVector<int, 8> NewMask;
7382 for (int M : SVN->getMask())
7383 for (int i = 0; i != MaskScale; ++i)
7384 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7386 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7388 std::swap(SV0, SV1);
7389 ShuffleVectorSDNode::commuteMask(NewMask);
7390 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7394 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7400 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7401 EVT VT = N->getValueType(0);
7402 return CombineConsecutiveLoads(N, VT);
7405 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7406 /// operands. DstEltVT indicates the destination element value type.
7407 SDValue DAGCombiner::
7408 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7409 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7411 // If this is already the right type, we're done.
7412 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7414 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7415 unsigned DstBitSize = DstEltVT.getSizeInBits();
7417 // If this is a conversion of N elements of one type to N elements of another
7418 // type, convert each element. This handles FP<->INT cases.
7419 if (SrcBitSize == DstBitSize) {
7420 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7421 BV->getValueType(0).getVectorNumElements());
7423 // Due to the FP element handling below calling this routine recursively,
7424 // we can end up with a scalar-to-vector node here.
7425 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7426 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7427 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7428 DstEltVT, BV->getOperand(0)));
7430 SmallVector<SDValue, 8> Ops;
7431 for (SDValue Op : BV->op_values()) {
7432 // If the vector element type is not legal, the BUILD_VECTOR operands
7433 // are promoted and implicitly truncated. Make that explicit here.
7434 if (Op.getValueType() != SrcEltVT)
7435 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7436 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7438 AddToWorklist(Ops.back().getNode());
7440 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7443 // Otherwise, we're growing or shrinking the elements. To avoid having to
7444 // handle annoying details of growing/shrinking FP values, we convert them to
7446 if (SrcEltVT.isFloatingPoint()) {
7447 // Convert the input float vector to a int vector where the elements are the
7449 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7450 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7454 // Now we know the input is an integer vector. If the output is a FP type,
7455 // convert to integer first, then to FP of the right size.
7456 if (DstEltVT.isFloatingPoint()) {
7457 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7458 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7460 // Next, convert to FP elements of the same size.
7461 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7466 // Okay, we know the src/dst types are both integers of differing types.
7467 // Handling growing first.
7468 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7469 if (SrcBitSize < DstBitSize) {
7470 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7472 SmallVector<SDValue, 8> Ops;
7473 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7474 i += NumInputsPerOutput) {
7475 bool isLE = DAG.getDataLayout().isLittleEndian();
7476 APInt NewBits = APInt(DstBitSize, 0);
7477 bool EltIsUndef = true;
7478 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7479 // Shift the previously computed bits over.
7480 NewBits <<= SrcBitSize;
7481 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7482 if (Op.getOpcode() == ISD::UNDEF) continue;
7485 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7486 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7490 Ops.push_back(DAG.getUNDEF(DstEltVT));
7492 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7495 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7496 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7499 // Finally, this must be the case where we are shrinking elements: each input
7500 // turns into multiple outputs.
7501 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7502 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7503 NumOutputsPerInput*BV->getNumOperands());
7504 SmallVector<SDValue, 8> Ops;
7506 for (const SDValue &Op : BV->op_values()) {
7507 if (Op.getOpcode() == ISD::UNDEF) {
7508 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7512 APInt OpVal = cast<ConstantSDNode>(Op)->
7513 getAPIntValue().zextOrTrunc(SrcBitSize);
7515 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7516 APInt ThisVal = OpVal.trunc(DstBitSize);
7517 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7518 OpVal = OpVal.lshr(DstBitSize);
7521 // For big endian targets, swap the order of the pieces of each element.
7522 if (DAG.getDataLayout().isBigEndian())
7523 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7526 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7529 /// Try to perform FMA combining on a given FADD node.
7530 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7531 SDValue N0 = N->getOperand(0);
7532 SDValue N1 = N->getOperand(1);
7533 EVT VT = N->getValueType(0);
7536 const TargetOptions &Options = DAG.getTarget().Options;
7538 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7540 // Floating-point multiply-add with intermediate rounding.
7541 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7543 // Floating-point multiply-add without intermediate rounding.
7545 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7546 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7548 // No valid opcode, do not combine.
7549 if (!HasFMAD && !HasFMA)
7552 // Always prefer FMAD to FMA for precision.
7553 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7554 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7555 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7557 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7558 // prefer to fold the multiply with fewer uses.
7559 if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7560 N1.getOpcode() == ISD::FMUL) {
7561 if (N0.getNode()->use_size() > N1.getNode()->use_size())
7565 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7566 if (N0.getOpcode() == ISD::FMUL &&
7567 (Aggressive || N0->hasOneUse())) {
7568 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7569 N0.getOperand(0), N0.getOperand(1), N1);
7572 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7573 // Note: Commutes FADD operands.
7574 if (N1.getOpcode() == ISD::FMUL &&
7575 (Aggressive || N1->hasOneUse())) {
7576 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577 N1.getOperand(0), N1.getOperand(1), N0);
7580 // Look through FP_EXTEND nodes to do more combining.
7581 if (AllowFusion && LookThroughFPExt) {
7582 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7583 if (N0.getOpcode() == ISD::FP_EXTEND) {
7584 SDValue N00 = N0.getOperand(0);
7585 if (N00.getOpcode() == ISD::FMUL)
7586 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7587 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7590 N00.getOperand(1)), N1);
7593 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7594 // Note: Commutes FADD operands.
7595 if (N1.getOpcode() == ISD::FP_EXTEND) {
7596 SDValue N10 = N1.getOperand(0);
7597 if (N10.getOpcode() == ISD::FMUL)
7598 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7599 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7601 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7602 N10.getOperand(1)), N0);
7606 // More folding opportunities when target permits.
7607 if ((AllowFusion || HasFMAD) && Aggressive) {
7608 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7609 if (N0.getOpcode() == PreferredFusedOpcode &&
7610 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7611 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7612 N0.getOperand(0), N0.getOperand(1),
7613 DAG.getNode(PreferredFusedOpcode, SL, VT,
7614 N0.getOperand(2).getOperand(0),
7615 N0.getOperand(2).getOperand(1),
7619 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7620 if (N1->getOpcode() == PreferredFusedOpcode &&
7621 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7622 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7623 N1.getOperand(0), N1.getOperand(1),
7624 DAG.getNode(PreferredFusedOpcode, SL, VT,
7625 N1.getOperand(2).getOperand(0),
7626 N1.getOperand(2).getOperand(1),
7630 if (AllowFusion && LookThroughFPExt) {
7631 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7632 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7633 auto FoldFAddFMAFPExtFMul = [&] (
7634 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7635 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7636 DAG.getNode(PreferredFusedOpcode, SL, VT,
7637 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7638 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7641 if (N0.getOpcode() == PreferredFusedOpcode) {
7642 SDValue N02 = N0.getOperand(2);
7643 if (N02.getOpcode() == ISD::FP_EXTEND) {
7644 SDValue N020 = N02.getOperand(0);
7645 if (N020.getOpcode() == ISD::FMUL)
7646 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7647 N020.getOperand(0), N020.getOperand(1),
7652 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7653 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7654 // FIXME: This turns two single-precision and one double-precision
7655 // operation into two double-precision operations, which might not be
7656 // interesting for all targets, especially GPUs.
7657 auto FoldFAddFPExtFMAFMul = [&] (
7658 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7659 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7660 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7661 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7662 DAG.getNode(PreferredFusedOpcode, SL, VT,
7663 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7664 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7667 if (N0.getOpcode() == ISD::FP_EXTEND) {
7668 SDValue N00 = N0.getOperand(0);
7669 if (N00.getOpcode() == PreferredFusedOpcode) {
7670 SDValue N002 = N00.getOperand(2);
7671 if (N002.getOpcode() == ISD::FMUL)
7672 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7673 N002.getOperand(0), N002.getOperand(1),
7678 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7679 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7680 if (N1.getOpcode() == PreferredFusedOpcode) {
7681 SDValue N12 = N1.getOperand(2);
7682 if (N12.getOpcode() == ISD::FP_EXTEND) {
7683 SDValue N120 = N12.getOperand(0);
7684 if (N120.getOpcode() == ISD::FMUL)
7685 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7686 N120.getOperand(0), N120.getOperand(1),
7691 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7692 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7693 // FIXME: This turns two single-precision and one double-precision
7694 // operation into two double-precision operations, which might not be
7695 // interesting for all targets, especially GPUs.
7696 if (N1.getOpcode() == ISD::FP_EXTEND) {
7697 SDValue N10 = N1.getOperand(0);
7698 if (N10.getOpcode() == PreferredFusedOpcode) {
7699 SDValue N102 = N10.getOperand(2);
7700 if (N102.getOpcode() == ISD::FMUL)
7701 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7702 N102.getOperand(0), N102.getOperand(1),
7712 /// Try to perform FMA combining on a given FSUB node.
7713 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7714 SDValue N0 = N->getOperand(0);
7715 SDValue N1 = N->getOperand(1);
7716 EVT VT = N->getValueType(0);
7719 const TargetOptions &Options = DAG.getTarget().Options;
7721 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7723 // Floating-point multiply-add with intermediate rounding.
7724 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7726 // Floating-point multiply-add without intermediate rounding.
7728 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7729 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7731 // No valid opcode, do not combine.
7732 if (!HasFMAD && !HasFMA)
7735 // Always prefer FMAD to FMA for precision.
7736 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7737 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7738 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7740 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7741 if (N0.getOpcode() == ISD::FMUL &&
7742 (Aggressive || N0->hasOneUse())) {
7743 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7744 N0.getOperand(0), N0.getOperand(1),
7745 DAG.getNode(ISD::FNEG, SL, VT, N1));
7748 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7749 // Note: Commutes FSUB operands.
7750 if (N1.getOpcode() == ISD::FMUL &&
7751 (Aggressive || N1->hasOneUse()))
7752 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7753 DAG.getNode(ISD::FNEG, SL, VT,
7755 N1.getOperand(1), N0);
7757 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7758 if (N0.getOpcode() == ISD::FNEG &&
7759 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7760 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7761 SDValue N00 = N0.getOperand(0).getOperand(0);
7762 SDValue N01 = N0.getOperand(0).getOperand(1);
7763 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7765 DAG.getNode(ISD::FNEG, SL, VT, N1));
7768 // Look through FP_EXTEND nodes to do more combining.
7769 if (AllowFusion && LookThroughFPExt) {
7770 // fold (fsub (fpext (fmul x, y)), z)
7771 // -> (fma (fpext x), (fpext y), (fneg z))
7772 if (N0.getOpcode() == ISD::FP_EXTEND) {
7773 SDValue N00 = N0.getOperand(0);
7774 if (N00.getOpcode() == ISD::FMUL)
7775 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7780 DAG.getNode(ISD::FNEG, SL, VT, N1));
7783 // fold (fsub x, (fpext (fmul y, z)))
7784 // -> (fma (fneg (fpext y)), (fpext z), x)
7785 // Note: Commutes FSUB operands.
7786 if (N1.getOpcode() == ISD::FP_EXTEND) {
7787 SDValue N10 = N1.getOperand(0);
7788 if (N10.getOpcode() == ISD::FMUL)
7789 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7790 DAG.getNode(ISD::FNEG, SL, VT,
7791 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7792 N10.getOperand(0))),
7793 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7798 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7799 // -> (fneg (fma (fpext x), (fpext y), z))
7800 // Note: This could be removed with appropriate canonicalization of the
7801 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7802 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7803 // from implementing the canonicalization in visitFSUB.
7804 if (N0.getOpcode() == ISD::FP_EXTEND) {
7805 SDValue N00 = N0.getOperand(0);
7806 if (N00.getOpcode() == ISD::FNEG) {
7807 SDValue N000 = N00.getOperand(0);
7808 if (N000.getOpcode() == ISD::FMUL) {
7809 return DAG.getNode(ISD::FNEG, SL, VT,
7810 DAG.getNode(PreferredFusedOpcode, SL, VT,
7811 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7812 N000.getOperand(0)),
7813 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7814 N000.getOperand(1)),
7820 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7821 // -> (fneg (fma (fpext x)), (fpext y), z)
7822 // Note: This could be removed with appropriate canonicalization of the
7823 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7824 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7825 // from implementing the canonicalization in visitFSUB.
7826 if (N0.getOpcode() == ISD::FNEG) {
7827 SDValue N00 = N0.getOperand(0);
7828 if (N00.getOpcode() == ISD::FP_EXTEND) {
7829 SDValue N000 = N00.getOperand(0);
7830 if (N000.getOpcode() == ISD::FMUL) {
7831 return DAG.getNode(ISD::FNEG, SL, VT,
7832 DAG.getNode(PreferredFusedOpcode, SL, VT,
7833 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7834 N000.getOperand(0)),
7835 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7836 N000.getOperand(1)),
7844 // More folding opportunities when target permits.
7845 if ((AllowFusion || HasFMAD) && Aggressive) {
7846 // fold (fsub (fma x, y, (fmul u, v)), z)
7847 // -> (fma x, y (fma u, v, (fneg z)))
7848 if (N0.getOpcode() == PreferredFusedOpcode &&
7849 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7850 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7851 N0.getOperand(0), N0.getOperand(1),
7852 DAG.getNode(PreferredFusedOpcode, SL, VT,
7853 N0.getOperand(2).getOperand(0),
7854 N0.getOperand(2).getOperand(1),
7855 DAG.getNode(ISD::FNEG, SL, VT,
7859 // fold (fsub x, (fma y, z, (fmul u, v)))
7860 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7861 if (N1.getOpcode() == PreferredFusedOpcode &&
7862 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7863 SDValue N20 = N1.getOperand(2).getOperand(0);
7864 SDValue N21 = N1.getOperand(2).getOperand(1);
7865 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7866 DAG.getNode(ISD::FNEG, SL, VT,
7869 DAG.getNode(PreferredFusedOpcode, SL, VT,
7870 DAG.getNode(ISD::FNEG, SL, VT, N20),
7875 if (AllowFusion && LookThroughFPExt) {
7876 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7877 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7878 if (N0.getOpcode() == PreferredFusedOpcode) {
7879 SDValue N02 = N0.getOperand(2);
7880 if (N02.getOpcode() == ISD::FP_EXTEND) {
7881 SDValue N020 = N02.getOperand(0);
7882 if (N020.getOpcode() == ISD::FMUL)
7883 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7884 N0.getOperand(0), N0.getOperand(1),
7885 DAG.getNode(PreferredFusedOpcode, SL, VT,
7886 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7887 N020.getOperand(0)),
7888 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7889 N020.getOperand(1)),
7890 DAG.getNode(ISD::FNEG, SL, VT,
7895 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7896 // -> (fma (fpext x), (fpext y),
7897 // (fma (fpext u), (fpext v), (fneg z)))
7898 // FIXME: This turns two single-precision and one double-precision
7899 // operation into two double-precision operations, which might not be
7900 // interesting for all targets, especially GPUs.
7901 if (N0.getOpcode() == ISD::FP_EXTEND) {
7902 SDValue N00 = N0.getOperand(0);
7903 if (N00.getOpcode() == PreferredFusedOpcode) {
7904 SDValue N002 = N00.getOperand(2);
7905 if (N002.getOpcode() == ISD::FMUL)
7906 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7907 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7909 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7911 DAG.getNode(PreferredFusedOpcode, SL, VT,
7912 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7913 N002.getOperand(0)),
7914 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7915 N002.getOperand(1)),
7916 DAG.getNode(ISD::FNEG, SL, VT,
7921 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7922 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7923 if (N1.getOpcode() == PreferredFusedOpcode &&
7924 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7925 SDValue N120 = N1.getOperand(2).getOperand(0);
7926 if (N120.getOpcode() == ISD::FMUL) {
7927 SDValue N1200 = N120.getOperand(0);
7928 SDValue N1201 = N120.getOperand(1);
7929 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7930 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7932 DAG.getNode(PreferredFusedOpcode, SL, VT,
7933 DAG.getNode(ISD::FNEG, SL, VT,
7934 DAG.getNode(ISD::FP_EXTEND, SL,
7936 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7942 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7943 // -> (fma (fneg (fpext y)), (fpext z),
7944 // (fma (fneg (fpext u)), (fpext v), x))
7945 // FIXME: This turns two single-precision and one double-precision
7946 // operation into two double-precision operations, which might not be
7947 // interesting for all targets, especially GPUs.
7948 if (N1.getOpcode() == ISD::FP_EXTEND &&
7949 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7950 SDValue N100 = N1.getOperand(0).getOperand(0);
7951 SDValue N101 = N1.getOperand(0).getOperand(1);
7952 SDValue N102 = N1.getOperand(0).getOperand(2);
7953 if (N102.getOpcode() == ISD::FMUL) {
7954 SDValue N1020 = N102.getOperand(0);
7955 SDValue N1021 = N102.getOperand(1);
7956 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7957 DAG.getNode(ISD::FNEG, SL, VT,
7958 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7960 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7961 DAG.getNode(PreferredFusedOpcode, SL, VT,
7962 DAG.getNode(ISD::FNEG, SL, VT,
7963 DAG.getNode(ISD::FP_EXTEND, SL,
7965 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7976 /// Try to perform FMA combining on a given FMUL node.
7977 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7978 SDValue N0 = N->getOperand(0);
7979 SDValue N1 = N->getOperand(1);
7980 EVT VT = N->getValueType(0);
7983 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7985 const TargetOptions &Options = DAG.getTarget().Options;
7987 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7989 // Floating-point multiply-add with intermediate rounding.
7990 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7992 // Floating-point multiply-add without intermediate rounding.
7994 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7995 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7997 // No valid opcode, do not combine.
7998 if (!HasFMAD && !HasFMA)
8001 // Always prefer FMAD to FMA for precision.
8002 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8003 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8005 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8006 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8007 auto FuseFADD = [&](SDValue X, SDValue Y) {
8008 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8009 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8010 if (XC1 && XC1->isExactlyValue(+1.0))
8011 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8012 if (XC1 && XC1->isExactlyValue(-1.0))
8013 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8014 DAG.getNode(ISD::FNEG, SL, VT, Y));
8019 if (SDValue FMA = FuseFADD(N0, N1))
8021 if (SDValue FMA = FuseFADD(N1, N0))
8024 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8025 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8026 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8027 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8028 auto FuseFSUB = [&](SDValue X, SDValue Y) {
8029 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8030 auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8031 if (XC0 && XC0->isExactlyValue(+1.0))
8032 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8033 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8035 if (XC0 && XC0->isExactlyValue(-1.0))
8036 return DAG.getNode(PreferredFusedOpcode, SL, VT,
8037 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8038 DAG.getNode(ISD::FNEG, SL, VT, Y));
8040 auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8041 if (XC1 && XC1->isExactlyValue(+1.0))
8042 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8043 DAG.getNode(ISD::FNEG, SL, VT, Y));
8044 if (XC1 && XC1->isExactlyValue(-1.0))
8045 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8050 if (SDValue FMA = FuseFSUB(N0, N1))
8052 if (SDValue FMA = FuseFSUB(N1, N0))
8058 SDValue DAGCombiner::visitFADD(SDNode *N) {
8059 SDValue N0 = N->getOperand(0);
8060 SDValue N1 = N->getOperand(1);
8061 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8062 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8063 EVT VT = N->getValueType(0);
8065 const TargetOptions &Options = DAG.getTarget().Options;
8066 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8070 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8073 // fold (fadd c1, c2) -> c1 + c2
8075 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8077 // canonicalize constant to RHS
8078 if (N0CFP && !N1CFP)
8079 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8081 // fold (fadd A, (fneg B)) -> (fsub A, B)
8082 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8083 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8084 return DAG.getNode(ISD::FSUB, DL, VT, N0,
8085 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8087 // fold (fadd (fneg A), B) -> (fsub B, A)
8088 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8089 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8090 return DAG.getNode(ISD::FSUB, DL, VT, N1,
8091 GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8093 // If 'unsafe math' is enabled, fold lots of things.
8094 if (Options.UnsafeFPMath) {
8095 // No FP constant should be created after legalization as Instruction
8096 // Selection pass has a hard time dealing with FP constants.
8097 bool AllowNewConst = (Level < AfterLegalizeDAG);
8099 // fold (fadd A, 0) -> A
8100 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8104 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8105 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8106 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8107 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8108 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8112 // If allowed, fold (fadd (fneg x), x) -> 0.0
8113 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8114 return DAG.getConstantFP(0.0, DL, VT);
8116 // If allowed, fold (fadd x, (fneg x)) -> 0.0
8117 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8118 return DAG.getConstantFP(0.0, DL, VT);
8120 // We can fold chains of FADD's of the same value into multiplications.
8121 // This transform is not safe in general because we are reducing the number
8122 // of rounding steps.
8123 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8124 if (N0.getOpcode() == ISD::FMUL) {
8125 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8126 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8128 // (fadd (fmul x, c), x) -> (fmul x, c+1)
8129 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8130 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8131 DAG.getConstantFP(1.0, DL, VT), Flags);
8132 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8135 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8136 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8137 N1.getOperand(0) == N1.getOperand(1) &&
8138 N0.getOperand(0) == N1.getOperand(0)) {
8139 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8140 DAG.getConstantFP(2.0, DL, VT), Flags);
8141 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8145 if (N1.getOpcode() == ISD::FMUL) {
8146 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8147 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8149 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8150 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8151 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8152 DAG.getConstantFP(1.0, DL, VT), Flags);
8153 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8156 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8157 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8158 N0.getOperand(0) == N0.getOperand(1) &&
8159 N1.getOperand(0) == N0.getOperand(0)) {
8160 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8161 DAG.getConstantFP(2.0, DL, VT), Flags);
8162 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8166 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8167 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8168 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8169 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8170 (N0.getOperand(0) == N1)) {
8171 return DAG.getNode(ISD::FMUL, DL, VT,
8172 N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8176 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8177 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8178 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8179 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8180 N1.getOperand(0) == N0) {
8181 return DAG.getNode(ISD::FMUL, DL, VT,
8182 N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8186 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8187 if (AllowNewConst &&
8188 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8189 N0.getOperand(0) == N0.getOperand(1) &&
8190 N1.getOperand(0) == N1.getOperand(1) &&
8191 N0.getOperand(0) == N1.getOperand(0)) {
8192 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8193 DAG.getConstantFP(4.0, DL, VT), Flags);
8196 } // enable-unsafe-fp-math
8198 // FADD -> FMA combines:
8199 if (SDValue Fused = visitFADDForFMACombine(N)) {
8200 AddToWorklist(Fused.getNode());
8207 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8208 SDValue N0 = N->getOperand(0);
8209 SDValue N1 = N->getOperand(1);
8210 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8211 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8212 EVT VT = N->getValueType(0);
8214 const TargetOptions &Options = DAG.getTarget().Options;
8215 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8219 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8222 // fold (fsub c1, c2) -> c1-c2
8224 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8226 // fold (fsub A, (fneg B)) -> (fadd A, B)
8227 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8228 return DAG.getNode(ISD::FADD, dl, VT, N0,
8229 GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8231 // If 'unsafe math' is enabled, fold lots of things.
8232 if (Options.UnsafeFPMath) {
8234 if (N1CFP && N1CFP->isZero())
8237 // (fsub 0, B) -> -B
8238 if (N0CFP && N0CFP->isZero()) {
8239 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8240 return GetNegatedExpression(N1, DAG, LegalOperations);
8241 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8242 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8245 // (fsub x, x) -> 0.0
8247 return DAG.getConstantFP(0.0f, dl, VT);
8249 // (fsub x, (fadd x, y)) -> (fneg y)
8250 // (fsub x, (fadd y, x)) -> (fneg y)
8251 if (N1.getOpcode() == ISD::FADD) {
8252 SDValue N10 = N1->getOperand(0);
8253 SDValue N11 = N1->getOperand(1);
8255 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8256 return GetNegatedExpression(N11, DAG, LegalOperations);
8258 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8259 return GetNegatedExpression(N10, DAG, LegalOperations);
8263 // FSUB -> FMA combines:
8264 if (SDValue Fused = visitFSUBForFMACombine(N)) {
8265 AddToWorklist(Fused.getNode());
8272 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8273 SDValue N0 = N->getOperand(0);
8274 SDValue N1 = N->getOperand(1);
8275 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8276 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8277 EVT VT = N->getValueType(0);
8279 const TargetOptions &Options = DAG.getTarget().Options;
8280 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8283 if (VT.isVector()) {
8284 // This just handles C1 * C2 for vectors. Other vector folds are below.
8285 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8289 // fold (fmul c1, c2) -> c1*c2
8291 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8293 // canonicalize constant to RHS
8294 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8295 !isConstantFPBuildVectorOrConstantFP(N1))
8296 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8298 // fold (fmul A, 1.0) -> A
8299 if (N1CFP && N1CFP->isExactlyValue(1.0))
8302 if (Options.UnsafeFPMath) {
8303 // fold (fmul A, 0) -> 0
8304 if (N1CFP && N1CFP->isZero())
8307 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8308 if (N0.getOpcode() == ISD::FMUL) {
8309 // Fold scalars or any vector constants (not just splats).
8310 // This fold is done in general by InstCombine, but extra fmul insts
8311 // may have been generated during lowering.
8312 SDValue N00 = N0.getOperand(0);
8313 SDValue N01 = N0.getOperand(1);
8314 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8315 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8316 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8318 // Check 1: Make sure that the first operand of the inner multiply is NOT
8319 // a constant. Otherwise, we may induce infinite looping.
8320 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8321 // Check 2: Make sure that the second operand of the inner multiply and
8322 // the second operand of the outer multiply are constants.
8323 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8324 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8325 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8326 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8331 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8332 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8333 // during an early run of DAGCombiner can prevent folding with fmuls
8334 // inserted during lowering.
8335 if (N0.getOpcode() == ISD::FADD &&
8336 (N0.getOperand(0) == N0.getOperand(1)) &&
8338 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8339 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8340 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8344 // fold (fmul X, 2.0) -> (fadd X, X)
8345 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8346 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8348 // fold (fmul X, -1.0) -> (fneg X)
8349 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8350 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8351 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8353 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8354 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8355 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8356 // Both can be negated for free, check to see if at least one is cheaper
8358 if (LHSNeg == 2 || RHSNeg == 2)
8359 return DAG.getNode(ISD::FMUL, DL, VT,
8360 GetNegatedExpression(N0, DAG, LegalOperations),
8361 GetNegatedExpression(N1, DAG, LegalOperations),
8366 // FMUL -> FMA combines:
8367 if (SDValue Fused = visitFMULForFMACombine(N)) {
8368 AddToWorklist(Fused.getNode());
8375 SDValue DAGCombiner::visitFMA(SDNode *N) {
8376 SDValue N0 = N->getOperand(0);
8377 SDValue N1 = N->getOperand(1);
8378 SDValue N2 = N->getOperand(2);
8379 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8380 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8381 EVT VT = N->getValueType(0);
8383 const TargetOptions &Options = DAG.getTarget().Options;
8385 // Constant fold FMA.
8386 if (isa<ConstantFPSDNode>(N0) &&
8387 isa<ConstantFPSDNode>(N1) &&
8388 isa<ConstantFPSDNode>(N2)) {
8389 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8392 if (Options.UnsafeFPMath) {
8393 if (N0CFP && N0CFP->isZero())
8395 if (N1CFP && N1CFP->isZero())
8398 // TODO: The FMA node should have flags that propagate to these nodes.
8399 if (N0CFP && N0CFP->isExactlyValue(1.0))
8400 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8401 if (N1CFP && N1CFP->isExactlyValue(1.0))
8402 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8404 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8405 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8406 !isConstantFPBuildVectorOrConstantFP(N1))
8407 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8409 // TODO: FMA nodes should have flags that propagate to the created nodes.
8410 // For now, create a Flags object for use with all unsafe math transforms.
8412 Flags.setUnsafeAlgebra(true);
8414 if (Options.UnsafeFPMath) {
8415 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8416 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8417 isConstantFPBuildVectorOrConstantFP(N1) &&
8418 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8419 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8420 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8424 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8425 if (N0.getOpcode() == ISD::FMUL &&
8426 isConstantFPBuildVectorOrConstantFP(N1) &&
8427 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8428 return DAG.getNode(ISD::FMA, dl, VT,
8430 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8436 // (fma x, 1, y) -> (fadd x, y)
8437 // (fma x, -1, y) -> (fadd (fneg x), y)
8439 if (N1CFP->isExactlyValue(1.0))
8440 // TODO: The FMA node should have flags that propagate to this node.
8441 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8443 if (N1CFP->isExactlyValue(-1.0) &&
8444 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8445 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8446 AddToWorklist(RHSNeg.getNode());
8447 // TODO: The FMA node should have flags that propagate to this node.
8448 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8452 if (Options.UnsafeFPMath) {
8453 // (fma x, c, x) -> (fmul x, (c+1))
8454 if (N1CFP && N0 == N2) {
8455 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8456 DAG.getNode(ISD::FADD, dl, VT,
8457 N1, DAG.getConstantFP(1.0, dl, VT),
8461 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8462 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8463 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8464 DAG.getNode(ISD::FADD, dl, VT,
8465 N1, DAG.getConstantFP(-1.0, dl, VT),
8473 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8475 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8476 // Notice that this is not always beneficial. One reason is different target
8477 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8478 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8479 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8480 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8481 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8482 const SDNodeFlags *Flags = N->getFlags();
8483 if (!UnsafeMath && !Flags->hasAllowReciprocal())
8486 // Skip if current node is a reciprocal.
8487 SDValue N0 = N->getOperand(0);
8488 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8489 if (N0CFP && N0CFP->isExactlyValue(1.0))
8492 // Exit early if the target does not want this transform or if there can't
8493 // possibly be enough uses of the divisor to make the transform worthwhile.
8494 SDValue N1 = N->getOperand(1);
8495 unsigned MinUses = TLI.combineRepeatedFPDivisors();
8496 if (!MinUses || N1->use_size() < MinUses)
8499 // Find all FDIV users of the same divisor.
8500 // Use a set because duplicates may be present in the user list.
8501 SetVector<SDNode *> Users;
8502 for (auto *U : N1->uses()) {
8503 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8504 // This division is eligible for optimization only if global unsafe math
8505 // is enabled or if this division allows reciprocal formation.
8506 if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8511 // Now that we have the actual number of divisor uses, make sure it meets
8512 // the minimum threshold specified by the target.
8513 if (Users.size() < MinUses)
8516 EVT VT = N->getValueType(0);
8518 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8519 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8521 // Dividend / Divisor -> Dividend * Reciprocal
8522 for (auto *U : Users) {
8523 SDValue Dividend = U->getOperand(0);
8524 if (Dividend != FPOne) {
8525 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8527 CombineTo(U, NewNode);
8528 } else if (U != Reciprocal.getNode()) {
8529 // In the absence of fast-math-flags, this user node is always the
8530 // same node as Reciprocal, but with FMF they may be different nodes.
8531 CombineTo(U, Reciprocal);
8534 return SDValue(N, 0); // N was replaced.
8537 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8538 SDValue N0 = N->getOperand(0);
8539 SDValue N1 = N->getOperand(1);
8540 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8541 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8542 EVT VT = N->getValueType(0);
8544 const TargetOptions &Options = DAG.getTarget().Options;
8545 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8549 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8552 // fold (fdiv c1, c2) -> c1/c2
8554 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8556 if (Options.UnsafeFPMath) {
8557 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8559 // Compute the reciprocal 1.0 / c2.
8560 APFloat N1APF = N1CFP->getValueAPF();
8561 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8562 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8563 // Only do the transform if the reciprocal is a legal fp immediate that
8564 // isn't too nasty (eg NaN, denormal, ...).
8565 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8566 (!LegalOperations ||
8567 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8568 // backend)... we should handle this gracefully after Legalize.
8569 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8570 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8571 TLI.isFPImmLegal(Recip, VT)))
8572 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8573 DAG.getConstantFP(Recip, DL, VT), Flags);
8576 // If this FDIV is part of a reciprocal square root, it may be folded
8577 // into a target-specific square root estimate instruction.
8578 if (N1.getOpcode() == ISD::FSQRT) {
8579 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8580 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8582 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8583 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8584 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8586 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8587 AddToWorklist(RV.getNode());
8588 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8590 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8591 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8592 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8594 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8595 AddToWorklist(RV.getNode());
8596 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8598 } else if (N1.getOpcode() == ISD::FMUL) {
8599 // Look through an FMUL. Even though this won't remove the FDIV directly,
8600 // it's still worthwhile to get rid of the FSQRT if possible.
8603 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8604 SqrtOp = N1.getOperand(0);
8605 OtherOp = N1.getOperand(1);
8606 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8607 SqrtOp = N1.getOperand(1);
8608 OtherOp = N1.getOperand(0);
8610 if (SqrtOp.getNode()) {
8611 // We found a FSQRT, so try to make this fold:
8612 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8613 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8614 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8615 AddToWorklist(RV.getNode());
8616 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8621 // Fold into a reciprocal estimate and multiply instead of a real divide.
8622 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8623 AddToWorklist(RV.getNode());
8624 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8628 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8629 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8630 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8631 // Both can be negated for free, check to see if at least one is cheaper
8633 if (LHSNeg == 2 || RHSNeg == 2)
8634 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8635 GetNegatedExpression(N0, DAG, LegalOperations),
8636 GetNegatedExpression(N1, DAG, LegalOperations),
8641 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8642 return CombineRepeatedDivisors;
8647 SDValue DAGCombiner::visitFREM(SDNode *N) {
8648 SDValue N0 = N->getOperand(0);
8649 SDValue N1 = N->getOperand(1);
8650 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8651 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8652 EVT VT = N->getValueType(0);
8654 // fold (frem c1, c2) -> fmod(c1,c2)
8656 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8657 &cast<BinaryWithFlagsSDNode>(N)->Flags);
8662 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8663 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8666 // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8667 // For now, create a Flags object for use with all unsafe math transforms.
8669 Flags.setUnsafeAlgebra(true);
8671 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8672 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8676 EVT VT = RV.getValueType();
8678 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8679 AddToWorklist(RV.getNode());
8681 // Unfortunately, RV is now NaN if the input was exactly 0.
8682 // Select out this case and force the answer to 0.
8683 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8684 EVT CCVT = getSetCCResultType(VT);
8685 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8686 AddToWorklist(ZeroCmp.getNode());
8687 AddToWorklist(RV.getNode());
8689 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8693 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8694 SDValue N0 = N->getOperand(0);
8695 SDValue N1 = N->getOperand(1);
8696 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8697 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8698 EVT VT = N->getValueType(0);
8700 if (N0CFP && N1CFP) // Constant fold
8701 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8704 const APFloat& V = N1CFP->getValueAPF();
8705 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8706 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8707 if (!V.isNegative()) {
8708 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8709 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8711 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8712 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8713 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8717 // copysign(fabs(x), y) -> copysign(x, y)
8718 // copysign(fneg(x), y) -> copysign(x, y)
8719 // copysign(copysign(x,z), y) -> copysign(x, y)
8720 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8721 N0.getOpcode() == ISD::FCOPYSIGN)
8722 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8723 N0.getOperand(0), N1);
8725 // copysign(x, abs(y)) -> abs(x)
8726 if (N1.getOpcode() == ISD::FABS)
8727 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8729 // copysign(x, copysign(y,z)) -> copysign(x, z)
8730 if (N1.getOpcode() == ISD::FCOPYSIGN)
8731 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8732 N0, N1.getOperand(1));
8734 // copysign(x, fp_extend(y)) -> copysign(x, y)
8735 // copysign(x, fp_round(y)) -> copysign(x, y)
8736 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8737 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8738 N0, N1.getOperand(0));
8743 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8744 SDValue N0 = N->getOperand(0);
8745 EVT VT = N->getValueType(0);
8746 EVT OpVT = N0.getValueType();
8748 // fold (sint_to_fp c1) -> c1fp
8749 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8750 // ...but only if the target supports immediate floating-point values
8751 (!LegalOperations ||
8752 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8753 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8755 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8756 // but UINT_TO_FP is legal on this target, try to convert.
8757 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8758 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8759 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8760 if (DAG.SignBitIsZero(N0))
8761 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8764 // The next optimizations are desirable only if SELECT_CC can be lowered.
8765 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8766 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8767 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8769 (!LegalOperations ||
8770 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8773 { N0.getOperand(0), N0.getOperand(1),
8774 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8776 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8779 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8780 // (select_cc x, y, 1.0, 0.0,, cc)
8781 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8782 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8783 (!LegalOperations ||
8784 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8787 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8788 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8789 N0.getOperand(0).getOperand(2) };
8790 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8797 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8798 SDValue N0 = N->getOperand(0);
8799 EVT VT = N->getValueType(0);
8800 EVT OpVT = N0.getValueType();
8802 // fold (uint_to_fp c1) -> c1fp
8803 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8804 // ...but only if the target supports immediate floating-point values
8805 (!LegalOperations ||
8806 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8807 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8809 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8810 // but SINT_TO_FP is legal on this target, try to convert.
8811 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8812 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8813 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8814 if (DAG.SignBitIsZero(N0))
8815 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8818 // The next optimizations are desirable only if SELECT_CC can be lowered.
8819 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8820 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8822 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8823 (!LegalOperations ||
8824 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8827 { N0.getOperand(0), N0.getOperand(1),
8828 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8830 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8837 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8838 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8839 SDValue N0 = N->getOperand(0);
8840 EVT VT = N->getValueType(0);
8842 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8845 SDValue Src = N0.getOperand(0);
8846 EVT SrcVT = Src.getValueType();
8847 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8848 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8850 // We can safely assume the conversion won't overflow the output range,
8851 // because (for example) (uint8_t)18293.f is undefined behavior.
8853 // Since we can assume the conversion won't overflow, our decision as to
8854 // whether the input will fit in the float should depend on the minimum
8855 // of the input range and output range.
8857 // This means this is also safe for a signed input and unsigned output, since
8858 // a negative input would lead to undefined behavior.
8859 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8860 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8861 unsigned ActualSize = std::min(InputSize, OutputSize);
8862 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8864 // We can only fold away the float conversion if the input range can be
8865 // represented exactly in the float range.
8866 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8867 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8868 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8870 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8872 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8873 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8876 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8881 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8882 SDValue N0 = N->getOperand(0);
8883 EVT VT = N->getValueType(0);
8885 // fold (fp_to_sint c1fp) -> c1
8886 if (isConstantFPBuildVectorOrConstantFP(N0))
8887 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8889 return FoldIntToFPToInt(N, DAG);
8892 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8893 SDValue N0 = N->getOperand(0);
8894 EVT VT = N->getValueType(0);
8896 // fold (fp_to_uint c1fp) -> c1
8897 if (isConstantFPBuildVectorOrConstantFP(N0))
8898 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8900 return FoldIntToFPToInt(N, DAG);
8903 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8904 SDValue N0 = N->getOperand(0);
8905 SDValue N1 = N->getOperand(1);
8906 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8907 EVT VT = N->getValueType(0);
8909 // fold (fp_round c1fp) -> c1fp
8911 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8913 // fold (fp_round (fp_extend x)) -> x
8914 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8915 return N0.getOperand(0);
8917 // fold (fp_round (fp_round x)) -> (fp_round x)
8918 if (N0.getOpcode() == ISD::FP_ROUND) {
8919 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8920 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8921 // If the first fp_round isn't a value preserving truncation, it might
8922 // introduce a tie in the second fp_round, that wouldn't occur in the
8923 // single-step fp_round we want to fold to.
8924 // In other words, double rounding isn't the same as rounding.
8925 // Also, this is a value preserving truncation iff both fp_round's are.
8926 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8928 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8929 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8933 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8934 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8935 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8936 N0.getOperand(0), N1);
8937 AddToWorklist(Tmp.getNode());
8938 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8939 Tmp, N0.getOperand(1));
8945 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8946 SDValue N0 = N->getOperand(0);
8947 EVT VT = N->getValueType(0);
8948 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8949 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8951 // fold (fp_round_inreg c1fp) -> c1fp
8952 if (N0CFP && isTypeLegal(EVT)) {
8954 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8955 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8961 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8962 SDValue N0 = N->getOperand(0);
8963 EVT VT = N->getValueType(0);
8965 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8966 if (N->hasOneUse() &&
8967 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8970 // fold (fp_extend c1fp) -> c1fp
8971 if (isConstantFPBuildVectorOrConstantFP(N0))
8972 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8974 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8975 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8976 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8977 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8979 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8981 if (N0.getOpcode() == ISD::FP_ROUND
8982 && N0.getNode()->getConstantOperandVal(1) == 1) {
8983 SDValue In = N0.getOperand(0);
8984 if (In.getValueType() == VT) return In;
8985 if (VT.bitsLT(In.getValueType()))
8986 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8987 In, N0.getOperand(1));
8988 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8991 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8992 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8993 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8994 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8995 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8997 LN0->getBasePtr(), N0.getValueType(),
8998 LN0->getMemOperand());
8999 CombineTo(N, ExtLoad);
9000 CombineTo(N0.getNode(),
9001 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9002 N0.getValueType(), ExtLoad,
9003 DAG.getIntPtrConstant(1, SDLoc(N0))),
9004 ExtLoad.getValue(1));
9005 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9011 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9012 SDValue N0 = N->getOperand(0);
9013 EVT VT = N->getValueType(0);
9015 // fold (fceil c1) -> fceil(c1)
9016 if (isConstantFPBuildVectorOrConstantFP(N0))
9017 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9022 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9023 SDValue N0 = N->getOperand(0);
9024 EVT VT = N->getValueType(0);
9026 // fold (ftrunc c1) -> ftrunc(c1)
9027 if (isConstantFPBuildVectorOrConstantFP(N0))
9028 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9033 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9034 SDValue N0 = N->getOperand(0);
9035 EVT VT = N->getValueType(0);
9037 // fold (ffloor c1) -> ffloor(c1)
9038 if (isConstantFPBuildVectorOrConstantFP(N0))
9039 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9044 // FIXME: FNEG and FABS have a lot in common; refactor.
9045 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9046 SDValue N0 = N->getOperand(0);
9047 EVT VT = N->getValueType(0);
9049 // Constant fold FNEG.
9050 if (isConstantFPBuildVectorOrConstantFP(N0))
9051 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9053 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9054 &DAG.getTarget().Options))
9055 return GetNegatedExpression(N0, DAG, LegalOperations);
9057 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9058 // constant pool values.
9059 if (!TLI.isFNegFree(VT) &&
9060 N0.getOpcode() == ISD::BITCAST &&
9061 N0.getNode()->hasOneUse()) {
9062 SDValue Int = N0.getOperand(0);
9063 EVT IntVT = Int.getValueType();
9064 if (IntVT.isInteger() && !IntVT.isVector()) {
9066 if (N0.getValueType().isVector()) {
9067 // For a vector, get a mask such as 0x80... per scalar element
9069 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9070 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9072 // For a scalar, just generate 0x80...
9073 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9076 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9077 DAG.getConstant(SignMask, DL0, IntVT));
9078 AddToWorklist(Int.getNode());
9079 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9083 // (fneg (fmul c, x)) -> (fmul -c, x)
9084 if (N0.getOpcode() == ISD::FMUL &&
9085 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9086 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9088 APFloat CVal = CFP1->getValueAPF();
9090 if (Level >= AfterLegalizeDAG &&
9091 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9092 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9093 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9094 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9096 &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9103 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9104 SDValue N0 = N->getOperand(0);
9105 SDValue N1 = N->getOperand(1);
9106 EVT VT = N->getValueType(0);
9107 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9108 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9110 if (N0CFP && N1CFP) {
9111 const APFloat &C0 = N0CFP->getValueAPF();
9112 const APFloat &C1 = N1CFP->getValueAPF();
9113 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9116 // Canonicalize to constant on RHS.
9117 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9118 !isConstantFPBuildVectorOrConstantFP(N1))
9119 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9124 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9125 SDValue N0 = N->getOperand(0);
9126 SDValue N1 = N->getOperand(1);
9127 EVT VT = N->getValueType(0);
9128 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9129 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9131 if (N0CFP && N1CFP) {
9132 const APFloat &C0 = N0CFP->getValueAPF();
9133 const APFloat &C1 = N1CFP->getValueAPF();
9134 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9137 // Canonicalize to constant on RHS.
9138 if (isConstantFPBuildVectorOrConstantFP(N0) &&
9139 !isConstantFPBuildVectorOrConstantFP(N1))
9140 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9145 SDValue DAGCombiner::visitFABS(SDNode *N) {
9146 SDValue N0 = N->getOperand(0);
9147 EVT VT = N->getValueType(0);
9149 // fold (fabs c1) -> fabs(c1)
9150 if (isConstantFPBuildVectorOrConstantFP(N0))
9151 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9153 // fold (fabs (fabs x)) -> (fabs x)
9154 if (N0.getOpcode() == ISD::FABS)
9155 return N->getOperand(0);
9157 // fold (fabs (fneg x)) -> (fabs x)
9158 // fold (fabs (fcopysign x, y)) -> (fabs x)
9159 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9160 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9162 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9163 // constant pool values.
9164 if (!TLI.isFAbsFree(VT) &&
9165 N0.getOpcode() == ISD::BITCAST &&
9166 N0.getNode()->hasOneUse()) {
9167 SDValue Int = N0.getOperand(0);
9168 EVT IntVT = Int.getValueType();
9169 if (IntVT.isInteger() && !IntVT.isVector()) {
9171 if (N0.getValueType().isVector()) {
9172 // For a vector, get a mask such as 0x7f... per scalar element
9174 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9175 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9177 // For a scalar, just generate 0x7f...
9178 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9181 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9182 DAG.getConstant(SignMask, DL, IntVT));
9183 AddToWorklist(Int.getNode());
9184 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9191 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9192 SDValue Chain = N->getOperand(0);
9193 SDValue N1 = N->getOperand(1);
9194 SDValue N2 = N->getOperand(2);
9196 // If N is a constant we could fold this into a fallthrough or unconditional
9197 // branch. However that doesn't happen very often in normal code, because
9198 // Instcombine/SimplifyCFG should have handled the available opportunities.
9199 // If we did this folding here, it would be necessary to update the
9200 // MachineBasicBlock CFG, which is awkward.
9202 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9204 if (N1.getOpcode() == ISD::SETCC &&
9205 TLI.isOperationLegalOrCustom(ISD::BR_CC,
9206 N1.getOperand(0).getValueType())) {
9207 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9208 Chain, N1.getOperand(2),
9209 N1.getOperand(0), N1.getOperand(1), N2);
9212 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9213 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9214 (N1.getOperand(0).hasOneUse() &&
9215 N1.getOperand(0).getOpcode() == ISD::SRL))) {
9216 SDNode *Trunc = nullptr;
9217 if (N1.getOpcode() == ISD::TRUNCATE) {
9218 // Look pass the truncate.
9219 Trunc = N1.getNode();
9220 N1 = N1.getOperand(0);
9223 // Match this pattern so that we can generate simpler code:
9226 // %b = and i32 %a, 2
9227 // %c = srl i32 %b, 1
9228 // brcond i32 %c ...
9233 // %b = and i32 %a, 2
9234 // %c = setcc eq %b, 0
9237 // This applies only when the AND constant value has one bit set and the
9238 // SRL constant is equal to the log2 of the AND constant. The back-end is
9239 // smart enough to convert the result into a TEST/JMP sequence.
9240 SDValue Op0 = N1.getOperand(0);
9241 SDValue Op1 = N1.getOperand(1);
9243 if (Op0.getOpcode() == ISD::AND &&
9244 Op1.getOpcode() == ISD::Constant) {
9245 SDValue AndOp1 = Op0.getOperand(1);
9247 if (AndOp1.getOpcode() == ISD::Constant) {
9248 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9250 if (AndConst.isPowerOf2() &&
9251 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9255 getSetCCResultType(Op0.getValueType()),
9256 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9259 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9260 MVT::Other, Chain, SetCC, N2);
9261 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9262 // will convert it back to (X & C1) >> C2.
9263 CombineTo(N, NewBRCond, false);
9264 // Truncate is dead.
9266 deleteAndRecombine(Trunc);
9267 // Replace the uses of SRL with SETCC
9268 WorklistRemover DeadNodes(*this);
9269 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9270 deleteAndRecombine(N1.getNode());
9271 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9277 // Restore N1 if the above transformation doesn't match.
9278 N1 = N->getOperand(1);
9281 // Transform br(xor(x, y)) -> br(x != y)
9282 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9283 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9284 SDNode *TheXor = N1.getNode();
9285 SDValue Op0 = TheXor->getOperand(0);
9286 SDValue Op1 = TheXor->getOperand(1);
9287 if (Op0.getOpcode() == Op1.getOpcode()) {
9288 // Avoid missing important xor optimizations.
9289 if (SDValue Tmp = visitXOR(TheXor)) {
9290 if (Tmp.getNode() != TheXor) {
9291 DEBUG(dbgs() << "\nReplacing.8 ";
9293 dbgs() << "\nWith: ";
9294 Tmp.getNode()->dump(&DAG);
9296 WorklistRemover DeadNodes(*this);
9297 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9298 deleteAndRecombine(TheXor);
9299 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9300 MVT::Other, Chain, Tmp, N2);
9303 // visitXOR has changed XOR's operands or replaced the XOR completely,
9305 return SDValue(N, 0);
9309 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9311 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9312 Op0.getOpcode() == ISD::XOR) {
9313 TheXor = Op0.getNode();
9317 EVT SetCCVT = N1.getValueType();
9319 SetCCVT = getSetCCResultType(SetCCVT);
9320 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9323 Equal ? ISD::SETEQ : ISD::SETNE);
9324 // Replace the uses of XOR with SETCC
9325 WorklistRemover DeadNodes(*this);
9326 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9327 deleteAndRecombine(N1.getNode());
9328 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9329 MVT::Other, Chain, SetCC, N2);
9336 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9338 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9339 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9340 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9342 // If N is a constant we could fold this into a fallthrough or unconditional
9343 // branch. However that doesn't happen very often in normal code, because
9344 // Instcombine/SimplifyCFG should have handled the available opportunities.
9345 // If we did this folding here, it would be necessary to update the
9346 // MachineBasicBlock CFG, which is awkward.
9348 // Use SimplifySetCC to simplify SETCC's.
9349 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9350 CondLHS, CondRHS, CC->get(), SDLoc(N),
9352 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9354 // fold to a simpler setcc
9355 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9356 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9357 N->getOperand(0), Simp.getOperand(2),
9358 Simp.getOperand(0), Simp.getOperand(1),
9364 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9365 /// and that N may be folded in the load / store addressing mode.
9366 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9368 const TargetLowering &TLI) {
9372 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9373 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9375 VT = LD->getMemoryVT();
9376 AS = LD->getAddressSpace();
9377 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9378 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9380 VT = ST->getMemoryVT();
9381 AS = ST->getAddressSpace();
9385 TargetLowering::AddrMode AM;
9386 if (N->getOpcode() == ISD::ADD) {
9387 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9390 AM.BaseOffs = Offset->getSExtValue();
9394 } else if (N->getOpcode() == ISD::SUB) {
9395 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9398 AM.BaseOffs = -Offset->getSExtValue();
9405 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9406 VT.getTypeForEVT(*DAG.getContext()), AS);
9409 /// Try turning a load/store into a pre-indexed load/store when the base
9410 /// pointer is an add or subtract and it has other uses besides the load/store.
9411 /// After the transformation, the new indexed load/store has effectively folded
9412 /// the add/subtract in and all of its other uses are redirected to the
9414 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9415 if (Level < AfterLegalizeDAG)
9421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9422 if (LD->isIndexed())
9424 VT = LD->getMemoryVT();
9425 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9426 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9428 Ptr = LD->getBasePtr();
9429 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9430 if (ST->isIndexed())
9432 VT = ST->getMemoryVT();
9433 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9434 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9436 Ptr = ST->getBasePtr();
9442 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9443 // out. There is no reason to make this a preinc/predec.
9444 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9445 Ptr.getNode()->hasOneUse())
9448 // Ask the target to do addressing mode selection.
9451 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9452 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9455 // Backends without true r+i pre-indexed forms may need to pass a
9456 // constant base with a variable offset so that constant coercion
9457 // will work with the patterns in canonical form.
9458 bool Swapped = false;
9459 if (isa<ConstantSDNode>(BasePtr)) {
9460 std::swap(BasePtr, Offset);
9464 // Don't create a indexed load / store with zero offset.
9465 if (isNullConstant(Offset))
9468 // Try turning it into a pre-indexed load / store except when:
9469 // 1) The new base ptr is a frame index.
9470 // 2) If N is a store and the new base ptr is either the same as or is a
9471 // predecessor of the value being stored.
9472 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9473 // that would create a cycle.
9474 // 4) All uses are load / store ops that use it as old base ptr.
9476 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9477 // (plus the implicit offset) to a register to preinc anyway.
9478 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9483 SDValue Val = cast<StoreSDNode>(N)->getValue();
9484 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9488 // If the offset is a constant, there may be other adds of constants that
9489 // can be folded with this one. We should do this to avoid having to keep
9490 // a copy of the original base pointer.
9491 SmallVector<SDNode *, 16> OtherUses;
9492 if (isa<ConstantSDNode>(Offset))
9493 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9494 UE = BasePtr.getNode()->use_end();
9496 SDUse &Use = UI.getUse();
9497 // Skip the use that is Ptr and uses of other results from BasePtr's
9498 // node (important for nodes that return multiple results).
9499 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9502 if (Use.getUser()->isPredecessorOf(N))
9505 if (Use.getUser()->getOpcode() != ISD::ADD &&
9506 Use.getUser()->getOpcode() != ISD::SUB) {
9511 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9512 if (!isa<ConstantSDNode>(Op1)) {
9517 // FIXME: In some cases, we can be smarter about this.
9518 if (Op1.getValueType() != Offset.getValueType()) {
9523 OtherUses.push_back(Use.getUser());
9527 std::swap(BasePtr, Offset);
9529 // Now check for #3 and #4.
9530 bool RealUse = false;
9532 // Caches for hasPredecessorHelper
9533 SmallPtrSet<const SDNode *, 32> Visited;
9534 SmallVector<const SDNode *, 16> Worklist;
9536 for (SDNode *Use : Ptr.getNode()->uses()) {
9539 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9542 // If Ptr may be folded in addressing mode of other use, then it's
9543 // not profitable to do this transformation.
9544 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9553 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9554 BasePtr, Offset, AM);
9556 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9557 BasePtr, Offset, AM);
9560 DEBUG(dbgs() << "\nReplacing.4 ";
9562 dbgs() << "\nWith: ";
9563 Result.getNode()->dump(&DAG);
9565 WorklistRemover DeadNodes(*this);
9567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9568 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9570 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9573 // Finally, since the node is now dead, remove it from the graph.
9574 deleteAndRecombine(N);
9577 std::swap(BasePtr, Offset);
9579 // Replace other uses of BasePtr that can be updated to use Ptr
9580 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9581 unsigned OffsetIdx = 1;
9582 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9584 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9585 BasePtr.getNode() && "Expected BasePtr operand");
9587 // We need to replace ptr0 in the following expression:
9588 // x0 * offset0 + y0 * ptr0 = t0
9590 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9592 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9593 // indexed load/store and the expresion that needs to be re-written.
9595 // Therefore, we have:
9596 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9598 ConstantSDNode *CN =
9599 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9601 APInt Offset0 = CN->getAPIntValue();
9602 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9604 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9605 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9606 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9607 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9609 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9611 APInt CNV = Offset0;
9612 if (X0 < 0) CNV = -CNV;
9613 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9614 else CNV = CNV - Offset1;
9616 SDLoc DL(OtherUses[i]);
9618 // We can now generate the new expression.
9619 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9620 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9622 SDValue NewUse = DAG.getNode(Opcode,
9624 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9625 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9626 deleteAndRecombine(OtherUses[i]);
9629 // Replace the uses of Ptr with uses of the updated base value.
9630 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9631 deleteAndRecombine(Ptr.getNode());
9636 /// Try to combine a load/store with a add/sub of the base pointer node into a
9637 /// post-indexed load/store. The transformation folded the add/subtract into the
9638 /// new indexed load/store effectively and all of its uses are redirected to the
9640 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9641 if (Level < AfterLegalizeDAG)
9647 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9648 if (LD->isIndexed())
9650 VT = LD->getMemoryVT();
9651 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9652 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9654 Ptr = LD->getBasePtr();
9655 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9656 if (ST->isIndexed())
9658 VT = ST->getMemoryVT();
9659 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9660 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9662 Ptr = ST->getBasePtr();
9668 if (Ptr.getNode()->hasOneUse())
9671 for (SDNode *Op : Ptr.getNode()->uses()) {
9673 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9678 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9679 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9680 // Don't create a indexed load / store with zero offset.
9681 if (isNullConstant(Offset))
9684 // Try turning it into a post-indexed load / store except when
9685 // 1) All uses are load / store ops that use it as base ptr (and
9686 // it may be folded as addressing mmode).
9687 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9688 // nor a successor of N. Otherwise, if Op is folded that would
9691 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9695 bool TryNext = false;
9696 for (SDNode *Use : BasePtr.getNode()->uses()) {
9697 if (Use == Ptr.getNode())
9700 // If all the uses are load / store addresses, then don't do the
9702 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9703 bool RealUse = false;
9704 for (SDNode *UseUse : Use->uses()) {
9705 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9720 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9721 SDValue Result = isLoad
9722 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9723 BasePtr, Offset, AM)
9724 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9725 BasePtr, Offset, AM);
9728 DEBUG(dbgs() << "\nReplacing.5 ";
9730 dbgs() << "\nWith: ";
9731 Result.getNode()->dump(&DAG);
9733 WorklistRemover DeadNodes(*this);
9735 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9738 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9741 // Finally, since the node is now dead, remove it from the graph.
9742 deleteAndRecombine(N);
9744 // Replace the uses of Use with uses of the updated base value.
9745 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9746 Result.getValue(isLoad ? 1 : 0));
9747 deleteAndRecombine(Op);
9756 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9757 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9758 ISD::MemIndexedMode AM = LD->getAddressingMode();
9759 assert(AM != ISD::UNINDEXED);
9760 SDValue BP = LD->getOperand(1);
9761 SDValue Inc = LD->getOperand(2);
9763 // Some backends use TargetConstants for load offsets, but don't expect
9764 // TargetConstants in general ADD nodes. We can convert these constants into
9765 // regular Constants (if the constant is not opaque).
9766 assert((Inc.getOpcode() != ISD::TargetConstant ||
9767 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9768 "Cannot split out indexing using opaque target constants");
9769 if (Inc.getOpcode() == ISD::TargetConstant) {
9770 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9771 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9772 ConstInc->getValueType(0));
9776 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9777 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9780 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9781 LoadSDNode *LD = cast<LoadSDNode>(N);
9782 SDValue Chain = LD->getChain();
9783 SDValue Ptr = LD->getBasePtr();
9785 // If load is not volatile and there are no uses of the loaded value (and
9786 // the updated indexed value in case of indexed loads), change uses of the
9787 // chain value into uses of the chain input (i.e. delete the dead load).
9788 if (!LD->isVolatile()) {
9789 if (N->getValueType(1) == MVT::Other) {
9791 if (!N->hasAnyUseOfValue(0)) {
9792 // It's not safe to use the two value CombineTo variant here. e.g.
9793 // v1, chain2 = load chain1, loc
9794 // v2, chain3 = load chain2, loc
9796 // Now we replace use of chain2 with chain1. This makes the second load
9797 // isomorphic to the one we are deleting, and thus makes this load live.
9798 DEBUG(dbgs() << "\nReplacing.6 ";
9800 dbgs() << "\nWith chain: ";
9801 Chain.getNode()->dump(&DAG);
9803 WorklistRemover DeadNodes(*this);
9804 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9807 deleteAndRecombine(N);
9809 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9813 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9815 // If this load has an opaque TargetConstant offset, then we cannot split
9816 // the indexing into an add/sub directly (that TargetConstant may not be
9817 // valid for a different type of node, and we cannot convert an opaque
9818 // target constant into a regular constant).
9819 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9820 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9822 if (!N->hasAnyUseOfValue(0) &&
9823 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9824 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9826 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9827 Index = SplitIndexingFromLoad(LD);
9828 // Try to fold the base pointer arithmetic into subsequent loads and
9830 AddUsersToWorklist(N);
9832 Index = DAG.getUNDEF(N->getValueType(1));
9833 DEBUG(dbgs() << "\nReplacing.7 ";
9835 dbgs() << "\nWith: ";
9836 Undef.getNode()->dump(&DAG);
9837 dbgs() << " and 2 other values\n");
9838 WorklistRemover DeadNodes(*this);
9839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9840 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9842 deleteAndRecombine(N);
9843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9848 // If this load is directly stored, replace the load value with the stored
9850 // TODO: Handle store large -> read small portion.
9851 // TODO: Handle TRUNCSTORE/LOADEXT
9852 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9853 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9854 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9855 if (PrevST->getBasePtr() == Ptr &&
9856 PrevST->getValue().getValueType() == N->getValueType(0))
9857 return CombineTo(N, Chain.getOperand(1), Chain);
9861 // Try to infer better alignment information than the load already has.
9862 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9863 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9864 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9866 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9867 LD->getValueType(0),
9868 Chain, Ptr, LD->getPointerInfo(),
9870 LD->isVolatile(), LD->isNonTemporal(),
9871 LD->isInvariant(), Align, LD->getAAInfo());
9872 if (NewLoad.getNode() != N)
9873 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9878 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9879 : DAG.getSubtarget().useAA();
9881 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9882 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9885 if (UseAA && LD->isUnindexed()) {
9886 // Walk up chain skipping non-aliasing memory nodes.
9887 SDValue BetterChain = FindBetterChain(N, Chain);
9889 // If there is a better chain.
9890 if (Chain != BetterChain) {
9893 // Replace the chain to void dependency.
9894 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9895 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9896 BetterChain, Ptr, LD->getMemOperand());
9898 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9899 LD->getValueType(0),
9900 BetterChain, Ptr, LD->getMemoryVT(),
9901 LD->getMemOperand());
9904 // Create token factor to keep old chain connected.
9905 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9906 MVT::Other, Chain, ReplLoad.getValue(1));
9908 // Make sure the new and old chains are cleaned up.
9909 AddToWorklist(Token.getNode());
9911 // Replace uses with load result and token factor. Don't add users
9913 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9917 // Try transforming N to an indexed load.
9918 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9919 return SDValue(N, 0);
9921 // Try to slice up N to more direct loads if the slices are mapped to
9922 // different register banks or pairing can take place.
9924 return SDValue(N, 0);
9930 /// \brief Helper structure used to slice a load in smaller loads.
9931 /// Basically a slice is obtained from the following sequence:
9932 /// Origin = load Ty1, Base
9933 /// Shift = srl Ty1 Origin, CstTy Amount
9934 /// Inst = trunc Shift to Ty2
9936 /// Then, it will be rewriten into:
9937 /// Slice = load SliceTy, Base + SliceOffset
9938 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9940 /// SliceTy is deduced from the number of bits that are actually used to
9942 struct LoadedSlice {
9943 /// \brief Helper structure used to compute the cost of a slice.
9945 /// Are we optimizing for code size.
9950 unsigned CrossRegisterBanksCopies;
9954 Cost(bool ForCodeSize = false)
9955 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9956 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9958 /// \brief Get the cost of one isolated slice.
9959 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9960 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9961 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9962 EVT TruncType = LS.Inst->getValueType(0);
9963 EVT LoadedType = LS.getLoadedType();
9964 if (TruncType != LoadedType &&
9965 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9969 /// \brief Account for slicing gain in the current cost.
9970 /// Slicing provide a few gains like removing a shift or a
9971 /// truncate. This method allows to grow the cost of the original
9972 /// load with the gain from this slice.
9973 void addSliceGain(const LoadedSlice &LS) {
9974 // Each slice saves a truncate.
9975 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9976 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9977 LS.Inst->getValueType(0)))
9979 // If there is a shift amount, this slice gets rid of it.
9982 // If this slice can merge a cross register bank copy, account for it.
9983 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9984 ++CrossRegisterBanksCopies;
9987 Cost &operator+=(const Cost &RHS) {
9989 Truncates += RHS.Truncates;
9990 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9996 bool operator==(const Cost &RHS) const {
9997 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9998 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9999 ZExts == RHS.ZExts && Shift == RHS.Shift;
10002 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10004 bool operator<(const Cost &RHS) const {
10005 // Assume cross register banks copies are as expensive as loads.
10006 // FIXME: Do we want some more target hooks?
10007 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10008 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10009 // Unless we are optimizing for code size, consider the
10010 // expensive operation first.
10011 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10012 return ExpensiveOpsLHS < ExpensiveOpsRHS;
10013 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10014 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10017 bool operator>(const Cost &RHS) const { return RHS < *this; }
10019 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10021 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10023 // The last instruction that represent the slice. This should be a
10024 // truncate instruction.
10026 // The original load instruction.
10027 LoadSDNode *Origin;
10028 // The right shift amount in bits from the original load.
10030 // The DAG from which Origin came from.
10031 // This is used to get some contextual information about legal types, etc.
10034 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10035 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10036 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10038 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10039 /// \return Result is \p BitWidth and has used bits set to 1 and
10040 /// not used bits set to 0.
10041 APInt getUsedBits() const {
10042 // Reproduce the trunc(lshr) sequence:
10043 // - Start from the truncated value.
10044 // - Zero extend to the desired bit width.
10046 assert(Origin && "No original load to compare against.");
10047 unsigned BitWidth = Origin->getValueSizeInBits(0);
10048 assert(Inst && "This slice is not bound to an instruction");
10049 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10050 "Extracted slice is bigger than the whole type!");
10051 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10052 UsedBits.setAllBits();
10053 UsedBits = UsedBits.zext(BitWidth);
10054 UsedBits <<= Shift;
10058 /// \brief Get the size of the slice to be loaded in bytes.
10059 unsigned getLoadedSize() const {
10060 unsigned SliceSize = getUsedBits().countPopulation();
10061 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10062 return SliceSize / 8;
10065 /// \brief Get the type that will be loaded for this slice.
10066 /// Note: This may not be the final type for the slice.
10067 EVT getLoadedType() const {
10068 assert(DAG && "Missing context");
10069 LLVMContext &Ctxt = *DAG->getContext();
10070 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10073 /// \brief Get the alignment of the load used for this slice.
10074 unsigned getAlignment() const {
10075 unsigned Alignment = Origin->getAlignment();
10076 unsigned Offset = getOffsetFromBase();
10078 Alignment = MinAlign(Alignment, Alignment + Offset);
10082 /// \brief Check if this slice can be rewritten with legal operations.
10083 bool isLegal() const {
10084 // An invalid slice is not legal.
10085 if (!Origin || !Inst || !DAG)
10088 // Offsets are for indexed load only, we do not handle that.
10089 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10092 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10094 // Check that the type is legal.
10095 EVT SliceType = getLoadedType();
10096 if (!TLI.isTypeLegal(SliceType))
10099 // Check that the load is legal for this type.
10100 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10103 // Check that the offset can be computed.
10104 // 1. Check its type.
10105 EVT PtrType = Origin->getBasePtr().getValueType();
10106 if (PtrType == MVT::Untyped || PtrType.isExtended())
10109 // 2. Check that it fits in the immediate.
10110 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10113 // 3. Check that the computation is legal.
10114 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10117 // Check that the zext is legal if it needs one.
10118 EVT TruncateType = Inst->getValueType(0);
10119 if (TruncateType != SliceType &&
10120 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10126 /// \brief Get the offset in bytes of this slice in the original chunk of
10128 /// \pre DAG != nullptr.
10129 uint64_t getOffsetFromBase() const {
10130 assert(DAG && "Missing context.");
10131 bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10132 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10133 uint64_t Offset = Shift / 8;
10134 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10135 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10136 "The size of the original loaded type is not a multiple of a"
10138 // If Offset is bigger than TySizeInBytes, it means we are loading all
10139 // zeros. This should have been optimized before in the process.
10140 assert(TySizeInBytes > Offset &&
10141 "Invalid shift amount for given loaded size");
10143 Offset = TySizeInBytes - Offset - getLoadedSize();
10147 /// \brief Generate the sequence of instructions to load the slice
10148 /// represented by this object and redirect the uses of this slice to
10149 /// this new sequence of instructions.
10150 /// \pre this->Inst && this->Origin are valid Instructions and this
10151 /// object passed the legal check: LoadedSlice::isLegal returned true.
10152 /// \return The last instruction of the sequence used to load the slice.
10153 SDValue loadSlice() const {
10154 assert(Inst && Origin && "Unable to replace a non-existing slice.");
10155 const SDValue &OldBaseAddr = Origin->getBasePtr();
10156 SDValue BaseAddr = OldBaseAddr;
10157 // Get the offset in that chunk of bytes w.r.t. the endianess.
10158 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10159 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10161 // BaseAddr = BaseAddr + Offset.
10162 EVT ArithType = BaseAddr.getValueType();
10164 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10165 DAG->getConstant(Offset, DL, ArithType));
10168 // Create the type of the loaded slice according to its size.
10169 EVT SliceType = getLoadedType();
10171 // Create the load for the slice.
10172 SDValue LastInst = DAG->getLoad(
10173 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10174 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10175 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10176 // If the final type is not the same as the loaded type, this means that
10177 // we have to pad with zero. Create a zero extend for that.
10178 EVT FinalType = Inst->getValueType(0);
10179 if (SliceType != FinalType)
10181 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10185 /// \brief Check if this slice can be merged with an expensive cross register
10186 /// bank copy. E.g.,
10188 /// f = bitcast i32 i to float
10189 bool canMergeExpensiveCrossRegisterBankCopy() const {
10190 if (!Inst || !Inst->hasOneUse())
10192 SDNode *Use = *Inst->use_begin();
10193 if (Use->getOpcode() != ISD::BITCAST)
10195 assert(DAG && "Missing context");
10196 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10197 EVT ResVT = Use->getValueType(0);
10198 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10199 const TargetRegisterClass *ArgRC =
10200 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10201 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10204 // At this point, we know that we perform a cross-register-bank copy.
10205 // Check if it is expensive.
10206 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10207 // Assume bitcasts are cheap, unless both register classes do not
10208 // explicitly share a common sub class.
10209 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10212 // Check if it will be merged with the load.
10213 // 1. Check the alignment constraint.
10214 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10215 ResVT.getTypeForEVT(*DAG->getContext()));
10217 if (RequiredAlignment > getAlignment())
10220 // 2. Check that the load is a legal operation for that type.
10221 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10224 // 3. Check that we do not have a zext in the way.
10225 if (Inst->getValueType(0) != getLoadedType())
10233 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10234 /// \p UsedBits looks like 0..0 1..1 0..0.
10235 static bool areUsedBitsDense(const APInt &UsedBits) {
10236 // If all the bits are one, this is dense!
10237 if (UsedBits.isAllOnesValue())
10240 // Get rid of the unused bits on the right.
10241 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10242 // Get rid of the unused bits on the left.
10243 if (NarrowedUsedBits.countLeadingZeros())
10244 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10245 // Check that the chunk of bits is completely used.
10246 return NarrowedUsedBits.isAllOnesValue();
10249 /// \brief Check whether or not \p First and \p Second are next to each other
10250 /// in memory. This means that there is no hole between the bits loaded
10251 /// by \p First and the bits loaded by \p Second.
10252 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10253 const LoadedSlice &Second) {
10254 assert(First.Origin == Second.Origin && First.Origin &&
10255 "Unable to match different memory origins.");
10256 APInt UsedBits = First.getUsedBits();
10257 assert((UsedBits & Second.getUsedBits()) == 0 &&
10258 "Slices are not supposed to overlap.");
10259 UsedBits |= Second.getUsedBits();
10260 return areUsedBitsDense(UsedBits);
10263 /// \brief Adjust the \p GlobalLSCost according to the target
10264 /// paring capabilities and the layout of the slices.
10265 /// \pre \p GlobalLSCost should account for at least as many loads as
10266 /// there is in the slices in \p LoadedSlices.
10267 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10268 LoadedSlice::Cost &GlobalLSCost) {
10269 unsigned NumberOfSlices = LoadedSlices.size();
10270 // If there is less than 2 elements, no pairing is possible.
10271 if (NumberOfSlices < 2)
10274 // Sort the slices so that elements that are likely to be next to each
10275 // other in memory are next to each other in the list.
10276 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10277 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10278 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10279 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10281 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10282 // First (resp. Second) is the first (resp. Second) potentially candidate
10283 // to be placed in a paired load.
10284 const LoadedSlice *First = nullptr;
10285 const LoadedSlice *Second = nullptr;
10286 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10287 // Set the beginning of the pair.
10290 Second = &LoadedSlices[CurrSlice];
10292 // If First is NULL, it means we start a new pair.
10293 // Get to the next slice.
10297 EVT LoadedType = First->getLoadedType();
10299 // If the types of the slices are different, we cannot pair them.
10300 if (LoadedType != Second->getLoadedType())
10303 // Check if the target supplies paired loads for this type.
10304 unsigned RequiredAlignment = 0;
10305 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10306 // move to the next pair, this type is hopeless.
10310 // Check if we meet the alignment requirement.
10311 if (RequiredAlignment > First->getAlignment())
10314 // Check that both loads are next to each other in memory.
10315 if (!areSlicesNextToEachOther(*First, *Second))
10318 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10319 --GlobalLSCost.Loads;
10320 // Move to the next pair.
10325 /// \brief Check the profitability of all involved LoadedSlice.
10326 /// Currently, it is considered profitable if there is exactly two
10327 /// involved slices (1) which are (2) next to each other in memory, and
10328 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10330 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10331 /// the elements themselves.
10333 /// FIXME: When the cost model will be mature enough, we can relax
10334 /// constraints (1) and (2).
10335 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10336 const APInt &UsedBits, bool ForCodeSize) {
10337 unsigned NumberOfSlices = LoadedSlices.size();
10338 if (StressLoadSlicing)
10339 return NumberOfSlices > 1;
10342 if (NumberOfSlices != 2)
10346 if (!areUsedBitsDense(UsedBits))
10350 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10351 // The original code has one big load.
10352 OrigCost.Loads = 1;
10353 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10354 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10355 // Accumulate the cost of all the slices.
10356 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10357 GlobalSlicingCost += SliceCost;
10359 // Account as cost in the original configuration the gain obtained
10360 // with the current slices.
10361 OrigCost.addSliceGain(LS);
10364 // If the target supports paired load, adjust the cost accordingly.
10365 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10366 return OrigCost > GlobalSlicingCost;
10369 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10370 /// operations, split it in the various pieces being extracted.
10372 /// This sort of thing is introduced by SROA.
10373 /// This slicing takes care not to insert overlapping loads.
10374 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10375 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10376 if (Level < AfterLegalizeDAG)
10379 LoadSDNode *LD = cast<LoadSDNode>(N);
10380 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10381 !LD->getValueType(0).isInteger())
10384 // Keep track of already used bits to detect overlapping values.
10385 // In that case, we will just abort the transformation.
10386 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10388 SmallVector<LoadedSlice, 4> LoadedSlices;
10390 // Check if this load is used as several smaller chunks of bits.
10391 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10392 // of computation for each trunc.
10393 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10394 UI != UIEnd; ++UI) {
10395 // Skip the uses of the chain.
10396 if (UI.getUse().getResNo() != 0)
10399 SDNode *User = *UI;
10400 unsigned Shift = 0;
10402 // Check if this is a trunc(lshr).
10403 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10404 isa<ConstantSDNode>(User->getOperand(1))) {
10405 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10406 User = *User->use_begin();
10409 // At this point, User is a Truncate, iff we encountered, trunc or
10411 if (User->getOpcode() != ISD::TRUNCATE)
10414 // The width of the type must be a power of 2 and greater than 8-bits.
10415 // Otherwise the load cannot be represented in LLVM IR.
10416 // Moreover, if we shifted with a non-8-bits multiple, the slice
10417 // will be across several bytes. We do not support that.
10418 unsigned Width = User->getValueSizeInBits(0);
10419 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10422 // Build the slice for this chain of computations.
10423 LoadedSlice LS(User, LD, Shift, &DAG);
10424 APInt CurrentUsedBits = LS.getUsedBits();
10426 // Check if this slice overlaps with another.
10427 if ((CurrentUsedBits & UsedBits) != 0)
10429 // Update the bits used globally.
10430 UsedBits |= CurrentUsedBits;
10432 // Check if the new slice would be legal.
10436 // Record the slice.
10437 LoadedSlices.push_back(LS);
10440 // Abort slicing if it does not seem to be profitable.
10441 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10446 // Rewrite each chain to use an independent load.
10447 // By construction, each chain can be represented by a unique load.
10449 // Prepare the argument for the new token factor for all the slices.
10450 SmallVector<SDValue, 8> ArgChains;
10451 for (SmallVectorImpl<LoadedSlice>::const_iterator
10452 LSIt = LoadedSlices.begin(),
10453 LSItEnd = LoadedSlices.end();
10454 LSIt != LSItEnd; ++LSIt) {
10455 SDValue SliceInst = LSIt->loadSlice();
10456 CombineTo(LSIt->Inst, SliceInst, true);
10457 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10458 SliceInst = SliceInst.getOperand(0);
10459 assert(SliceInst->getOpcode() == ISD::LOAD &&
10460 "It takes more than a zext to get to the loaded slice!!");
10461 ArgChains.push_back(SliceInst.getValue(1));
10464 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10470 /// Check to see if V is (and load (ptr), imm), where the load is having
10471 /// specific bytes cleared out. If so, return the byte size being masked out
10472 /// and the shift amount.
10473 static std::pair<unsigned, unsigned>
10474 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10475 std::pair<unsigned, unsigned> Result(0, 0);
10477 // Check for the structure we're looking for.
10478 if (V->getOpcode() != ISD::AND ||
10479 !isa<ConstantSDNode>(V->getOperand(1)) ||
10480 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10483 // Check the chain and pointer.
10484 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10485 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10487 // The store should be chained directly to the load or be an operand of a
10489 if (LD == Chain.getNode())
10491 else if (Chain->getOpcode() != ISD::TokenFactor)
10492 return Result; // Fail.
10495 for (const SDValue &ChainOp : Chain->op_values())
10496 if (ChainOp.getNode() == LD) {
10500 if (!isOk) return Result;
10503 // This only handles simple types.
10504 if (V.getValueType() != MVT::i16 &&
10505 V.getValueType() != MVT::i32 &&
10506 V.getValueType() != MVT::i64)
10509 // Check the constant mask. Invert it so that the bits being masked out are
10510 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10511 // follow the sign bit for uniformity.
10512 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10513 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10514 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10515 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10516 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10517 if (NotMaskLZ == 64) return Result; // All zero mask.
10519 // See if we have a continuous run of bits. If so, we have 0*1+0*
10520 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10523 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10524 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10525 NotMaskLZ -= 64-V.getValueSizeInBits();
10527 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10528 switch (MaskedBytes) {
10532 default: return Result; // All one mask, or 5-byte mask.
10535 // Verify that the first bit starts at a multiple of mask so that the access
10536 // is aligned the same as the access width.
10537 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10539 Result.first = MaskedBytes;
10540 Result.second = NotMaskTZ/8;
10545 /// Check to see if IVal is something that provides a value as specified by
10546 /// MaskInfo. If so, replace the specified store with a narrower store of
10547 /// truncated IVal.
10549 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10550 SDValue IVal, StoreSDNode *St,
10552 unsigned NumBytes = MaskInfo.first;
10553 unsigned ByteShift = MaskInfo.second;
10554 SelectionDAG &DAG = DC->getDAG();
10556 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10557 // that uses this. If not, this is not a replacement.
10558 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10559 ByteShift*8, (ByteShift+NumBytes)*8);
10560 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10562 // Check that it is legal on the target to do this. It is legal if the new
10563 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10565 MVT VT = MVT::getIntegerVT(NumBytes*8);
10566 if (!DC->isTypeLegal(VT))
10569 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10570 // shifted by ByteShift and truncated down to NumBytes.
10573 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10574 DAG.getConstant(ByteShift*8, DL,
10575 DC->getShiftAmountTy(IVal.getValueType())));
10578 // Figure out the offset for the store and the alignment of the access.
10580 unsigned NewAlign = St->getAlignment();
10582 if (DAG.getDataLayout().isLittleEndian())
10583 StOffset = ByteShift;
10585 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10587 SDValue Ptr = St->getBasePtr();
10590 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10591 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10592 NewAlign = MinAlign(NewAlign, StOffset);
10595 // Truncate down to the new size.
10596 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10599 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10600 St->getPointerInfo().getWithOffset(StOffset),
10601 false, false, NewAlign).getNode();
10605 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10606 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10607 /// narrowing the load and store if it would end up being a win for performance
10609 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10610 StoreSDNode *ST = cast<StoreSDNode>(N);
10611 if (ST->isVolatile())
10614 SDValue Chain = ST->getChain();
10615 SDValue Value = ST->getValue();
10616 SDValue Ptr = ST->getBasePtr();
10617 EVT VT = Value.getValueType();
10619 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10622 unsigned Opc = Value.getOpcode();
10624 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10625 // is a byte mask indicating a consecutive number of bytes, check to see if
10626 // Y is known to provide just those bytes. If so, we try to replace the
10627 // load + replace + store sequence with a single (narrower) store, which makes
10629 if (Opc == ISD::OR) {
10630 std::pair<unsigned, unsigned> MaskedLoad;
10631 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10632 if (MaskedLoad.first)
10633 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10634 Value.getOperand(1), ST,this))
10635 return SDValue(NewST, 0);
10637 // Or is commutative, so try swapping X and Y.
10638 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10639 if (MaskedLoad.first)
10640 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10641 Value.getOperand(0), ST,this))
10642 return SDValue(NewST, 0);
10645 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10646 Value.getOperand(1).getOpcode() != ISD::Constant)
10649 SDValue N0 = Value.getOperand(0);
10650 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10651 Chain == SDValue(N0.getNode(), 1)) {
10652 LoadSDNode *LD = cast<LoadSDNode>(N0);
10653 if (LD->getBasePtr() != Ptr ||
10654 LD->getPointerInfo().getAddrSpace() !=
10655 ST->getPointerInfo().getAddrSpace())
10658 // Find the type to narrow it the load / op / store to.
10659 SDValue N1 = Value.getOperand(1);
10660 unsigned BitWidth = N1.getValueSizeInBits();
10661 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10662 if (Opc == ISD::AND)
10663 Imm ^= APInt::getAllOnesValue(BitWidth);
10664 if (Imm == 0 || Imm.isAllOnesValue())
10666 unsigned ShAmt = Imm.countTrailingZeros();
10667 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10668 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10669 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10670 // The narrowing should be profitable, the load/store operation should be
10671 // legal (or custom) and the store size should be equal to the NewVT width.
10672 while (NewBW < BitWidth &&
10673 (NewVT.getStoreSizeInBits() != NewBW ||
10674 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10675 !TLI.isNarrowingProfitable(VT, NewVT))) {
10676 NewBW = NextPowerOf2(NewBW);
10677 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10679 if (NewBW >= BitWidth)
10682 // If the lsb changed does not start at the type bitwidth boundary,
10683 // start at the previous one.
10685 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10686 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10687 std::min(BitWidth, ShAmt + NewBW));
10688 if ((Imm & Mask) == Imm) {
10689 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10690 if (Opc == ISD::AND)
10691 NewImm ^= APInt::getAllOnesValue(NewBW);
10692 uint64_t PtrOff = ShAmt / 8;
10693 // For big endian targets, we need to adjust the offset to the pointer to
10694 // load the correct bytes.
10695 if (DAG.getDataLayout().isBigEndian())
10696 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10698 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10699 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10700 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10703 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10704 Ptr.getValueType(), Ptr,
10705 DAG.getConstant(PtrOff, SDLoc(LD),
10706 Ptr.getValueType()));
10707 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10708 LD->getChain(), NewPtr,
10709 LD->getPointerInfo().getWithOffset(PtrOff),
10710 LD->isVolatile(), LD->isNonTemporal(),
10711 LD->isInvariant(), NewAlign,
10713 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10714 DAG.getConstant(NewImm, SDLoc(Value),
10716 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10718 ST->getPointerInfo().getWithOffset(PtrOff),
10719 false, false, NewAlign);
10721 AddToWorklist(NewPtr.getNode());
10722 AddToWorklist(NewLD.getNode());
10723 AddToWorklist(NewVal.getNode());
10724 WorklistRemover DeadNodes(*this);
10725 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10734 /// For a given floating point load / store pair, if the load value isn't used
10735 /// by any other operations, then consider transforming the pair to integer
10736 /// load / store operations if the target deems the transformation profitable.
10737 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10738 StoreSDNode *ST = cast<StoreSDNode>(N);
10739 SDValue Chain = ST->getChain();
10740 SDValue Value = ST->getValue();
10741 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10742 Value.hasOneUse() &&
10743 Chain == SDValue(Value.getNode(), 1)) {
10744 LoadSDNode *LD = cast<LoadSDNode>(Value);
10745 EVT VT = LD->getMemoryVT();
10746 if (!VT.isFloatingPoint() ||
10747 VT != ST->getMemoryVT() ||
10748 LD->isNonTemporal() ||
10749 ST->isNonTemporal() ||
10750 LD->getPointerInfo().getAddrSpace() != 0 ||
10751 ST->getPointerInfo().getAddrSpace() != 0)
10754 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10755 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10756 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10757 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10758 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10761 unsigned LDAlign = LD->getAlignment();
10762 unsigned STAlign = ST->getAlignment();
10763 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10764 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10765 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10768 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10769 LD->getChain(), LD->getBasePtr(),
10770 LD->getPointerInfo(),
10771 false, false, false, LDAlign);
10773 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10774 NewLD, ST->getBasePtr(),
10775 ST->getPointerInfo(),
10776 false, false, STAlign);
10778 AddToWorklist(NewLD.getNode());
10779 AddToWorklist(NewST.getNode());
10780 WorklistRemover DeadNodes(*this);
10781 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10790 /// Helper struct to parse and store a memory address as base + index + offset.
10791 /// We ignore sign extensions when it is safe to do so.
10792 /// The following two expressions are not equivalent. To differentiate we need
10793 /// to store whether there was a sign extension involved in the index
10795 /// (load (i64 add (i64 copyfromreg %c)
10796 /// (i64 signextend (add (i8 load %index)
10800 /// (load (i64 add (i64 copyfromreg %c)
10801 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10803 struct BaseIndexOffset {
10807 bool IsIndexSignExt;
10809 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10811 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10812 bool IsIndexSignExt) :
10813 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10815 bool equalBaseIndex(const BaseIndexOffset &Other) {
10816 return Other.Base == Base && Other.Index == Index &&
10817 Other.IsIndexSignExt == IsIndexSignExt;
10820 /// Parses tree in Ptr for base, index, offset addresses.
10821 static BaseIndexOffset match(SDValue Ptr) {
10822 bool IsIndexSignExt = false;
10824 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10825 // instruction, then it could be just the BASE or everything else we don't
10826 // know how to handle. Just use Ptr as BASE and give up.
10827 if (Ptr->getOpcode() != ISD::ADD)
10828 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10830 // We know that we have at least an ADD instruction. Try to pattern match
10831 // the simple case of BASE + OFFSET.
10832 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10833 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10834 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10838 // Inside a loop the current BASE pointer is calculated using an ADD and a
10839 // MUL instruction. In this case Ptr is the actual BASE pointer.
10840 // (i64 add (i64 %array_ptr)
10841 // (i64 mul (i64 %induction_var)
10842 // (i64 %element_size)))
10843 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10844 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10846 // Look at Base + Index + Offset cases.
10847 SDValue Base = Ptr->getOperand(0);
10848 SDValue IndexOffset = Ptr->getOperand(1);
10850 // Skip signextends.
10851 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10852 IndexOffset = IndexOffset->getOperand(0);
10853 IsIndexSignExt = true;
10856 // Either the case of Base + Index (no offset) or something else.
10857 if (IndexOffset->getOpcode() != ISD::ADD)
10858 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10860 // Now we have the case of Base + Index + offset.
10861 SDValue Index = IndexOffset->getOperand(0);
10862 SDValue Offset = IndexOffset->getOperand(1);
10864 if (!isa<ConstantSDNode>(Offset))
10865 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10867 // Ignore signextends.
10868 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10869 Index = Index->getOperand(0);
10870 IsIndexSignExt = true;
10871 } else IsIndexSignExt = false;
10873 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10874 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10879 // This is a helper function for visitMUL to check the profitability
10880 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10881 // MulNode is the original multiply, AddNode is (add x, c1),
10882 // and ConstNode is c2.
10884 // If the (add x, c1) has multiple uses, we could increase
10885 // the number of adds if we make this transformation.
10886 // It would only be worth doing this if we can remove a
10887 // multiply in the process. Check for that here.
10891 // We're checking for cases where we have common "c3 * A" expressions.
10892 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10894 SDValue &ConstNode) {
10897 // If the add only has one use, this would be OK to do.
10898 if (AddNode.getNode()->hasOneUse())
10901 // Walk all the users of the constant with which we're multiplying.
10902 for (SDNode *Use : ConstNode->uses()) {
10904 if (Use == MulNode) // This use is the one we're on right now. Skip it.
10907 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10909 SDNode *MulVar = AddNode.getOperand(0).getNode();
10911 // OtherOp is what we're multiplying against the constant.
10912 if (Use->getOperand(0) == ConstNode)
10913 OtherOp = Use->getOperand(1).getNode();
10915 OtherOp = Use->getOperand(0).getNode();
10917 // Check to see if multiply is with the same operand of our "add".
10919 // ConstNode = CONST
10920 // Use = ConstNode * A <-- visiting Use. OtherOp is A.
10922 // AddNode = (A + c1) <-- MulVar is A.
10923 // = AddNode * ConstNode <-- current visiting instruction.
10925 // If we make this transformation, we will have a common
10926 // multiply (ConstNode * A) that we can save.
10927 if (OtherOp == MulVar)
10930 // Now check to see if a future expansion will give us a common
10933 // ConstNode = CONST
10934 // AddNode = (A + c1)
10935 // ... = AddNode * ConstNode <-- current visiting instruction.
10937 // OtherOp = (A + c2)
10938 // Use = OtherOp * ConstNode <-- visiting Use.
10940 // If we make this transformation, we will have a common
10941 // multiply (CONST * A) after we also do the same transformation
10942 // to the "t2" instruction.
10943 if (OtherOp->getOpcode() == ISD::ADD &&
10944 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10945 OtherOp->getOperand(0).getNode() == MulVar)
10950 // Didn't find a case where this would be profitable.
10954 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10956 ArrayRef<MemOpLink> Stores,
10957 SmallVectorImpl<SDValue> &Chains,
10959 SmallVector<SDValue, 8> BuildVector;
10961 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10962 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10963 Chains.push_back(St->getChain());
10964 BuildVector.push_back(St->getValue());
10967 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10970 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10971 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10972 unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10973 // Make sure we have something to merge.
10977 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10978 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10979 unsigned LatestNodeUsed = 0;
10981 for (unsigned i=0; i < NumStores; ++i) {
10982 // Find a chain for the new wide-store operand. Notice that some
10983 // of the store nodes that we found may not be selected for inclusion
10984 // in the wide store. The chain we use needs to be the chain of the
10985 // latest store node which is *used* and replaced by the wide store.
10986 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10987 LatestNodeUsed = i;
10990 SmallVector<SDValue, 8> Chains;
10992 // The latest Node in the DAG.
10993 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10994 SDLoc DL(StoreNodes[0].MemNode);
10998 bool IsVec = MemVT.isVector();
10999 unsigned Elts = NumStores;
11001 // When merging vector stores, get the total number of elements.
11002 Elts *= MemVT.getVectorNumElements();
11004 // Get the type for the merged vector store.
11005 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11006 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11008 if (IsConstantSrc) {
11009 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11011 SmallVector<SDValue, 8> Ops;
11012 for (unsigned i = 0; i < NumStores; ++i) {
11013 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11014 SDValue Val = St->getValue();
11015 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11016 if (Val.getValueType() != MemVT)
11018 Ops.push_back(Val);
11019 Chains.push_back(St->getChain());
11022 // Build the extracted vector elements back into a vector.
11023 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11026 // We should always use a vector store when merging extracted vector
11027 // elements, so this path implies a store of constants.
11028 assert(IsConstantSrc && "Merged vector elements should use vector store");
11030 unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11031 APInt StoreInt(SizeInBits, 0);
11033 // Construct a single integer constant which is made of the smaller
11034 // constant inputs.
11035 bool IsLE = DAG.getDataLayout().isLittleEndian();
11036 for (unsigned i = 0; i < NumStores; ++i) {
11037 unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11038 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11039 Chains.push_back(St->getChain());
11041 SDValue Val = St->getValue();
11042 StoreInt <<= ElementSizeBytes * 8;
11043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11044 StoreInt |= C->getAPIntValue().zext(SizeInBits);
11045 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11046 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11048 llvm_unreachable("Invalid constant element type");
11052 // Create the new Load and Store operations.
11053 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11054 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11057 assert(!Chains.empty());
11059 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11060 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11061 FirstInChain->getBasePtr(),
11062 FirstInChain->getPointerInfo(),
11064 FirstInChain->getAlignment());
11066 // Replace the last store with the new store
11067 CombineTo(LatestOp, NewStore);
11068 // Erase all other stores.
11069 for (unsigned i = 0; i < NumStores; ++i) {
11070 if (StoreNodes[i].MemNode == LatestOp)
11072 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11073 // ReplaceAllUsesWith will replace all uses that existed when it was
11074 // called, but graph optimizations may cause new ones to appear. For
11075 // example, the case in pr14333 looks like
11077 // St's chain -> St -> another store -> X
11079 // And the only difference from St to the other store is the chain.
11080 // When we change it's chain to be St's chain they become identical,
11081 // get CSEed and the net result is that X is now a use of St.
11082 // Since we know that St is redundant, just iterate.
11083 while (!St->use_empty())
11084 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11085 deleteAndRecombine(St);
11091 void DAGCombiner::getStoreMergeAndAliasCandidates(
11092 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11093 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11094 // This holds the base pointer, index, and the offset in bytes from the base
11096 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11098 // We must have a base and an offset.
11099 if (!BasePtr.Base.getNode())
11102 // Do not handle stores to undef base pointers.
11103 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11106 // Walk up the chain and look for nodes with offsets from the same
11107 // base pointer. Stop when reaching an instruction with a different kind
11108 // or instruction which has a different base pointer.
11109 EVT MemVT = St->getMemoryVT();
11111 StoreSDNode *Index = St;
11114 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11115 : DAG.getSubtarget().useAA();
11118 // Look at other users of the same chain. Stores on the same chain do not
11119 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11120 // to be on the same chain, so don't bother looking at adjacent chains.
11122 SDValue Chain = St->getChain();
11123 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11124 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11125 if (I.getOperandNo() != 0)
11128 if (OtherST->isVolatile() || OtherST->isIndexed())
11131 if (OtherST->getMemoryVT() != MemVT)
11134 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11136 if (Ptr.equalBaseIndex(BasePtr))
11137 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11145 // If the chain has more than one use, then we can't reorder the mem ops.
11146 if (Index != St && !SDValue(Index, 0)->hasOneUse())
11149 // Find the base pointer and offset for this memory node.
11150 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11152 // Check that the base pointer is the same as the original one.
11153 if (!Ptr.equalBaseIndex(BasePtr))
11156 // The memory operands must not be volatile.
11157 if (Index->isVolatile() || Index->isIndexed())
11161 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11162 if (St->isTruncatingStore())
11165 // The stored memory type must be the same.
11166 if (Index->getMemoryVT() != MemVT)
11169 // We do not allow under-aligned stores in order to prevent
11170 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD
11171 // be irrelevant here; what MATTERS is that we not move memory
11172 // operations that potentially overlap past each-other.
11173 if (Index->getAlignment() < MemVT.getStoreSize())
11176 // We found a potential memory operand to merge.
11177 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11179 // Find the next memory operand in the chain. If the next operand in the
11180 // chain is a store then move up and continue the scan with the next
11181 // memory operand. If the next operand is a load save it and use alias
11182 // information to check if it interferes with anything.
11183 SDNode *NextInChain = Index->getChain().getNode();
11185 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11186 // We found a store node. Use it for the next iteration.
11189 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11190 if (Ldn->isVolatile()) {
11195 // Save the load node for later. Continue the scan.
11196 AliasLoadNodes.push_back(Ldn);
11197 NextInChain = Ldn->getChain().getNode();
11207 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11208 if (OptLevel == CodeGenOpt::None)
11211 EVT MemVT = St->getMemoryVT();
11212 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11213 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11214 Attribute::NoImplicitFloat);
11216 // This function cannot currently deal with non-byte-sized memory sizes.
11217 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11220 if (!MemVT.isSimple())
11223 // Perform an early exit check. Do not bother looking at stored values that
11224 // are not constants, loads, or extracted vector elements.
11225 SDValue StoredVal = St->getValue();
11226 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11227 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11228 isa<ConstantFPSDNode>(StoredVal);
11229 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11230 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11232 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11235 // Don't merge vectors into wider vectors if the source data comes from loads.
11236 // TODO: This restriction can be lifted by using logic similar to the
11237 // ExtractVecSrc case.
11238 if (MemVT.isVector() && IsLoadSrc)
11241 // Only look at ends of store sequences.
11242 SDValue Chain = SDValue(St, 0);
11243 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11246 // Save the LoadSDNodes that we find in the chain.
11247 // We need to make sure that these nodes do not interfere with
11248 // any of the store nodes.
11249 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11251 // Save the StoreSDNodes that we find in the chain.
11252 SmallVector<MemOpLink, 8> StoreNodes;
11254 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11256 // Check if there is anything to merge.
11257 if (StoreNodes.size() < 2)
11260 // Sort the memory operands according to their distance from the
11261 // base pointer. As a secondary criteria: make sure stores coming
11262 // later in the code come first in the list. This is important for
11263 // the non-UseAA case, because we're merging stores into the FINAL
11264 // store along a chain which potentially contains aliasing stores.
11265 // Thus, if there are multiple stores to the same address, the last
11266 // one can be considered for merging but not the others.
11267 std::sort(StoreNodes.begin(), StoreNodes.end(),
11268 [](MemOpLink LHS, MemOpLink RHS) {
11269 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11270 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11271 LHS.SequenceNum < RHS.SequenceNum);
11274 // Scan the memory operations on the chain and find the first non-consecutive
11275 // store memory address.
11276 unsigned LastConsecutiveStore = 0;
11277 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11278 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11280 // Check that the addresses are consecutive starting from the second
11281 // element in the list of stores.
11283 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11284 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11288 bool Alias = false;
11289 // Check if this store interferes with any of the loads that we found.
11290 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11291 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11295 // We found a load that alias with this store. Stop the sequence.
11299 // Mark this node as useful.
11300 LastConsecutiveStore = i;
11303 // The node with the lowest store address.
11304 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11305 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11306 unsigned FirstStoreAlign = FirstInChain->getAlignment();
11307 LLVMContext &Context = *DAG.getContext();
11308 const DataLayout &DL = DAG.getDataLayout();
11310 // Store the constants into memory as one consecutive store.
11311 if (IsConstantSrc) {
11312 unsigned LastLegalType = 0;
11313 unsigned LastLegalVectorType = 0;
11314 bool NonZero = false;
11315 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11316 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11317 SDValue StoredVal = St->getValue();
11319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11320 NonZero |= !C->isNullValue();
11321 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11322 NonZero |= !C->getConstantFPValue()->isNullValue();
11328 // Find a legal type for the constant store.
11329 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11330 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11332 if (TLI.isTypeLegal(StoreTy) &&
11333 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11334 FirstStoreAlign, &IsFast) && IsFast) {
11335 LastLegalType = i+1;
11336 // Or check whether a truncstore is legal.
11337 } else if (TLI.getTypeAction(Context, StoreTy) ==
11338 TargetLowering::TypePromoteInteger) {
11339 EVT LegalizedStoredValueTy =
11340 TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11341 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11342 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11343 FirstStoreAS, FirstStoreAlign, &IsFast) &&
11345 LastLegalType = i + 1;
11349 // We only use vectors if the constant is known to be zero or the target
11350 // allows it and the function is not marked with the noimplicitfloat
11352 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11355 // Find a legal type for the vector store.
11356 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11357 if (TLI.isTypeLegal(Ty) &&
11358 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11359 FirstStoreAlign, &IsFast) && IsFast)
11360 LastLegalVectorType = i + 1;
11364 // Check if we found a legal integer type to store.
11365 if (LastLegalType == 0 && LastLegalVectorType == 0)
11368 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11369 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11371 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11375 // When extracting multiple vector elements, try to store them
11376 // in one vector store rather than a sequence of scalar stores.
11377 if (IsExtractVecSrc) {
11378 unsigned NumStoresToMerge = 0;
11379 bool IsVec = MemVT.isVector();
11380 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11381 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11382 unsigned StoreValOpcode = St->getValue().getOpcode();
11383 // This restriction could be loosened.
11384 // Bail out if any stored values are not elements extracted from a vector.
11385 // It should be possible to handle mixed sources, but load sources need
11386 // more careful handling (see the block of code below that handles
11387 // consecutive loads).
11388 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11389 StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11392 // Find a legal type for the vector store.
11393 unsigned Elts = i + 1;
11395 // When merging vector stores, get the total number of elements.
11396 Elts *= MemVT.getVectorNumElements();
11398 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11400 if (TLI.isTypeLegal(Ty) &&
11401 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11402 FirstStoreAlign, &IsFast) && IsFast)
11403 NumStoresToMerge = i + 1;
11406 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11410 // Below we handle the case of multiple consecutive stores that
11411 // come from multiple consecutive loads. We merge them into a single
11412 // wide load and a single wide store.
11414 // Look for load nodes which are used by the stored values.
11415 SmallVector<MemOpLink, 8> LoadNodes;
11417 // Find acceptable loads. Loads need to have the same chain (token factor),
11418 // must not be zext, volatile, indexed, and they must be consecutive.
11419 BaseIndexOffset LdBasePtr;
11420 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11421 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11422 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11425 // Loads must only have one use.
11426 if (!Ld->hasNUsesOfValue(1, 0))
11429 // The memory operands must not be volatile.
11430 if (Ld->isVolatile() || Ld->isIndexed())
11433 // We do not accept ext loads.
11434 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11437 // The stored memory type must be the same.
11438 if (Ld->getMemoryVT() != MemVT)
11441 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11442 // If this is not the first ptr that we check.
11443 if (LdBasePtr.Base.getNode()) {
11444 // The base ptr must be the same.
11445 if (!LdPtr.equalBaseIndex(LdBasePtr))
11448 // Check that all other base pointers are the same as this one.
11452 // We found a potential memory operand to merge.
11453 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11456 if (LoadNodes.size() < 2)
11459 // If we have load/store pair instructions and we only have two values,
11461 unsigned RequiredAlignment;
11462 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11463 St->getAlignment() >= RequiredAlignment)
11466 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11467 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11468 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11470 // Scan the memory operations on the chain and find the first non-consecutive
11471 // load memory address. These variables hold the index in the store node
11473 unsigned LastConsecutiveLoad = 0;
11474 // This variable refers to the size and not index in the array.
11475 unsigned LastLegalVectorType = 0;
11476 unsigned LastLegalIntegerType = 0;
11477 StartAddress = LoadNodes[0].OffsetFromBase;
11478 SDValue FirstChain = FirstLoad->getChain();
11479 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11480 // All loads much share the same chain.
11481 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11484 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11485 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11487 LastConsecutiveLoad = i;
11488 // Find a legal type for the vector store.
11489 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11490 bool IsFastSt, IsFastLd;
11491 if (TLI.isTypeLegal(StoreTy) &&
11492 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11493 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11494 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11495 FirstLoadAlign, &IsFastLd) && IsFastLd) {
11496 LastLegalVectorType = i + 1;
11499 // Find a legal type for the integer store.
11500 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11501 StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11502 if (TLI.isTypeLegal(StoreTy) &&
11503 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11504 FirstStoreAlign, &IsFastSt) && IsFastSt &&
11505 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11506 FirstLoadAlign, &IsFastLd) && IsFastLd)
11507 LastLegalIntegerType = i + 1;
11508 // Or check whether a truncstore and extload is legal.
11509 else if (TLI.getTypeAction(Context, StoreTy) ==
11510 TargetLowering::TypePromoteInteger) {
11511 EVT LegalizedStoredValueTy =
11512 TLI.getTypeToTransformTo(Context, StoreTy);
11513 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11514 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11515 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11516 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11517 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11518 FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11520 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11521 FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11523 LastLegalIntegerType = i+1;
11527 // Only use vector types if the vector type is larger than the integer type.
11528 // If they are the same, use integers.
11529 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11530 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11532 // We add +1 here because the LastXXX variables refer to location while
11533 // the NumElem refers to array/index size.
11534 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11535 NumElem = std::min(LastLegalType, NumElem);
11540 // Collect the chains from all merged stores.
11541 SmallVector<SDValue, 8> MergeStoreChains;
11542 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11544 // The latest Node in the DAG.
11545 unsigned LatestNodeUsed = 0;
11546 for (unsigned i=1; i<NumElem; ++i) {
11547 // Find a chain for the new wide-store operand. Notice that some
11548 // of the store nodes that we found may not be selected for inclusion
11549 // in the wide store. The chain we use needs to be the chain of the
11550 // latest store node which is *used* and replaced by the wide store.
11551 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11552 LatestNodeUsed = i;
11554 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11557 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11559 // Find if it is better to use vectors or integers to load and store
11563 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11565 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11566 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11569 SDLoc LoadDL(LoadNodes[0].MemNode);
11570 SDLoc StoreDL(StoreNodes[0].MemNode);
11572 // The merged loads are required to have the same chain, so using the first's
11573 // chain is acceptable.
11574 SDValue NewLoad = DAG.getLoad(
11575 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11576 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11578 SDValue NewStoreChain =
11579 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11581 SDValue NewStore = DAG.getStore(
11582 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11583 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11585 // Replace one of the loads with the new load.
11586 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11587 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11588 SDValue(NewLoad.getNode(), 1));
11590 // Remove the rest of the load chains.
11591 for (unsigned i = 1; i < NumElem ; ++i) {
11592 // Replace all chain users of the old load nodes with the chain of the new
11594 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11595 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11598 // Replace the last store with the new store.
11599 CombineTo(LatestOp, NewStore);
11600 // Erase all other stores.
11601 for (unsigned i = 0; i < NumElem ; ++i) {
11602 // Remove all Store nodes.
11603 if (StoreNodes[i].MemNode == LatestOp)
11605 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11606 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11607 deleteAndRecombine(St);
11613 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11617 // Replace the chain to avoid dependency.
11618 if (ST->isTruncatingStore()) {
11619 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11620 ST->getBasePtr(), ST->getMemoryVT(),
11621 ST->getMemOperand());
11623 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11624 ST->getMemOperand());
11627 // Create token to keep both nodes around.
11628 SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11629 MVT::Other, ST->getChain(), ReplStore);
11631 // Make sure the new and old chains are cleaned up.
11632 AddToWorklist(Token.getNode());
11634 // Don't add users to work list.
11635 return CombineTo(ST, Token, false);
11638 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11639 SDValue Value = ST->getValue();
11640 if (Value.getOpcode() == ISD::TargetConstantFP)
11645 SDValue Chain = ST->getChain();
11646 SDValue Ptr = ST->getBasePtr();
11648 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11650 // NOTE: If the original store is volatile, this transform must not increase
11651 // the number of stores. For example, on x86-32 an f64 can be stored in one
11652 // processor operation but an i64 (which is not legal) requires two. So the
11653 // transform should not be done in this case.
11656 switch (CFP->getSimpleValueType(0).SimpleTy) {
11658 llvm_unreachable("Unknown FP type");
11659 case MVT::f16: // We don't do this for these yet.
11665 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11666 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11668 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11669 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11671 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11676 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11677 !ST->isVolatile()) ||
11678 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11680 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11681 getZExtValue(), SDLoc(CFP), MVT::i64);
11682 return DAG.getStore(Chain, DL, Tmp,
11683 Ptr, ST->getMemOperand());
11686 if (!ST->isVolatile() &&
11687 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11688 // Many FP stores are not made apparent until after legalize, e.g. for
11689 // argument passing. Since this is so common, custom legalize the
11690 // 64-bit integer store into two 32-bit stores.
11691 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11692 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11693 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11694 if (DAG.getDataLayout().isBigEndian())
11697 unsigned Alignment = ST->getAlignment();
11698 bool isVolatile = ST->isVolatile();
11699 bool isNonTemporal = ST->isNonTemporal();
11700 AAMDNodes AAInfo = ST->getAAInfo();
11702 SDValue St0 = DAG.getStore(Chain, DL, Lo,
11703 Ptr, ST->getPointerInfo(),
11704 isVolatile, isNonTemporal,
11705 ST->getAlignment(), AAInfo);
11706 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11707 DAG.getConstant(4, DL, Ptr.getValueType()));
11708 Alignment = MinAlign(Alignment, 4U);
11709 SDValue St1 = DAG.getStore(Chain, DL, Hi,
11710 Ptr, ST->getPointerInfo().getWithOffset(4),
11711 isVolatile, isNonTemporal,
11712 Alignment, AAInfo);
11713 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11721 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11722 StoreSDNode *ST = cast<StoreSDNode>(N);
11723 SDValue Chain = ST->getChain();
11724 SDValue Value = ST->getValue();
11725 SDValue Ptr = ST->getBasePtr();
11727 // If this is a store of a bit convert, store the input value if the
11728 // resultant store does not need a higher alignment than the original.
11729 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11730 ST->isUnindexed()) {
11731 unsigned OrigAlign = ST->getAlignment();
11732 EVT SVT = Value.getOperand(0).getValueType();
11733 unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11734 SVT.getTypeForEVT(*DAG.getContext()));
11735 if (Align <= OrigAlign &&
11736 ((!LegalOperations && !ST->isVolatile()) ||
11737 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11738 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11739 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11740 ST->isNonTemporal(), OrigAlign,
11744 // Turn 'store undef, Ptr' -> nothing.
11745 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11748 // Try to infer better alignment information than the store already has.
11749 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11750 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11751 if (Align > ST->getAlignment()) {
11753 DAG.getTruncStore(Chain, SDLoc(N), Value,
11754 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11755 ST->isVolatile(), ST->isNonTemporal(), Align,
11757 if (NewStore.getNode() != N)
11758 return CombineTo(ST, NewStore, true);
11763 // Try transforming a pair floating point load / store ops to integer
11764 // load / store ops.
11765 if (SDValue NewST = TransformFPLoadStorePair(N))
11768 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11769 : DAG.getSubtarget().useAA();
11771 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11772 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11775 if (UseAA && ST->isUnindexed()) {
11776 // FIXME: We should do this even without AA enabled. AA will just allow
11777 // FindBetterChain to work in more situations. The problem with this is that
11778 // any combine that expects memory operations to be on consecutive chains
11779 // first needs to be updated to look for users of the same chain.
11781 // Walk up chain skipping non-aliasing memory nodes, on this store and any
11782 // adjacent stores.
11783 if (findBetterNeighborChains(ST)) {
11784 // replaceStoreChain uses CombineTo, which handled all of the worklist
11785 // manipulation. Return the original node to not do anything else.
11786 return SDValue(ST, 0);
11790 // Try transforming N to an indexed store.
11791 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11792 return SDValue(N, 0);
11794 // FIXME: is there such a thing as a truncating indexed store?
11795 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11796 Value.getValueType().isInteger()) {
11797 // See if we can simplify the input to this truncstore with knowledge that
11798 // only the low bits are being used. For example:
11799 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11801 GetDemandedBits(Value,
11802 APInt::getLowBitsSet(
11803 Value.getValueType().getScalarType().getSizeInBits(),
11804 ST->getMemoryVT().getScalarType().getSizeInBits()));
11805 AddToWorklist(Value.getNode());
11806 if (Shorter.getNode())
11807 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11808 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11810 // Otherwise, see if we can simplify the operation with
11811 // SimplifyDemandedBits, which only works if the value has a single use.
11812 if (SimplifyDemandedBits(Value,
11813 APInt::getLowBitsSet(
11814 Value.getValueType().getScalarType().getSizeInBits(),
11815 ST->getMemoryVT().getScalarType().getSizeInBits())))
11816 return SDValue(N, 0);
11819 // If this is a load followed by a store to the same location, then the store
11821 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11822 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11823 ST->isUnindexed() && !ST->isVolatile() &&
11824 // There can't be any side effects between the load and store, such as
11825 // a call or store.
11826 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11827 // The store is dead, remove it.
11832 // If this is a store followed by a store with the same value to the same
11833 // location, then the store is dead/noop.
11834 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11835 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11836 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11837 ST1->isUnindexed() && !ST1->isVolatile()) {
11838 // The store is dead, remove it.
11843 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11844 // truncating store. We can do this even if this is already a truncstore.
11845 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11846 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11847 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11848 ST->getMemoryVT())) {
11849 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11850 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11853 // Only perform this optimization before the types are legal, because we
11854 // don't want to perform this optimization on every DAGCombine invocation.
11856 bool EverChanged = false;
11859 // There can be multiple store sequences on the same chain.
11860 // Keep trying to merge store sequences until we are unable to do so
11861 // or until we merge the last store on the chain.
11862 bool Changed = MergeConsecutiveStores(ST);
11863 EverChanged |= Changed;
11864 if (!Changed) break;
11865 } while (ST->getOpcode() != ISD::DELETED_NODE);
11868 return SDValue(N, 0);
11871 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11873 // Make sure to do this only after attempting to merge stores in order to
11874 // avoid changing the types of some subset of stores due to visit order,
11875 // preventing their merging.
11876 if (isa<ConstantFPSDNode>(Value)) {
11877 if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11881 return ReduceLoadOpStoreWidth(N);
11884 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11885 SDValue InVec = N->getOperand(0);
11886 SDValue InVal = N->getOperand(1);
11887 SDValue EltNo = N->getOperand(2);
11890 // If the inserted element is an UNDEF, just use the input vector.
11891 if (InVal.getOpcode() == ISD::UNDEF)
11894 EVT VT = InVec.getValueType();
11896 // If we can't generate a legal BUILD_VECTOR, exit
11897 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11900 // Check that we know which element is being inserted
11901 if (!isa<ConstantSDNode>(EltNo))
11903 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11905 // Canonicalize insert_vector_elt dag nodes.
11907 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11908 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11910 // Do this only if the child insert_vector node has one use; also
11911 // do this only if indices are both constants and Idx1 < Idx0.
11912 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11913 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11914 unsigned OtherElt =
11915 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11916 if (Elt < OtherElt) {
11918 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11919 InVec.getOperand(0), InVal, EltNo);
11920 AddToWorklist(NewOp.getNode());
11921 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11922 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11926 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11927 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11928 // vector elements.
11929 SmallVector<SDValue, 8> Ops;
11930 // Do not combine these two vectors if the output vector will not replace
11931 // the input vector.
11932 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11933 Ops.append(InVec.getNode()->op_begin(),
11934 InVec.getNode()->op_end());
11935 } else if (InVec.getOpcode() == ISD::UNDEF) {
11936 unsigned NElts = VT.getVectorNumElements();
11937 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11942 // Insert the element
11943 if (Elt < Ops.size()) {
11944 // All the operands of BUILD_VECTOR must have the same type;
11945 // we enforce that here.
11946 EVT OpVT = Ops[0].getValueType();
11947 if (InVal.getValueType() != OpVT)
11948 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11949 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11950 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11954 // Return the new vector
11955 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11958 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11959 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11960 EVT ResultVT = EVE->getValueType(0);
11961 EVT VecEltVT = InVecVT.getVectorElementType();
11962 unsigned Align = OriginalLoad->getAlignment();
11963 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11964 VecEltVT.getTypeForEVT(*DAG.getContext()));
11966 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11971 SDValue NewPtr = OriginalLoad->getBasePtr();
11973 EVT PtrType = NewPtr.getValueType();
11974 MachinePointerInfo MPI;
11976 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11977 int Elt = ConstEltNo->getZExtValue();
11978 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11979 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11980 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11982 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11983 Offset = DAG.getNode(
11984 ISD::MUL, DL, PtrType, Offset,
11985 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11986 MPI = OriginalLoad->getPointerInfo();
11988 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11990 // The replacement we need to do here is a little tricky: we need to
11991 // replace an extractelement of a load with a load.
11992 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11993 // Note that this replacement assumes that the extractvalue is the only
11994 // use of the load; that's okay because we don't want to perform this
11995 // transformation in other cases anyway.
11998 if (ResultVT.bitsGT(VecEltVT)) {
11999 // If the result type of vextract is wider than the load, then issue an
12000 // extending load instead.
12001 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
12005 Load = DAG.getExtLoad(
12006 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
12007 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12008 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12009 Chain = Load.getValue(1);
12011 Load = DAG.getLoad(
12012 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
12013 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12014 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12015 Chain = Load.getValue(1);
12016 if (ResultVT.bitsLT(VecEltVT))
12017 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12019 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12021 WorklistRemover DeadNodes(*this);
12022 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12023 SDValue To[] = { Load, Chain };
12024 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12025 // Since we're explicitly calling ReplaceAllUses, add the new node to the
12026 // worklist explicitly as well.
12027 AddToWorklist(Load.getNode());
12028 AddUsersToWorklist(Load.getNode()); // Add users too
12029 // Make sure to revisit this node to clean it up; it will usually be dead.
12030 AddToWorklist(EVE);
12032 return SDValue(EVE, 0);
12035 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12036 // (vextract (scalar_to_vector val, 0) -> val
12037 SDValue InVec = N->getOperand(0);
12038 EVT VT = InVec.getValueType();
12039 EVT NVT = N->getValueType(0);
12041 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12042 // Check if the result type doesn't match the inserted element type. A
12043 // SCALAR_TO_VECTOR may truncate the inserted element and the
12044 // EXTRACT_VECTOR_ELT may widen the extracted vector.
12045 SDValue InOp = InVec.getOperand(0);
12046 if (InOp.getValueType() != NVT) {
12047 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12048 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12053 SDValue EltNo = N->getOperand(1);
12054 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12056 // extract_vector_elt (build_vector x, y), 1 -> y
12058 InVec.getOpcode() == ISD::BUILD_VECTOR &&
12059 TLI.isTypeLegal(VT) &&
12060 (InVec.hasOneUse() ||
12061 TLI.aggressivelyPreferBuildVectorSources(VT))) {
12062 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12063 EVT InEltVT = Elt.getValueType();
12065 // Sometimes build_vector's scalar input types do not match result type.
12066 if (NVT == InEltVT)
12069 // TODO: It may be useful to truncate if free if the build_vector implicitly
12073 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12074 // We only perform this optimization before the op legalization phase because
12075 // we may introduce new vector instructions which are not backed by TD
12076 // patterns. For example on AVX, extracting elements from a wide vector
12077 // without using extract_subvector. However, if we can find an underlying
12078 // scalar value, then we can always use that.
12079 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12080 int NumElem = VT.getVectorNumElements();
12081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12082 // Find the new index to extract from.
12083 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12085 // Extracting an undef index is undef.
12087 return DAG.getUNDEF(NVT);
12089 // Select the right vector half to extract from.
12091 if (OrigElt < NumElem) {
12092 SVInVec = InVec->getOperand(0);
12094 SVInVec = InVec->getOperand(1);
12095 OrigElt -= NumElem;
12098 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12099 SDValue InOp = SVInVec.getOperand(OrigElt);
12100 if (InOp.getValueType() != NVT) {
12101 assert(InOp.getValueType().isInteger() && NVT.isInteger());
12102 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12108 // FIXME: We should handle recursing on other vector shuffles and
12109 // scalar_to_vector here as well.
12111 if (!LegalOperations) {
12112 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12113 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12114 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12118 bool BCNumEltsChanged = false;
12119 EVT ExtVT = VT.getVectorElementType();
12122 // If the result of load has to be truncated, then it's not necessarily
12124 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12127 if (InVec.getOpcode() == ISD::BITCAST) {
12128 // Don't duplicate a load with other uses.
12129 if (!InVec.hasOneUse())
12132 EVT BCVT = InVec.getOperand(0).getValueType();
12133 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12135 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12136 BCNumEltsChanged = true;
12137 InVec = InVec.getOperand(0);
12138 ExtVT = BCVT.getVectorElementType();
12141 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12142 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12143 ISD::isNormalLoad(InVec.getNode()) &&
12144 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12145 SDValue Index = N->getOperand(1);
12146 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12147 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12151 // Perform only after legalization to ensure build_vector / vector_shuffle
12152 // optimizations have already been done.
12153 if (!LegalOperations) return SDValue();
12155 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12156 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12157 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12160 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12162 LoadSDNode *LN0 = nullptr;
12163 const ShuffleVectorSDNode *SVN = nullptr;
12164 if (ISD::isNormalLoad(InVec.getNode())) {
12165 LN0 = cast<LoadSDNode>(InVec);
12166 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12167 InVec.getOperand(0).getValueType() == ExtVT &&
12168 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12169 // Don't duplicate a load with other uses.
12170 if (!InVec.hasOneUse())
12173 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12174 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12175 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12177 // (load $addr+1*size)
12179 // Don't duplicate a load with other uses.
12180 if (!InVec.hasOneUse())
12183 // If the bit convert changed the number of elements, it is unsafe
12184 // to examine the mask.
12185 if (BCNumEltsChanged)
12188 // Select the input vector, guarding against out of range extract vector.
12189 unsigned NumElems = VT.getVectorNumElements();
12190 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12191 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12193 if (InVec.getOpcode() == ISD::BITCAST) {
12194 // Don't duplicate a load with other uses.
12195 if (!InVec.hasOneUse())
12198 InVec = InVec.getOperand(0);
12200 if (ISD::isNormalLoad(InVec.getNode())) {
12201 LN0 = cast<LoadSDNode>(InVec);
12202 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12203 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12207 // Make sure we found a non-volatile load and the extractelement is
12209 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12212 // If Idx was -1 above, Elt is going to be -1, so just return undef.
12214 return DAG.getUNDEF(LVT);
12216 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12222 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12223 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12224 // We perform this optimization post type-legalization because
12225 // the type-legalizer often scalarizes integer-promoted vectors.
12226 // Performing this optimization before may create bit-casts which
12227 // will be type-legalized to complex code sequences.
12228 // We perform this optimization only before the operation legalizer because we
12229 // may introduce illegal operations.
12230 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12233 unsigned NumInScalars = N->getNumOperands();
12235 EVT VT = N->getValueType(0);
12237 // Check to see if this is a BUILD_VECTOR of a bunch of values
12238 // which come from any_extend or zero_extend nodes. If so, we can create
12239 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12240 // optimizations. We do not handle sign-extend because we can't fill the sign
12242 EVT SourceType = MVT::Other;
12243 bool AllAnyExt = true;
12245 for (unsigned i = 0; i != NumInScalars; ++i) {
12246 SDValue In = N->getOperand(i);
12247 // Ignore undef inputs.
12248 if (In.getOpcode() == ISD::UNDEF) continue;
12250 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
12251 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12253 // Abort if the element is not an extension.
12254 if (!ZeroExt && !AnyExt) {
12255 SourceType = MVT::Other;
12259 // The input is a ZeroExt or AnyExt. Check the original type.
12260 EVT InTy = In.getOperand(0).getValueType();
12262 // Check that all of the widened source types are the same.
12263 if (SourceType == MVT::Other)
12266 else if (InTy != SourceType) {
12267 // Multiple income types. Abort.
12268 SourceType = MVT::Other;
12272 // Check if all of the extends are ANY_EXTENDs.
12273 AllAnyExt &= AnyExt;
12276 // In order to have valid types, all of the inputs must be extended from the
12277 // same source type and all of the inputs must be any or zero extend.
12278 // Scalar sizes must be a power of two.
12279 EVT OutScalarTy = VT.getScalarType();
12280 bool ValidTypes = SourceType != MVT::Other &&
12281 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12282 isPowerOf2_32(SourceType.getSizeInBits());
12284 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12285 // turn into a single shuffle instruction.
12289 bool isLE = DAG.getDataLayout().isLittleEndian();
12290 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12291 assert(ElemRatio > 1 && "Invalid element size ratio");
12292 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12293 DAG.getConstant(0, SDLoc(N), SourceType);
12295 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12296 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12298 // Populate the new build_vector
12299 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12300 SDValue Cast = N->getOperand(i);
12301 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12302 Cast.getOpcode() == ISD::ZERO_EXTEND ||
12303 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12305 if (Cast.getOpcode() == ISD::UNDEF)
12306 In = DAG.getUNDEF(SourceType);
12308 In = Cast->getOperand(0);
12309 unsigned Index = isLE ? (i * ElemRatio) :
12310 (i * ElemRatio + (ElemRatio - 1));
12312 assert(Index < Ops.size() && "Invalid index");
12316 // The type of the new BUILD_VECTOR node.
12317 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12318 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12319 "Invalid vector size");
12320 // Check if the new vector type is legal.
12321 if (!isTypeLegal(VecVT)) return SDValue();
12323 // Make the new BUILD_VECTOR.
12324 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12326 // The new BUILD_VECTOR node has the potential to be further optimized.
12327 AddToWorklist(BV.getNode());
12328 // Bitcast to the desired type.
12329 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12332 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12333 EVT VT = N->getValueType(0);
12335 unsigned NumInScalars = N->getNumOperands();
12338 EVT SrcVT = MVT::Other;
12339 unsigned Opcode = ISD::DELETED_NODE;
12340 unsigned NumDefs = 0;
12342 for (unsigned i = 0; i != NumInScalars; ++i) {
12343 SDValue In = N->getOperand(i);
12344 unsigned Opc = In.getOpcode();
12346 if (Opc == ISD::UNDEF)
12349 // If all scalar values are floats and converted from integers.
12350 if (Opcode == ISD::DELETED_NODE &&
12351 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12358 EVT InVT = In.getOperand(0).getValueType();
12360 // If all scalar values are typed differently, bail out. It's chosen to
12361 // simplify BUILD_VECTOR of integer types.
12362 if (SrcVT == MVT::Other)
12369 // If the vector has just one element defined, it's not worth to fold it into
12370 // a vectorized one.
12374 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12375 && "Should only handle conversion from integer to float.");
12376 assert(SrcVT != MVT::Other && "Cannot determine source type!");
12378 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12380 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12383 // Just because the floating-point vector type is legal does not necessarily
12384 // mean that the corresponding integer vector type is.
12385 if (!isTypeLegal(NVT))
12388 SmallVector<SDValue, 8> Opnds;
12389 for (unsigned i = 0; i != NumInScalars; ++i) {
12390 SDValue In = N->getOperand(i);
12392 if (In.getOpcode() == ISD::UNDEF)
12393 Opnds.push_back(DAG.getUNDEF(SrcVT));
12395 Opnds.push_back(In.getOperand(0));
12397 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12398 AddToWorklist(BV.getNode());
12400 return DAG.getNode(Opcode, dl, VT, BV);
12403 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12404 unsigned NumInScalars = N->getNumOperands();
12406 EVT VT = N->getValueType(0);
12408 // A vector built entirely of undefs is undef.
12409 if (ISD::allOperandsUndef(N))
12410 return DAG.getUNDEF(VT);
12412 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12415 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12418 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12419 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12420 // at most two distinct vectors, turn this into a shuffle node.
12422 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12423 if (!isTypeLegal(VT))
12426 // May only combine to shuffle after legalize if shuffle is legal.
12427 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12430 SDValue VecIn1, VecIn2;
12431 bool UsesZeroVector = false;
12432 for (unsigned i = 0; i != NumInScalars; ++i) {
12433 SDValue Op = N->getOperand(i);
12434 // Ignore undef inputs.
12435 if (Op.getOpcode() == ISD::UNDEF) continue;
12437 // See if we can combine this build_vector into a blend with a zero vector.
12438 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12439 UsesZeroVector = true;
12443 // If this input is something other than a EXTRACT_VECTOR_ELT with a
12444 // constant index, bail out.
12445 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12446 !isa<ConstantSDNode>(Op.getOperand(1))) {
12447 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12451 // We allow up to two distinct input vectors.
12452 SDValue ExtractedFromVec = Op.getOperand(0);
12453 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12456 if (!VecIn1.getNode()) {
12457 VecIn1 = ExtractedFromVec;
12458 } else if (!VecIn2.getNode() && !UsesZeroVector) {
12459 VecIn2 = ExtractedFromVec;
12461 // Too many inputs.
12462 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12467 // If everything is good, we can make a shuffle operation.
12468 if (VecIn1.getNode()) {
12469 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12470 SmallVector<int, 8> Mask;
12471 for (unsigned i = 0; i != NumInScalars; ++i) {
12472 unsigned Opcode = N->getOperand(i).getOpcode();
12473 if (Opcode == ISD::UNDEF) {
12474 Mask.push_back(-1);
12478 // Operands can also be zero.
12479 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12480 assert(UsesZeroVector &&
12481 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12482 "Unexpected node found!");
12483 Mask.push_back(NumInScalars+i);
12487 // If extracting from the first vector, just use the index directly.
12488 SDValue Extract = N->getOperand(i);
12489 SDValue ExtVal = Extract.getOperand(1);
12490 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12491 if (Extract.getOperand(0) == VecIn1) {
12492 Mask.push_back(ExtIndex);
12496 // Otherwise, use InIdx + InputVecSize
12497 Mask.push_back(InNumElements + ExtIndex);
12500 // Avoid introducing illegal shuffles with zero.
12501 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12504 // We can't generate a shuffle node with mismatched input and output types.
12505 // Attempt to transform a single input vector to the correct type.
12506 if ((VT != VecIn1.getValueType())) {
12507 // If the input vector type has a different base type to the output
12508 // vector type, bail out.
12509 EVT VTElemType = VT.getVectorElementType();
12510 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12511 (VecIn2.getNode() &&
12512 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12515 // If the input vector is too small, widen it.
12516 // We only support widening of vectors which are half the size of the
12517 // output registers. For example XMM->YMM widening on X86 with AVX.
12518 EVT VecInT = VecIn1.getValueType();
12519 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12520 // If we only have one small input, widen it by adding undef values.
12521 if (!VecIn2.getNode())
12522 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12523 DAG.getUNDEF(VecIn1.getValueType()));
12524 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12525 // If we have two small inputs of the same type, try to concat them.
12526 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12527 VecIn2 = SDValue(nullptr, 0);
12530 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12531 // If the input vector is too large, try to split it.
12532 // We don't support having two input vectors that are too large.
12533 // If the zero vector was used, we can not split the vector,
12534 // since we'd need 3 inputs.
12535 if (UsesZeroVector || VecIn2.getNode())
12538 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12541 // Try to replace VecIn1 with two extract_subvectors
12542 // No need to update the masks, they should still be correct.
12543 VecIn2 = DAG.getNode(
12544 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12545 DAG.getConstant(VT.getVectorNumElements(), dl,
12546 TLI.getVectorIdxTy(DAG.getDataLayout())));
12547 VecIn1 = DAG.getNode(
12548 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12549 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12554 if (UsesZeroVector)
12555 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12556 DAG.getConstantFP(0.0, dl, VT);
12558 // If VecIn2 is unused then change it to undef.
12559 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12561 // Check that we were able to transform all incoming values to the same
12563 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12564 VecIn1.getValueType() != VT)
12567 // Return the new VECTOR_SHUFFLE node.
12571 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12577 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12579 EVT OpVT = N->getOperand(0).getValueType();
12581 // If the operands are legal vectors, leave them alone.
12582 if (TLI.isTypeLegal(OpVT))
12586 EVT VT = N->getValueType(0);
12587 SmallVector<SDValue, 8> Ops;
12589 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12590 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12592 // Keep track of what we encounter.
12593 bool AnyInteger = false;
12594 bool AnyFP = false;
12595 for (const SDValue &Op : N->ops()) {
12596 if (ISD::BITCAST == Op.getOpcode() &&
12597 !Op.getOperand(0).getValueType().isVector())
12598 Ops.push_back(Op.getOperand(0));
12599 else if (ISD::UNDEF == Op.getOpcode())
12600 Ops.push_back(ScalarUndef);
12604 // Note whether we encounter an integer or floating point scalar.
12605 // If it's neither, bail out, it could be something weird like x86mmx.
12606 EVT LastOpVT = Ops.back().getValueType();
12607 if (LastOpVT.isFloatingPoint())
12609 else if (LastOpVT.isInteger())
12615 // If any of the operands is a floating point scalar bitcast to a vector,
12616 // use floating point types throughout, and bitcast everything.
12617 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12619 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12620 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12622 for (SDValue &Op : Ops) {
12623 if (Op.getValueType() == SVT)
12625 if (Op.getOpcode() == ISD::UNDEF)
12628 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12633 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12634 VT.getSizeInBits() / SVT.getSizeInBits());
12635 return DAG.getNode(ISD::BITCAST, DL, VT,
12636 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12639 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12640 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12641 // most two distinct vectors the same size as the result, attempt to turn this
12642 // into a legal shuffle.
12643 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12644 EVT VT = N->getValueType(0);
12645 EVT OpVT = N->getOperand(0).getValueType();
12646 int NumElts = VT.getVectorNumElements();
12647 int NumOpElts = OpVT.getVectorNumElements();
12649 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12650 SmallVector<int, 8> Mask;
12652 for (SDValue Op : N->ops()) {
12653 // Peek through any bitcast.
12654 while (Op.getOpcode() == ISD::BITCAST)
12655 Op = Op.getOperand(0);
12657 // UNDEF nodes convert to UNDEF shuffle mask values.
12658 if (Op.getOpcode() == ISD::UNDEF) {
12659 Mask.append((unsigned)NumOpElts, -1);
12663 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12666 // What vector are we extracting the subvector from and at what index?
12667 SDValue ExtVec = Op.getOperand(0);
12669 // We want the EVT of the original extraction to correctly scale the
12670 // extraction index.
12671 EVT ExtVT = ExtVec.getValueType();
12673 // Peek through any bitcast.
12674 while (ExtVec.getOpcode() == ISD::BITCAST)
12675 ExtVec = ExtVec.getOperand(0);
12677 // UNDEF nodes convert to UNDEF shuffle mask values.
12678 if (ExtVec.getOpcode() == ISD::UNDEF) {
12679 Mask.append((unsigned)NumOpElts, -1);
12683 if (!isa<ConstantSDNode>(Op.getOperand(1)))
12685 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12687 // Ensure that we are extracting a subvector from a vector the same
12688 // size as the result.
12689 if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12692 // Scale the subvector index to account for any bitcast.
12693 int NumExtElts = ExtVT.getVectorNumElements();
12694 if (0 == (NumExtElts % NumElts))
12695 ExtIdx /= (NumExtElts / NumElts);
12696 else if (0 == (NumElts % NumExtElts))
12697 ExtIdx *= (NumElts / NumExtElts);
12701 // At most we can reference 2 inputs in the final shuffle.
12702 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12704 for (int i = 0; i != NumOpElts; ++i)
12705 Mask.push_back(i + ExtIdx);
12706 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12708 for (int i = 0; i != NumOpElts; ++i)
12709 Mask.push_back(i + ExtIdx + NumElts);
12715 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12718 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12719 DAG.getBitcast(VT, SV1), Mask);
12722 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12723 // If we only have one input vector, we don't need to do any concatenation.
12724 if (N->getNumOperands() == 1)
12725 return N->getOperand(0);
12727 // Check if all of the operands are undefs.
12728 EVT VT = N->getValueType(0);
12729 if (ISD::allOperandsUndef(N))
12730 return DAG.getUNDEF(VT);
12732 // Optimize concat_vectors where all but the first of the vectors are undef.
12733 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12734 return Op.getOpcode() == ISD::UNDEF;
12736 SDValue In = N->getOperand(0);
12737 assert(In.getValueType().isVector() && "Must concat vectors");
12739 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12740 if (In->getOpcode() == ISD::BITCAST &&
12741 !In->getOperand(0)->getValueType(0).isVector()) {
12742 SDValue Scalar = In->getOperand(0);
12744 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12745 // look through the trunc so we can still do the transform:
12746 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12747 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12748 !TLI.isTypeLegal(Scalar.getValueType()) &&
12749 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12750 Scalar = Scalar->getOperand(0);
12752 EVT SclTy = Scalar->getValueType(0);
12754 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12757 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12758 VT.getSizeInBits() / SclTy.getSizeInBits());
12759 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12762 SDLoc dl = SDLoc(N);
12763 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12764 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12768 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12769 // We have already tested above for an UNDEF only concatenation.
12770 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12771 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12772 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12773 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12775 bool AllBuildVectorsOrUndefs =
12776 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12777 if (AllBuildVectorsOrUndefs) {
12778 SmallVector<SDValue, 8> Opnds;
12779 EVT SVT = VT.getScalarType();
12782 if (!SVT.isFloatingPoint()) {
12783 // If BUILD_VECTOR are from built from integer, they may have different
12784 // operand types. Get the smallest type and truncate all operands to it.
12785 bool FoundMinVT = false;
12786 for (const SDValue &Op : N->ops())
12787 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12788 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12789 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12792 assert(FoundMinVT && "Concat vector type mismatch");
12795 for (const SDValue &Op : N->ops()) {
12796 EVT OpVT = Op.getValueType();
12797 unsigned NumElts = OpVT.getVectorNumElements();
12799 if (ISD::UNDEF == Op.getOpcode())
12800 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12802 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12803 if (SVT.isFloatingPoint()) {
12804 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12805 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12807 for (unsigned i = 0; i != NumElts; ++i)
12809 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12814 assert(VT.getVectorNumElements() == Opnds.size() &&
12815 "Concat vector type mismatch");
12816 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12819 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12820 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12823 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12824 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12825 if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12828 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12829 // nodes often generate nop CONCAT_VECTOR nodes.
12830 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12831 // place the incoming vectors at the exact same location.
12832 SDValue SingleSource = SDValue();
12833 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12835 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12836 SDValue Op = N->getOperand(i);
12838 if (Op.getOpcode() == ISD::UNDEF)
12841 // Check if this is the identity extract:
12842 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12845 // Find the single incoming vector for the extract_subvector.
12846 if (SingleSource.getNode()) {
12847 if (Op.getOperand(0) != SingleSource)
12850 SingleSource = Op.getOperand(0);
12852 // Check the source type is the same as the type of the result.
12853 // If not, this concat may extend the vector, so we can not
12854 // optimize it away.
12855 if (SingleSource.getValueType() != N->getValueType(0))
12859 unsigned IdentityIndex = i * PartNumElem;
12860 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12861 // The extract index must be constant.
12865 // Check that we are reading from the identity index.
12866 if (CS->getZExtValue() != IdentityIndex)
12870 if (SingleSource.getNode())
12871 return SingleSource;
12876 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12877 EVT NVT = N->getValueType(0);
12878 SDValue V = N->getOperand(0);
12880 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12882 // (extract_subvec (concat V1, V2, ...), i)
12885 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12887 if (V->getOperand(0).getValueType() != NVT)
12889 unsigned Idx = N->getConstantOperandVal(1);
12890 unsigned NumElems = NVT.getVectorNumElements();
12891 assert((Idx % NumElems) == 0 &&
12892 "IDX in concat is not a multiple of the result vector length.");
12893 return V->getOperand(Idx / NumElems);
12897 if (V->getOpcode() == ISD::BITCAST)
12898 V = V.getOperand(0);
12900 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12902 // Handle only simple case where vector being inserted and vector
12903 // being extracted are of same type, and are half size of larger vectors.
12904 EVT BigVT = V->getOperand(0).getValueType();
12905 EVT SmallVT = V->getOperand(1).getValueType();
12906 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12909 // Only handle cases where both indexes are constants with the same type.
12910 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12911 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12913 if (InsIdx && ExtIdx &&
12914 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12915 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12917 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12919 // indices are equal or bit offsets are equal => V1
12920 // otherwise => (extract_subvec V1, ExtIdx)
12921 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12922 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12923 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12924 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12925 DAG.getNode(ISD::BITCAST, dl,
12926 N->getOperand(0).getValueType(),
12927 V->getOperand(0)), N->getOperand(1));
12934 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12935 SDValue V, SelectionDAG &DAG) {
12937 EVT VT = V.getValueType();
12939 switch (V.getOpcode()) {
12943 case ISD::CONCAT_VECTORS: {
12944 EVT OpVT = V->getOperand(0).getValueType();
12945 int OpSize = OpVT.getVectorNumElements();
12946 SmallBitVector OpUsedElements(OpSize, false);
12947 bool FoundSimplification = false;
12948 SmallVector<SDValue, 4> NewOps;
12949 NewOps.reserve(V->getNumOperands());
12950 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12951 SDValue Op = V->getOperand(i);
12952 bool OpUsed = false;
12953 for (int j = 0; j < OpSize; ++j)
12954 if (UsedElements[i * OpSize + j]) {
12955 OpUsedElements[j] = true;
12959 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12960 : DAG.getUNDEF(OpVT));
12961 FoundSimplification |= Op == NewOps.back();
12962 OpUsedElements.reset();
12964 if (FoundSimplification)
12965 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12969 case ISD::INSERT_SUBVECTOR: {
12970 SDValue BaseV = V->getOperand(0);
12971 SDValue SubV = V->getOperand(1);
12972 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12976 int SubSize = SubV.getValueType().getVectorNumElements();
12977 int Idx = IdxN->getZExtValue();
12978 bool SubVectorUsed = false;
12979 SmallBitVector SubUsedElements(SubSize, false);
12980 for (int i = 0; i < SubSize; ++i)
12981 if (UsedElements[i + Idx]) {
12982 SubVectorUsed = true;
12983 SubUsedElements[i] = true;
12984 UsedElements[i + Idx] = false;
12987 // Now recurse on both the base and sub vectors.
12988 SDValue SimplifiedSubV =
12990 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12991 : DAG.getUNDEF(SubV.getValueType());
12992 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12993 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12994 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12995 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
13001 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
13002 SDValue N1, SelectionDAG &DAG) {
13003 EVT VT = SVN->getValueType(0);
13004 int NumElts = VT.getVectorNumElements();
13005 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
13006 for (int M : SVN->getMask())
13007 if (M >= 0 && M < NumElts)
13008 N0UsedElements[M] = true;
13009 else if (M >= NumElts)
13010 N1UsedElements[M - NumElts] = true;
13012 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
13013 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13014 if (S0 == N0 && S1 == N1)
13017 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13020 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13021 // or turn a shuffle of a single concat into simpler shuffle then concat.
13022 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13023 EVT VT = N->getValueType(0);
13024 unsigned NumElts = VT.getVectorNumElements();
13026 SDValue N0 = N->getOperand(0);
13027 SDValue N1 = N->getOperand(1);
13028 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13030 SmallVector<SDValue, 4> Ops;
13031 EVT ConcatVT = N0.getOperand(0).getValueType();
13032 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13033 unsigned NumConcats = NumElts / NumElemsPerConcat;
13035 // Special case: shuffle(concat(A,B)) can be more efficiently represented
13036 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13037 // half vector elements.
13038 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13039 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13040 SVN->getMask().end(), [](int i) { return i == -1; })) {
13041 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13042 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13043 N1 = DAG.getUNDEF(ConcatVT);
13044 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13047 // Look at every vector that's inserted. We're looking for exact
13048 // subvector-sized copies from a concatenated vector
13049 for (unsigned I = 0; I != NumConcats; ++I) {
13050 // Make sure we're dealing with a copy.
13051 unsigned Begin = I * NumElemsPerConcat;
13052 bool AllUndef = true, NoUndef = true;
13053 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13054 if (SVN->getMaskElt(J) >= 0)
13061 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13064 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13065 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13068 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13069 if (FirstElt < N0.getNumOperands())
13070 Ops.push_back(N0.getOperand(FirstElt));
13072 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13074 } else if (AllUndef) {
13075 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13076 } else { // Mixed with general masks and undefs, can't do optimization.
13081 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13084 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13085 EVT VT = N->getValueType(0);
13086 unsigned NumElts = VT.getVectorNumElements();
13088 SDValue N0 = N->getOperand(0);
13089 SDValue N1 = N->getOperand(1);
13091 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13093 // Canonicalize shuffle undef, undef -> undef
13094 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13095 return DAG.getUNDEF(VT);
13097 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13099 // Canonicalize shuffle v, v -> v, undef
13101 SmallVector<int, 8> NewMask;
13102 for (unsigned i = 0; i != NumElts; ++i) {
13103 int Idx = SVN->getMaskElt(i);
13104 if (Idx >= (int)NumElts) Idx -= NumElts;
13105 NewMask.push_back(Idx);
13107 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13111 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
13112 if (N0.getOpcode() == ISD::UNDEF) {
13113 SmallVector<int, 8> NewMask;
13114 for (unsigned i = 0; i != NumElts; ++i) {
13115 int Idx = SVN->getMaskElt(i);
13117 if (Idx >= (int)NumElts)
13120 Idx = -1; // remove reference to lhs
13122 NewMask.push_back(Idx);
13124 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13128 // Remove references to rhs if it is undef
13129 if (N1.getOpcode() == ISD::UNDEF) {
13130 bool Changed = false;
13131 SmallVector<int, 8> NewMask;
13132 for (unsigned i = 0; i != NumElts; ++i) {
13133 int Idx = SVN->getMaskElt(i);
13134 if (Idx >= (int)NumElts) {
13138 NewMask.push_back(Idx);
13141 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13144 // If it is a splat, check if the argument vector is another splat or a
13146 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13147 SDNode *V = N0.getNode();
13149 // If this is a bit convert that changes the element type of the vector but
13150 // not the number of vector elements, look through it. Be careful not to
13151 // look though conversions that change things like v4f32 to v2f64.
13152 if (V->getOpcode() == ISD::BITCAST) {
13153 SDValue ConvInput = V->getOperand(0);
13154 if (ConvInput.getValueType().isVector() &&
13155 ConvInput.getValueType().getVectorNumElements() == NumElts)
13156 V = ConvInput.getNode();
13159 if (V->getOpcode() == ISD::BUILD_VECTOR) {
13160 assert(V->getNumOperands() == NumElts &&
13161 "BUILD_VECTOR has wrong number of operands");
13163 bool AllSame = true;
13164 for (unsigned i = 0; i != NumElts; ++i) {
13165 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13166 Base = V->getOperand(i);
13170 // Splat of <u, u, u, u>, return <u, u, u, u>
13171 if (!Base.getNode())
13173 for (unsigned i = 0; i != NumElts; ++i) {
13174 if (V->getOperand(i) != Base) {
13179 // Splat of <x, x, x, x>, return <x, x, x, x>
13183 // Canonicalize any other splat as a build_vector.
13184 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13185 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13186 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13187 V->getValueType(0), Ops);
13189 // We may have jumped through bitcasts, so the type of the
13190 // BUILD_VECTOR may not match the type of the shuffle.
13191 if (V->getValueType(0) != VT)
13192 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13197 // There are various patterns used to build up a vector from smaller vectors,
13198 // subvectors, or elements. Scan chains of these and replace unused insertions
13199 // or components with undef.
13200 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13203 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13204 Level < AfterLegalizeVectorOps &&
13205 (N1.getOpcode() == ISD::UNDEF ||
13206 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13207 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13208 SDValue V = partitionShuffleOfConcats(N, DAG);
13214 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13215 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13216 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13217 SmallVector<SDValue, 8> Ops;
13218 for (int M : SVN->getMask()) {
13219 SDValue Op = DAG.getUNDEF(VT.getScalarType());
13221 int Idx = M % NumElts;
13222 SDValue &S = (M < (int)NumElts ? N0 : N1);
13223 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13224 Op = S.getOperand(Idx);
13225 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13227 Op = S.getOperand(0);
13229 // Operand can't be combined - bail out.
13235 if (Ops.size() == VT.getVectorNumElements()) {
13236 // BUILD_VECTOR requires all inputs to be of the same type, find the
13237 // maximum type and extend them all.
13238 EVT SVT = VT.getScalarType();
13239 if (SVT.isInteger())
13240 for (SDValue &Op : Ops)
13241 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13242 if (SVT != VT.getScalarType())
13243 for (SDValue &Op : Ops)
13244 Op = TLI.isZExtFree(Op.getValueType(), SVT)
13245 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13246 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13247 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13251 // If this shuffle only has a single input that is a bitcasted shuffle,
13252 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13253 // back to their original types.
13254 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13255 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13256 TLI.isTypeLegal(VT)) {
13258 // Peek through the bitcast only if there is one user.
13260 while (BC0.getOpcode() == ISD::BITCAST) {
13261 if (!BC0.hasOneUse())
13263 BC0 = BC0.getOperand(0);
13266 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13268 return SmallVector<int, 8>(Mask.begin(), Mask.end());
13270 SmallVector<int, 8> NewMask;
13272 for (int s = 0; s != Scale; ++s)
13273 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13277 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13278 EVT SVT = VT.getScalarType();
13279 EVT InnerVT = BC0->getValueType(0);
13280 EVT InnerSVT = InnerVT.getScalarType();
13282 // Determine which shuffle works with the smaller scalar type.
13283 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13284 EVT ScaleSVT = ScaleVT.getScalarType();
13286 if (TLI.isTypeLegal(ScaleVT) &&
13287 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13288 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13290 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13291 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13293 // Scale the shuffle masks to the smaller scalar type.
13294 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13295 SmallVector<int, 8> InnerMask =
13296 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13297 SmallVector<int, 8> OuterMask =
13298 ScaleShuffleMask(SVN->getMask(), OuterScale);
13300 // Merge the shuffle masks.
13301 SmallVector<int, 8> NewMask;
13302 for (int M : OuterMask)
13303 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13305 // Test for shuffle mask legality over both commutations.
13306 SDValue SV0 = BC0->getOperand(0);
13307 SDValue SV1 = BC0->getOperand(1);
13308 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13310 std::swap(SV0, SV1);
13311 ShuffleVectorSDNode::commuteMask(NewMask);
13312 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13316 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13317 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13318 return DAG.getNode(
13319 ISD::BITCAST, SDLoc(N), VT,
13320 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13326 // Canonicalize shuffles according to rules:
13327 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13328 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13329 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13330 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13331 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13332 TLI.isTypeLegal(VT)) {
13333 // The incoming shuffle must be of the same type as the result of the
13334 // current shuffle.
13335 assert(N1->getOperand(0).getValueType() == VT &&
13336 "Shuffle types don't match");
13338 SDValue SV0 = N1->getOperand(0);
13339 SDValue SV1 = N1->getOperand(1);
13340 bool HasSameOp0 = N0 == SV0;
13341 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13342 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13343 // Commute the operands of this shuffle so that next rule
13345 return DAG.getCommutedVectorShuffle(*SVN);
13348 // Try to fold according to rules:
13349 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13350 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13351 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13352 // Don't try to fold shuffles with illegal type.
13353 // Only fold if this shuffle is the only user of the other shuffle.
13354 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13355 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13356 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13358 // The incoming shuffle must be of the same type as the result of the
13359 // current shuffle.
13360 assert(OtherSV->getOperand(0).getValueType() == VT &&
13361 "Shuffle types don't match");
13364 SmallVector<int, 4> Mask;
13365 // Compute the combined shuffle mask for a shuffle with SV0 as the first
13366 // operand, and SV1 as the second operand.
13367 for (unsigned i = 0; i != NumElts; ++i) {
13368 int Idx = SVN->getMaskElt(i);
13370 // Propagate Undef.
13371 Mask.push_back(Idx);
13375 SDValue CurrentVec;
13376 if (Idx < (int)NumElts) {
13377 // This shuffle index refers to the inner shuffle N0. Lookup the inner
13378 // shuffle mask to identify which vector is actually referenced.
13379 Idx = OtherSV->getMaskElt(Idx);
13381 // Propagate Undef.
13382 Mask.push_back(Idx);
13386 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13387 : OtherSV->getOperand(1);
13389 // This shuffle index references an element within N1.
13393 // Simple case where 'CurrentVec' is UNDEF.
13394 if (CurrentVec.getOpcode() == ISD::UNDEF) {
13395 Mask.push_back(-1);
13399 // Canonicalize the shuffle index. We don't know yet if CurrentVec
13400 // will be the first or second operand of the combined shuffle.
13401 Idx = Idx % NumElts;
13402 if (!SV0.getNode() || SV0 == CurrentVec) {
13403 // Ok. CurrentVec is the left hand side.
13404 // Update the mask accordingly.
13406 Mask.push_back(Idx);
13410 // Bail out if we cannot convert the shuffle pair into a single shuffle.
13411 if (SV1.getNode() && SV1 != CurrentVec)
13414 // Ok. CurrentVec is the right hand side.
13415 // Update the mask accordingly.
13417 Mask.push_back(Idx + NumElts);
13420 // Check if all indices in Mask are Undef. In case, propagate Undef.
13421 bool isUndefMask = true;
13422 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13423 isUndefMask &= Mask[i] < 0;
13426 return DAG.getUNDEF(VT);
13428 if (!SV0.getNode())
13429 SV0 = DAG.getUNDEF(VT);
13430 if (!SV1.getNode())
13431 SV1 = DAG.getUNDEF(VT);
13433 // Avoid introducing shuffles with illegal mask.
13434 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13435 ShuffleVectorSDNode::commuteMask(Mask);
13437 if (!TLI.isShuffleMaskLegal(Mask, VT))
13440 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13441 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13442 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13443 std::swap(SV0, SV1);
13446 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13447 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13448 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13449 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13455 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13456 SDValue InVal = N->getOperand(0);
13457 EVT VT = N->getValueType(0);
13459 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13460 // with a VECTOR_SHUFFLE.
13461 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13462 SDValue InVec = InVal->getOperand(0);
13463 SDValue EltNo = InVal->getOperand(1);
13465 // FIXME: We could support implicit truncation if the shuffle can be
13466 // scaled to a smaller vector scalar type.
13467 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13468 if (C0 && VT == InVec.getValueType() &&
13469 VT.getScalarType() == InVal.getValueType()) {
13470 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13471 int Elt = C0->getZExtValue();
13474 if (TLI.isShuffleMaskLegal(NewMask, VT))
13475 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13483 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13484 SDValue N0 = N->getOperand(0);
13485 SDValue N2 = N->getOperand(2);
13487 // If the input vector is a concatenation, and the insert replaces
13488 // one of the halves, we can optimize into a single concat_vectors.
13489 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13490 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13491 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13492 EVT VT = N->getValueType(0);
13494 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13495 // (concat_vectors Z, Y)
13497 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13498 N->getOperand(1), N0.getOperand(1));
13500 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13501 // (concat_vectors X, Z)
13502 if (InsIdx == VT.getVectorNumElements()/2)
13503 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13504 N0.getOperand(0), N->getOperand(1));
13510 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13511 SDValue N0 = N->getOperand(0);
13513 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13514 if (N0->getOpcode() == ISD::FP16_TO_FP)
13515 return N0->getOperand(0);
13520 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13521 SDValue N0 = N->getOperand(0);
13523 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13524 if (N0->getOpcode() == ISD::AND) {
13525 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13526 if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13527 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13535 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13536 /// with the destination vector and a zero vector.
13537 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13538 /// vector_shuffle V, Zero, <0, 4, 2, 4>
13539 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13540 EVT VT = N->getValueType(0);
13541 SDValue LHS = N->getOperand(0);
13542 SDValue RHS = N->getOperand(1);
13545 // Make sure we're not running after operation legalization where it
13546 // may have custom lowered the vector shuffles.
13547 if (LegalOperations)
13550 if (N->getOpcode() != ISD::AND)
13553 if (RHS.getOpcode() == ISD::BITCAST)
13554 RHS = RHS.getOperand(0);
13556 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13559 EVT RVT = RHS.getValueType();
13560 unsigned NumElts = RHS.getNumOperands();
13562 // Attempt to create a valid clear mask, splitting the mask into
13563 // sub elements and checking to see if each is
13564 // all zeros or all ones - suitable for shuffle masking.
13565 auto BuildClearMask = [&](int Split) {
13566 int NumSubElts = NumElts * Split;
13567 int NumSubBits = RVT.getScalarSizeInBits() / Split;
13569 SmallVector<int, 8> Indices;
13570 for (int i = 0; i != NumSubElts; ++i) {
13571 int EltIdx = i / Split;
13572 int SubIdx = i % Split;
13573 SDValue Elt = RHS.getOperand(EltIdx);
13574 if (Elt.getOpcode() == ISD::UNDEF) {
13575 Indices.push_back(-1);
13580 if (isa<ConstantSDNode>(Elt))
13581 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13582 else if (isa<ConstantFPSDNode>(Elt))
13583 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13587 // Extract the sub element from the constant bit mask.
13588 if (DAG.getDataLayout().isBigEndian()) {
13589 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13591 Bits = Bits.lshr(SubIdx * NumSubBits);
13595 Bits = Bits.trunc(NumSubBits);
13597 if (Bits.isAllOnesValue())
13598 Indices.push_back(i);
13599 else if (Bits == 0)
13600 Indices.push_back(i + NumSubElts);
13605 // Let's see if the target supports this vector_shuffle.
13606 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13607 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13608 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13611 SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13612 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13613 DAG.getBitcast(ClearVT, LHS),
13614 Zero, &Indices[0]));
13617 // Determine maximum split level (byte level masking).
13619 if (RVT.getScalarSizeInBits() % 8 == 0)
13620 MaxSplit = RVT.getScalarSizeInBits() / 8;
13622 for (int Split = 1; Split <= MaxSplit; ++Split)
13623 if (RVT.getScalarSizeInBits() % Split == 0)
13624 if (SDValue S = BuildClearMask(Split))
13630 /// Visit a binary vector operation, like ADD.
13631 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13632 assert(N->getValueType(0).isVector() &&
13633 "SimplifyVBinOp only works on vectors!");
13635 SDValue LHS = N->getOperand(0);
13636 SDValue RHS = N->getOperand(1);
13637 SDValue Ops[] = {LHS, RHS};
13639 // See if we can constant fold the vector operation.
13640 if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13641 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13644 // Try to convert a constant mask AND into a shuffle clear mask.
13645 if (SDValue Shuffle = XformToShuffleWithZero(N))
13648 // Type legalization might introduce new shuffles in the DAG.
13649 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13650 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13651 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13652 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13653 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13654 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13655 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13656 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13658 if (SVN0->getMask().equals(SVN1->getMask())) {
13659 EVT VT = N->getValueType(0);
13660 SDValue UndefVector = LHS.getOperand(1);
13661 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13662 LHS.getOperand(0), RHS.getOperand(0),
13664 AddUsersToWorklist(N);
13665 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13666 &SVN0->getMask()[0]);
13673 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13674 SDValue N1, SDValue N2){
13675 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13677 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13678 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13680 // If we got a simplified select_cc node back from SimplifySelectCC, then
13681 // break it down into a new SETCC node, and a new SELECT node, and then return
13682 // the SELECT node, since we were called with a SELECT node.
13683 if (SCC.getNode()) {
13684 // Check to see if we got a select_cc back (to turn into setcc/select).
13685 // Otherwise, just return whatever node we got back, like fabs.
13686 if (SCC.getOpcode() == ISD::SELECT_CC) {
13687 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13689 SCC.getOperand(0), SCC.getOperand(1),
13690 SCC.getOperand(4));
13691 AddToWorklist(SETCC.getNode());
13692 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13693 SCC.getOperand(2), SCC.getOperand(3));
13701 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13702 /// being selected between, see if we can simplify the select. Callers of this
13703 /// should assume that TheSelect is deleted if this returns true. As such, they
13704 /// should return the appropriate thing (e.g. the node) back to the top-level of
13705 /// the DAG combiner loop to avoid it being looked at.
13706 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13709 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13710 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13711 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13712 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13713 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13714 SDValue Sqrt = RHS;
13717 const ConstantFPSDNode *NegZero = nullptr;
13719 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13720 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13721 CmpLHS = TheSelect->getOperand(0);
13722 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13724 // SELECT or VSELECT
13725 SDValue Cmp = TheSelect->getOperand(0);
13726 if (Cmp.getOpcode() == ISD::SETCC) {
13727 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13728 CmpLHS = Cmp.getOperand(0);
13729 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13732 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13733 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13734 CC == ISD::SETULT || CC == ISD::SETLT)) {
13735 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13736 CombineTo(TheSelect, Sqrt);
13741 // Cannot simplify select with vector condition
13742 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13744 // If this is a select from two identical things, try to pull the operation
13745 // through the select.
13746 if (LHS.getOpcode() != RHS.getOpcode() ||
13747 !LHS.hasOneUse() || !RHS.hasOneUse())
13750 // If this is a load and the token chain is identical, replace the select
13751 // of two loads with a load through a select of the address to load from.
13752 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13753 // constants have been dropped into the constant pool.
13754 if (LHS.getOpcode() == ISD::LOAD) {
13755 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13756 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13758 // Token chains must be identical.
13759 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13760 // Do not let this transformation reduce the number of volatile loads.
13761 LLD->isVolatile() || RLD->isVolatile() ||
13762 // FIXME: If either is a pre/post inc/dec load,
13763 // we'd need to split out the address adjustment.
13764 LLD->isIndexed() || RLD->isIndexed() ||
13765 // If this is an EXTLOAD, the VT's must match.
13766 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13767 // If this is an EXTLOAD, the kind of extension must match.
13768 (LLD->getExtensionType() != RLD->getExtensionType() &&
13769 // The only exception is if one of the extensions is anyext.
13770 LLD->getExtensionType() != ISD::EXTLOAD &&
13771 RLD->getExtensionType() != ISD::EXTLOAD) ||
13772 // FIXME: this discards src value information. This is
13773 // over-conservative. It would be beneficial to be able to remember
13774 // both potential memory locations. Since we are discarding
13775 // src value info, don't do the transformation if the memory
13776 // locations are not in the default address space.
13777 LLD->getPointerInfo().getAddrSpace() != 0 ||
13778 RLD->getPointerInfo().getAddrSpace() != 0 ||
13779 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13780 LLD->getBasePtr().getValueType()))
13783 // Check that the select condition doesn't reach either load. If so,
13784 // folding this will induce a cycle into the DAG. If not, this is safe to
13785 // xform, so create a select of the addresses.
13787 if (TheSelect->getOpcode() == ISD::SELECT) {
13788 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13789 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13790 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13792 // The loads must not depend on one another.
13793 if (LLD->isPredecessorOf(RLD) ||
13794 RLD->isPredecessorOf(LLD))
13796 Addr = DAG.getSelect(SDLoc(TheSelect),
13797 LLD->getBasePtr().getValueType(),
13798 TheSelect->getOperand(0), LLD->getBasePtr(),
13799 RLD->getBasePtr());
13800 } else { // Otherwise SELECT_CC
13801 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13802 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13804 if ((LLD->hasAnyUseOfValue(1) &&
13805 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13806 (RLD->hasAnyUseOfValue(1) &&
13807 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13810 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13811 LLD->getBasePtr().getValueType(),
13812 TheSelect->getOperand(0),
13813 TheSelect->getOperand(1),
13814 LLD->getBasePtr(), RLD->getBasePtr(),
13815 TheSelect->getOperand(4));
13819 // It is safe to replace the two loads if they have different alignments,
13820 // but the new load must be the minimum (most restrictive) alignment of the
13822 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13823 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13824 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13825 Load = DAG.getLoad(TheSelect->getValueType(0),
13827 // FIXME: Discards pointer and AA info.
13828 LLD->getChain(), Addr, MachinePointerInfo(),
13829 LLD->isVolatile(), LLD->isNonTemporal(),
13830 isInvariant, Alignment);
13832 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13833 RLD->getExtensionType() : LLD->getExtensionType(),
13835 TheSelect->getValueType(0),
13836 // FIXME: Discards pointer and AA info.
13837 LLD->getChain(), Addr, MachinePointerInfo(),
13838 LLD->getMemoryVT(), LLD->isVolatile(),
13839 LLD->isNonTemporal(), isInvariant, Alignment);
13842 // Users of the select now use the result of the load.
13843 CombineTo(TheSelect, Load);
13845 // Users of the old loads now use the new load's chain. We know the
13846 // old-load value is dead now.
13847 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13848 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13855 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13856 /// where 'cond' is the comparison specified by CC.
13857 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13858 SDValue N2, SDValue N3,
13859 ISD::CondCode CC, bool NotExtCompare) {
13860 // (x ? y : y) -> y.
13861 if (N2 == N3) return N2;
13863 EVT VT = N2.getValueType();
13864 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13865 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13867 // Determine if the condition we're dealing with is constant
13868 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13869 N0, N1, CC, DL, false);
13870 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13872 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13873 // fold select_cc true, x, y -> x
13874 // fold select_cc false, x, y -> y
13875 return !SCCC->isNullValue() ? N2 : N3;
13878 // Check to see if we can simplify the select into an fabs node
13879 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13880 // Allow either -0.0 or 0.0
13881 if (CFP->isZero()) {
13882 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13883 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13884 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13885 N2 == N3.getOperand(0))
13886 return DAG.getNode(ISD::FABS, DL, VT, N0);
13888 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13889 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13890 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13891 N2.getOperand(0) == N3)
13892 return DAG.getNode(ISD::FABS, DL, VT, N3);
13896 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13897 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13898 // in it. This is a win when the constant is not otherwise available because
13899 // it replaces two constant pool loads with one. We only do this if the FP
13900 // type is known to be legal, because if it isn't, then we are before legalize
13901 // types an we want the other legalization to happen first (e.g. to avoid
13902 // messing with soft float) and if the ConstantFP is not legal, because if
13903 // it is legal, we may not need to store the FP constant in a constant pool.
13904 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13905 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13906 if (TLI.isTypeLegal(N2.getValueType()) &&
13907 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13908 TargetLowering::Legal &&
13909 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13910 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13911 // If both constants have multiple uses, then we won't need to do an
13912 // extra load, they are likely around in registers for other users.
13913 (TV->hasOneUse() || FV->hasOneUse())) {
13914 Constant *Elts[] = {
13915 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13916 const_cast<ConstantFP*>(TV->getConstantFPValue())
13918 Type *FPTy = Elts[0]->getType();
13919 const DataLayout &TD = DAG.getDataLayout();
13921 // Create a ConstantArray of the two constants.
13922 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13924 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13925 TD.getPrefTypeAlignment(FPTy));
13926 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13928 // Get the offsets to the 0 and 1 element of the array so that we can
13929 // select between them.
13930 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13931 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13932 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13934 SDValue Cond = DAG.getSetCC(DL,
13935 getSetCCResultType(N0.getValueType()),
13937 AddToWorklist(Cond.getNode());
13938 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13940 AddToWorklist(CstOffset.getNode());
13941 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13943 AddToWorklist(CPIdx.getNode());
13944 return DAG.getLoad(
13945 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13946 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13947 false, false, false, Alignment);
13951 // Check to see if we can perform the "gzip trick", transforming
13952 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13953 if (isNullConstant(N3) && CC == ISD::SETLT &&
13954 (isNullConstant(N1) || // (a < 0) ? b : 0
13955 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13956 EVT XType = N0.getValueType();
13957 EVT AType = N2.getValueType();
13958 if (XType.bitsGE(AType)) {
13959 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13960 // single-bit constant.
13961 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13962 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13963 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13964 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13965 getShiftAmountTy(N0.getValueType()));
13966 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13968 AddToWorklist(Shift.getNode());
13970 if (XType.bitsGT(AType)) {
13971 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13972 AddToWorklist(Shift.getNode());
13975 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13978 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13980 DAG.getConstant(XType.getSizeInBits() - 1,
13982 getShiftAmountTy(N0.getValueType())));
13983 AddToWorklist(Shift.getNode());
13985 if (XType.bitsGT(AType)) {
13986 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13987 AddToWorklist(Shift.getNode());
13990 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13994 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13995 // where y is has a single bit set.
13996 // A plaintext description would be, we can turn the SELECT_CC into an AND
13997 // when the condition can be materialized as an all-ones register. Any
13998 // single bit-test can be materialized as an all-ones register with
13999 // shift-left and shift-right-arith.
14000 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
14001 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
14002 SDValue AndLHS = N0->getOperand(0);
14003 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14004 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
14005 // Shift the tested bit over the sign bit.
14006 APInt AndMask = ConstAndRHS->getAPIntValue();
14008 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
14009 getShiftAmountTy(AndLHS.getValueType()));
14010 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
14012 // Now arithmetic right shift it all the way over, so the result is either
14013 // all-ones, or zero.
14015 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14016 getShiftAmountTy(Shl.getValueType()));
14017 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14019 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14023 // fold select C, 16, 0 -> shl C, 4
14024 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14025 TLI.getBooleanContents(N0.getValueType()) ==
14026 TargetLowering::ZeroOrOneBooleanContent) {
14028 // If the caller doesn't want us to simplify this into a zext of a compare,
14030 if (NotExtCompare && N2C->isOne())
14033 // Get a SetCC of the condition
14034 // NOTE: Don't create a SETCC if it's not legal on this target.
14035 if (!LegalOperations ||
14036 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14038 // cast from setcc result type to select result type
14040 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14042 if (N2.getValueType().bitsLT(SCC.getValueType()))
14043 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14044 N2.getValueType());
14046 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14047 N2.getValueType(), SCC);
14049 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14050 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14051 N2.getValueType(), SCC);
14054 AddToWorklist(SCC.getNode());
14055 AddToWorklist(Temp.getNode());
14060 // shl setcc result by log2 n2c
14061 return DAG.getNode(
14062 ISD::SHL, DL, N2.getValueType(), Temp,
14063 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14064 getShiftAmountTy(Temp.getValueType())));
14068 // Check to see if this is an integer abs.
14069 // select_cc setg[te] X, 0, X, -X ->
14070 // select_cc setgt X, -1, X, -X ->
14071 // select_cc setl[te] X, 0, -X, X ->
14072 // select_cc setlt X, 1, -X, X ->
14073 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14075 ConstantSDNode *SubC = nullptr;
14076 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14077 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14078 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14079 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14080 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14081 (N1C->isOne() && CC == ISD::SETLT)) &&
14082 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14083 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14085 EVT XType = N0.getValueType();
14086 if (SubC && SubC->isNullValue() && XType.isInteger()) {
14088 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14090 DAG.getConstant(XType.getSizeInBits() - 1, DL,
14091 getShiftAmountTy(N0.getValueType())));
14092 SDValue Add = DAG.getNode(ISD::ADD, DL,
14094 AddToWorklist(Shift.getNode());
14095 AddToWorklist(Add.getNode());
14096 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14103 /// This is a stub for TargetLowering::SimplifySetCC.
14104 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14105 SDValue N1, ISD::CondCode Cond,
14106 SDLoc DL, bool foldBooleans) {
14107 TargetLowering::DAGCombinerInfo
14108 DagCombineInfo(DAG, Level, false, this);
14109 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14112 /// Given an ISD::SDIV node expressing a divide by constant, return
14113 /// a DAG expression to select that will generate the same value by multiplying
14114 /// by a magic number.
14115 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14116 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14117 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14121 // Avoid division by zero.
14122 if (C->isNullValue())
14125 std::vector<SDNode*> Built;
14127 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14129 for (SDNode *N : Built)
14134 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14135 /// DAG expression that will generate the same value by right shifting.
14136 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14137 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14141 // Avoid division by zero.
14142 if (C->isNullValue())
14145 std::vector<SDNode *> Built;
14146 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14148 for (SDNode *N : Built)
14153 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14154 /// expression that will generate the same value by multiplying by a magic
14156 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14157 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14158 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14162 // Avoid division by zero.
14163 if (C->isNullValue())
14166 std::vector<SDNode*> Built;
14168 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14170 for (SDNode *N : Built)
14175 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14176 if (Level >= AfterLegalizeDAG)
14179 // Expose the DAG combiner to the target combiner implementations.
14180 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14182 unsigned Iterations = 0;
14183 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14185 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14186 // For the reciprocal, we need to find the zero of the function:
14187 // F(X) = A X - 1 [which has a zero at X = 1/A]
14189 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14190 // does not require additional intermediate precision]
14191 EVT VT = Op.getValueType();
14193 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14195 AddToWorklist(Est.getNode());
14197 // Newton iterations: Est = Est + Est (1 - Arg * Est)
14198 for (unsigned i = 0; i < Iterations; ++i) {
14199 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14200 AddToWorklist(NewEst.getNode());
14202 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14203 AddToWorklist(NewEst.getNode());
14205 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14206 AddToWorklist(NewEst.getNode());
14208 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14209 AddToWorklist(Est.getNode());
14218 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14219 /// For the reciprocal sqrt, we need to find the zero of the function:
14220 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14222 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14223 /// As a result, we precompute A/2 prior to the iteration loop.
14224 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14225 unsigned Iterations,
14226 SDNodeFlags *Flags) {
14227 EVT VT = Arg.getValueType();
14229 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14231 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14232 // this entire sequence requires only one FP constant.
14233 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14234 AddToWorklist(HalfArg.getNode());
14236 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14237 AddToWorklist(HalfArg.getNode());
14239 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14240 for (unsigned i = 0; i < Iterations; ++i) {
14241 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14242 AddToWorklist(NewEst.getNode());
14244 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14245 AddToWorklist(NewEst.getNode());
14247 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14248 AddToWorklist(NewEst.getNode());
14250 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14251 AddToWorklist(Est.getNode());
14256 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14257 /// For the reciprocal sqrt, we need to find the zero of the function:
14258 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14260 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14261 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14262 unsigned Iterations,
14263 SDNodeFlags *Flags) {
14264 EVT VT = Arg.getValueType();
14266 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14267 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14269 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14270 for (unsigned i = 0; i < Iterations; ++i) {
14271 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14272 AddToWorklist(HalfEst.getNode());
14274 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14275 AddToWorklist(Est.getNode());
14277 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14278 AddToWorklist(Est.getNode());
14280 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14281 AddToWorklist(Est.getNode());
14283 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14284 AddToWorklist(Est.getNode());
14289 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14290 if (Level >= AfterLegalizeDAG)
14293 // Expose the DAG combiner to the target combiner implementations.
14294 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14295 unsigned Iterations = 0;
14296 bool UseOneConstNR = false;
14297 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14298 AddToWorklist(Est.getNode());
14300 Est = UseOneConstNR ?
14301 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14302 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14310 /// Return true if base is a frame index, which is known not to alias with
14311 /// anything but itself. Provides base object and offset as results.
14312 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14313 const GlobalValue *&GV, const void *&CV) {
14314 // Assume it is a primitive operation.
14315 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14317 // If it's an adding a simple constant then integrate the offset.
14318 if (Base.getOpcode() == ISD::ADD) {
14319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14320 Base = Base.getOperand(0);
14321 Offset += C->getZExtValue();
14325 // Return the underlying GlobalValue, and update the Offset. Return false
14326 // for GlobalAddressSDNode since the same GlobalAddress may be represented
14327 // by multiple nodes with different offsets.
14328 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14329 GV = G->getGlobal();
14330 Offset += G->getOffset();
14334 // Return the underlying Constant value, and update the Offset. Return false
14335 // for ConstantSDNodes since the same constant pool entry may be represented
14336 // by multiple nodes with different offsets.
14337 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14338 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14339 : (const void *)C->getConstVal();
14340 Offset += C->getOffset();
14343 // If it's any of the following then it can't alias with anything but itself.
14344 return isa<FrameIndexSDNode>(Base);
14347 /// Return true if there is any possibility that the two addresses overlap.
14348 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14349 // If they are the same then they must be aliases.
14350 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14352 // If they are both volatile then they cannot be reordered.
14353 if (Op0->isVolatile() && Op1->isVolatile()) return true;
14355 // If one operation reads from invariant memory, and the other may store, they
14356 // cannot alias. These should really be checking the equivalent of mayWrite,
14357 // but it only matters for memory nodes other than load /store.
14358 if (Op0->isInvariant() && Op1->writeMem())
14361 if (Op1->isInvariant() && Op0->writeMem())
14364 // Gather base node and offset information.
14365 SDValue Base1, Base2;
14366 int64_t Offset1, Offset2;
14367 const GlobalValue *GV1, *GV2;
14368 const void *CV1, *CV2;
14369 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14370 Base1, Offset1, GV1, CV1);
14371 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14372 Base2, Offset2, GV2, CV2);
14374 // If they have a same base address then check to see if they overlap.
14375 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14376 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14377 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14379 // It is possible for different frame indices to alias each other, mostly
14380 // when tail call optimization reuses return address slots for arguments.
14381 // To catch this case, look up the actual index of frame indices to compute
14382 // the real alias relationship.
14383 if (isFrameIndex1 && isFrameIndex2) {
14384 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14385 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14386 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14387 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14388 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14391 // Otherwise, if we know what the bases are, and they aren't identical, then
14392 // we know they cannot alias.
14393 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14396 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14397 // compared to the size and offset of the access, we may be able to prove they
14398 // do not alias. This check is conservative for now to catch cases created by
14399 // splitting vector types.
14400 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14401 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14402 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14403 Op1->getMemoryVT().getSizeInBits() >> 3) &&
14404 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14405 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14406 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14408 // There is no overlap between these relatively aligned accesses of similar
14409 // size, return no alias.
14410 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14411 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14415 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14417 : DAG.getSubtarget().useAA();
14419 if (CombinerAAOnlyFunc.getNumOccurrences() &&
14420 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14424 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14425 // Use alias analysis information.
14426 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14427 Op1->getSrcValueOffset());
14428 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14429 Op0->getSrcValueOffset() - MinOffset;
14430 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14431 Op1->getSrcValueOffset() - MinOffset;
14432 AliasResult AAResult =
14433 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14434 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14435 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14436 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14437 if (AAResult == NoAlias)
14441 // Otherwise we have to assume they alias.
14445 /// Walk up chain skipping non-aliasing memory nodes,
14446 /// looking for aliasing nodes and adding them to the Aliases vector.
14447 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14448 SmallVectorImpl<SDValue> &Aliases) {
14449 SmallVector<SDValue, 8> Chains; // List of chains to visit.
14450 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
14452 // Get alias information for node.
14453 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14456 Chains.push_back(OriginalChain);
14457 unsigned Depth = 0;
14459 // Look at each chain and determine if it is an alias. If so, add it to the
14460 // aliases list. If not, then continue up the chain looking for the next
14462 while (!Chains.empty()) {
14463 SDValue Chain = Chains.pop_back_val();
14465 // For TokenFactor nodes, look at each operand and only continue up the
14466 // chain until we reach the depth limit.
14468 // FIXME: The depth check could be made to return the last non-aliasing
14469 // chain we found before we hit a tokenfactor rather than the original
14473 Aliases.push_back(OriginalChain);
14477 // Don't bother if we've been before.
14478 if (!Visited.insert(Chain.getNode()).second)
14481 switch (Chain.getOpcode()) {
14482 case ISD::EntryToken:
14483 // Entry token is ideal chain operand, but handled in FindBetterChain.
14488 // Get alias information for Chain.
14489 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14490 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14492 // If chain is alias then stop here.
14493 if (!(IsLoad && IsOpLoad) &&
14494 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14495 Aliases.push_back(Chain);
14497 // Look further up the chain.
14498 Chains.push_back(Chain.getOperand(0));
14504 case ISD::TokenFactor:
14505 // We have to check each of the operands of the token factor for "small"
14506 // token factors, so we queue them up. Adding the operands to the queue
14507 // (stack) in reverse order maintains the original order and increases the
14508 // likelihood that getNode will find a matching token factor (CSE.)
14509 if (Chain.getNumOperands() > 16) {
14510 Aliases.push_back(Chain);
14513 for (unsigned n = Chain.getNumOperands(); n;)
14514 Chains.push_back(Chain.getOperand(--n));
14519 // For all other instructions we will just have to take what we can get.
14520 Aliases.push_back(Chain);
14525 // We need to be careful here to also search for aliases through the
14526 // value operand of a store, etc. Consider the following situation:
14528 // L1 = load Token1, %52
14529 // S1 = store Token1, L1, %51
14530 // L2 = load Token1, %52+8
14531 // S2 = store Token1, L2, %51+8
14532 // Token2 = Token(S1, S2)
14533 // L3 = load Token2, %53
14534 // S3 = store Token2, L3, %52
14535 // L4 = load Token2, %53+8
14536 // S4 = store Token2, L4, %52+8
14537 // If we search for aliases of S3 (which loads address %52), and we look
14538 // only through the chain, then we'll miss the trivial dependence on L1
14539 // (which also loads from %52). We then might change all loads and
14540 // stores to use Token1 as their chain operand, which could result in
14541 // copying %53 into %52 before copying %52 into %51 (which should
14544 // The problem is, however, that searching for such data dependencies
14545 // can become expensive, and the cost is not directly related to the
14546 // chain depth. Instead, we'll rule out such configurations here by
14547 // insisting that we've visited all chain users (except for users
14548 // of the original chain, which is not necessary). When doing this,
14549 // we need to look through nodes we don't care about (otherwise, things
14550 // like register copies will interfere with trivial cases).
14552 SmallVector<const SDNode *, 16> Worklist;
14553 for (const SDNode *N : Visited)
14554 if (N != OriginalChain.getNode())
14555 Worklist.push_back(N);
14557 while (!Worklist.empty()) {
14558 const SDNode *M = Worklist.pop_back_val();
14560 // We have already visited M, and want to make sure we've visited any uses
14561 // of M that we care about. For uses that we've not visisted, and don't
14562 // care about, queue them to the worklist.
14564 for (SDNode::use_iterator UI = M->use_begin(),
14565 UIE = M->use_end(); UI != UIE; ++UI)
14566 if (UI.getUse().getValueType() == MVT::Other &&
14567 Visited.insert(*UI).second) {
14568 if (isa<MemSDNode>(*UI)) {
14569 // We've not visited this use, and we care about it (it could have an
14570 // ordering dependency with the original node).
14572 Aliases.push_back(OriginalChain);
14576 // We've not visited this use, but we don't care about it. Mark it as
14577 // visited and enqueue it to the worklist.
14578 Worklist.push_back(*UI);
14583 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14584 /// (aliasing node.)
14585 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14586 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14588 // Accumulate all the aliases to this node.
14589 GatherAllAliases(N, OldChain, Aliases);
14591 // If no operands then chain to entry token.
14592 if (Aliases.size() == 0)
14593 return DAG.getEntryNode();
14595 // If a single operand then chain to it. We don't need to revisit it.
14596 if (Aliases.size() == 1)
14599 // Construct a custom tailored token factor.
14600 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14603 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14604 // This holds the base pointer, index, and the offset in bytes from the base
14606 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14608 // We must have a base and an offset.
14609 if (!BasePtr.Base.getNode())
14612 // Do not handle stores to undef base pointers.
14613 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14616 SmallVector<StoreSDNode *, 8> ChainedStores;
14617 ChainedStores.push_back(St);
14619 // Walk up the chain and look for nodes with offsets from the same
14620 // base pointer. Stop when reaching an instruction with a different kind
14621 // or instruction which has a different base pointer.
14622 StoreSDNode *Index = St;
14624 // If the chain has more than one use, then we can't reorder the mem ops.
14625 if (Index != St && !SDValue(Index, 0)->hasOneUse())
14628 if (Index->isVolatile() || Index->isIndexed())
14631 // Find the base pointer and offset for this memory node.
14632 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14634 // Check that the base pointer is the same as the original one.
14635 if (!Ptr.equalBaseIndex(BasePtr))
14638 // Find the next memory operand in the chain. If the next operand in the
14639 // chain is a store then move up and continue the scan with the next
14640 // memory operand. If the next operand is a load save it and use alias
14641 // information to check if it interferes with anything.
14642 SDNode *NextInChain = Index->getChain().getNode();
14644 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14645 // We found a store node. Use it for the next iteration.
14646 ChainedStores.push_back(STn);
14649 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14650 NextInChain = Ldn->getChain().getNode();
14659 bool MadeChange = false;
14660 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14662 for (StoreSDNode *ChainedStore : ChainedStores) {
14663 SDValue Chain = ChainedStore->getChain();
14664 SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14666 if (Chain != BetterChain) {
14668 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14672 // Do all replacements after finding the replacements to make to avoid making
14673 // the chains more complicated by introducing new TokenFactors.
14674 for (auto Replacement : BetterChains)
14675 replaceStoreChain(Replacement.first, Replacement.second);
14680 /// This is the entry point for the file.
14681 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14682 CodeGenOpt::Level OptLevel) {
14683 /// This is the main entry point to this class.
14684 DAGCombiner(*this, AA, OptLevel).Run(Level);