1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// Remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitBSWAP(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273 SDValue visitTRUNCATE(SDNode *N);
274 SDValue visitBITCAST(SDNode *N);
275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
279 SDValue visitFMA(SDNode *N);
280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
282 SDValue visitFSQRT(SDNode *N);
283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
301 SDValue visitSTORE(SDNode *N);
302 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304 SDValue visitBUILD_VECTOR(SDNode *N);
305 SDValue visitCONCAT_VECTORS(SDNode *N);
306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307 SDValue visitVECTOR_SHUFFLE(SDNode *N);
308 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309 SDValue visitINSERT_SUBVECTOR(SDNode *N);
310 SDValue visitMLOAD(SDNode *N);
311 SDValue visitMSTORE(SDNode *N);
312 SDValue visitMGATHER(SDNode *N);
313 SDValue visitMSCATTER(SDNode *N);
314 SDValue visitFP_TO_FP16(SDNode *N);
316 SDValue visitFADDForFMACombine(SDNode *N);
317 SDValue visitFSUBForFMACombine(SDNode *N);
319 SDValue XformToShuffleWithZero(SDNode *N);
320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328 SDValue N3, ISD::CondCode CC,
329 bool NotExtCompare = false);
330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331 SDLoc DL, bool foldBooleans = true);
333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
335 bool isOneUseSetCC(SDValue N) const;
337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340 SDValue CombineExtLoad(SDNode *N);
341 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342 SDValue BuildSDIV(SDNode *N);
343 SDValue BuildSDIVPow2(SDNode *N);
344 SDValue BuildUDIV(SDNode *N);
345 SDValue BuildReciprocalEstimate(SDValue Op);
346 SDValue BuildRsqrtEstimate(SDValue Op);
347 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350 bool DemandHighBits = true);
351 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353 SDValue InnerPos, SDValue InnerNeg,
354 unsigned PosOpcode, unsigned NegOpcode,
356 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357 SDValue ReduceLoadWidth(SDNode *N);
358 SDValue ReduceLoadOpStoreWidth(SDNode *N);
359 SDValue TransformFPLoadStorePair(SDNode *N);
360 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365 /// Walk up chain skipping non-aliasing memory nodes,
366 /// looking for aliasing nodes and adding them to the Aliases vector.
367 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368 SmallVectorImpl<SDValue> &Aliases);
370 /// Return true if there is any possibility that the two addresses overlap.
371 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374 /// chain (aliasing node.)
375 SDValue FindBetterChain(SDNode *N, SDValue Chain);
377 /// Holds a pointer to an LSBaseSDNode as well as information on where it
378 /// is located in a sequence of memory operations connected by a chain.
380 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382 // Ptr to the mem node.
383 LSBaseSDNode *MemNode;
384 // Offset from the base ptr.
385 int64_t OffsetFromBase;
386 // What is the sequence number of this mem node.
387 // Lowest mem operand in the DAG starts at zero.
388 unsigned SequenceNum;
391 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
392 /// constant build_vector of the stored constant values in Stores.
393 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395 ArrayRef<MemOpLink> Stores,
398 /// This is a helper function for MergeConsecutiveStores. When the source
399 /// elements of the consecutive stores are all constants or all extracted
400 /// vector elements, try to merge them into one larger store.
401 /// \return True if a merged store was created.
402 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403 EVT MemVT, unsigned NumElem,
404 bool IsConstantSrc, bool UseVector);
406 /// Merge consecutive store operations into a wide store.
407 /// This optimization uses wide integers or vectors when possible.
408 /// \return True if some memory operations were changed.
409 bool MergeConsecutiveStores(StoreSDNode *N);
411 /// \brief Try to transform a truncation where C is a constant:
412 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
414 /// \p N needs to be a truncation and its first operand an AND. Other
415 /// requirements are checked by the function (e.g. that trunc is
416 /// single-use) and if missed an empty SDValue is returned.
417 SDValue distributeTruncateThroughAnd(SDNode *N);
420 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
421 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
422 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
423 auto *F = DAG.getMachineFunction().getFunction();
424 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
425 F->hasFnAttribute(Attribute::MinSize);
428 /// Runs the dag combiner on all nodes in the work list
429 void Run(CombineLevel AtLevel);
431 SelectionDAG &getDAG() const { return DAG; }
433 /// Returns a type large enough to hold any valid shift amount - before type
434 /// legalization these can be huge.
435 EVT getShiftAmountTy(EVT LHSTy) {
436 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
437 if (LHSTy.isVector())
439 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
440 : TLI.getPointerTy();
443 /// This method returns true if we are running before type legalization or
444 /// if the specified VT is legal.
445 bool isTypeLegal(const EVT &VT) {
446 if (!LegalTypes) return true;
447 return TLI.isTypeLegal(VT);
450 /// Convenience wrapper around TargetLowering::getSetCCResultType
451 EVT getSetCCResultType(EVT VT) const {
452 return TLI.getSetCCResultType(*DAG.getContext(), VT);
459 /// This class is a DAGUpdateListener that removes any deleted
460 /// nodes from the worklist.
461 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
464 explicit WorklistRemover(DAGCombiner &dc)
465 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
467 void NodeDeleted(SDNode *N, SDNode *E) override {
468 DC.removeFromWorklist(N);
473 //===----------------------------------------------------------------------===//
474 // TargetLowering::DAGCombinerInfo implementation
475 //===----------------------------------------------------------------------===//
477 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
478 ((DAGCombiner*)DC)->AddToWorklist(N);
481 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
482 ((DAGCombiner*)DC)->removeFromWorklist(N);
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
487 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
490 SDValue TargetLowering::DAGCombinerInfo::
491 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
492 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
496 SDValue TargetLowering::DAGCombinerInfo::
497 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
498 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
501 void TargetLowering::DAGCombinerInfo::
502 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
503 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
506 //===----------------------------------------------------------------------===//
508 //===----------------------------------------------------------------------===//
510 void DAGCombiner::deleteAndRecombine(SDNode *N) {
511 removeFromWorklist(N);
513 // If the operands of this node are only used by the node, they will now be
514 // dead. Make sure to re-visit them and recursively delete dead nodes.
515 for (const SDValue &Op : N->ops())
516 // For an operand generating multiple values, one of the values may
517 // become dead allowing further simplification (e.g. split index
518 // arithmetic from an indexed load).
519 if (Op->hasOneUse() || Op->getNumValues() > 1)
520 AddToWorklist(Op.getNode());
525 /// Return 1 if we can compute the negated form of the specified expression for
526 /// the same cost as the expression itself, or 2 if we can compute the negated
527 /// form more cheaply than the expression itself.
528 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
529 const TargetLowering &TLI,
530 const TargetOptions *Options,
531 unsigned Depth = 0) {
532 // fneg is removable even if it has multiple uses.
533 if (Op.getOpcode() == ISD::FNEG) return 2;
535 // Don't allow anything with multiple uses.
536 if (!Op.hasOneUse()) return 0;
538 // Don't recurse exponentially.
539 if (Depth > 6) return 0;
541 switch (Op.getOpcode()) {
542 default: return false;
543 case ISD::ConstantFP:
544 // Don't invert constant FP values after legalize. The negated constant
545 // isn't necessarily legal.
546 return LegalOperations ? 0 : 1;
548 // FIXME: determine better conditions for this xform.
549 if (!Options->UnsafeFPMath) return 0;
551 // After operation legalization, it might not be legal to create new FSUBs.
552 if (LegalOperations &&
553 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
556 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
557 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
560 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
561 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
564 // We can't turn -(A-B) into B-A when we honor signed zeros.
565 if (!Options->UnsafeFPMath) return 0;
567 // fold (fneg (fsub A, B)) -> (fsub B, A)
572 if (Options->HonorSignDependentRoundingFPMath()) return 0;
574 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
575 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
579 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
585 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
590 /// If isNegatibleForFree returns true, return the newly negated expression.
591 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
592 bool LegalOperations, unsigned Depth = 0) {
593 const TargetOptions &Options = DAG.getTarget().Options;
594 // fneg is removable even if it has multiple uses.
595 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
597 // Don't allow anything with multiple uses.
598 assert(Op.hasOneUse() && "Unknown reuse!");
600 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
601 switch (Op.getOpcode()) {
602 default: llvm_unreachable("Unknown code");
603 case ISD::ConstantFP: {
604 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
606 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
609 // FIXME: determine better conditions for this xform.
610 assert(Options.UnsafeFPMath);
612 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
613 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
614 DAG.getTargetLoweringInfo(), &Options, Depth+1))
615 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1),
619 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
620 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621 GetNegatedExpression(Op.getOperand(1), DAG,
622 LegalOperations, Depth+1),
625 // We can't turn -(A-B) into B-A when we honor signed zeros.
626 assert(Options.UnsafeFPMath);
628 // fold (fneg (fsub 0, B)) -> B
629 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
631 return Op.getOperand(1);
633 // fold (fneg (fsub A, B)) -> (fsub B, A)
634 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
635 Op.getOperand(1), Op.getOperand(0));
639 assert(!Options.HonorSignDependentRoundingFPMath());
641 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
642 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
643 DAG.getTargetLoweringInfo(), &Options, Depth+1))
644 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
645 GetNegatedExpression(Op.getOperand(0), DAG,
646 LegalOperations, Depth+1),
649 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
650 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
652 GetNegatedExpression(Op.getOperand(1), DAG,
653 LegalOperations, Depth+1));
657 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
658 GetNegatedExpression(Op.getOperand(0), DAG,
659 LegalOperations, Depth+1));
661 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
662 GetNegatedExpression(Op.getOperand(0), DAG,
663 LegalOperations, Depth+1),
668 // Return true if this node is a setcc, or is a select_cc
669 // that selects between the target values used for true and false, making it
670 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
671 // the appropriate nodes based on the type of node we are checking. This
672 // simplifies life a bit for the callers.
673 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
675 if (N.getOpcode() == ISD::SETCC) {
676 LHS = N.getOperand(0);
677 RHS = N.getOperand(1);
678 CC = N.getOperand(2);
682 if (N.getOpcode() != ISD::SELECT_CC ||
683 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
684 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
687 if (TLI.getBooleanContents(N.getValueType()) ==
688 TargetLowering::UndefinedBooleanContent)
691 LHS = N.getOperand(0);
692 RHS = N.getOperand(1);
693 CC = N.getOperand(4);
697 /// Return true if this is a SetCC-equivalent operation with only one use.
698 /// If this is true, it allows the users to invert the operation for free when
699 /// it is profitable to do so.
700 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
702 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
707 /// Returns true if N is a BUILD_VECTOR node whose
708 /// elements are all the same constant or undefined.
709 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
710 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
715 unsigned SplatBitSize;
717 EVT EltVT = N->getValueType(0).getVectorElementType();
718 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
720 EltVT.getSizeInBits() >= SplatBitSize);
723 // \brief Returns the SDNode if it is a constant integer BuildVector
724 // or constant integer.
725 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
726 if (isa<ConstantSDNode>(N))
728 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
733 // \brief Returns the SDNode if it is a constant float BuildVector
734 // or constant float.
735 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
736 if (isa<ConstantFPSDNode>(N))
738 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
743 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
745 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
746 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
749 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
750 BitVector UndefElements;
751 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
753 // BuildVectors can truncate their operands. Ignore that case here.
754 // FIXME: We blindly ignore splats which include undef which is overly
756 if (CN && UndefElements.none() &&
757 CN->getValueType(0) == N.getValueType().getScalarType())
764 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
766 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
767 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
770 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
771 BitVector UndefElements;
772 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
774 if (CN && UndefElements.none())
781 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
782 SDValue N0, SDValue N1) {
783 EVT VT = N0.getValueType();
784 if (N0.getOpcode() == Opc) {
785 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
786 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
787 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
788 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
789 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
792 if (N0.hasOneUse()) {
793 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
795 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
796 if (!OpNode.getNode())
798 AddToWorklist(OpNode.getNode());
799 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
804 if (N1.getOpcode() == Opc) {
805 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
806 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
807 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
808 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
809 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
812 if (N1.hasOneUse()) {
813 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
815 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
816 if (!OpNode.getNode())
818 AddToWorklist(OpNode.getNode());
819 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
827 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
829 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
831 DEBUG(dbgs() << "\nReplacing.1 ";
833 dbgs() << "\nWith: ";
834 To[0].getNode()->dump(&DAG);
835 dbgs() << " and " << NumTo-1 << " other values\n");
836 for (unsigned i = 0, e = NumTo; i != e; ++i)
837 assert((!To[i].getNode() ||
838 N->getValueType(i) == To[i].getValueType()) &&
839 "Cannot combine value to value of different type!");
841 WorklistRemover DeadNodes(*this);
842 DAG.ReplaceAllUsesWith(N, To);
844 // Push the new nodes and any users onto the worklist
845 for (unsigned i = 0, e = NumTo; i != e; ++i) {
846 if (To[i].getNode()) {
847 AddToWorklist(To[i].getNode());
848 AddUsersToWorklist(To[i].getNode());
853 // Finally, if the node is now dead, remove it from the graph. The node
854 // may not be dead if the replacement process recursively simplified to
855 // something else needing this node.
857 deleteAndRecombine(N);
858 return SDValue(N, 0);
862 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
863 // Replace all uses. If any nodes become isomorphic to other nodes and
864 // are deleted, make sure to remove them from our worklist.
865 WorklistRemover DeadNodes(*this);
866 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
868 // Push the new node and any (possibly new) users onto the worklist.
869 AddToWorklist(TLO.New.getNode());
870 AddUsersToWorklist(TLO.New.getNode());
872 // Finally, if the node is now dead, remove it from the graph. The node
873 // may not be dead if the replacement process recursively simplified to
874 // something else needing this node.
875 if (TLO.Old.getNode()->use_empty())
876 deleteAndRecombine(TLO.Old.getNode());
879 /// Check the specified integer node value to see if it can be simplified or if
880 /// things it uses can be simplified by bit propagation. If so, return true.
881 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
882 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
883 APInt KnownZero, KnownOne;
884 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
888 AddToWorklist(Op.getNode());
890 // Replace the old value with the new one.
892 DEBUG(dbgs() << "\nReplacing.2 ";
893 TLO.Old.getNode()->dump(&DAG);
894 dbgs() << "\nWith: ";
895 TLO.New.getNode()->dump(&DAG);
898 CommitTargetLoweringOpt(TLO);
902 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
904 EVT VT = Load->getValueType(0);
905 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
907 DEBUG(dbgs() << "\nReplacing.9 ";
909 dbgs() << "\nWith: ";
910 Trunc.getNode()->dump(&DAG);
912 WorklistRemover DeadNodes(*this);
913 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
914 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
915 deleteAndRecombine(Load);
916 AddToWorklist(Trunc.getNode());
919 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
922 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
923 EVT MemVT = LD->getMemoryVT();
924 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
925 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
927 : LD->getExtensionType();
929 return DAG.getExtLoad(ExtType, dl, PVT,
930 LD->getChain(), LD->getBasePtr(),
931 MemVT, LD->getMemOperand());
934 unsigned Opc = Op.getOpcode();
937 case ISD::AssertSext:
938 return DAG.getNode(ISD::AssertSext, dl, PVT,
939 SExtPromoteOperand(Op.getOperand(0), PVT),
941 case ISD::AssertZext:
942 return DAG.getNode(ISD::AssertZext, dl, PVT,
943 ZExtPromoteOperand(Op.getOperand(0), PVT),
945 case ISD::Constant: {
947 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
948 return DAG.getNode(ExtOpc, dl, PVT, Op);
952 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
954 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
957 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
958 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
960 EVT OldVT = Op.getValueType();
962 bool Replace = false;
963 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
964 if (!NewOp.getNode())
966 AddToWorklist(NewOp.getNode());
969 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
970 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
971 DAG.getValueType(OldVT));
974 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
975 EVT OldVT = Op.getValueType();
977 bool Replace = false;
978 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
979 if (!NewOp.getNode())
981 AddToWorklist(NewOp.getNode());
984 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
985 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
988 /// Promote the specified integer binary operation if the target indicates it is
989 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
990 /// i32 since i16 instructions are longer.
991 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
992 if (!LegalOperations)
995 EVT VT = Op.getValueType();
996 if (VT.isVector() || !VT.isInteger())
999 // If operation type is 'undesirable', e.g. i16 on x86, consider
1001 unsigned Opc = Op.getOpcode();
1002 if (TLI.isTypeDesirableForOp(Opc, VT))
1006 // Consult target whether it is a good idea to promote this operation and
1007 // what's the right type to promote it to.
1008 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1009 assert(PVT != VT && "Don't know what type to promote to!");
1011 bool Replace0 = false;
1012 SDValue N0 = Op.getOperand(0);
1013 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1017 bool Replace1 = false;
1018 SDValue N1 = Op.getOperand(1);
1023 NN1 = PromoteOperand(N1, PVT, Replace1);
1028 AddToWorklist(NN0.getNode());
1030 AddToWorklist(NN1.getNode());
1033 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1035 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1037 DEBUG(dbgs() << "\nPromoting ";
1038 Op.getNode()->dump(&DAG));
1040 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1041 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1046 /// Promote the specified integer shift operation if the target indicates it is
1047 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1048 /// i32 since i16 instructions are longer.
1049 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1050 if (!LegalOperations)
1053 EVT VT = Op.getValueType();
1054 if (VT.isVector() || !VT.isInteger())
1057 // If operation type is 'undesirable', e.g. i16 on x86, consider
1059 unsigned Opc = Op.getOpcode();
1060 if (TLI.isTypeDesirableForOp(Opc, VT))
1064 // Consult target whether it is a good idea to promote this operation and
1065 // what's the right type to promote it to.
1066 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1067 assert(PVT != VT && "Don't know what type to promote to!");
1069 bool Replace = false;
1070 SDValue N0 = Op.getOperand(0);
1071 if (Opc == ISD::SRA)
1072 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1073 else if (Opc == ISD::SRL)
1074 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1076 N0 = PromoteOperand(N0, PVT, Replace);
1080 AddToWorklist(N0.getNode());
1082 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1084 DEBUG(dbgs() << "\nPromoting ";
1085 Op.getNode()->dump(&DAG));
1087 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1088 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1093 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1094 if (!LegalOperations)
1097 EVT VT = Op.getValueType();
1098 if (VT.isVector() || !VT.isInteger())
1101 // If operation type is 'undesirable', e.g. i16 on x86, consider
1103 unsigned Opc = Op.getOpcode();
1104 if (TLI.isTypeDesirableForOp(Opc, VT))
1108 // Consult target whether it is a good idea to promote this operation and
1109 // what's the right type to promote it to.
1110 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1111 assert(PVT != VT && "Don't know what type to promote to!");
1112 // fold (aext (aext x)) -> (aext x)
1113 // fold (aext (zext x)) -> (zext x)
1114 // fold (aext (sext x)) -> (sext x)
1115 DEBUG(dbgs() << "\nPromoting ";
1116 Op.getNode()->dump(&DAG));
1117 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1122 bool DAGCombiner::PromoteLoad(SDValue Op) {
1123 if (!LegalOperations)
1126 EVT VT = Op.getValueType();
1127 if (VT.isVector() || !VT.isInteger())
1130 // If operation type is 'undesirable', e.g. i16 on x86, consider
1132 unsigned Opc = Op.getOpcode();
1133 if (TLI.isTypeDesirableForOp(Opc, VT))
1137 // Consult target whether it is a good idea to promote this operation and
1138 // what's the right type to promote it to.
1139 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1140 assert(PVT != VT && "Don't know what type to promote to!");
1143 SDNode *N = Op.getNode();
1144 LoadSDNode *LD = cast<LoadSDNode>(N);
1145 EVT MemVT = LD->getMemoryVT();
1146 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1147 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1149 : LD->getExtensionType();
1150 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1151 LD->getChain(), LD->getBasePtr(),
1152 MemVT, LD->getMemOperand());
1153 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1155 DEBUG(dbgs() << "\nPromoting ";
1158 Result.getNode()->dump(&DAG);
1160 WorklistRemover DeadNodes(*this);
1161 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1162 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1163 deleteAndRecombine(N);
1164 AddToWorklist(Result.getNode());
1170 /// \brief Recursively delete a node which has no uses and any operands for
1171 /// which it is the only use.
1173 /// Note that this both deletes the nodes and removes them from the worklist.
1174 /// It also adds any nodes who have had a user deleted to the worklist as they
1175 /// may now have only one use and subject to other combines.
1176 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1177 if (!N->use_empty())
1180 SmallSetVector<SDNode *, 16> Nodes;
1183 N = Nodes.pop_back_val();
1187 if (N->use_empty()) {
1188 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1189 Nodes.insert(N->getOperand(i).getNode());
1191 removeFromWorklist(N);
1196 } while (!Nodes.empty());
1200 //===----------------------------------------------------------------------===//
1201 // Main DAG Combiner implementation
1202 //===----------------------------------------------------------------------===//
1204 void DAGCombiner::Run(CombineLevel AtLevel) {
1205 // set the instance variables, so that the various visit routines may use it.
1207 LegalOperations = Level >= AfterLegalizeVectorOps;
1208 LegalTypes = Level >= AfterLegalizeTypes;
1210 // Add all the dag nodes to the worklist.
1211 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1212 E = DAG.allnodes_end(); I != E; ++I)
1215 // Create a dummy node (which is not added to allnodes), that adds a reference
1216 // to the root node, preventing it from being deleted, and tracking any
1217 // changes of the root.
1218 HandleSDNode Dummy(DAG.getRoot());
1220 // while the worklist isn't empty, find a node and
1221 // try and combine it.
1222 while (!WorklistMap.empty()) {
1224 // The Worklist holds the SDNodes in order, but it may contain null entries.
1226 N = Worklist.pop_back_val();
1229 bool GoodWorklistEntry = WorklistMap.erase(N);
1230 (void)GoodWorklistEntry;
1231 assert(GoodWorklistEntry &&
1232 "Found a worklist entry without a corresponding map entry!");
1234 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1235 // N is deleted from the DAG, since they too may now be dead or may have a
1236 // reduced number of uses, allowing other xforms.
1237 if (recursivelyDeleteUnusedNodes(N))
1240 WorklistRemover DeadNodes(*this);
1242 // If this combine is running after legalizing the DAG, re-legalize any
1243 // nodes pulled off the worklist.
1244 if (Level == AfterLegalizeDAG) {
1245 SmallSetVector<SDNode *, 16> UpdatedNodes;
1246 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1248 for (SDNode *LN : UpdatedNodes) {
1250 AddUsersToWorklist(LN);
1256 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1258 // Add any operands of the new node which have not yet been combined to the
1259 // worklist as well. Because the worklist uniques things already, this
1260 // won't repeatedly process the same operand.
1261 CombinedNodes.insert(N);
1262 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1263 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1264 AddToWorklist(N->getOperand(i).getNode());
1266 SDValue RV = combine(N);
1273 // If we get back the same node we passed in, rather than a new node or
1274 // zero, we know that the node must have defined multiple values and
1275 // CombineTo was used. Since CombineTo takes care of the worklist
1276 // mechanics for us, we have no work to do in this case.
1277 if (RV.getNode() == N)
1280 assert(N->getOpcode() != ISD::DELETED_NODE &&
1281 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1282 "Node was deleted but visit returned new node!");
1284 DEBUG(dbgs() << " ... into: ";
1285 RV.getNode()->dump(&DAG));
1287 // Transfer debug value.
1288 DAG.TransferDbgValues(SDValue(N, 0), RV);
1289 if (N->getNumValues() == RV.getNode()->getNumValues())
1290 DAG.ReplaceAllUsesWith(N, RV.getNode());
1292 assert(N->getValueType(0) == RV.getValueType() &&
1293 N->getNumValues() == 1 && "Type mismatch");
1295 DAG.ReplaceAllUsesWith(N, &OpV);
1298 // Push the new node and any users onto the worklist
1299 AddToWorklist(RV.getNode());
1300 AddUsersToWorklist(RV.getNode());
1302 // Finally, if the node is now dead, remove it from the graph. The node
1303 // may not be dead if the replacement process recursively simplified to
1304 // something else needing this node. This will also take care of adding any
1305 // operands which have lost a user to the worklist.
1306 recursivelyDeleteUnusedNodes(N);
1309 // If the root changed (e.g. it was a dead load, update the root).
1310 DAG.setRoot(Dummy.getValue());
1311 DAG.RemoveDeadNodes();
1314 SDValue DAGCombiner::visit(SDNode *N) {
1315 switch (N->getOpcode()) {
1317 case ISD::TokenFactor: return visitTokenFactor(N);
1318 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1319 case ISD::ADD: return visitADD(N);
1320 case ISD::SUB: return visitSUB(N);
1321 case ISD::ADDC: return visitADDC(N);
1322 case ISD::SUBC: return visitSUBC(N);
1323 case ISD::ADDE: return visitADDE(N);
1324 case ISD::SUBE: return visitSUBE(N);
1325 case ISD::MUL: return visitMUL(N);
1326 case ISD::SDIV: return visitSDIV(N);
1327 case ISD::UDIV: return visitUDIV(N);
1328 case ISD::SREM: return visitSREM(N);
1329 case ISD::UREM: return visitUREM(N);
1330 case ISD::MULHU: return visitMULHU(N);
1331 case ISD::MULHS: return visitMULHS(N);
1332 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1333 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1334 case ISD::SMULO: return visitSMULO(N);
1335 case ISD::UMULO: return visitUMULO(N);
1336 case ISD::SDIVREM: return visitSDIVREM(N);
1337 case ISD::UDIVREM: return visitUDIVREM(N);
1338 case ISD::AND: return visitAND(N);
1339 case ISD::OR: return visitOR(N);
1340 case ISD::XOR: return visitXOR(N);
1341 case ISD::SHL: return visitSHL(N);
1342 case ISD::SRA: return visitSRA(N);
1343 case ISD::SRL: return visitSRL(N);
1345 case ISD::ROTL: return visitRotate(N);
1346 case ISD::BSWAP: return visitBSWAP(N);
1347 case ISD::CTLZ: return visitCTLZ(N);
1348 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1349 case ISD::CTTZ: return visitCTTZ(N);
1350 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1351 case ISD::CTPOP: return visitCTPOP(N);
1352 case ISD::SELECT: return visitSELECT(N);
1353 case ISD::VSELECT: return visitVSELECT(N);
1354 case ISD::SELECT_CC: return visitSELECT_CC(N);
1355 case ISD::SETCC: return visitSETCC(N);
1356 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1357 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1358 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1359 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1360 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1361 case ISD::TRUNCATE: return visitTRUNCATE(N);
1362 case ISD::BITCAST: return visitBITCAST(N);
1363 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1364 case ISD::FADD: return visitFADD(N);
1365 case ISD::FSUB: return visitFSUB(N);
1366 case ISD::FMUL: return visitFMUL(N);
1367 case ISD::FMA: return visitFMA(N);
1368 case ISD::FDIV: return visitFDIV(N);
1369 case ISD::FREM: return visitFREM(N);
1370 case ISD::FSQRT: return visitFSQRT(N);
1371 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1372 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1373 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1374 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1375 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1376 case ISD::FP_ROUND: return visitFP_ROUND(N);
1377 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1378 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1379 case ISD::FNEG: return visitFNEG(N);
1380 case ISD::FABS: return visitFABS(N);
1381 case ISD::FFLOOR: return visitFFLOOR(N);
1382 case ISD::FMINNUM: return visitFMINNUM(N);
1383 case ISD::FMAXNUM: return visitFMAXNUM(N);
1384 case ISD::FCEIL: return visitFCEIL(N);
1385 case ISD::FTRUNC: return visitFTRUNC(N);
1386 case ISD::BRCOND: return visitBRCOND(N);
1387 case ISD::BR_CC: return visitBR_CC(N);
1388 case ISD::LOAD: return visitLOAD(N);
1389 case ISD::STORE: return visitSTORE(N);
1390 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1391 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1392 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1393 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1394 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1395 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1396 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1397 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1398 case ISD::MGATHER: return visitMGATHER(N);
1399 case ISD::MLOAD: return visitMLOAD(N);
1400 case ISD::MSCATTER: return visitMSCATTER(N);
1401 case ISD::MSTORE: return visitMSTORE(N);
1402 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1407 SDValue DAGCombiner::combine(SDNode *N) {
1408 SDValue RV = visit(N);
1410 // If nothing happened, try a target-specific DAG combine.
1411 if (!RV.getNode()) {
1412 assert(N->getOpcode() != ISD::DELETED_NODE &&
1413 "Node was deleted but visit returned NULL!");
1415 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1416 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1418 // Expose the DAG combiner to the target combiner impls.
1419 TargetLowering::DAGCombinerInfo
1420 DagCombineInfo(DAG, Level, false, this);
1422 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1426 // If nothing happened still, try promoting the operation.
1427 if (!RV.getNode()) {
1428 switch (N->getOpcode()) {
1436 RV = PromoteIntBinOp(SDValue(N, 0));
1441 RV = PromoteIntShiftOp(SDValue(N, 0));
1443 case ISD::SIGN_EXTEND:
1444 case ISD::ZERO_EXTEND:
1445 case ISD::ANY_EXTEND:
1446 RV = PromoteExtend(SDValue(N, 0));
1449 if (PromoteLoad(SDValue(N, 0)))
1455 // If N is a commutative binary node, try commuting it to enable more
1457 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1458 N->getNumValues() == 1) {
1459 SDValue N0 = N->getOperand(0);
1460 SDValue N1 = N->getOperand(1);
1462 // Constant operands are canonicalized to RHS.
1463 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1464 SDValue Ops[] = {N1, N0};
1466 if (const BinaryWithFlagsSDNode *BinNode =
1467 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1468 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1469 BinNode->Flags.hasNoUnsignedWrap(),
1470 BinNode->Flags.hasNoSignedWrap(),
1471 BinNode->Flags.hasExact());
1473 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1476 return SDValue(CSENode, 0);
1483 /// Given a node, return its input chain if it has one, otherwise return a null
1485 static SDValue getInputChainForNode(SDNode *N) {
1486 if (unsigned NumOps = N->getNumOperands()) {
1487 if (N->getOperand(0).getValueType() == MVT::Other)
1488 return N->getOperand(0);
1489 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1490 return N->getOperand(NumOps-1);
1491 for (unsigned i = 1; i < NumOps-1; ++i)
1492 if (N->getOperand(i).getValueType() == MVT::Other)
1493 return N->getOperand(i);
1498 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1499 // If N has two operands, where one has an input chain equal to the other,
1500 // the 'other' chain is redundant.
1501 if (N->getNumOperands() == 2) {
1502 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1503 return N->getOperand(0);
1504 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1505 return N->getOperand(1);
1508 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1509 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1510 SmallPtrSet<SDNode*, 16> SeenOps;
1511 bool Changed = false; // If we should replace this token factor.
1513 // Start out with this token factor.
1516 // Iterate through token factors. The TFs grows when new token factors are
1518 for (unsigned i = 0; i < TFs.size(); ++i) {
1519 SDNode *TF = TFs[i];
1521 // Check each of the operands.
1522 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1523 SDValue Op = TF->getOperand(i);
1525 switch (Op.getOpcode()) {
1526 case ISD::EntryToken:
1527 // Entry tokens don't need to be added to the list. They are
1532 case ISD::TokenFactor:
1533 if (Op.hasOneUse() &&
1534 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1535 // Queue up for processing.
1536 TFs.push_back(Op.getNode());
1537 // Clean up in case the token factor is removed.
1538 AddToWorklist(Op.getNode());
1545 // Only add if it isn't already in the list.
1546 if (SeenOps.insert(Op.getNode()).second)
1557 // If we've changed things around then replace token factor.
1560 // The entry token is the only possible outcome.
1561 Result = DAG.getEntryNode();
1563 // New and improved token factor.
1564 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1567 // Add users to worklist if AA is enabled, since it may introduce
1568 // a lot of new chained token factors while removing memory deps.
1569 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1570 : DAG.getSubtarget().useAA();
1571 return CombineTo(N, Result, UseAA /*add to worklist*/);
1577 /// MERGE_VALUES can always be eliminated.
1578 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1579 WorklistRemover DeadNodes(*this);
1580 // Replacing results may cause a different MERGE_VALUES to suddenly
1581 // be CSE'd with N, and carry its uses with it. Iterate until no
1582 // uses remain, to ensure that the node can be safely deleted.
1583 // First add the users of this node to the work list so that they
1584 // can be tried again once they have new operands.
1585 AddUsersToWorklist(N);
1587 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1588 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1589 } while (!N->use_empty());
1590 deleteAndRecombine(N);
1591 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1594 static bool isNullConstant(SDValue V) {
1595 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1596 return Const != nullptr && Const->isNullValue();
1599 static bool isNullFPConstant(SDValue V) {
1600 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1601 return Const != nullptr && Const->isZero() && !Const->isNegative();
1604 static bool isAllOnesConstant(SDValue V) {
1605 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1606 return Const != nullptr && Const->isAllOnesValue();
1609 static bool isOneConstant(SDValue V) {
1610 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1611 return Const != nullptr && Const->isOne();
1614 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1615 /// ContantSDNode pointer else nullptr.
1616 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1617 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1618 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1621 SDValue DAGCombiner::visitADD(SDNode *N) {
1622 SDValue N0 = N->getOperand(0);
1623 SDValue N1 = N->getOperand(1);
1624 EVT VT = N0.getValueType();
1627 if (VT.isVector()) {
1628 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1631 // fold (add x, 0) -> x, vector edition
1632 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1634 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1638 // fold (add x, undef) -> undef
1639 if (N0.getOpcode() == ISD::UNDEF)
1641 if (N1.getOpcode() == ISD::UNDEF)
1643 // fold (add c1, c2) -> c1+c2
1644 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1645 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1647 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1648 // canonicalize constant to RHS
1649 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1650 !isConstantIntBuildVectorOrConstantInt(N1))
1651 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1652 // fold (add x, 0) -> x
1653 if (isNullConstant(N1))
1655 // fold (add Sym, c) -> Sym+c
1656 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1657 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1658 GA->getOpcode() == ISD::GlobalAddress)
1659 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1661 (uint64_t)N1C->getSExtValue());
1662 // fold ((c1-A)+c2) -> (c1+c2)-A
1663 if (N1C && N0.getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1666 return DAG.getNode(ISD::SUB, DL, VT,
1667 DAG.getConstant(N1C->getAPIntValue()+
1668 N0C->getAPIntValue(), DL, VT),
1672 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1674 // fold ((0-A) + B) -> B-A
1675 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1676 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1677 // fold (A + (0-B)) -> A-B
1678 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1679 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1680 // fold (A+(B-A)) -> B
1681 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1682 return N1.getOperand(0);
1683 // fold ((B-A)+A) -> B
1684 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1685 return N0.getOperand(0);
1686 // fold (A+(B-(A+C))) to (B-C)
1687 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1688 N0 == N1.getOperand(1).getOperand(0))
1689 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1690 N1.getOperand(1).getOperand(1));
1691 // fold (A+(B-(C+A))) to (B-C)
1692 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1693 N0 == N1.getOperand(1).getOperand(1))
1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1695 N1.getOperand(1).getOperand(0));
1696 // fold (A+((B-A)+or-C)) to (B+or-C)
1697 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1698 N1.getOperand(0).getOpcode() == ISD::SUB &&
1699 N0 == N1.getOperand(0).getOperand(1))
1700 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1701 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1703 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1704 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1705 SDValue N00 = N0.getOperand(0);
1706 SDValue N01 = N0.getOperand(1);
1707 SDValue N10 = N1.getOperand(0);
1708 SDValue N11 = N1.getOperand(1);
1710 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1711 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1712 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1713 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1716 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1717 return SDValue(N, 0);
1719 // fold (a+b) -> (a|b) iff a and b share no bits.
1720 if (VT.isInteger() && !VT.isVector()) {
1721 APInt LHSZero, LHSOne;
1722 APInt RHSZero, RHSOne;
1723 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1725 if (LHSZero.getBoolValue()) {
1726 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1728 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1729 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1730 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1731 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1732 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1737 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1738 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1739 isNullConstant(N1.getOperand(0).getOperand(0)))
1740 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1741 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1742 N1.getOperand(0).getOperand(1),
1744 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1745 isNullConstant(N0.getOperand(0).getOperand(0)))
1746 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1747 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1748 N0.getOperand(0).getOperand(1),
1751 if (N1.getOpcode() == ISD::AND) {
1752 SDValue AndOp0 = N1.getOperand(0);
1753 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1754 unsigned DestBits = VT.getScalarType().getSizeInBits();
1756 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1757 // and similar xforms where the inner op is either ~0 or 0.
1758 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1760 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1764 // add (sext i1), X -> sub X, (zext i1)
1765 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1766 N0.getOperand(0).getValueType() == MVT::i1 &&
1767 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1769 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1770 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1773 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1774 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1775 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1776 if (TN->getVT() == MVT::i1) {
1778 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1779 DAG.getConstant(1, DL, VT));
1780 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1787 SDValue DAGCombiner::visitADDC(SDNode *N) {
1788 SDValue N0 = N->getOperand(0);
1789 SDValue N1 = N->getOperand(1);
1790 EVT VT = N0.getValueType();
1792 // If the flag result is dead, turn this into an ADD.
1793 if (!N->hasAnyUseOfValue(1))
1794 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1795 DAG.getNode(ISD::CARRY_FALSE,
1796 SDLoc(N), MVT::Glue));
1798 // canonicalize constant to RHS.
1799 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1800 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1804 // fold (addc x, 0) -> x + no carry out
1805 if (isNullConstant(N1))
1806 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1807 SDLoc(N), MVT::Glue));
1809 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1810 APInt LHSZero, LHSOne;
1811 APInt RHSZero, RHSOne;
1812 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1814 if (LHSZero.getBoolValue()) {
1815 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1817 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1818 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1819 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1820 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1821 DAG.getNode(ISD::CARRY_FALSE,
1822 SDLoc(N), MVT::Glue));
1828 SDValue DAGCombiner::visitADDE(SDNode *N) {
1829 SDValue N0 = N->getOperand(0);
1830 SDValue N1 = N->getOperand(1);
1831 SDValue CarryIn = N->getOperand(2);
1833 // canonicalize constant to RHS
1834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1837 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1840 // fold (adde x, y, false) -> (addc x, y)
1841 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1842 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1847 // Since it may not be valid to emit a fold to zero for vector initializers
1848 // check if we can before folding.
1849 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1851 bool LegalOperations, bool LegalTypes) {
1853 return DAG.getConstant(0, DL, VT);
1854 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1855 return DAG.getConstant(0, DL, VT);
1859 SDValue DAGCombiner::visitSUB(SDNode *N) {
1860 SDValue N0 = N->getOperand(0);
1861 SDValue N1 = N->getOperand(1);
1862 EVT VT = N0.getValueType();
1865 if (VT.isVector()) {
1866 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1869 // fold (sub x, 0) -> x, vector edition
1870 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1874 // fold (sub x, x) -> 0
1875 // FIXME: Refactor this and xor and other similar operations together.
1877 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1878 // fold (sub c1, c2) -> c1-c2
1879 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1880 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1882 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1883 // fold (sub x, c) -> (add x, -c)
1886 return DAG.getNode(ISD::ADD, DL, VT, N0,
1887 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1889 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1890 if (isAllOnesConstant(N0))
1891 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1892 // fold A-(A-B) -> B
1893 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1894 return N1.getOperand(1);
1895 // fold (A+B)-A -> B
1896 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1897 return N0.getOperand(1);
1898 // fold (A+B)-B -> A
1899 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1900 return N0.getOperand(0);
1901 // fold C2-(A+C1) -> (C2-C1)-A
1902 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1903 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1904 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1906 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1908 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1911 // fold ((A+(B+or-C))-B) -> A+or-C
1912 if (N0.getOpcode() == ISD::ADD &&
1913 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1914 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1915 N0.getOperand(1).getOperand(0) == N1)
1916 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1917 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1918 // fold ((A+(C+B))-B) -> A+C
1919 if (N0.getOpcode() == ISD::ADD &&
1920 N0.getOperand(1).getOpcode() == ISD::ADD &&
1921 N0.getOperand(1).getOperand(1) == N1)
1922 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1923 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1924 // fold ((A-(B-C))-C) -> A-B
1925 if (N0.getOpcode() == ISD::SUB &&
1926 N0.getOperand(1).getOpcode() == ISD::SUB &&
1927 N0.getOperand(1).getOperand(1) == N1)
1928 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1929 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1931 // If either operand of a sub is undef, the result is undef
1932 if (N0.getOpcode() == ISD::UNDEF)
1934 if (N1.getOpcode() == ISD::UNDEF)
1937 // If the relocation model supports it, consider symbol offsets.
1938 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1939 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1940 // fold (sub Sym, c) -> Sym-c
1941 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1942 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1944 (uint64_t)N1C->getSExtValue());
1945 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1946 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1947 if (GA->getGlobal() == GB->getGlobal())
1948 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1952 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1953 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1954 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1955 if (TN->getVT() == MVT::i1) {
1957 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1958 DAG.getConstant(1, DL, VT));
1959 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1966 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
1969 EVT VT = N0.getValueType();
1971 // If the flag result is dead, turn this into an SUB.
1972 if (!N->hasAnyUseOfValue(1))
1973 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1974 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1977 // fold (subc x, x) -> 0 + no borrow
1980 return CombineTo(N, DAG.getConstant(0, DL, VT),
1981 DAG.getNode(ISD::CARRY_FALSE, DL,
1985 // fold (subc x, 0) -> x + no borrow
1986 if (isNullConstant(N1))
1987 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1990 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1991 if (isAllOnesConstant(N0))
1992 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1993 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1999 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2000 SDValue N0 = N->getOperand(0);
2001 SDValue N1 = N->getOperand(1);
2002 SDValue CarryIn = N->getOperand(2);
2004 // fold (sube x, y, false) -> (subc x, y)
2005 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2006 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2011 SDValue DAGCombiner::visitMUL(SDNode *N) {
2012 SDValue N0 = N->getOperand(0);
2013 SDValue N1 = N->getOperand(1);
2014 EVT VT = N0.getValueType();
2016 // fold (mul x, undef) -> 0
2017 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2018 return DAG.getConstant(0, SDLoc(N), VT);
2020 bool N0IsConst = false;
2021 bool N1IsConst = false;
2022 bool N1IsOpaqueConst = false;
2023 bool N0IsOpaqueConst = false;
2024 APInt ConstValue0, ConstValue1;
2026 if (VT.isVector()) {
2027 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2030 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2031 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2033 N0IsConst = isa<ConstantSDNode>(N0);
2035 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2036 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2038 N1IsConst = isa<ConstantSDNode>(N1);
2040 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2041 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2045 // fold (mul c1, c2) -> c1*c2
2046 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2047 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2048 N0.getNode(), N1.getNode());
2050 // canonicalize constant to RHS (vector doesn't have to splat)
2051 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2052 !isConstantIntBuildVectorOrConstantInt(N1))
2053 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2054 // fold (mul x, 0) -> 0
2055 if (N1IsConst && ConstValue1 == 0)
2057 // We require a splat of the entire scalar bit width for non-contiguous
2060 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2061 // fold (mul x, 1) -> x
2062 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2064 // fold (mul x, -1) -> 0-x
2065 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2067 return DAG.getNode(ISD::SUB, DL, VT,
2068 DAG.getConstant(0, DL, VT), N0);
2070 // fold (mul x, (1 << c)) -> x << c
2071 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2074 return DAG.getNode(ISD::SHL, DL, VT, N0,
2075 DAG.getConstant(ConstValue1.logBase2(), DL,
2076 getShiftAmountTy(N0.getValueType())));
2078 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2079 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2081 unsigned Log2Val = (-ConstValue1).logBase2();
2083 // FIXME: If the input is something that is easily negated (e.g. a
2084 // single-use add), we should put the negate there.
2085 return DAG.getNode(ISD::SUB, DL, VT,
2086 DAG.getConstant(0, DL, VT),
2087 DAG.getNode(ISD::SHL, DL, VT, N0,
2088 DAG.getConstant(Log2Val, DL,
2089 getShiftAmountTy(N0.getValueType()))));
2093 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2094 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2095 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096 isa<ConstantSDNode>(N0.getOperand(1)))) {
2097 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2098 N1, N0.getOperand(1));
2099 AddToWorklist(C3.getNode());
2100 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2101 N0.getOperand(0), C3);
2104 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2107 SDValue Sh(nullptr,0), Y(nullptr,0);
2108 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2109 if (N0.getOpcode() == ISD::SHL &&
2110 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2111 isa<ConstantSDNode>(N0.getOperand(1))) &&
2112 N0.getNode()->hasOneUse()) {
2114 } else if (N1.getOpcode() == ISD::SHL &&
2115 isa<ConstantSDNode>(N1.getOperand(1)) &&
2116 N1.getNode()->hasOneUse()) {
2121 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2122 Sh.getOperand(0), Y);
2123 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2124 Mul, Sh.getOperand(1));
2128 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2129 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2130 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2131 isa<ConstantSDNode>(N0.getOperand(1))))
2132 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2133 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2134 N0.getOperand(0), N1),
2135 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2136 N0.getOperand(1), N1));
2139 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2145 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2146 SDValue N0 = N->getOperand(0);
2147 SDValue N1 = N->getOperand(1);
2148 EVT VT = N->getValueType(0);
2152 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2155 // fold (sdiv c1, c2) -> c1/c2
2156 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2157 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2158 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2159 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2160 // fold (sdiv X, 1) -> X
2161 if (N1C && N1C->isOne())
2163 // fold (sdiv X, -1) -> 0-X
2164 if (N1C && N1C->isAllOnesValue()) {
2166 return DAG.getNode(ISD::SUB, DL, VT,
2167 DAG.getConstant(0, DL, VT), N0);
2169 // If we know the sign bits of both operands are zero, strength reduce to a
2170 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2171 if (!VT.isVector()) {
2172 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2173 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2177 // fold (sdiv X, pow2) -> simple ops after legalize
2178 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2179 (N1C->getAPIntValue().isPowerOf2() ||
2180 (-N1C->getAPIntValue()).isPowerOf2())) {
2181 // If dividing by powers of two is cheap, then don't perform the following
2183 if (TLI.isPow2SDivCheap())
2186 // Target-specific implementation of sdiv x, pow2.
2187 SDValue Res = BuildSDIVPow2(N);
2191 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2194 // Splat the sign bit into the register
2196 DAG.getNode(ISD::SRA, DL, VT, N0,
2197 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2198 getShiftAmountTy(N0.getValueType())));
2199 AddToWorklist(SGN.getNode());
2201 // Add (N0 < 0) ? abs2 - 1 : 0;
2203 DAG.getNode(ISD::SRL, DL, VT, SGN,
2204 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2205 getShiftAmountTy(SGN.getValueType())));
2206 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2207 AddToWorklist(SRL.getNode());
2208 AddToWorklist(ADD.getNode()); // Divide by pow2
2209 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2210 DAG.getConstant(lg2, DL,
2211 getShiftAmountTy(ADD.getValueType())));
2213 // If we're dividing by a positive value, we're done. Otherwise, we must
2214 // negate the result.
2215 if (N1C->getAPIntValue().isNonNegative())
2218 AddToWorklist(SRA.getNode());
2219 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2222 // If integer divide is expensive and we satisfy the requirements, emit an
2223 // alternate sequence.
2224 if (N1C && !TLI.isIntDivCheap()) {
2225 SDValue Op = BuildSDIV(N);
2226 if (Op.getNode()) return Op;
2230 if (N0.getOpcode() == ISD::UNDEF)
2231 return DAG.getConstant(0, SDLoc(N), VT);
2232 // X / undef -> undef
2233 if (N1.getOpcode() == ISD::UNDEF)
2239 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2240 SDValue N0 = N->getOperand(0);
2241 SDValue N1 = N->getOperand(1);
2242 EVT VT = N->getValueType(0);
2246 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2249 // fold (udiv c1, c2) -> c1/c2
2250 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2251 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2253 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2256 // fold (udiv x, (1 << c)) -> x >>u c
2257 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2259 return DAG.getNode(ISD::SRL, DL, VT, N0,
2260 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2261 getShiftAmountTy(N0.getValueType())));
2263 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2264 if (N1.getOpcode() == ISD::SHL) {
2265 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2266 if (SHC->getAPIntValue().isPowerOf2()) {
2267 EVT ADDVT = N1.getOperand(1).getValueType();
2269 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2271 DAG.getConstant(SHC->getAPIntValue()
2274 AddToWorklist(Add.getNode());
2275 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2279 // fold (udiv x, c) -> alternate
2280 if (N1C && !TLI.isIntDivCheap()) {
2281 SDValue Op = BuildUDIV(N);
2282 if (Op.getNode()) return Op;
2286 if (N0.getOpcode() == ISD::UNDEF)
2287 return DAG.getConstant(0, SDLoc(N), VT);
2288 // X / undef -> undef
2289 if (N1.getOpcode() == ISD::UNDEF)
2295 SDValue DAGCombiner::visitSREM(SDNode *N) {
2296 SDValue N0 = N->getOperand(0);
2297 SDValue N1 = N->getOperand(1);
2298 EVT VT = N->getValueType(0);
2300 // fold (srem c1, c2) -> c1%c2
2301 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2304 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2307 // If we know the sign bits of both operands are zero, strength reduce to a
2308 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2309 if (!VT.isVector()) {
2310 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2311 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2314 // If X/C can be simplified by the division-by-constant logic, lower
2315 // X%C to the equivalent of X-X/C*C.
2316 if (N1C && !N1C->isNullValue()) {
2317 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2318 AddToWorklist(Div.getNode());
2319 SDValue OptimizedDiv = combine(Div.getNode());
2320 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2321 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2323 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2324 AddToWorklist(Mul.getNode());
2330 if (N0.getOpcode() == ISD::UNDEF)
2331 return DAG.getConstant(0, SDLoc(N), VT);
2332 // X % undef -> undef
2333 if (N1.getOpcode() == ISD::UNDEF)
2339 SDValue DAGCombiner::visitUREM(SDNode *N) {
2340 SDValue N0 = N->getOperand(0);
2341 SDValue N1 = N->getOperand(1);
2342 EVT VT = N->getValueType(0);
2344 // fold (urem c1, c2) -> c1%c2
2345 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2346 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2348 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2351 // fold (urem x, pow2) -> (and x, pow2-1)
2352 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2353 N1C->getAPIntValue().isPowerOf2()) {
2355 return DAG.getNode(ISD::AND, DL, VT, N0,
2356 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2358 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2359 if (N1.getOpcode() == ISD::SHL) {
2360 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2361 if (SHC->getAPIntValue().isPowerOf2()) {
2364 DAG.getNode(ISD::ADD, DL, VT, N1,
2365 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2367 AddToWorklist(Add.getNode());
2368 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2373 // If X/C can be simplified by the division-by-constant logic, lower
2374 // X%C to the equivalent of X-X/C*C.
2375 if (N1C && !N1C->isNullValue()) {
2376 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2377 AddToWorklist(Div.getNode());
2378 SDValue OptimizedDiv = combine(Div.getNode());
2379 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2380 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2382 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2383 AddToWorklist(Mul.getNode());
2389 if (N0.getOpcode() == ISD::UNDEF)
2390 return DAG.getConstant(0, SDLoc(N), VT);
2391 // X % undef -> undef
2392 if (N1.getOpcode() == ISD::UNDEF)
2398 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2399 SDValue N0 = N->getOperand(0);
2400 SDValue N1 = N->getOperand(1);
2401 EVT VT = N->getValueType(0);
2404 // fold (mulhs x, 0) -> 0
2405 if (isNullConstant(N1))
2407 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2408 if (isOneConstant(N1)) {
2410 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2411 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2413 getShiftAmountTy(N0.getValueType())));
2415 // fold (mulhs x, undef) -> 0
2416 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2417 return DAG.getConstant(0, SDLoc(N), VT);
2419 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2421 if (VT.isSimple() && !VT.isVector()) {
2422 MVT Simple = VT.getSimpleVT();
2423 unsigned SimpleSize = Simple.getSizeInBits();
2424 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2425 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2426 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2427 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2428 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2429 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2430 DAG.getConstant(SimpleSize, DL,
2431 getShiftAmountTy(N1.getValueType())));
2432 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2439 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2440 SDValue N0 = N->getOperand(0);
2441 SDValue N1 = N->getOperand(1);
2442 EVT VT = N->getValueType(0);
2445 // fold (mulhu x, 0) -> 0
2446 if (isNullConstant(N1))
2448 // fold (mulhu x, 1) -> 0
2449 if (isOneConstant(N1))
2450 return DAG.getConstant(0, DL, N0.getValueType());
2451 // fold (mulhu x, undef) -> 0
2452 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2453 return DAG.getConstant(0, DL, VT);
2455 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2457 if (VT.isSimple() && !VT.isVector()) {
2458 MVT Simple = VT.getSimpleVT();
2459 unsigned SimpleSize = Simple.getSizeInBits();
2460 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2461 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2462 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2463 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2464 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2465 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2466 DAG.getConstant(SimpleSize, DL,
2467 getShiftAmountTy(N1.getValueType())));
2468 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2475 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2476 /// give the opcodes for the two computations that are being performed. Return
2477 /// true if a simplification was made.
2478 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2480 // If the high half is not needed, just compute the low half.
2481 bool HiExists = N->hasAnyUseOfValue(1);
2483 (!LegalOperations ||
2484 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2485 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2486 return CombineTo(N, Res, Res);
2489 // If the low half is not needed, just compute the high half.
2490 bool LoExists = N->hasAnyUseOfValue(0);
2492 (!LegalOperations ||
2493 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2494 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2495 return CombineTo(N, Res, Res);
2498 // If both halves are used, return as it is.
2499 if (LoExists && HiExists)
2502 // If the two computed results can be simplified separately, separate them.
2504 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2505 AddToWorklist(Lo.getNode());
2506 SDValue LoOpt = combine(Lo.getNode());
2507 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2508 (!LegalOperations ||
2509 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2510 return CombineTo(N, LoOpt, LoOpt);
2514 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2515 AddToWorklist(Hi.getNode());
2516 SDValue HiOpt = combine(Hi.getNode());
2517 if (HiOpt.getNode() && HiOpt != Hi &&
2518 (!LegalOperations ||
2519 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2520 return CombineTo(N, HiOpt, HiOpt);
2526 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2527 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2528 if (Res.getNode()) return Res;
2530 EVT VT = N->getValueType(0);
2533 // If the type is twice as wide is legal, transform the mulhu to a wider
2534 // multiply plus a shift.
2535 if (VT.isSimple() && !VT.isVector()) {
2536 MVT Simple = VT.getSimpleVT();
2537 unsigned SimpleSize = Simple.getSizeInBits();
2538 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2539 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2540 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2541 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2542 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2543 // Compute the high part as N1.
2544 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2545 DAG.getConstant(SimpleSize, DL,
2546 getShiftAmountTy(Lo.getValueType())));
2547 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2548 // Compute the low part as N0.
2549 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2550 return CombineTo(N, Lo, Hi);
2557 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2558 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2559 if (Res.getNode()) return Res;
2561 EVT VT = N->getValueType(0);
2564 // If the type is twice as wide is legal, transform the mulhu to a wider
2565 // multiply plus a shift.
2566 if (VT.isSimple() && !VT.isVector()) {
2567 MVT Simple = VT.getSimpleVT();
2568 unsigned SimpleSize = Simple.getSizeInBits();
2569 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2570 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2571 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2572 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2573 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2574 // Compute the high part as N1.
2575 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2576 DAG.getConstant(SimpleSize, DL,
2577 getShiftAmountTy(Lo.getValueType())));
2578 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2579 // Compute the low part as N0.
2580 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2581 return CombineTo(N, Lo, Hi);
2588 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2589 // (smulo x, 2) -> (saddo x, x)
2590 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2591 if (C2->getAPIntValue() == 2)
2592 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2593 N->getOperand(0), N->getOperand(0));
2598 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2599 // (umulo x, 2) -> (uaddo x, x)
2600 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2601 if (C2->getAPIntValue() == 2)
2602 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2603 N->getOperand(0), N->getOperand(0));
2608 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2609 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2610 if (Res.getNode()) return Res;
2615 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2616 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2617 if (Res.getNode()) return Res;
2622 /// If this is a binary operator with two operands of the same opcode, try to
2624 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2625 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2626 EVT VT = N0.getValueType();
2627 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2629 // Bail early if none of these transforms apply.
2630 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2632 // For each of OP in AND/OR/XOR:
2633 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2634 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2635 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2636 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2637 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2639 // do not sink logical op inside of a vector extend, since it may combine
2641 EVT Op0VT = N0.getOperand(0).getValueType();
2642 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2643 N0.getOpcode() == ISD::SIGN_EXTEND ||
2644 N0.getOpcode() == ISD::BSWAP ||
2645 // Avoid infinite looping with PromoteIntBinOp.
2646 (N0.getOpcode() == ISD::ANY_EXTEND &&
2647 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2648 (N0.getOpcode() == ISD::TRUNCATE &&
2649 (!TLI.isZExtFree(VT, Op0VT) ||
2650 !TLI.isTruncateFree(Op0VT, VT)) &&
2651 TLI.isTypeLegal(Op0VT))) &&
2653 Op0VT == N1.getOperand(0).getValueType() &&
2654 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2655 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2656 N0.getOperand(0).getValueType(),
2657 N0.getOperand(0), N1.getOperand(0));
2658 AddToWorklist(ORNode.getNode());
2659 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2662 // For each of OP in SHL/SRL/SRA/AND...
2663 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2664 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2665 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2666 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2667 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2668 N0.getOperand(1) == N1.getOperand(1)) {
2669 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2670 N0.getOperand(0).getValueType(),
2671 N0.getOperand(0), N1.getOperand(0));
2672 AddToWorklist(ORNode.getNode());
2673 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2674 ORNode, N0.getOperand(1));
2677 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2678 // Only perform this optimization after type legalization and before
2679 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2680 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2681 // we don't want to undo this promotion.
2682 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2684 if ((N0.getOpcode() == ISD::BITCAST ||
2685 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2686 Level == AfterLegalizeTypes) {
2687 SDValue In0 = N0.getOperand(0);
2688 SDValue In1 = N1.getOperand(0);
2689 EVT In0Ty = In0.getValueType();
2690 EVT In1Ty = In1.getValueType();
2692 // If both incoming values are integers, and the original types are the
2694 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2695 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2696 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2697 AddToWorklist(Op.getNode());
2702 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2703 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2704 // If both shuffles use the same mask, and both shuffle within a single
2705 // vector, then it is worthwhile to move the swizzle after the operation.
2706 // The type-legalizer generates this pattern when loading illegal
2707 // vector types from memory. In many cases this allows additional shuffle
2709 // There are other cases where moving the shuffle after the xor/and/or
2710 // is profitable even if shuffles don't perform a swizzle.
2711 // If both shuffles use the same mask, and both shuffles have the same first
2712 // or second operand, then it might still be profitable to move the shuffle
2713 // after the xor/and/or operation.
2714 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2715 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2716 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2718 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2719 "Inputs to shuffles are not the same type");
2721 // Check that both shuffles use the same mask. The masks are known to be of
2722 // the same length because the result vector type is the same.
2723 // Check also that shuffles have only one use to avoid introducing extra
2725 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2726 SVN0->getMask().equals(SVN1->getMask())) {
2727 SDValue ShOp = N0->getOperand(1);
2729 // Don't try to fold this node if it requires introducing a
2730 // build vector of all zeros that might be illegal at this stage.
2731 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2733 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2738 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2739 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2740 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2741 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2742 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2743 N0->getOperand(0), N1->getOperand(0));
2744 AddToWorklist(NewNode.getNode());
2745 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2746 &SVN0->getMask()[0]);
2749 // Don't try to fold this node if it requires introducing a
2750 // build vector of all zeros that might be illegal at this stage.
2751 ShOp = N0->getOperand(0);
2752 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2754 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2759 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2760 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2761 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2762 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2763 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2764 N0->getOperand(1), N1->getOperand(1));
2765 AddToWorklist(NewNode.getNode());
2766 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2767 &SVN0->getMask()[0]);
2775 /// This contains all DAGCombine rules which reduce two values combined by
2776 /// an And operation to a single value. This makes them reusable in the context
2777 /// of visitSELECT(). Rules involving constants are not included as
2778 /// visitSELECT() already handles those cases.
2779 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2780 SDNode *LocReference) {
2781 EVT VT = N1.getValueType();
2783 // fold (and x, undef) -> 0
2784 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2785 return DAG.getConstant(0, SDLoc(LocReference), VT);
2786 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2787 SDValue LL, LR, RL, RR, CC0, CC1;
2788 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2789 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2790 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2792 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2793 LL.getValueType().isInteger()) {
2794 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2795 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2796 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2797 LR.getValueType(), LL, RL);
2798 AddToWorklist(ORNode.getNode());
2799 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2801 if (isAllOnesConstant(LR)) {
2802 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2803 if (Op1 == ISD::SETEQ) {
2804 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2805 LR.getValueType(), LL, RL);
2806 AddToWorklist(ANDNode.getNode());
2807 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2809 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2810 if (Op1 == ISD::SETGT) {
2811 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2812 LR.getValueType(), LL, RL);
2813 AddToWorklist(ORNode.getNode());
2814 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2818 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2819 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2820 Op0 == Op1 && LL.getValueType().isInteger() &&
2821 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2822 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2824 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2825 LL, DAG.getConstant(1, DL,
2826 LL.getValueType()));
2827 AddToWorklist(ADDNode.getNode());
2828 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2829 DAG.getConstant(2, DL, LL.getValueType()),
2832 // canonicalize equivalent to ll == rl
2833 if (LL == RR && LR == RL) {
2834 Op1 = ISD::getSetCCSwappedOperands(Op1);
2837 if (LL == RL && LR == RR) {
2838 bool isInteger = LL.getValueType().isInteger();
2839 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2840 if (Result != ISD::SETCC_INVALID &&
2841 (!LegalOperations ||
2842 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2843 TLI.isOperationLegal(ISD::SETCC,
2844 getSetCCResultType(N0.getSimpleValueType())))))
2845 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2850 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2851 VT.getSizeInBits() <= 64) {
2852 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2853 APInt ADDC = ADDI->getAPIntValue();
2854 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2855 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2856 // immediate for an add, but it is legal if its top c2 bits are set,
2857 // transform the ADD so the immediate doesn't need to be materialized
2859 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2860 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2861 SRLI->getZExtValue());
2862 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2864 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2867 DAG.getNode(ISD::ADD, DL, VT,
2868 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2869 CombineTo(N0.getNode(), NewAdd);
2870 // Return N so it doesn't get rechecked!
2871 return SDValue(LocReference, 0);
2882 SDValue DAGCombiner::visitAND(SDNode *N) {
2883 SDValue N0 = N->getOperand(0);
2884 SDValue N1 = N->getOperand(1);
2885 EVT VT = N1.getValueType();
2888 if (VT.isVector()) {
2889 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2892 // fold (and x, 0) -> 0, vector edition
2893 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2894 // do not return N0, because undef node may exist in N0
2895 return DAG.getConstant(
2896 APInt::getNullValue(
2897 N0.getValueType().getScalarType().getSizeInBits()),
2898 SDLoc(N), N0.getValueType());
2899 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2900 // do not return N1, because undef node may exist in N1
2901 return DAG.getConstant(
2902 APInt::getNullValue(
2903 N1.getValueType().getScalarType().getSizeInBits()),
2904 SDLoc(N), N1.getValueType());
2906 // fold (and x, -1) -> x, vector edition
2907 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2909 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2913 // fold (and c1, c2) -> c1&c2
2914 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2916 if (N0C && N1C && !N1C->isOpaque())
2917 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2918 // canonicalize constant to RHS
2919 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2920 !isConstantIntBuildVectorOrConstantInt(N1))
2921 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2922 // fold (and x, -1) -> x
2923 if (isAllOnesConstant(N1))
2925 // if (and x, c) is known to be zero, return 0
2926 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2927 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2928 APInt::getAllOnesValue(BitWidth)))
2929 return DAG.getConstant(0, SDLoc(N), VT);
2931 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2933 // fold (and (or x, C), D) -> D if (C & D) == D
2934 if (N1C && N0.getOpcode() == ISD::OR)
2935 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2936 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2938 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2939 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2940 SDValue N0Op0 = N0.getOperand(0);
2941 APInt Mask = ~N1C->getAPIntValue();
2942 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2943 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2944 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2945 N0.getValueType(), N0Op0);
2947 // Replace uses of the AND with uses of the Zero extend node.
2950 // We actually want to replace all uses of the any_extend with the
2951 // zero_extend, to avoid duplicating things. This will later cause this
2952 // AND to be folded.
2953 CombineTo(N0.getNode(), Zext);
2954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2957 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2958 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2959 // already be zero by virtue of the width of the base type of the load.
2961 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2963 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2964 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2965 N0.getOpcode() == ISD::LOAD) {
2966 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2967 N0 : N0.getOperand(0) );
2969 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2970 // This can be a pure constant or a vector splat, in which case we treat the
2971 // vector as a scalar and use the splat value.
2972 APInt Constant = APInt::getNullValue(1);
2973 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2974 Constant = C->getAPIntValue();
2975 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2976 APInt SplatValue, SplatUndef;
2977 unsigned SplatBitSize;
2979 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2980 SplatBitSize, HasAnyUndefs);
2982 // Undef bits can contribute to a possible optimisation if set, so
2984 SplatValue |= SplatUndef;
2986 // The splat value may be something like "0x00FFFFFF", which means 0 for
2987 // the first vector value and FF for the rest, repeating. We need a mask
2988 // that will apply equally to all members of the vector, so AND all the
2989 // lanes of the constant together.
2990 EVT VT = Vector->getValueType(0);
2991 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2993 // If the splat value has been compressed to a bitlength lower
2994 // than the size of the vector lane, we need to re-expand it to
2996 if (BitWidth > SplatBitSize)
2997 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2998 SplatBitSize < BitWidth;
2999 SplatBitSize = SplatBitSize * 2)
3000 SplatValue |= SplatValue.shl(SplatBitSize);
3002 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3003 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3004 if (SplatBitSize % BitWidth == 0) {
3005 Constant = APInt::getAllOnesValue(BitWidth);
3006 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3007 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3012 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3013 // actually legal and isn't going to get expanded, else this is a false
3015 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3016 Load->getValueType(0),
3017 Load->getMemoryVT());
3019 // Resize the constant to the same size as the original memory access before
3020 // extension. If it is still the AllOnesValue then this AND is completely
3023 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3026 switch (Load->getExtensionType()) {
3027 default: B = false; break;
3028 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3030 case ISD::NON_EXTLOAD: B = true; break;
3033 if (B && Constant.isAllOnesValue()) {
3034 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3035 // preserve semantics once we get rid of the AND.
3036 SDValue NewLoad(Load, 0);
3037 if (Load->getExtensionType() == ISD::EXTLOAD) {
3038 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3039 Load->getValueType(0), SDLoc(Load),
3040 Load->getChain(), Load->getBasePtr(),
3041 Load->getOffset(), Load->getMemoryVT(),
3042 Load->getMemOperand());
3043 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3044 if (Load->getNumValues() == 3) {
3045 // PRE/POST_INC loads have 3 values.
3046 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3047 NewLoad.getValue(2) };
3048 CombineTo(Load, To, 3, true);
3050 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3054 // Fold the AND away, taking care not to fold to the old load node if we
3056 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3058 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3062 // fold (and (load x), 255) -> (zextload x, i8)
3063 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3064 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3065 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3066 (N0.getOpcode() == ISD::ANY_EXTEND &&
3067 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3068 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3069 LoadSDNode *LN0 = HasAnyExt
3070 ? cast<LoadSDNode>(N0.getOperand(0))
3071 : cast<LoadSDNode>(N0);
3072 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3073 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3074 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3075 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3076 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3077 EVT LoadedVT = LN0->getMemoryVT();
3078 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3080 if (ExtVT == LoadedVT &&
3081 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3085 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3086 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3087 LN0->getMemOperand());
3089 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3090 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3093 // Do not change the width of a volatile load.
3094 // Do not generate loads of non-round integer types since these can
3095 // be expensive (and would be wrong if the type is not byte sized).
3096 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3097 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3099 EVT PtrType = LN0->getOperand(1).getValueType();
3101 unsigned Alignment = LN0->getAlignment();
3102 SDValue NewPtr = LN0->getBasePtr();
3104 // For big endian targets, we need to add an offset to the pointer
3105 // to load the correct bytes. For little endian systems, we merely
3106 // need to read fewer bytes from the same pointer.
3107 if (TLI.isBigEndian()) {
3108 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3109 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3110 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3112 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3113 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3114 Alignment = MinAlign(Alignment, PtrOff);
3117 AddToWorklist(NewPtr.getNode());
3120 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3121 LN0->getChain(), NewPtr,
3122 LN0->getPointerInfo(),
3123 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3124 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3126 CombineTo(LN0, Load, Load.getValue(1));
3127 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3133 if (SDValue Combined = visitANDLike(N0, N1, N))
3136 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3137 if (N0.getOpcode() == N1.getOpcode()) {
3138 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3139 if (Tmp.getNode()) return Tmp;
3142 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3143 // fold (and (sra)) -> (and (srl)) when possible.
3144 if (!VT.isVector() &&
3145 SimplifyDemandedBits(SDValue(N, 0)))
3146 return SDValue(N, 0);
3148 // fold (zext_inreg (extload x)) -> (zextload x)
3149 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3150 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3151 EVT MemVT = LN0->getMemoryVT();
3152 // If we zero all the possible extended bits, then we can turn this into
3153 // a zextload if we are running before legalize or the operation is legal.
3154 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3155 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3156 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3157 ((!LegalOperations && !LN0->isVolatile()) ||
3158 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3159 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3160 LN0->getChain(), LN0->getBasePtr(),
3161 MemVT, LN0->getMemOperand());
3163 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3164 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3167 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3168 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3170 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3171 EVT MemVT = LN0->getMemoryVT();
3172 // If we zero all the possible extended bits, then we can turn this into
3173 // a zextload if we are running before legalize or the operation is legal.
3174 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3175 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3176 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3177 ((!LegalOperations && !LN0->isVolatile()) ||
3178 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3179 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3180 LN0->getChain(), LN0->getBasePtr(),
3181 MemVT, LN0->getMemOperand());
3183 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3184 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3187 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3188 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3189 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3190 N0.getOperand(1), false);
3191 if (BSwap.getNode())
3198 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3199 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3200 bool DemandHighBits) {
3201 if (!LegalOperations)
3204 EVT VT = N->getValueType(0);
3205 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3207 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3210 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3211 bool LookPassAnd0 = false;
3212 bool LookPassAnd1 = false;
3213 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3215 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3217 if (N0.getOpcode() == ISD::AND) {
3218 if (!N0.getNode()->hasOneUse())
3220 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3221 if (!N01C || N01C->getZExtValue() != 0xFF00)
3223 N0 = N0.getOperand(0);
3224 LookPassAnd0 = true;
3227 if (N1.getOpcode() == ISD::AND) {
3228 if (!N1.getNode()->hasOneUse())
3230 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3231 if (!N11C || N11C->getZExtValue() != 0xFF)
3233 N1 = N1.getOperand(0);
3234 LookPassAnd1 = true;
3237 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3239 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3241 if (!N0.getNode()->hasOneUse() ||
3242 !N1.getNode()->hasOneUse())
3245 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3246 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3249 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3252 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3253 SDValue N00 = N0->getOperand(0);
3254 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3255 if (!N00.getNode()->hasOneUse())
3257 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3258 if (!N001C || N001C->getZExtValue() != 0xFF)
3260 N00 = N00.getOperand(0);
3261 LookPassAnd0 = true;
3264 SDValue N10 = N1->getOperand(0);
3265 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3266 if (!N10.getNode()->hasOneUse())
3268 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3269 if (!N101C || N101C->getZExtValue() != 0xFF00)
3271 N10 = N10.getOperand(0);
3272 LookPassAnd1 = true;
3278 // Make sure everything beyond the low halfword gets set to zero since the SRL
3279 // 16 will clear the top bits.
3280 unsigned OpSizeInBits = VT.getSizeInBits();
3281 if (DemandHighBits && OpSizeInBits > 16) {
3282 // If the left-shift isn't masked out then the only way this is a bswap is
3283 // if all bits beyond the low 8 are 0. In that case the entire pattern
3284 // reduces to a left shift anyway: leave it for other parts of the combiner.
3288 // However, if the right shift isn't masked out then it might be because
3289 // it's not needed. See if we can spot that too.
3290 if (!LookPassAnd1 &&
3291 !DAG.MaskedValueIsZero(
3292 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3296 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3297 if (OpSizeInBits > 16) {
3299 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3300 DAG.getConstant(OpSizeInBits - 16, DL,
3301 getShiftAmountTy(VT)));
3306 /// Return true if the specified node is an element that makes up a 32-bit
3307 /// packed halfword byteswap.
3308 /// ((x & 0x000000ff) << 8) |
3309 /// ((x & 0x0000ff00) >> 8) |
3310 /// ((x & 0x00ff0000) << 8) |
3311 /// ((x & 0xff000000) >> 8)
3312 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3313 if (!N.getNode()->hasOneUse())
3316 unsigned Opc = N.getOpcode();
3317 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3320 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3325 switch (N1C->getZExtValue()) {
3328 case 0xFF: Num = 0; break;
3329 case 0xFF00: Num = 1; break;
3330 case 0xFF0000: Num = 2; break;
3331 case 0xFF000000: Num = 3; break;
3334 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3335 SDValue N0 = N.getOperand(0);
3336 if (Opc == ISD::AND) {
3337 if (Num == 0 || Num == 2) {
3339 // (x >> 8) & 0xff0000
3340 if (N0.getOpcode() != ISD::SRL)
3342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3343 if (!C || C->getZExtValue() != 8)
3346 // (x << 8) & 0xff00
3347 // (x << 8) & 0xff000000
3348 if (N0.getOpcode() != ISD::SHL)
3350 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3351 if (!C || C->getZExtValue() != 8)
3354 } else if (Opc == ISD::SHL) {
3356 // (x & 0xff0000) << 8
3357 if (Num != 0 && Num != 2)
3359 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3360 if (!C || C->getZExtValue() != 8)
3362 } else { // Opc == ISD::SRL
3363 // (x & 0xff00) >> 8
3364 // (x & 0xff000000) >> 8
3365 if (Num != 1 && Num != 3)
3367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3368 if (!C || C->getZExtValue() != 8)
3375 Parts[Num] = N0.getOperand(0).getNode();
3379 /// Match a 32-bit packed halfword bswap. That is
3380 /// ((x & 0x000000ff) << 8) |
3381 /// ((x & 0x0000ff00) >> 8) |
3382 /// ((x & 0x00ff0000) << 8) |
3383 /// ((x & 0xff000000) >> 8)
3384 /// => (rotl (bswap x), 16)
3385 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3386 if (!LegalOperations)
3389 EVT VT = N->getValueType(0);
3392 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3396 // (or (or (and), (and)), (or (and), (and)))
3397 // (or (or (or (and), (and)), (and)), (and))
3398 if (N0.getOpcode() != ISD::OR)
3400 SDValue N00 = N0.getOperand(0);
3401 SDValue N01 = N0.getOperand(1);
3402 SDNode *Parts[4] = {};
3404 if (N1.getOpcode() == ISD::OR &&
3405 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3406 // (or (or (and), (and)), (or (and), (and)))
3407 SDValue N000 = N00.getOperand(0);
3408 if (!isBSwapHWordElement(N000, Parts))
3411 SDValue N001 = N00.getOperand(1);
3412 if (!isBSwapHWordElement(N001, Parts))
3414 SDValue N010 = N01.getOperand(0);
3415 if (!isBSwapHWordElement(N010, Parts))
3417 SDValue N011 = N01.getOperand(1);
3418 if (!isBSwapHWordElement(N011, Parts))
3421 // (or (or (or (and), (and)), (and)), (and))
3422 if (!isBSwapHWordElement(N1, Parts))
3424 if (!isBSwapHWordElement(N01, Parts))
3426 if (N00.getOpcode() != ISD::OR)
3428 SDValue N000 = N00.getOperand(0);
3429 if (!isBSwapHWordElement(N000, Parts))
3431 SDValue N001 = N00.getOperand(1);
3432 if (!isBSwapHWordElement(N001, Parts))
3436 // Make sure the parts are all coming from the same node.
3437 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3441 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3442 SDValue(Parts[0], 0));
3444 // Result of the bswap should be rotated by 16. If it's not legal, then
3445 // do (x << 16) | (x >> 16).
3446 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3447 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3448 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3449 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3450 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3451 return DAG.getNode(ISD::OR, DL, VT,
3452 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3453 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3456 /// This contains all DAGCombine rules which reduce two values combined by
3457 /// an Or operation to a single value \see visitANDLike().
3458 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3459 EVT VT = N1.getValueType();
3460 // fold (or x, undef) -> -1
3461 if (!LegalOperations &&
3462 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3463 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3464 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3465 SDLoc(LocReference), VT);
3467 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3468 SDValue LL, LR, RL, RR, CC0, CC1;
3469 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3470 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3471 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3473 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3474 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3475 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3476 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3477 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3478 LR.getValueType(), LL, RL);
3479 AddToWorklist(ORNode.getNode());
3480 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3482 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3483 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3484 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3485 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3486 LR.getValueType(), LL, RL);
3487 AddToWorklist(ANDNode.getNode());
3488 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3491 // canonicalize equivalent to ll == rl
3492 if (LL == RR && LR == RL) {
3493 Op1 = ISD::getSetCCSwappedOperands(Op1);
3496 if (LL == RL && LR == RR) {
3497 bool isInteger = LL.getValueType().isInteger();
3498 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3499 if (Result != ISD::SETCC_INVALID &&
3500 (!LegalOperations ||
3501 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3502 TLI.isOperationLegal(ISD::SETCC,
3503 getSetCCResultType(N0.getValueType())))))
3504 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3509 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3510 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3511 // Don't increase # computations.
3512 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3513 // We can only do this xform if we know that bits from X that are set in C2
3514 // but not in C1 are already zero. Likewise for Y.
3515 if (const ConstantSDNode *N0O1C =
3516 getAsNonOpaqueConstant(N0.getOperand(1))) {
3517 if (const ConstantSDNode *N1O1C =
3518 getAsNonOpaqueConstant(N1.getOperand(1))) {
3519 // We can only do this xform if we know that bits from X that are set in
3520 // C2 but not in C1 are already zero. Likewise for Y.
3521 const APInt &LHSMask = N0O1C->getAPIntValue();
3522 const APInt &RHSMask = N1O1C->getAPIntValue();
3524 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3525 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3526 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3527 N0.getOperand(0), N1.getOperand(0));
3528 SDLoc DL(LocReference);
3529 return DAG.getNode(ISD::AND, DL, VT, X,
3530 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3536 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3537 if (N0.getOpcode() == ISD::AND &&
3538 N1.getOpcode() == ISD::AND &&
3539 N0.getOperand(0) == N1.getOperand(0) &&
3540 // Don't increase # computations.
3541 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3542 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3543 N0.getOperand(1), N1.getOperand(1));
3544 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3550 SDValue DAGCombiner::visitOR(SDNode *N) {
3551 SDValue N0 = N->getOperand(0);
3552 SDValue N1 = N->getOperand(1);
3553 EVT VT = N1.getValueType();
3556 if (VT.isVector()) {
3557 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3560 // fold (or x, 0) -> x, vector edition
3561 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3563 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3566 // fold (or x, -1) -> -1, vector edition
3567 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3568 // do not return N0, because undef node may exist in N0
3569 return DAG.getConstant(
3570 APInt::getAllOnesValue(
3571 N0.getValueType().getScalarType().getSizeInBits()),
3572 SDLoc(N), N0.getValueType());
3573 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3574 // do not return N1, because undef node may exist in N1
3575 return DAG.getConstant(
3576 APInt::getAllOnesValue(
3577 N1.getValueType().getScalarType().getSizeInBits()),
3578 SDLoc(N), N1.getValueType());
3580 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3581 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3582 // Do this only if the resulting shuffle is legal.
3583 if (isa<ShuffleVectorSDNode>(N0) &&
3584 isa<ShuffleVectorSDNode>(N1) &&
3585 // Avoid folding a node with illegal type.
3586 TLI.isTypeLegal(VT) &&
3587 N0->getOperand(1) == N1->getOperand(1) &&
3588 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3589 bool CanFold = true;
3590 unsigned NumElts = VT.getVectorNumElements();
3591 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3592 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3593 // We construct two shuffle masks:
3594 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3595 // and N1 as the second operand.
3596 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3597 // and N0 as the second operand.
3598 // We do this because OR is commutable and therefore there might be
3599 // two ways to fold this node into a shuffle.
3600 SmallVector<int,4> Mask1;
3601 SmallVector<int,4> Mask2;
3603 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3604 int M0 = SV0->getMaskElt(i);
3605 int M1 = SV1->getMaskElt(i);
3607 // Both shuffle indexes are undef. Propagate Undef.
3608 if (M0 < 0 && M1 < 0) {
3609 Mask1.push_back(M0);
3610 Mask2.push_back(M0);
3614 if (M0 < 0 || M1 < 0 ||
3615 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3616 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3621 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3622 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3626 // Fold this sequence only if the resulting shuffle is 'legal'.
3627 if (TLI.isShuffleMaskLegal(Mask1, VT))
3628 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3629 N1->getOperand(0), &Mask1[0]);
3630 if (TLI.isShuffleMaskLegal(Mask2, VT))
3631 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3632 N0->getOperand(0), &Mask2[0]);
3637 // fold (or c1, c2) -> c1|c2
3638 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3639 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3640 if (N0C && N1C && !N1C->isOpaque())
3641 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3642 // canonicalize constant to RHS
3643 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3644 !isConstantIntBuildVectorOrConstantInt(N1))
3645 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3646 // fold (or x, 0) -> x
3647 if (isNullConstant(N1))
3649 // fold (or x, -1) -> -1
3650 if (isAllOnesConstant(N1))
3652 // fold (or x, c) -> c iff (x & ~c) == 0
3653 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3656 if (SDValue Combined = visitORLike(N0, N1, N))
3659 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3660 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3661 if (BSwap.getNode())
3663 BSwap = MatchBSwapHWordLow(N, N0, N1);
3664 if (BSwap.getNode())
3668 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3670 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3671 // iff (c1 & c2) == 0.
3672 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3673 isa<ConstantSDNode>(N0.getOperand(1))) {
3674 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3675 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3676 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3679 ISD::AND, SDLoc(N), VT,
3680 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3684 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3685 if (N0.getOpcode() == N1.getOpcode()) {
3686 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3687 if (Tmp.getNode()) return Tmp;
3690 // See if this is some rotate idiom.
3691 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3692 return SDValue(Rot, 0);
3694 // Simplify the operands using demanded-bits information.
3695 if (!VT.isVector() &&
3696 SimplifyDemandedBits(SDValue(N, 0)))
3697 return SDValue(N, 0);
3702 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3703 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3704 if (Op.getOpcode() == ISD::AND) {
3705 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3706 Mask = Op.getOperand(1);
3707 Op = Op.getOperand(0);
3713 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3721 // Return true if we can prove that, whenever Neg and Pos are both in the
3722 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3723 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3725 // (or (shift1 X, Neg), (shift2 X, Pos))
3727 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3728 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3729 // to consider shift amounts with defined behavior.
3730 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3731 // If OpSize is a power of 2 then:
3733 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3734 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3736 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3737 // for the stronger condition:
3739 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3741 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3742 // we can just replace Neg with Neg' for the rest of the function.
3744 // In other cases we check for the even stronger condition:
3746 // Neg == OpSize - Pos [B]
3748 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3749 // behavior if Pos == 0 (and consequently Neg == OpSize).
3751 // We could actually use [A] whenever OpSize is a power of 2, but the
3752 // only extra cases that it would match are those uninteresting ones
3753 // where Neg and Pos are never in range at the same time. E.g. for
3754 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3755 // as well as (sub 32, Pos), but:
3757 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3759 // always invokes undefined behavior for 32-bit X.
3761 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3762 unsigned MaskLoBits = 0;
3763 if (Neg.getOpcode() == ISD::AND &&
3764 isPowerOf2_64(OpSize) &&
3765 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3766 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3767 Neg = Neg.getOperand(0);
3768 MaskLoBits = Log2_64(OpSize);
3771 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3772 if (Neg.getOpcode() != ISD::SUB)
3774 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3777 SDValue NegOp1 = Neg.getOperand(1);
3779 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3780 // Pos'. The truncation is redundant for the purpose of the equality.
3782 Pos.getOpcode() == ISD::AND &&
3783 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3784 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3785 Pos = Pos.getOperand(0);
3787 // The condition we need is now:
3789 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3791 // If NegOp1 == Pos then we need:
3793 // OpSize & Mask == NegC & Mask
3795 // (because "x & Mask" is a truncation and distributes through subtraction).
3798 Width = NegC->getAPIntValue();
3799 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3800 // Then the condition we want to prove becomes:
3802 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3804 // which, again because "x & Mask" is a truncation, becomes:
3806 // NegC & Mask == (OpSize - PosC) & Mask
3807 // OpSize & Mask == (NegC + PosC) & Mask
3808 else if (Pos.getOpcode() == ISD::ADD &&
3809 Pos.getOperand(0) == NegOp1 &&
3810 Pos.getOperand(1).getOpcode() == ISD::Constant)
3811 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3812 NegC->getAPIntValue());
3816 // Now we just need to check that OpSize & Mask == Width & Mask.
3818 // Opsize & Mask is 0 since Mask is Opsize - 1.
3819 return Width.getLoBits(MaskLoBits) == 0;
3820 return Width == OpSize;
3823 // A subroutine of MatchRotate used once we have found an OR of two opposite
3824 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3825 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3826 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3827 // Neg with outer conversions stripped away.
3828 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3829 SDValue Neg, SDValue InnerPos,
3830 SDValue InnerNeg, unsigned PosOpcode,
3831 unsigned NegOpcode, SDLoc DL) {
3832 // fold (or (shl x, (*ext y)),
3833 // (srl x, (*ext (sub 32, y)))) ->
3834 // (rotl x, y) or (rotr x, (sub 32, y))
3836 // fold (or (shl x, (*ext (sub 32, y))),
3837 // (srl x, (*ext y))) ->
3838 // (rotr x, y) or (rotl x, (sub 32, y))
3839 EVT VT = Shifted.getValueType();
3840 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3841 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3842 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3843 HasPos ? Pos : Neg).getNode();
3849 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3850 // idioms for rotate, and if the target supports rotation instructions, generate
3852 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3853 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3854 EVT VT = LHS.getValueType();
3855 if (!TLI.isTypeLegal(VT)) return nullptr;
3857 // The target must have at least one rotate flavor.
3858 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3859 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3860 if (!HasROTL && !HasROTR) return nullptr;
3862 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3863 SDValue LHSShift; // The shift.
3864 SDValue LHSMask; // AND value if any.
3865 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3866 return nullptr; // Not part of a rotate.
3868 SDValue RHSShift; // The shift.
3869 SDValue RHSMask; // AND value if any.
3870 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3871 return nullptr; // Not part of a rotate.
3873 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3874 return nullptr; // Not shifting the same value.
3876 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3877 return nullptr; // Shifts must disagree.
3879 // Canonicalize shl to left side in a shl/srl pair.
3880 if (RHSShift.getOpcode() == ISD::SHL) {
3881 std::swap(LHS, RHS);
3882 std::swap(LHSShift, RHSShift);
3883 std::swap(LHSMask , RHSMask );
3886 unsigned OpSizeInBits = VT.getSizeInBits();
3887 SDValue LHSShiftArg = LHSShift.getOperand(0);
3888 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3889 SDValue RHSShiftArg = RHSShift.getOperand(0);
3890 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3892 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3893 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3894 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3895 RHSShiftAmt.getOpcode() == ISD::Constant) {
3896 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3897 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3898 if ((LShVal + RShVal) != OpSizeInBits)
3901 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3902 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3904 // If there is an AND of either shifted operand, apply it to the result.
3905 if (LHSMask.getNode() || RHSMask.getNode()) {
3906 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3908 if (LHSMask.getNode()) {
3909 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3910 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3912 if (RHSMask.getNode()) {
3913 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3914 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3917 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3920 return Rot.getNode();
3923 // If there is a mask here, and we have a variable shift, we can't be sure
3924 // that we're masking out the right stuff.
3925 if (LHSMask.getNode() || RHSMask.getNode())
3928 // If the shift amount is sign/zext/any-extended just peel it off.
3929 SDValue LExtOp0 = LHSShiftAmt;
3930 SDValue RExtOp0 = RHSShiftAmt;
3931 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3932 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3933 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3934 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3935 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3936 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3937 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3938 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3939 LExtOp0 = LHSShiftAmt.getOperand(0);
3940 RExtOp0 = RHSShiftAmt.getOperand(0);
3943 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3944 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3948 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3949 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3956 SDValue DAGCombiner::visitXOR(SDNode *N) {
3957 SDValue N0 = N->getOperand(0);
3958 SDValue N1 = N->getOperand(1);
3959 EVT VT = N0.getValueType();
3962 if (VT.isVector()) {
3963 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3966 // fold (xor x, 0) -> x, vector edition
3967 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3969 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3973 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3974 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3975 return DAG.getConstant(0, SDLoc(N), VT);
3976 // fold (xor x, undef) -> undef
3977 if (N0.getOpcode() == ISD::UNDEF)
3979 if (N1.getOpcode() == ISD::UNDEF)
3981 // fold (xor c1, c2) -> c1^c2
3982 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3983 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3985 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3986 // canonicalize constant to RHS
3987 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3988 !isConstantIntBuildVectorOrConstantInt(N1))
3989 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3990 // fold (xor x, 0) -> x
3991 if (isNullConstant(N1))
3994 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3997 // fold !(x cc y) -> (x !cc y)
3998 SDValue LHS, RHS, CC;
3999 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4000 bool isInt = LHS.getValueType().isInteger();
4001 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4004 if (!LegalOperations ||
4005 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4006 switch (N0.getOpcode()) {
4008 llvm_unreachable("Unhandled SetCC Equivalent!");
4010 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4011 case ISD::SELECT_CC:
4012 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4013 N0.getOperand(3), NotCC);
4018 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4019 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4020 N0.getNode()->hasOneUse() &&
4021 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4022 SDValue V = N0.getOperand(0);
4024 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4025 DAG.getConstant(1, DL, V.getValueType()));
4026 AddToWorklist(V.getNode());
4027 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4030 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4031 if (isOneConstant(N1) && VT == MVT::i1 &&
4032 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4033 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4034 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4035 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4036 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4037 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4038 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4039 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4042 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4043 if (isAllOnesConstant(N1) &&
4044 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4045 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4046 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4047 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4048 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4049 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4050 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4051 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4054 // fold (xor (and x, y), y) -> (and (not x), y)
4055 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4056 N0->getOperand(1) == N1) {
4057 SDValue X = N0->getOperand(0);
4058 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4059 AddToWorklist(NotX.getNode());
4060 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4062 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4063 if (N1C && N0.getOpcode() == ISD::XOR) {
4064 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4066 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4067 DAG.getConstant(N1C->getAPIntValue() ^
4068 N00C->getAPIntValue(), DL, VT));
4070 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4072 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4073 DAG.getConstant(N1C->getAPIntValue() ^
4074 N01C->getAPIntValue(), DL, VT));
4077 // fold (xor x, x) -> 0
4079 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4081 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4082 // Here is a concrete example of this equivalence:
4084 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4085 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4089 // i16 ~1 == 0b1111111111111110
4090 // i16 rol(~1, 14) == 0b1011111111111111
4092 // Some additional tips to help conceptualize this transform:
4093 // - Try to see the operation as placing a single zero in a value of all ones.
4094 // - There exists no value for x which would allow the result to contain zero.
4095 // - Values of x larger than the bitwidth are undefined and do not require a
4096 // consistent result.
4097 // - Pushing the zero left requires shifting one bits in from the right.
4098 // A rotate left of ~1 is a nice way of achieving the desired result.
4099 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4100 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4102 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4106 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4107 if (N0.getOpcode() == N1.getOpcode()) {
4108 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4109 if (Tmp.getNode()) return Tmp;
4112 // Simplify the expression using non-local knowledge.
4113 if (!VT.isVector() &&
4114 SimplifyDemandedBits(SDValue(N, 0)))
4115 return SDValue(N, 0);
4120 /// Handle transforms common to the three shifts, when the shift amount is a
4122 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4123 SDNode *LHS = N->getOperand(0).getNode();
4124 if (!LHS->hasOneUse()) return SDValue();
4126 // We want to pull some binops through shifts, so that we have (and (shift))
4127 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4128 // thing happens with address calculations, so it's important to canonicalize
4130 bool HighBitSet = false; // Can we transform this if the high bit is set?
4132 switch (LHS->getOpcode()) {
4133 default: return SDValue();
4136 HighBitSet = false; // We can only transform sra if the high bit is clear.
4139 HighBitSet = true; // We can only transform sra if the high bit is set.
4142 if (N->getOpcode() != ISD::SHL)
4143 return SDValue(); // only shl(add) not sr[al](add).
4144 HighBitSet = false; // We can only transform sra if the high bit is clear.
4148 // We require the RHS of the binop to be a constant and not opaque as well.
4149 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4150 if (!BinOpCst) return SDValue();
4152 // FIXME: disable this unless the input to the binop is a shift by a constant.
4153 // If it is not a shift, it pessimizes some common cases like:
4155 // void foo(int *X, int i) { X[i & 1235] = 1; }
4156 // int bar(int *X, int i) { return X[i & 255]; }
4157 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4158 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4159 BinOpLHSVal->getOpcode() != ISD::SRA &&
4160 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4161 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4164 EVT VT = N->getValueType(0);
4166 // If this is a signed shift right, and the high bit is modified by the
4167 // logical operation, do not perform the transformation. The highBitSet
4168 // boolean indicates the value of the high bit of the constant which would
4169 // cause it to be modified for this operation.
4170 if (N->getOpcode() == ISD::SRA) {
4171 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4172 if (BinOpRHSSignSet != HighBitSet)
4176 if (!TLI.isDesirableToCommuteWithShift(LHS))
4179 // Fold the constants, shifting the binop RHS by the shift amount.
4180 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4182 LHS->getOperand(1), N->getOperand(1));
4183 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4185 // Create the new shift.
4186 SDValue NewShift = DAG.getNode(N->getOpcode(),
4187 SDLoc(LHS->getOperand(0)),
4188 VT, LHS->getOperand(0), N->getOperand(1));
4190 // Create the new binop.
4191 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4194 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4195 assert(N->getOpcode() == ISD::TRUNCATE);
4196 assert(N->getOperand(0).getOpcode() == ISD::AND);
4198 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4199 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4200 SDValue N01 = N->getOperand(0).getOperand(1);
4202 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4203 if (!N01C->isOpaque()) {
4204 EVT TruncVT = N->getValueType(0);
4205 SDValue N00 = N->getOperand(0).getOperand(0);
4206 APInt TruncC = N01C->getAPIntValue();
4207 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4210 return DAG.getNode(ISD::AND, DL, TruncVT,
4211 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4212 DAG.getConstant(TruncC, DL, TruncVT));
4220 SDValue DAGCombiner::visitRotate(SDNode *N) {
4221 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4222 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4223 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4224 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4225 if (NewOp1.getNode())
4226 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4227 N->getOperand(0), NewOp1);
4232 SDValue DAGCombiner::visitSHL(SDNode *N) {
4233 SDValue N0 = N->getOperand(0);
4234 SDValue N1 = N->getOperand(1);
4235 EVT VT = N0.getValueType();
4236 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4240 if (VT.isVector()) {
4241 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4244 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4245 // If setcc produces all-one true value then:
4246 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4247 if (N1CV && N1CV->isConstant()) {
4248 if (N0.getOpcode() == ISD::AND) {
4249 SDValue N00 = N0->getOperand(0);
4250 SDValue N01 = N0->getOperand(1);
4251 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4253 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4254 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4255 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4256 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4258 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4261 N1C = isConstOrConstSplat(N1);
4266 // fold (shl c1, c2) -> c1<<c2
4267 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4268 if (N0C && N1C && !N1C->isOpaque())
4269 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4270 // fold (shl 0, x) -> 0
4271 if (isNullConstant(N0))
4273 // fold (shl x, c >= size(x)) -> undef
4274 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4275 return DAG.getUNDEF(VT);
4276 // fold (shl x, 0) -> x
4277 if (N1C && N1C->isNullValue())
4279 // fold (shl undef, x) -> 0
4280 if (N0.getOpcode() == ISD::UNDEF)
4281 return DAG.getConstant(0, SDLoc(N), VT);
4282 // if (shl x, c) is known to be zero, return 0
4283 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4284 APInt::getAllOnesValue(OpSizeInBits)))
4285 return DAG.getConstant(0, SDLoc(N), VT);
4286 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4287 if (N1.getOpcode() == ISD::TRUNCATE &&
4288 N1.getOperand(0).getOpcode() == ISD::AND) {
4289 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4290 if (NewOp1.getNode())
4291 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4294 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4295 return SDValue(N, 0);
4297 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4298 if (N1C && N0.getOpcode() == ISD::SHL) {
4299 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4300 uint64_t c1 = N0C1->getZExtValue();
4301 uint64_t c2 = N1C->getZExtValue();
4303 if (c1 + c2 >= OpSizeInBits)
4304 return DAG.getConstant(0, DL, VT);
4305 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4306 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4310 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4311 // For this to be valid, the second form must not preserve any of the bits
4312 // that are shifted out by the inner shift in the first form. This means
4313 // the outer shift size must be >= the number of bits added by the ext.
4314 // As a corollary, we don't care what kind of ext it is.
4315 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4316 N0.getOpcode() == ISD::ANY_EXTEND ||
4317 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4318 N0.getOperand(0).getOpcode() == ISD::SHL) {
4319 SDValue N0Op0 = N0.getOperand(0);
4320 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4321 uint64_t c1 = N0Op0C1->getZExtValue();
4322 uint64_t c2 = N1C->getZExtValue();
4323 EVT InnerShiftVT = N0Op0.getValueType();
4324 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4325 if (c2 >= OpSizeInBits - InnerShiftSize) {
4327 if (c1 + c2 >= OpSizeInBits)
4328 return DAG.getConstant(0, DL, VT);
4329 return DAG.getNode(ISD::SHL, DL, VT,
4330 DAG.getNode(N0.getOpcode(), DL, VT,
4331 N0Op0->getOperand(0)),
4332 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4337 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4338 // Only fold this if the inner zext has no other uses to avoid increasing
4339 // the total number of instructions.
4340 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4341 N0.getOperand(0).getOpcode() == ISD::SRL) {
4342 SDValue N0Op0 = N0.getOperand(0);
4343 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4344 uint64_t c1 = N0Op0C1->getZExtValue();
4345 if (c1 < VT.getScalarSizeInBits()) {
4346 uint64_t c2 = N1C->getZExtValue();
4348 SDValue NewOp0 = N0.getOperand(0);
4349 EVT CountVT = NewOp0.getOperand(1).getValueType();
4351 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4353 DAG.getConstant(c2, DL, CountVT));
4354 AddToWorklist(NewSHL.getNode());
4355 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4361 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4362 // (and (srl x, (sub c1, c2), MASK)
4363 // Only fold this if the inner shift has no other uses -- if it does, folding
4364 // this will increase the total number of instructions.
4365 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4366 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4367 uint64_t c1 = N0C1->getZExtValue();
4368 if (c1 < OpSizeInBits) {
4369 uint64_t c2 = N1C->getZExtValue();
4370 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4373 Mask = Mask.shl(c2 - c1);
4375 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4376 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4378 Mask = Mask.lshr(c1 - c2);
4380 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4381 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4384 return DAG.getNode(ISD::AND, DL, VT, Shift,
4385 DAG.getConstant(Mask, DL, VT));
4389 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4390 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4391 unsigned BitSize = VT.getScalarSizeInBits();
4393 SDValue HiBitsMask =
4394 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4395 BitSize - N1C->getZExtValue()),
4397 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4401 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4402 // Variant of version done on multiply, except mul by a power of 2 is turned
4405 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4406 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4407 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4408 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4409 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4410 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4413 if (N1C && !N1C->isOpaque()) {
4414 SDValue NewSHL = visitShiftByConstant(N, N1C);
4415 if (NewSHL.getNode())
4422 SDValue DAGCombiner::visitSRA(SDNode *N) {
4423 SDValue N0 = N->getOperand(0);
4424 SDValue N1 = N->getOperand(1);
4425 EVT VT = N0.getValueType();
4426 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4429 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4430 if (VT.isVector()) {
4431 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4434 N1C = isConstOrConstSplat(N1);
4437 // fold (sra c1, c2) -> (sra c1, c2)
4438 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4439 if (N0C && N1C && !N1C->isOpaque())
4440 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4441 // fold (sra 0, x) -> 0
4442 if (isNullConstant(N0))
4444 // fold (sra -1, x) -> -1
4445 if (isAllOnesConstant(N0))
4447 // fold (sra x, (setge c, size(x))) -> undef
4448 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4449 return DAG.getUNDEF(VT);
4450 // fold (sra x, 0) -> x
4451 if (N1C && N1C->isNullValue())
4453 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4455 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4456 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4457 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4459 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4460 ExtVT, VT.getVectorNumElements());
4461 if ((!LegalOperations ||
4462 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4463 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4464 N0.getOperand(0), DAG.getValueType(ExtVT));
4467 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4468 if (N1C && N0.getOpcode() == ISD::SRA) {
4469 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4470 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4471 if (Sum >= OpSizeInBits)
4472 Sum = OpSizeInBits - 1;
4474 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4475 DAG.getConstant(Sum, DL, N1.getValueType()));
4479 // fold (sra (shl X, m), (sub result_size, n))
4480 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4481 // result_size - n != m.
4482 // If truncate is free for the target sext(shl) is likely to result in better
4484 if (N0.getOpcode() == ISD::SHL && N1C) {
4485 // Get the two constanst of the shifts, CN0 = m, CN = n.
4486 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4488 LLVMContext &Ctx = *DAG.getContext();
4489 // Determine what the truncate's result bitsize and type would be.
4490 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4493 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4495 // Determine the residual right-shift amount.
4496 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4498 // If the shift is not a no-op (in which case this should be just a sign
4499 // extend already), the truncated to type is legal, sign_extend is legal
4500 // on that type, and the truncate to that type is both legal and free,
4501 // perform the transform.
4502 if ((ShiftAmt > 0) &&
4503 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4504 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4505 TLI.isTruncateFree(VT, TruncVT)) {
4508 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4509 getShiftAmountTy(N0.getOperand(0).getValueType()));
4510 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4511 N0.getOperand(0), Amt);
4512 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4514 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4515 N->getValueType(0), Trunc);
4520 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4521 if (N1.getOpcode() == ISD::TRUNCATE &&
4522 N1.getOperand(0).getOpcode() == ISD::AND) {
4523 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4524 if (NewOp1.getNode())
4525 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4528 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4529 // if c1 is equal to the number of bits the trunc removes
4530 if (N0.getOpcode() == ISD::TRUNCATE &&
4531 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4532 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4533 N0.getOperand(0).hasOneUse() &&
4534 N0.getOperand(0).getOperand(1).hasOneUse() &&
4536 SDValue N0Op0 = N0.getOperand(0);
4537 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4538 unsigned LargeShiftVal = LargeShift->getZExtValue();
4539 EVT LargeVT = N0Op0.getValueType();
4541 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4544 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4545 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4546 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4547 N0Op0.getOperand(0), Amt);
4548 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4553 // Simplify, based on bits shifted out of the LHS.
4554 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4555 return SDValue(N, 0);
4558 // If the sign bit is known to be zero, switch this to a SRL.
4559 if (DAG.SignBitIsZero(N0))
4560 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4562 if (N1C && !N1C->isOpaque()) {
4563 SDValue NewSRA = visitShiftByConstant(N, N1C);
4564 if (NewSRA.getNode())
4571 SDValue DAGCombiner::visitSRL(SDNode *N) {
4572 SDValue N0 = N->getOperand(0);
4573 SDValue N1 = N->getOperand(1);
4574 EVT VT = N0.getValueType();
4575 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4578 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4579 if (VT.isVector()) {
4580 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4583 N1C = isConstOrConstSplat(N1);
4586 // fold (srl c1, c2) -> c1 >>u c2
4587 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4588 if (N0C && N1C && !N1C->isOpaque())
4589 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4590 // fold (srl 0, x) -> 0
4591 if (isNullConstant(N0))
4593 // fold (srl x, c >= size(x)) -> undef
4594 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4595 return DAG.getUNDEF(VT);
4596 // fold (srl x, 0) -> x
4597 if (N1C && N1C->isNullValue())
4599 // if (srl x, c) is known to be zero, return 0
4600 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4601 APInt::getAllOnesValue(OpSizeInBits)))
4602 return DAG.getConstant(0, SDLoc(N), VT);
4604 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4605 if (N1C && N0.getOpcode() == ISD::SRL) {
4606 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4607 uint64_t c1 = N01C->getZExtValue();
4608 uint64_t c2 = N1C->getZExtValue();
4610 if (c1 + c2 >= OpSizeInBits)
4611 return DAG.getConstant(0, DL, VT);
4612 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4613 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4617 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4618 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4619 N0.getOperand(0).getOpcode() == ISD::SRL &&
4620 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4622 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4623 uint64_t c2 = N1C->getZExtValue();
4624 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4625 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4626 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4627 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4628 if (c1 + OpSizeInBits == InnerShiftSize) {
4630 if (c1 + c2 >= InnerShiftSize)
4631 return DAG.getConstant(0, DL, VT);
4632 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4633 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4634 N0.getOperand(0)->getOperand(0),
4635 DAG.getConstant(c1 + c2, DL,
4640 // fold (srl (shl x, c), c) -> (and x, cst2)
4641 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4642 unsigned BitSize = N0.getScalarValueSizeInBits();
4643 if (BitSize <= 64) {
4644 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4646 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4647 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4651 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4652 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4653 // Shifting in all undef bits?
4654 EVT SmallVT = N0.getOperand(0).getValueType();
4655 unsigned BitSize = SmallVT.getScalarSizeInBits();
4656 if (N1C->getZExtValue() >= BitSize)
4657 return DAG.getUNDEF(VT);
4659 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4660 uint64_t ShiftAmt = N1C->getZExtValue();
4662 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4664 DAG.getConstant(ShiftAmt, DL0,
4665 getShiftAmountTy(SmallVT)));
4666 AddToWorklist(SmallShift.getNode());
4667 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4669 return DAG.getNode(ISD::AND, DL, VT,
4670 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4671 DAG.getConstant(Mask, DL, VT));
4675 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4676 // bit, which is unmodified by sra.
4677 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4678 if (N0.getOpcode() == ISD::SRA)
4679 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4682 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4683 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4684 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4685 APInt KnownZero, KnownOne;
4686 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4688 // If any of the input bits are KnownOne, then the input couldn't be all
4689 // zeros, thus the result of the srl will always be zero.
4690 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4692 // If all of the bits input the to ctlz node are known to be zero, then
4693 // the result of the ctlz is "32" and the result of the shift is one.
4694 APInt UnknownBits = ~KnownZero;
4695 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4697 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4698 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4699 // Okay, we know that only that the single bit specified by UnknownBits
4700 // could be set on input to the CTLZ node. If this bit is set, the SRL
4701 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4702 // to an SRL/XOR pair, which is likely to simplify more.
4703 unsigned ShAmt = UnknownBits.countTrailingZeros();
4704 SDValue Op = N0.getOperand(0);
4708 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4709 DAG.getConstant(ShAmt, DL,
4710 getShiftAmountTy(Op.getValueType())));
4711 AddToWorklist(Op.getNode());
4715 return DAG.getNode(ISD::XOR, DL, VT,
4716 Op, DAG.getConstant(1, DL, VT));
4720 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4721 if (N1.getOpcode() == ISD::TRUNCATE &&
4722 N1.getOperand(0).getOpcode() == ISD::AND) {
4723 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4724 if (NewOp1.getNode())
4725 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4728 // fold operands of srl based on knowledge that the low bits are not
4730 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4731 return SDValue(N, 0);
4733 if (N1C && !N1C->isOpaque()) {
4734 SDValue NewSRL = visitShiftByConstant(N, N1C);
4735 if (NewSRL.getNode())
4739 // Attempt to convert a srl of a load into a narrower zero-extending load.
4740 SDValue NarrowLoad = ReduceLoadWidth(N);
4741 if (NarrowLoad.getNode())
4744 // Here is a common situation. We want to optimize:
4747 // %b = and i32 %a, 2
4748 // %c = srl i32 %b, 1
4749 // brcond i32 %c ...
4755 // %c = setcc eq %b, 0
4758 // However when after the source operand of SRL is optimized into AND, the SRL
4759 // itself may not be optimized further. Look for it and add the BRCOND into
4761 if (N->hasOneUse()) {
4762 SDNode *Use = *N->use_begin();
4763 if (Use->getOpcode() == ISD::BRCOND)
4765 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4766 // Also look pass the truncate.
4767 Use = *Use->use_begin();
4768 if (Use->getOpcode() == ISD::BRCOND)
4776 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4777 SDValue N0 = N->getOperand(0);
4778 EVT VT = N->getValueType(0);
4780 // fold (bswap c1) -> c2
4781 if (isConstantIntBuildVectorOrConstantInt(N0))
4782 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4783 // fold (bswap (bswap x)) -> x
4784 if (N0.getOpcode() == ISD::BSWAP)
4785 return N0->getOperand(0);
4789 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4790 SDValue N0 = N->getOperand(0);
4791 EVT VT = N->getValueType(0);
4793 // fold (ctlz c1) -> c2
4794 if (isConstantIntBuildVectorOrConstantInt(N0))
4795 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4799 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4800 SDValue N0 = N->getOperand(0);
4801 EVT VT = N->getValueType(0);
4803 // fold (ctlz_zero_undef c1) -> c2
4804 if (isConstantIntBuildVectorOrConstantInt(N0))
4805 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4809 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4810 SDValue N0 = N->getOperand(0);
4811 EVT VT = N->getValueType(0);
4813 // fold (cttz c1) -> c2
4814 if (isConstantIntBuildVectorOrConstantInt(N0))
4815 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4819 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4820 SDValue N0 = N->getOperand(0);
4821 EVT VT = N->getValueType(0);
4823 // fold (cttz_zero_undef c1) -> c2
4824 if (isConstantIntBuildVectorOrConstantInt(N0))
4825 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4829 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4830 SDValue N0 = N->getOperand(0);
4831 EVT VT = N->getValueType(0);
4833 // fold (ctpop c1) -> c2
4834 if (isConstantIntBuildVectorOrConstantInt(N0))
4835 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4840 /// \brief Generate Min/Max node
4841 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4842 SDValue True, SDValue False,
4843 ISD::CondCode CC, const TargetLowering &TLI,
4844 SelectionDAG &DAG) {
4845 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4855 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4856 if (TLI.isOperationLegal(Opcode, VT))
4857 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4866 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4867 if (TLI.isOperationLegal(Opcode, VT))
4868 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4876 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4877 SDValue N0 = N->getOperand(0);
4878 SDValue N1 = N->getOperand(1);
4879 SDValue N2 = N->getOperand(2);
4880 EVT VT = N->getValueType(0);
4881 EVT VT0 = N0.getValueType();
4883 // fold (select C, X, X) -> X
4886 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4887 // fold (select true, X, Y) -> X
4888 // fold (select false, X, Y) -> Y
4889 return !N0C->isNullValue() ? N1 : N2;
4891 // fold (select C, 1, X) -> (or C, X)
4892 if (VT == MVT::i1 && isOneConstant(N1))
4893 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4894 // fold (select C, 0, 1) -> (xor C, 1)
4895 // We can't do this reliably if integer based booleans have different contents
4896 // to floating point based booleans. This is because we can't tell whether we
4897 // have an integer-based boolean or a floating-point-based boolean unless we
4898 // can find the SETCC that produced it and inspect its operands. This is
4899 // fairly easy if C is the SETCC node, but it can potentially be
4900 // undiscoverable (or not reasonably discoverable). For example, it could be
4901 // in another basic block or it could require searching a complicated
4903 if (VT.isInteger() &&
4904 (VT0 == MVT::i1 || (VT0.isInteger() &&
4905 TLI.getBooleanContents(false, false) ==
4906 TLI.getBooleanContents(false, true) &&
4907 TLI.getBooleanContents(false, false) ==
4908 TargetLowering::ZeroOrOneBooleanContent)) &&
4909 isNullConstant(N1) && isOneConstant(N2)) {
4913 return DAG.getNode(ISD::XOR, DL, VT0,
4914 N0, DAG.getConstant(1, DL, VT0));
4917 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4918 N0, DAG.getConstant(1, DL0, VT0));
4919 AddToWorklist(XORNode.getNode());
4921 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4922 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4924 // fold (select C, 0, X) -> (and (not C), X)
4925 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4926 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4927 AddToWorklist(NOTNode.getNode());
4928 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4930 // fold (select C, X, 1) -> (or (not C), X)
4931 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4932 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4933 AddToWorklist(NOTNode.getNode());
4934 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4936 // fold (select C, X, 0) -> (and C, X)
4937 if (VT == MVT::i1 && isNullConstant(N2))
4938 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4939 // fold (select X, X, Y) -> (or X, Y)
4940 // fold (select X, 1, Y) -> (or X, Y)
4941 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4942 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4943 // fold (select X, Y, X) -> (and X, Y)
4944 // fold (select X, Y, 0) -> (and X, Y)
4945 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4946 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4948 // If we can fold this based on the true/false value, do so.
4949 if (SimplifySelectOps(N, N1, N2))
4950 return SDValue(N, 0); // Don't revisit N.
4952 // fold selects based on a setcc into other things, such as min/max/abs
4953 if (N0.getOpcode() == ISD::SETCC) {
4954 // select x, y (fcmp lt x, y) -> fminnum x, y
4955 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4957 // This is OK if we don't care about what happens if either operand is a
4961 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4962 // no signed zeros as well as no nans.
4963 const TargetOptions &Options = DAG.getTarget().Options;
4964 if (Options.UnsafeFPMath &&
4965 VT.isFloatingPoint() && N0.hasOneUse() &&
4966 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4967 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4970 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4971 N1, N2, CC, TLI, DAG);
4976 if ((!LegalOperations &&
4977 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4978 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4979 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4980 N0.getOperand(0), N0.getOperand(1),
4981 N1, N2, N0.getOperand(2));
4982 return SimplifySelect(SDLoc(N), N0, N1, N2);
4985 if (VT0 == MVT::i1) {
4986 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4987 // select (and Cond0, Cond1), X, Y
4988 // -> select Cond0, (select Cond1, X, Y), Y
4989 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4990 SDValue Cond0 = N0->getOperand(0);
4991 SDValue Cond1 = N0->getOperand(1);
4992 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4993 N1.getValueType(), Cond1, N1, N2);
4994 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4997 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4998 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4999 SDValue Cond0 = N0->getOperand(0);
5000 SDValue Cond1 = N0->getOperand(1);
5001 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5002 N1.getValueType(), Cond1, N1, N2);
5003 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5008 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5009 if (N1->getOpcode() == ISD::SELECT) {
5010 SDValue N1_0 = N1->getOperand(0);
5011 SDValue N1_1 = N1->getOperand(1);
5012 SDValue N1_2 = N1->getOperand(2);
5013 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5014 // Create the actual and node if we can generate good code for it.
5015 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5016 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5018 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5021 // Otherwise see if we can optimize the "and" to a better pattern.
5022 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5023 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5027 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5028 if (N2->getOpcode() == ISD::SELECT) {
5029 SDValue N2_0 = N2->getOperand(0);
5030 SDValue N2_1 = N2->getOperand(1);
5031 SDValue N2_2 = N2->getOperand(2);
5032 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5033 // Create the actual or node if we can generate good code for it.
5034 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5035 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5037 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5040 // Otherwise see if we can optimize to a better pattern.
5041 if (SDValue Combined = visitORLike(N0, N2_0, N))
5042 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5052 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5055 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5057 // Split the inputs.
5058 SDValue Lo, Hi, LL, LH, RL, RH;
5059 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5060 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5062 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5063 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5065 return std::make_pair(Lo, Hi);
5068 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5069 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5070 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5072 SDValue Cond = N->getOperand(0);
5073 SDValue LHS = N->getOperand(1);
5074 SDValue RHS = N->getOperand(2);
5075 EVT VT = N->getValueType(0);
5076 int NumElems = VT.getVectorNumElements();
5077 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5078 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5079 Cond.getOpcode() == ISD::BUILD_VECTOR);
5081 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5082 // binary ones here.
5083 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5086 // We're sure we have an even number of elements due to the
5087 // concat_vectors we have as arguments to vselect.
5088 // Skip BV elements until we find one that's not an UNDEF
5089 // After we find an UNDEF element, keep looping until we get to half the
5090 // length of the BV and see if all the non-undef nodes are the same.
5091 ConstantSDNode *BottomHalf = nullptr;
5092 for (int i = 0; i < NumElems / 2; ++i) {
5093 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5096 if (BottomHalf == nullptr)
5097 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5098 else if (Cond->getOperand(i).getNode() != BottomHalf)
5102 // Do the same for the second half of the BuildVector
5103 ConstantSDNode *TopHalf = nullptr;
5104 for (int i = NumElems / 2; i < NumElems; ++i) {
5105 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5108 if (TopHalf == nullptr)
5109 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5110 else if (Cond->getOperand(i).getNode() != TopHalf)
5114 assert(TopHalf && BottomHalf &&
5115 "One half of the selector was all UNDEFs and the other was all the "
5116 "same value. This should have been addressed before this function.");
5118 ISD::CONCAT_VECTORS, dl, VT,
5119 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5120 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5123 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5125 if (Level >= AfterLegalizeTypes)
5128 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5129 SDValue Mask = MSC->getMask();
5130 SDValue Data = MSC->getValue();
5133 // If the MSCATTER data type requires splitting and the mask is provided by a
5134 // SETCC, then split both nodes and its operands before legalization. This
5135 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5136 // and enables future optimizations (e.g. min/max pattern matching on X86).
5137 if (Mask.getOpcode() != ISD::SETCC)
5140 // Check if any splitting is required.
5141 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5142 TargetLowering::TypeSplitVector)
5144 SDValue MaskLo, MaskHi, Lo, Hi;
5145 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5148 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5150 SDValue Chain = MSC->getChain();
5152 EVT MemoryVT = MSC->getMemoryVT();
5153 unsigned Alignment = MSC->getOriginalAlignment();
5155 EVT LoMemVT, HiMemVT;
5156 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5158 SDValue DataLo, DataHi;
5159 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5161 SDValue BasePtr = MSC->getBasePtr();
5162 SDValue IndexLo, IndexHi;
5163 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5165 MachineMemOperand *MMO = DAG.getMachineFunction().
5166 getMachineMemOperand(MSC->getPointerInfo(),
5167 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5168 Alignment, MSC->getAAInfo(), MSC->getRanges());
5170 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5171 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5174 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5175 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5178 AddToWorklist(Lo.getNode());
5179 AddToWorklist(Hi.getNode());
5181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5184 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5186 if (Level >= AfterLegalizeTypes)
5189 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5190 SDValue Mask = MST->getMask();
5191 SDValue Data = MST->getValue();
5194 // If the MSTORE data type requires splitting and the mask is provided by a
5195 // SETCC, then split both nodes and its operands before legalization. This
5196 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5197 // and enables future optimizations (e.g. min/max pattern matching on X86).
5198 if (Mask.getOpcode() == ISD::SETCC) {
5200 // Check if any splitting is required.
5201 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5202 TargetLowering::TypeSplitVector)
5205 SDValue MaskLo, MaskHi, Lo, Hi;
5206 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5209 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5211 SDValue Chain = MST->getChain();
5212 SDValue Ptr = MST->getBasePtr();
5214 EVT MemoryVT = MST->getMemoryVT();
5215 unsigned Alignment = MST->getOriginalAlignment();
5217 // if Alignment is equal to the vector size,
5218 // take the half of it for the second part
5219 unsigned SecondHalfAlignment =
5220 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5221 Alignment/2 : Alignment;
5223 EVT LoMemVT, HiMemVT;
5224 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5226 SDValue DataLo, DataHi;
5227 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5229 MachineMemOperand *MMO = DAG.getMachineFunction().
5230 getMachineMemOperand(MST->getPointerInfo(),
5231 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5232 Alignment, MST->getAAInfo(), MST->getRanges());
5234 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5235 MST->isTruncatingStore());
5237 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5238 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5239 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5241 MMO = DAG.getMachineFunction().
5242 getMachineMemOperand(MST->getPointerInfo(),
5243 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5244 SecondHalfAlignment, MST->getAAInfo(),
5247 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5248 MST->isTruncatingStore());
5250 AddToWorklist(Lo.getNode());
5251 AddToWorklist(Hi.getNode());
5253 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5258 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5260 if (Level >= AfterLegalizeTypes)
5263 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5264 SDValue Mask = MGT->getMask();
5267 // If the MGATHER result requires splitting and the mask is provided by a
5268 // SETCC, then split both nodes and its operands before legalization. This
5269 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5270 // and enables future optimizations (e.g. min/max pattern matching on X86).
5272 if (Mask.getOpcode() != ISD::SETCC)
5275 EVT VT = N->getValueType(0);
5277 // Check if any splitting is required.
5278 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5279 TargetLowering::TypeSplitVector)
5282 SDValue MaskLo, MaskHi, Lo, Hi;
5283 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5285 SDValue Src0 = MGT->getValue();
5286 SDValue Src0Lo, Src0Hi;
5287 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5290 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5292 SDValue Chain = MGT->getChain();
5293 EVT MemoryVT = MGT->getMemoryVT();
5294 unsigned Alignment = MGT->getOriginalAlignment();
5296 EVT LoMemVT, HiMemVT;
5297 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5299 SDValue BasePtr = MGT->getBasePtr();
5300 SDValue Index = MGT->getIndex();
5301 SDValue IndexLo, IndexHi;
5302 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5304 MachineMemOperand *MMO = DAG.getMachineFunction().
5305 getMachineMemOperand(MGT->getPointerInfo(),
5306 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5307 Alignment, MGT->getAAInfo(), MGT->getRanges());
5309 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5310 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5313 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5314 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5317 AddToWorklist(Lo.getNode());
5318 AddToWorklist(Hi.getNode());
5320 // Build a factor node to remember that this load is independent of the
5322 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5325 // Legalized the chain result - switch anything that used the old chain to
5327 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5329 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5331 SDValue RetOps[] = { GatherRes, Chain };
5332 return DAG.getMergeValues(RetOps, DL);
5335 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5337 if (Level >= AfterLegalizeTypes)
5340 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5341 SDValue Mask = MLD->getMask();
5344 // If the MLOAD result requires splitting and the mask is provided by a
5345 // SETCC, then split both nodes and its operands before legalization. This
5346 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5347 // and enables future optimizations (e.g. min/max pattern matching on X86).
5349 if (Mask.getOpcode() == ISD::SETCC) {
5350 EVT VT = N->getValueType(0);
5352 // Check if any splitting is required.
5353 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5354 TargetLowering::TypeSplitVector)
5357 SDValue MaskLo, MaskHi, Lo, Hi;
5358 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5360 SDValue Src0 = MLD->getSrc0();
5361 SDValue Src0Lo, Src0Hi;
5362 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5365 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5367 SDValue Chain = MLD->getChain();
5368 SDValue Ptr = MLD->getBasePtr();
5369 EVT MemoryVT = MLD->getMemoryVT();
5370 unsigned Alignment = MLD->getOriginalAlignment();
5372 // if Alignment is equal to the vector size,
5373 // take the half of it for the second part
5374 unsigned SecondHalfAlignment =
5375 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5376 Alignment/2 : Alignment;
5378 EVT LoMemVT, HiMemVT;
5379 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5381 MachineMemOperand *MMO = DAG.getMachineFunction().
5382 getMachineMemOperand(MLD->getPointerInfo(),
5383 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5384 Alignment, MLD->getAAInfo(), MLD->getRanges());
5386 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5389 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5390 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5391 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5393 MMO = DAG.getMachineFunction().
5394 getMachineMemOperand(MLD->getPointerInfo(),
5395 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5396 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5398 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5401 AddToWorklist(Lo.getNode());
5402 AddToWorklist(Hi.getNode());
5404 // Build a factor node to remember that this load is independent of the
5406 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5409 // Legalized the chain result - switch anything that used the old chain to
5411 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5413 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5415 SDValue RetOps[] = { LoadRes, Chain };
5416 return DAG.getMergeValues(RetOps, DL);
5421 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5422 SDValue N0 = N->getOperand(0);
5423 SDValue N1 = N->getOperand(1);
5424 SDValue N2 = N->getOperand(2);
5427 // Canonicalize integer abs.
5428 // vselect (setg[te] X, 0), X, -X ->
5429 // vselect (setgt X, -1), X, -X ->
5430 // vselect (setl[te] X, 0), -X, X ->
5431 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5432 if (N0.getOpcode() == ISD::SETCC) {
5433 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5434 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5436 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5438 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5439 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5440 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5441 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5442 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5443 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5444 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5447 EVT VT = LHS.getValueType();
5448 SDValue Shift = DAG.getNode(
5449 ISD::SRA, DL, VT, LHS,
5450 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5451 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5452 AddToWorklist(Shift.getNode());
5453 AddToWorklist(Add.getNode());
5454 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5458 if (SimplifySelectOps(N, N1, N2))
5459 return SDValue(N, 0); // Don't revisit N.
5461 // If the VSELECT result requires splitting and the mask is provided by a
5462 // SETCC, then split both nodes and its operands before legalization. This
5463 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5464 // and enables future optimizations (e.g. min/max pattern matching on X86).
5465 if (N0.getOpcode() == ISD::SETCC) {
5466 EVT VT = N->getValueType(0);
5468 // Check if any splitting is required.
5469 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5470 TargetLowering::TypeSplitVector)
5473 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5474 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5475 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5476 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5478 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5479 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5481 // Add the new VSELECT nodes to the work list in case they need to be split
5483 AddToWorklist(Lo.getNode());
5484 AddToWorklist(Hi.getNode());
5486 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5489 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5490 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5492 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5493 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5496 // The ConvertSelectToConcatVector function is assuming both the above
5497 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5499 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5500 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5501 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5502 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5510 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5511 SDValue N0 = N->getOperand(0);
5512 SDValue N1 = N->getOperand(1);
5513 SDValue N2 = N->getOperand(2);
5514 SDValue N3 = N->getOperand(3);
5515 SDValue N4 = N->getOperand(4);
5516 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5518 // fold select_cc lhs, rhs, x, x, cc -> x
5522 // Determine if the condition we're dealing with is constant
5523 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5524 N0, N1, CC, SDLoc(N), false);
5525 if (SCC.getNode()) {
5526 AddToWorklist(SCC.getNode());
5528 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5529 if (!SCCC->isNullValue())
5530 return N2; // cond always true -> true val
5532 return N3; // cond always false -> false val
5533 } else if (SCC->getOpcode() == ISD::UNDEF) {
5534 // When the condition is UNDEF, just return the first operand. This is
5535 // coherent the DAG creation, no setcc node is created in this case
5537 } else if (SCC.getOpcode() == ISD::SETCC) {
5538 // Fold to a simpler select_cc
5539 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5540 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5545 // If we can fold this based on the true/false value, do so.
5546 if (SimplifySelectOps(N, N2, N3))
5547 return SDValue(N, 0); // Don't revisit N.
5549 // fold select_cc into other things, such as min/max/abs
5550 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5553 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5554 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5555 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5559 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5560 // dag node into a ConstantSDNode or a build_vector of constants.
5561 // This function is called by the DAGCombiner when visiting sext/zext/aext
5562 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5563 // Vector extends are not folded if operations are legal; this is to
5564 // avoid introducing illegal build_vector dag nodes.
5565 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5566 SelectionDAG &DAG, bool LegalTypes,
5567 bool LegalOperations) {
5568 unsigned Opcode = N->getOpcode();
5569 SDValue N0 = N->getOperand(0);
5570 EVT VT = N->getValueType(0);
5572 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5573 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5574 && "Expected EXTEND dag node in input!");
5576 // fold (sext c1) -> c1
5577 // fold (zext c1) -> c1
5578 // fold (aext c1) -> c1
5579 if (isa<ConstantSDNode>(N0))
5580 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5582 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5583 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5584 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5585 EVT SVT = VT.getScalarType();
5586 if (!(VT.isVector() &&
5587 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5588 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5591 // We can fold this node into a build_vector.
5592 unsigned VTBits = SVT.getSizeInBits();
5593 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5594 unsigned ShAmt = VTBits - EVTBits;
5595 SmallVector<SDValue, 8> Elts;
5596 unsigned NumElts = VT.getVectorNumElements();
5599 for (unsigned i=0; i != NumElts; ++i) {
5600 SDValue Op = N0->getOperand(i);
5601 if (Op->getOpcode() == ISD::UNDEF) {
5602 Elts.push_back(DAG.getUNDEF(SVT));
5607 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5608 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5609 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5610 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5613 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5617 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5620 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5621 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5622 // transformation. Returns true if extension are possible and the above
5623 // mentioned transformation is profitable.
5624 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5626 SmallVectorImpl<SDNode *> &ExtendNodes,
5627 const TargetLowering &TLI) {
5628 bool HasCopyToRegUses = false;
5629 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5630 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5631 UE = N0.getNode()->use_end();
5636 if (UI.getUse().getResNo() != N0.getResNo())
5638 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5639 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5640 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5641 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5642 // Sign bits will be lost after a zext.
5645 for (unsigned i = 0; i != 2; ++i) {
5646 SDValue UseOp = User->getOperand(i);
5649 if (!isa<ConstantSDNode>(UseOp))
5654 ExtendNodes.push_back(User);
5657 // If truncates aren't free and there are users we can't
5658 // extend, it isn't worthwhile.
5661 // Remember if this value is live-out.
5662 if (User->getOpcode() == ISD::CopyToReg)
5663 HasCopyToRegUses = true;
5666 if (HasCopyToRegUses) {
5667 bool BothLiveOut = false;
5668 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5670 SDUse &Use = UI.getUse();
5671 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5677 // Both unextended and extended values are live out. There had better be
5678 // a good reason for the transformation.
5679 return ExtendNodes.size();
5684 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5685 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5686 ISD::NodeType ExtType) {
5687 // Extend SetCC uses if necessary.
5688 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5689 SDNode *SetCC = SetCCs[i];
5690 SmallVector<SDValue, 4> Ops;
5692 for (unsigned j = 0; j != 2; ++j) {
5693 SDValue SOp = SetCC->getOperand(j);
5695 Ops.push_back(ExtLoad);
5697 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5700 Ops.push_back(SetCC->getOperand(2));
5701 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5705 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5706 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5707 SDValue N0 = N->getOperand(0);
5708 EVT DstVT = N->getValueType(0);
5709 EVT SrcVT = N0.getValueType();
5711 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5712 N->getOpcode() == ISD::ZERO_EXTEND) &&
5713 "Unexpected node type (not an extend)!");
5715 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5716 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5717 // (v8i32 (sext (v8i16 (load x))))
5719 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5720 // (v4i32 (sextload (x + 16)))))
5721 // Where uses of the original load, i.e.:
5723 // are replaced with:
5725 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5726 // (v4i32 (sextload (x + 16)))))))
5728 // This combine is only applicable to illegal, but splittable, vectors.
5729 // All legal types, and illegal non-vector types, are handled elsewhere.
5730 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5732 if (N0->getOpcode() != ISD::LOAD)
5735 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5737 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5738 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5739 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5742 SmallVector<SDNode *, 4> SetCCs;
5743 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5746 ISD::LoadExtType ExtType =
5747 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5749 // Try to split the vector types to get down to legal types.
5750 EVT SplitSrcVT = SrcVT;
5751 EVT SplitDstVT = DstVT;
5752 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5753 SplitSrcVT.getVectorNumElements() > 1) {
5754 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5755 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5758 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5762 const unsigned NumSplits =
5763 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5764 const unsigned Stride = SplitSrcVT.getStoreSize();
5765 SmallVector<SDValue, 4> Loads;
5766 SmallVector<SDValue, 4> Chains;
5768 SDValue BasePtr = LN0->getBasePtr();
5769 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5770 const unsigned Offset = Idx * Stride;
5771 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5773 SDValue SplitLoad = DAG.getExtLoad(
5774 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5775 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5776 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5777 Align, LN0->getAAInfo());
5779 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5780 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5782 Loads.push_back(SplitLoad.getValue(0));
5783 Chains.push_back(SplitLoad.getValue(1));
5786 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5787 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5789 CombineTo(N, NewValue);
5791 // Replace uses of the original load (before extension)
5792 // with a truncate of the concatenated sextloaded vectors.
5794 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5795 CombineTo(N0.getNode(), Trunc, NewChain);
5796 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5797 (ISD::NodeType)N->getOpcode());
5798 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5801 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5802 SDValue N0 = N->getOperand(0);
5803 EVT VT = N->getValueType(0);
5805 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5807 return SDValue(Res, 0);
5809 // fold (sext (sext x)) -> (sext x)
5810 // fold (sext (aext x)) -> (sext x)
5811 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5812 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5815 if (N0.getOpcode() == ISD::TRUNCATE) {
5816 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5817 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5818 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5819 if (NarrowLoad.getNode()) {
5820 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5821 if (NarrowLoad.getNode() != N0.getNode()) {
5822 CombineTo(N0.getNode(), NarrowLoad);
5823 // CombineTo deleted the truncate, if needed, but not what's under it.
5826 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5829 // See if the value being truncated is already sign extended. If so, just
5830 // eliminate the trunc/sext pair.
5831 SDValue Op = N0.getOperand(0);
5832 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5833 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5834 unsigned DestBits = VT.getScalarType().getSizeInBits();
5835 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5837 if (OpBits == DestBits) {
5838 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5839 // bits, it is already ready.
5840 if (NumSignBits > DestBits-MidBits)
5842 } else if (OpBits < DestBits) {
5843 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5844 // bits, just sext from i32.
5845 if (NumSignBits > OpBits-MidBits)
5846 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5848 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5849 // bits, just truncate to i32.
5850 if (NumSignBits > OpBits-MidBits)
5851 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5854 // fold (sext (truncate x)) -> (sextinreg x).
5855 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5856 N0.getValueType())) {
5857 if (OpBits < DestBits)
5858 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5859 else if (OpBits > DestBits)
5860 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5861 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5862 DAG.getValueType(N0.getValueType()));
5866 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5867 // Only generate vector extloads when 1) they're legal, and 2) they are
5868 // deemed desirable by the target.
5869 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5870 ((!LegalOperations && !VT.isVector() &&
5871 !cast<LoadSDNode>(N0)->isVolatile()) ||
5872 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5873 bool DoXform = true;
5874 SmallVector<SDNode*, 4> SetCCs;
5875 if (!N0.hasOneUse())
5876 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5878 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5880 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5881 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5883 LN0->getBasePtr(), N0.getValueType(),
5884 LN0->getMemOperand());
5885 CombineTo(N, ExtLoad);
5886 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5887 N0.getValueType(), ExtLoad);
5888 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5889 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5895 // fold (sext (load x)) to multiple smaller sextloads.
5896 // Only on illegal but splittable vectors.
5897 if (SDValue ExtLoad = CombineExtLoad(N))
5900 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5901 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5902 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5903 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5905 EVT MemVT = LN0->getMemoryVT();
5906 if ((!LegalOperations && !LN0->isVolatile()) ||
5907 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5908 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5910 LN0->getBasePtr(), MemVT,
5911 LN0->getMemOperand());
5912 CombineTo(N, ExtLoad);
5913 CombineTo(N0.getNode(),
5914 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5915 N0.getValueType(), ExtLoad),
5916 ExtLoad.getValue(1));
5917 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5921 // fold (sext (and/or/xor (load x), cst)) ->
5922 // (and/or/xor (sextload x), (sext cst))
5923 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5924 N0.getOpcode() == ISD::XOR) &&
5925 isa<LoadSDNode>(N0.getOperand(0)) &&
5926 N0.getOperand(1).getOpcode() == ISD::Constant &&
5927 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5928 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5929 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5930 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5931 bool DoXform = true;
5932 SmallVector<SDNode*, 4> SetCCs;
5933 if (!N0.hasOneUse())
5934 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5937 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5938 LN0->getChain(), LN0->getBasePtr(),
5940 LN0->getMemOperand());
5941 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5942 Mask = Mask.sext(VT.getSizeInBits());
5944 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5945 ExtLoad, DAG.getConstant(Mask, DL, VT));
5946 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5947 SDLoc(N0.getOperand(0)),
5948 N0.getOperand(0).getValueType(), ExtLoad);
5950 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5951 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5958 if (N0.getOpcode() == ISD::SETCC) {
5959 EVT N0VT = N0.getOperand(0).getValueType();
5960 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5961 // Only do this before legalize for now.
5962 if (VT.isVector() && !LegalOperations &&
5963 TLI.getBooleanContents(N0VT) ==
5964 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5965 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5966 // of the same size as the compared operands. Only optimize sext(setcc())
5967 // if this is the case.
5968 EVT SVT = getSetCCResultType(N0VT);
5970 // We know that the # elements of the results is the same as the
5971 // # elements of the compare (and the # elements of the compare result
5972 // for that matter). Check to see that they are the same size. If so,
5973 // we know that the element size of the sext'd result matches the
5974 // element size of the compare operands.
5975 if (VT.getSizeInBits() == SVT.getSizeInBits())
5976 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5978 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5980 // If the desired elements are smaller or larger than the source
5981 // elements we can use a matching integer vector type and then
5982 // truncate/sign extend
5983 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5984 if (SVT == MatchingVectorType) {
5985 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5986 N0.getOperand(0), N0.getOperand(1),
5987 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5988 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5992 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5993 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5996 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5998 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5999 NegOne, DAG.getConstant(0, DL, VT),
6000 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6001 if (SCC.getNode()) return SCC;
6003 if (!VT.isVector()) {
6004 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6005 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6007 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6008 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6009 N0.getOperand(0), N0.getOperand(1), CC);
6010 return DAG.getSelect(DL, VT, SetCC,
6011 NegOne, DAG.getConstant(0, DL, VT));
6016 // fold (sext x) -> (zext x) if the sign bit is known zero.
6017 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6018 DAG.SignBitIsZero(N0))
6019 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6024 // isTruncateOf - If N is a truncate of some other value, return true, record
6025 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6026 // This function computes KnownZero to avoid a duplicated call to
6027 // computeKnownBits in the caller.
6028 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6031 if (N->getOpcode() == ISD::TRUNCATE) {
6032 Op = N->getOperand(0);
6033 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6037 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6038 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6041 SDValue Op0 = N->getOperand(0);
6042 SDValue Op1 = N->getOperand(1);
6043 assert(Op0.getValueType() == Op1.getValueType());
6045 if (isNullConstant(Op0))
6047 else if (isNullConstant(Op1))
6052 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6054 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6060 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6061 SDValue N0 = N->getOperand(0);
6062 EVT VT = N->getValueType(0);
6064 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6066 return SDValue(Res, 0);
6068 // fold (zext (zext x)) -> (zext x)
6069 // fold (zext (aext x)) -> (zext x)
6070 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6074 // fold (zext (truncate x)) -> (zext x) or
6075 // (zext (truncate x)) -> (truncate x)
6076 // This is valid when the truncated bits of x are already zero.
6077 // FIXME: We should extend this to work for vectors too.
6080 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6081 APInt TruncatedBits =
6082 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6083 APInt(Op.getValueSizeInBits(), 0) :
6084 APInt::getBitsSet(Op.getValueSizeInBits(),
6085 N0.getValueSizeInBits(),
6086 std::min(Op.getValueSizeInBits(),
6087 VT.getSizeInBits()));
6088 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6089 if (VT.bitsGT(Op.getValueType()))
6090 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6091 if (VT.bitsLT(Op.getValueType()))
6092 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6098 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6099 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6100 if (N0.getOpcode() == ISD::TRUNCATE) {
6101 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6102 if (NarrowLoad.getNode()) {
6103 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6104 if (NarrowLoad.getNode() != N0.getNode()) {
6105 CombineTo(N0.getNode(), NarrowLoad);
6106 // CombineTo deleted the truncate, if needed, but not what's under it.
6109 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6113 // fold (zext (truncate x)) -> (and x, mask)
6114 if (N0.getOpcode() == ISD::TRUNCATE &&
6115 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6117 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6118 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6119 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6120 if (NarrowLoad.getNode()) {
6121 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6122 if (NarrowLoad.getNode() != N0.getNode()) {
6123 CombineTo(N0.getNode(), NarrowLoad);
6124 // CombineTo deleted the truncate, if needed, but not what's under it.
6127 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6130 SDValue Op = N0.getOperand(0);
6131 if (Op.getValueType().bitsLT(VT)) {
6132 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6133 AddToWorklist(Op.getNode());
6134 } else if (Op.getValueType().bitsGT(VT)) {
6135 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6136 AddToWorklist(Op.getNode());
6138 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6139 N0.getValueType().getScalarType());
6142 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6143 // if either of the casts is not free.
6144 if (N0.getOpcode() == ISD::AND &&
6145 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6146 N0.getOperand(1).getOpcode() == ISD::Constant &&
6147 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6148 N0.getValueType()) ||
6149 !TLI.isZExtFree(N0.getValueType(), VT))) {
6150 SDValue X = N0.getOperand(0).getOperand(0);
6151 if (X.getValueType().bitsLT(VT)) {
6152 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6153 } else if (X.getValueType().bitsGT(VT)) {
6154 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6156 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6157 Mask = Mask.zext(VT.getSizeInBits());
6159 return DAG.getNode(ISD::AND, DL, VT,
6160 X, DAG.getConstant(Mask, DL, VT));
6163 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6164 // Only generate vector extloads when 1) they're legal, and 2) they are
6165 // deemed desirable by the target.
6166 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6167 ((!LegalOperations && !VT.isVector() &&
6168 !cast<LoadSDNode>(N0)->isVolatile()) ||
6169 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6170 bool DoXform = true;
6171 SmallVector<SDNode*, 4> SetCCs;
6172 if (!N0.hasOneUse())
6173 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6175 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6177 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6178 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6180 LN0->getBasePtr(), N0.getValueType(),
6181 LN0->getMemOperand());
6182 CombineTo(N, ExtLoad);
6183 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6184 N0.getValueType(), ExtLoad);
6185 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6187 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6189 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6193 // fold (zext (load x)) to multiple smaller zextloads.
6194 // Only on illegal but splittable vectors.
6195 if (SDValue ExtLoad = CombineExtLoad(N))
6198 // fold (zext (and/or/xor (load x), cst)) ->
6199 // (and/or/xor (zextload x), (zext cst))
6200 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6201 N0.getOpcode() == ISD::XOR) &&
6202 isa<LoadSDNode>(N0.getOperand(0)) &&
6203 N0.getOperand(1).getOpcode() == ISD::Constant &&
6204 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6205 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6206 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6207 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6208 bool DoXform = true;
6209 SmallVector<SDNode*, 4> SetCCs;
6210 if (!N0.hasOneUse())
6211 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6214 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6215 LN0->getChain(), LN0->getBasePtr(),
6217 LN0->getMemOperand());
6218 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6219 Mask = Mask.zext(VT.getSizeInBits());
6221 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6222 ExtLoad, DAG.getConstant(Mask, DL, VT));
6223 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6224 SDLoc(N0.getOperand(0)),
6225 N0.getOperand(0).getValueType(), ExtLoad);
6227 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6228 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6230 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6235 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6236 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6237 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6238 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6239 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6240 EVT MemVT = LN0->getMemoryVT();
6241 if ((!LegalOperations && !LN0->isVolatile()) ||
6242 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6243 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6245 LN0->getBasePtr(), MemVT,
6246 LN0->getMemOperand());
6247 CombineTo(N, ExtLoad);
6248 CombineTo(N0.getNode(),
6249 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6251 ExtLoad.getValue(1));
6252 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6256 if (N0.getOpcode() == ISD::SETCC) {
6257 if (!LegalOperations && VT.isVector() &&
6258 N0.getValueType().getVectorElementType() == MVT::i1) {
6259 EVT N0VT = N0.getOperand(0).getValueType();
6260 if (getSetCCResultType(N0VT) == N0.getValueType())
6263 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6264 // Only do this before legalize for now.
6265 EVT EltVT = VT.getVectorElementType();
6267 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6268 DAG.getConstant(1, DL, EltVT));
6269 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6270 // We know that the # elements of the results is the same as the
6271 // # elements of the compare (and the # elements of the compare result
6272 // for that matter). Check to see that they are the same size. If so,
6273 // we know that the element size of the sext'd result matches the
6274 // element size of the compare operands.
6275 return DAG.getNode(ISD::AND, DL, VT,
6276 DAG.getSetCC(DL, VT, N0.getOperand(0),
6278 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6279 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6282 // If the desired elements are smaller or larger than the source
6283 // elements we can use a matching integer vector type and then
6284 // truncate/sign extend
6285 EVT MatchingElementType =
6286 EVT::getIntegerVT(*DAG.getContext(),
6287 N0VT.getScalarType().getSizeInBits());
6288 EVT MatchingVectorType =
6289 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6290 N0VT.getVectorNumElements());
6292 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6294 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6295 return DAG.getNode(ISD::AND, DL, VT,
6296 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6297 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6300 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6303 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6304 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6305 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6306 if (SCC.getNode()) return SCC;
6309 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6310 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6311 isa<ConstantSDNode>(N0.getOperand(1)) &&
6312 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6314 SDValue ShAmt = N0.getOperand(1);
6315 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6316 if (N0.getOpcode() == ISD::SHL) {
6317 SDValue InnerZExt = N0.getOperand(0);
6318 // If the original shl may be shifting out bits, do not perform this
6320 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6321 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6322 if (ShAmtVal > KnownZeroBits)
6328 // Ensure that the shift amount is wide enough for the shifted value.
6329 if (VT.getSizeInBits() >= 256)
6330 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6332 return DAG.getNode(N0.getOpcode(), DL, VT,
6333 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6340 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6341 SDValue N0 = N->getOperand(0);
6342 EVT VT = N->getValueType(0);
6344 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6346 return SDValue(Res, 0);
6348 // fold (aext (aext x)) -> (aext x)
6349 // fold (aext (zext x)) -> (zext x)
6350 // fold (aext (sext x)) -> (sext x)
6351 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6352 N0.getOpcode() == ISD::ZERO_EXTEND ||
6353 N0.getOpcode() == ISD::SIGN_EXTEND)
6354 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6356 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6357 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6358 if (N0.getOpcode() == ISD::TRUNCATE) {
6359 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6360 if (NarrowLoad.getNode()) {
6361 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6362 if (NarrowLoad.getNode() != N0.getNode()) {
6363 CombineTo(N0.getNode(), NarrowLoad);
6364 // CombineTo deleted the truncate, if needed, but not what's under it.
6367 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6371 // fold (aext (truncate x))
6372 if (N0.getOpcode() == ISD::TRUNCATE) {
6373 SDValue TruncOp = N0.getOperand(0);
6374 if (TruncOp.getValueType() == VT)
6375 return TruncOp; // x iff x size == zext size.
6376 if (TruncOp.getValueType().bitsGT(VT))
6377 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6378 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6381 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6382 // if the trunc is not free.
6383 if (N0.getOpcode() == ISD::AND &&
6384 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6385 N0.getOperand(1).getOpcode() == ISD::Constant &&
6386 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6387 N0.getValueType())) {
6388 SDValue X = N0.getOperand(0).getOperand(0);
6389 if (X.getValueType().bitsLT(VT)) {
6390 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6391 } else if (X.getValueType().bitsGT(VT)) {
6392 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6394 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6395 Mask = Mask.zext(VT.getSizeInBits());
6397 return DAG.getNode(ISD::AND, DL, VT,
6398 X, DAG.getConstant(Mask, DL, VT));
6401 // fold (aext (load x)) -> (aext (truncate (extload x)))
6402 // None of the supported targets knows how to perform load and any_ext
6403 // on vectors in one instruction. We only perform this transformation on
6405 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6406 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6407 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6408 bool DoXform = true;
6409 SmallVector<SDNode*, 4> SetCCs;
6410 if (!N0.hasOneUse())
6411 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6413 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6414 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6416 LN0->getBasePtr(), N0.getValueType(),
6417 LN0->getMemOperand());
6418 CombineTo(N, ExtLoad);
6419 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6420 N0.getValueType(), ExtLoad);
6421 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6422 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6424 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6428 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6429 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6430 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6431 if (N0.getOpcode() == ISD::LOAD &&
6432 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6434 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6435 ISD::LoadExtType ExtType = LN0->getExtensionType();
6436 EVT MemVT = LN0->getMemoryVT();
6437 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6438 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6439 VT, LN0->getChain(), LN0->getBasePtr(),
6440 MemVT, LN0->getMemOperand());
6441 CombineTo(N, ExtLoad);
6442 CombineTo(N0.getNode(),
6443 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6444 N0.getValueType(), ExtLoad),
6445 ExtLoad.getValue(1));
6446 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6450 if (N0.getOpcode() == ISD::SETCC) {
6452 // aext(setcc) -> vsetcc
6453 // aext(setcc) -> truncate(vsetcc)
6454 // aext(setcc) -> aext(vsetcc)
6455 // Only do this before legalize for now.
6456 if (VT.isVector() && !LegalOperations) {
6457 EVT N0VT = N0.getOperand(0).getValueType();
6458 // We know that the # elements of the results is the same as the
6459 // # elements of the compare (and the # elements of the compare result
6460 // for that matter). Check to see that they are the same size. If so,
6461 // we know that the element size of the sext'd result matches the
6462 // element size of the compare operands.
6463 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6464 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6466 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6467 // If the desired elements are smaller or larger than the source
6468 // elements we can use a matching integer vector type and then
6469 // truncate/any extend
6471 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6473 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6475 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6476 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6480 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6483 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6484 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6485 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6493 /// See if the specified operand can be simplified with the knowledge that only
6494 /// the bits specified by Mask are used. If so, return the simpler operand,
6495 /// otherwise return a null SDValue.
6496 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6497 switch (V.getOpcode()) {
6499 case ISD::Constant: {
6500 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6501 assert(CV && "Const value should be ConstSDNode.");
6502 const APInt &CVal = CV->getAPIntValue();
6503 APInt NewVal = CVal & Mask;
6505 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6510 // If the LHS or RHS don't contribute bits to the or, drop them.
6511 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6512 return V.getOperand(1);
6513 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6514 return V.getOperand(0);
6517 // Only look at single-use SRLs.
6518 if (!V.getNode()->hasOneUse())
6520 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6521 // See if we can recursively simplify the LHS.
6522 unsigned Amt = RHSC->getZExtValue();
6524 // Watch out for shift count overflow though.
6525 if (Amt >= Mask.getBitWidth()) break;
6526 APInt NewMask = Mask << Amt;
6527 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6528 if (SimplifyLHS.getNode())
6529 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6530 SimplifyLHS, V.getOperand(1));
6536 /// If the result of a wider load is shifted to right of N bits and then
6537 /// truncated to a narrower type and where N is a multiple of number of bits of
6538 /// the narrower type, transform it to a narrower load from address + N / num of
6539 /// bits of new type. If the result is to be extended, also fold the extension
6540 /// to form a extending load.
6541 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6542 unsigned Opc = N->getOpcode();
6544 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6545 SDValue N0 = N->getOperand(0);
6546 EVT VT = N->getValueType(0);
6549 // This transformation isn't valid for vector loads.
6553 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6555 if (Opc == ISD::SIGN_EXTEND_INREG) {
6556 ExtType = ISD::SEXTLOAD;
6557 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6558 } else if (Opc == ISD::SRL) {
6559 // Another special-case: SRL is basically zero-extending a narrower value.
6560 ExtType = ISD::ZEXTLOAD;
6562 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6563 if (!N01) return SDValue();
6564 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6565 VT.getSizeInBits() - N01->getZExtValue());
6567 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6570 unsigned EVTBits = ExtVT.getSizeInBits();
6572 // Do not generate loads of non-round integer types since these can
6573 // be expensive (and would be wrong if the type is not byte sized).
6574 if (!ExtVT.isRound())
6578 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6579 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6580 ShAmt = N01->getZExtValue();
6581 // Is the shift amount a multiple of size of VT?
6582 if ((ShAmt & (EVTBits-1)) == 0) {
6583 N0 = N0.getOperand(0);
6584 // Is the load width a multiple of size of VT?
6585 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6589 // At this point, we must have a load or else we can't do the transform.
6590 if (!isa<LoadSDNode>(N0)) return SDValue();
6592 // Because a SRL must be assumed to *need* to zero-extend the high bits
6593 // (as opposed to anyext the high bits), we can't combine the zextload
6594 // lowering of SRL and an sextload.
6595 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6598 // If the shift amount is larger than the input type then we're not
6599 // accessing any of the loaded bytes. If the load was a zextload/extload
6600 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6601 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6606 // If the load is shifted left (and the result isn't shifted back right),
6607 // we can fold the truncate through the shift.
6608 unsigned ShLeftAmt = 0;
6609 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6610 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6611 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6612 ShLeftAmt = N01->getZExtValue();
6613 N0 = N0.getOperand(0);
6617 // If we haven't found a load, we can't narrow it. Don't transform one with
6618 // multiple uses, this would require adding a new load.
6619 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6622 // Don't change the width of a volatile load.
6623 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6624 if (LN0->isVolatile())
6627 // Verify that we are actually reducing a load width here.
6628 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6631 // For the transform to be legal, the load must produce only two values
6632 // (the value loaded and the chain). Don't transform a pre-increment
6633 // load, for example, which produces an extra value. Otherwise the
6634 // transformation is not equivalent, and the downstream logic to replace
6635 // uses gets things wrong.
6636 if (LN0->getNumValues() > 2)
6639 // If the load that we're shrinking is an extload and we're not just
6640 // discarding the extension we can't simply shrink the load. Bail.
6641 // TODO: It would be possible to merge the extensions in some cases.
6642 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6643 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6646 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6649 EVT PtrType = N0.getOperand(1).getValueType();
6651 if (PtrType == MVT::Untyped || PtrType.isExtended())
6652 // It's not possible to generate a constant of extended or untyped type.
6655 // For big endian targets, we need to adjust the offset to the pointer to
6656 // load the correct bytes.
6657 if (TLI.isBigEndian()) {
6658 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6659 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6660 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6663 uint64_t PtrOff = ShAmt / 8;
6664 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6666 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6667 PtrType, LN0->getBasePtr(),
6668 DAG.getConstant(PtrOff, DL, PtrType));
6669 AddToWorklist(NewPtr.getNode());
6672 if (ExtType == ISD::NON_EXTLOAD)
6673 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6674 LN0->getPointerInfo().getWithOffset(PtrOff),
6675 LN0->isVolatile(), LN0->isNonTemporal(),
6676 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6678 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6679 LN0->getPointerInfo().getWithOffset(PtrOff),
6680 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6681 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6683 // Replace the old load's chain with the new load's chain.
6684 WorklistRemover DeadNodes(*this);
6685 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6687 // Shift the result left, if we've swallowed a left shift.
6688 SDValue Result = Load;
6689 if (ShLeftAmt != 0) {
6690 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6691 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6693 // If the shift amount is as large as the result size (but, presumably,
6694 // no larger than the source) then the useful bits of the result are
6695 // zero; we can't simply return the shortened shift, because the result
6696 // of that operation is undefined.
6698 if (ShLeftAmt >= VT.getSizeInBits())
6699 Result = DAG.getConstant(0, DL, VT);
6701 Result = DAG.getNode(ISD::SHL, DL, VT,
6702 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6705 // Return the new loaded value.
6709 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6710 SDValue N0 = N->getOperand(0);
6711 SDValue N1 = N->getOperand(1);
6712 EVT VT = N->getValueType(0);
6713 EVT EVT = cast<VTSDNode>(N1)->getVT();
6714 unsigned VTBits = VT.getScalarType().getSizeInBits();
6715 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6717 // fold (sext_in_reg c1) -> c1
6718 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6719 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6721 // If the input is already sign extended, just drop the extension.
6722 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6725 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6726 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6727 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6728 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6729 N0.getOperand(0), N1);
6731 // fold (sext_in_reg (sext x)) -> (sext x)
6732 // fold (sext_in_reg (aext x)) -> (sext x)
6733 // if x is small enough.
6734 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6735 SDValue N00 = N0.getOperand(0);
6736 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6737 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6738 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6741 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6742 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6743 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6745 // fold operands of sext_in_reg based on knowledge that the top bits are not
6747 if (SimplifyDemandedBits(SDValue(N, 0)))
6748 return SDValue(N, 0);
6750 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6751 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6752 SDValue NarrowLoad = ReduceLoadWidth(N);
6753 if (NarrowLoad.getNode())
6756 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6757 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6758 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6759 if (N0.getOpcode() == ISD::SRL) {
6760 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6761 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6762 // We can turn this into an SRA iff the input to the SRL is already sign
6764 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6765 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6766 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6767 N0.getOperand(0), N0.getOperand(1));
6771 // fold (sext_inreg (extload x)) -> (sextload x)
6772 if (ISD::isEXTLoad(N0.getNode()) &&
6773 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6774 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6775 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6776 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6777 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6778 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6780 LN0->getBasePtr(), EVT,
6781 LN0->getMemOperand());
6782 CombineTo(N, ExtLoad);
6783 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6784 AddToWorklist(ExtLoad.getNode());
6785 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6787 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6788 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6790 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6791 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6792 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6793 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6794 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6796 LN0->getBasePtr(), EVT,
6797 LN0->getMemOperand());
6798 CombineTo(N, ExtLoad);
6799 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6800 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6803 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6804 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6805 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6806 N0.getOperand(1), false);
6807 if (BSwap.getNode())
6808 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6812 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6813 // into a build_vector.
6814 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6815 SmallVector<SDValue, 8> Elts;
6816 unsigned NumElts = N0->getNumOperands();
6817 unsigned ShAmt = VTBits - EVTBits;
6819 for (unsigned i = 0; i != NumElts; ++i) {
6820 SDValue Op = N0->getOperand(i);
6821 if (Op->getOpcode() == ISD::UNDEF) {
6826 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6827 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6828 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6829 SDLoc(Op), Op.getValueType()));
6832 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6838 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6839 SDValue N0 = N->getOperand(0);
6840 EVT VT = N->getValueType(0);
6842 if (N0.getOpcode() == ISD::UNDEF)
6843 return DAG.getUNDEF(VT);
6845 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6847 return SDValue(Res, 0);
6852 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6853 SDValue N0 = N->getOperand(0);
6854 EVT VT = N->getValueType(0);
6855 bool isLE = TLI.isLittleEndian();
6858 if (N0.getValueType() == N->getValueType(0))
6860 // fold (truncate c1) -> c1
6861 if (isConstantIntBuildVectorOrConstantInt(N0))
6862 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6863 // fold (truncate (truncate x)) -> (truncate x)
6864 if (N0.getOpcode() == ISD::TRUNCATE)
6865 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6866 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6867 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6868 N0.getOpcode() == ISD::SIGN_EXTEND ||
6869 N0.getOpcode() == ISD::ANY_EXTEND) {
6870 if (N0.getOperand(0).getValueType().bitsLT(VT))
6871 // if the source is smaller than the dest, we still need an extend
6872 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6874 if (N0.getOperand(0).getValueType().bitsGT(VT))
6875 // if the source is larger than the dest, than we just need the truncate
6876 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6877 // if the source and dest are the same type, we can drop both the extend
6878 // and the truncate.
6879 return N0.getOperand(0);
6882 // Fold extract-and-trunc into a narrow extract. For example:
6883 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6884 // i32 y = TRUNCATE(i64 x)
6886 // v16i8 b = BITCAST (v2i64 val)
6887 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6889 // Note: We only run this optimization after type legalization (which often
6890 // creates this pattern) and before operation legalization after which
6891 // we need to be more careful about the vector instructions that we generate.
6892 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6893 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6895 EVT VecTy = N0.getOperand(0).getValueType();
6896 EVT ExTy = N0.getValueType();
6897 EVT TrTy = N->getValueType(0);
6899 unsigned NumElem = VecTy.getVectorNumElements();
6900 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6902 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6903 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6905 SDValue EltNo = N0->getOperand(1);
6906 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6907 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6908 EVT IndexTy = TLI.getVectorIdxTy();
6909 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6911 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6912 NVT, N0.getOperand(0));
6915 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6917 DAG.getConstant(Index, DL, IndexTy));
6921 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6922 if (N0.getOpcode() == ISD::SELECT) {
6923 EVT SrcVT = N0.getValueType();
6924 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6925 TLI.isTruncateFree(SrcVT, VT)) {
6927 SDValue Cond = N0.getOperand(0);
6928 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6929 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6930 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6934 // Fold a series of buildvector, bitcast, and truncate if possible.
6936 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6937 // (2xi32 (buildvector x, y)).
6938 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6939 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6940 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6941 N0.getOperand(0).hasOneUse()) {
6943 SDValue BuildVect = N0.getOperand(0);
6944 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6945 EVT TruncVecEltTy = VT.getVectorElementType();
6947 // Check that the element types match.
6948 if (BuildVectEltTy == TruncVecEltTy) {
6949 // Now we only need to compute the offset of the truncated elements.
6950 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6951 unsigned TruncVecNumElts = VT.getVectorNumElements();
6952 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6954 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6955 "Invalid number of elements");
6957 SmallVector<SDValue, 8> Opnds;
6958 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6959 Opnds.push_back(BuildVect.getOperand(i));
6961 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6965 // See if we can simplify the input to this truncate through knowledge that
6966 // only the low bits are being used.
6967 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6968 // Currently we only perform this optimization on scalars because vectors
6969 // may have different active low bits.
6970 if (!VT.isVector()) {
6972 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6973 VT.getSizeInBits()));
6974 if (Shorter.getNode())
6975 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6977 // fold (truncate (load x)) -> (smaller load x)
6978 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6979 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6980 SDValue Reduced = ReduceLoadWidth(N);
6981 if (Reduced.getNode())
6983 // Handle the case where the load remains an extending load even
6984 // after truncation.
6985 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6987 if (!LN0->isVolatile() &&
6988 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6989 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6990 VT, LN0->getChain(), LN0->getBasePtr(),
6992 LN0->getMemOperand());
6993 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6998 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6999 // where ... are all 'undef'.
7000 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7001 SmallVector<EVT, 8> VTs;
7004 unsigned NumDefs = 0;
7006 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7007 SDValue X = N0.getOperand(i);
7008 if (X.getOpcode() != ISD::UNDEF) {
7013 // Stop if more than one members are non-undef.
7016 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7017 VT.getVectorElementType(),
7018 X.getValueType().getVectorNumElements()));
7022 return DAG.getUNDEF(VT);
7025 assert(V.getNode() && "The single defined operand is empty!");
7026 SmallVector<SDValue, 8> Opnds;
7027 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7029 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7032 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7033 AddToWorklist(NV.getNode());
7034 Opnds.push_back(NV);
7036 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7040 // Simplify the operands using demanded-bits information.
7041 if (!VT.isVector() &&
7042 SimplifyDemandedBits(SDValue(N, 0)))
7043 return SDValue(N, 0);
7048 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7049 SDValue Elt = N->getOperand(i);
7050 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7051 return Elt.getNode();
7052 return Elt.getOperand(Elt.getResNo()).getNode();
7055 /// build_pair (load, load) -> load
7056 /// if load locations are consecutive.
7057 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7058 assert(N->getOpcode() == ISD::BUILD_PAIR);
7060 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7061 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7062 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7063 LD1->getAddressSpace() != LD2->getAddressSpace())
7065 EVT LD1VT = LD1->getValueType(0);
7067 if (ISD::isNON_EXTLoad(LD2) &&
7069 // If both are volatile this would reduce the number of volatile loads.
7070 // If one is volatile it might be ok, but play conservative and bail out.
7071 !LD1->isVolatile() &&
7072 !LD2->isVolatile() &&
7073 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7074 unsigned Align = LD1->getAlignment();
7075 unsigned NewAlign = TLI.getDataLayout()->
7076 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7078 if (NewAlign <= Align &&
7079 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7080 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7081 LD1->getBasePtr(), LD1->getPointerInfo(),
7082 false, false, false, Align);
7088 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7089 SDValue N0 = N->getOperand(0);
7090 EVT VT = N->getValueType(0);
7092 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7093 // Only do this before legalize, since afterward the target may be depending
7094 // on the bitconvert.
7095 // First check to see if this is all constant.
7097 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7099 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7101 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7102 assert(!DestEltVT.isVector() &&
7103 "Element type of vector ValueType must not be vector!");
7105 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7108 // If the input is a constant, let getNode fold it.
7109 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7110 // If we can't allow illegal operations, we need to check that this is just
7111 // a fp -> int or int -> conversion and that the resulting operation will
7113 if (!LegalOperations ||
7114 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7115 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7116 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7117 TLI.isOperationLegal(ISD::Constant, VT)))
7118 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7121 // (conv (conv x, t1), t2) -> (conv x, t2)
7122 if (N0.getOpcode() == ISD::BITCAST)
7123 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7126 // fold (conv (load x)) -> (load (conv*)x)
7127 // If the resultant load doesn't need a higher alignment than the original!
7128 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7129 // Do not change the width of a volatile load.
7130 !cast<LoadSDNode>(N0)->isVolatile() &&
7131 // Do not remove the cast if the types differ in endian layout.
7132 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7133 TLI.hasBigEndianPartOrdering(VT) &&
7134 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7135 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7136 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7137 unsigned Align = TLI.getDataLayout()->
7138 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7139 unsigned OrigAlign = LN0->getAlignment();
7141 if (Align <= OrigAlign) {
7142 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7143 LN0->getBasePtr(), LN0->getPointerInfo(),
7144 LN0->isVolatile(), LN0->isNonTemporal(),
7145 LN0->isInvariant(), OrigAlign,
7147 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7152 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7153 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7154 // This often reduces constant pool loads.
7155 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7156 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7157 N0.getNode()->hasOneUse() && VT.isInteger() &&
7158 !VT.isVector() && !N0.getValueType().isVector()) {
7159 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7161 AddToWorklist(NewConv.getNode());
7164 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7165 if (N0.getOpcode() == ISD::FNEG)
7166 return DAG.getNode(ISD::XOR, DL, VT,
7167 NewConv, DAG.getConstant(SignBit, DL, VT));
7168 assert(N0.getOpcode() == ISD::FABS);
7169 return DAG.getNode(ISD::AND, DL, VT,
7170 NewConv, DAG.getConstant(~SignBit, DL, VT));
7173 // fold (bitconvert (fcopysign cst, x)) ->
7174 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7175 // Note that we don't handle (copysign x, cst) because this can always be
7176 // folded to an fneg or fabs.
7177 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7178 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7179 VT.isInteger() && !VT.isVector()) {
7180 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7181 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7182 if (isTypeLegal(IntXVT)) {
7183 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7184 IntXVT, N0.getOperand(1));
7185 AddToWorklist(X.getNode());
7187 // If X has a different width than the result/lhs, sext it or truncate it.
7188 unsigned VTWidth = VT.getSizeInBits();
7189 if (OrigXWidth < VTWidth) {
7190 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7191 AddToWorklist(X.getNode());
7192 } else if (OrigXWidth > VTWidth) {
7193 // To get the sign bit in the right place, we have to shift it right
7194 // before truncating.
7196 X = DAG.getNode(ISD::SRL, DL,
7197 X.getValueType(), X,
7198 DAG.getConstant(OrigXWidth-VTWidth, DL,
7200 AddToWorklist(X.getNode());
7201 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7202 AddToWorklist(X.getNode());
7205 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7206 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7207 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7208 AddToWorklist(X.getNode());
7210 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7211 VT, N0.getOperand(0));
7212 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7213 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7214 AddToWorklist(Cst.getNode());
7216 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7220 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7221 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7222 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7223 if (CombineLD.getNode())
7227 // Remove double bitcasts from shuffles - this is often a legacy of
7228 // XformToShuffleWithZero being used to combine bitmaskings (of
7229 // float vectors bitcast to integer vectors) into shuffles.
7230 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7231 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7232 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7233 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7234 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7235 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7237 // If operands are a bitcast, peek through if it casts the original VT.
7238 // If operands are a UNDEF or constant, just bitcast back to original VT.
7239 auto PeekThroughBitcast = [&](SDValue Op) {
7240 if (Op.getOpcode() == ISD::BITCAST &&
7241 Op.getOperand(0)->getValueType(0) == VT)
7242 return SDValue(Op.getOperand(0));
7243 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7244 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7245 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7249 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7250 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7255 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7256 SmallVector<int, 8> NewMask;
7257 for (int M : SVN->getMask())
7258 for (int i = 0; i != MaskScale; ++i)
7259 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7261 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7263 std::swap(SV0, SV1);
7264 ShuffleVectorSDNode::commuteMask(NewMask);
7265 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7269 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7275 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7276 EVT VT = N->getValueType(0);
7277 return CombineConsecutiveLoads(N, VT);
7280 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7281 /// operands. DstEltVT indicates the destination element value type.
7282 SDValue DAGCombiner::
7283 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7284 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7286 // If this is already the right type, we're done.
7287 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7289 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7290 unsigned DstBitSize = DstEltVT.getSizeInBits();
7292 // If this is a conversion of N elements of one type to N elements of another
7293 // type, convert each element. This handles FP<->INT cases.
7294 if (SrcBitSize == DstBitSize) {
7295 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7296 BV->getValueType(0).getVectorNumElements());
7298 // Due to the FP element handling below calling this routine recursively,
7299 // we can end up with a scalar-to-vector node here.
7300 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7301 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7302 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7303 DstEltVT, BV->getOperand(0)));
7305 SmallVector<SDValue, 8> Ops;
7306 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7307 SDValue Op = BV->getOperand(i);
7308 // If the vector element type is not legal, the BUILD_VECTOR operands
7309 // are promoted and implicitly truncated. Make that explicit here.
7310 if (Op.getValueType() != SrcEltVT)
7311 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7312 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7314 AddToWorklist(Ops.back().getNode());
7316 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7319 // Otherwise, we're growing or shrinking the elements. To avoid having to
7320 // handle annoying details of growing/shrinking FP values, we convert them to
7322 if (SrcEltVT.isFloatingPoint()) {
7323 // Convert the input float vector to a int vector where the elements are the
7325 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7326 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7330 // Now we know the input is an integer vector. If the output is a FP type,
7331 // convert to integer first, then to FP of the right size.
7332 if (DstEltVT.isFloatingPoint()) {
7333 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7334 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7336 // Next, convert to FP elements of the same size.
7337 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7342 // Okay, we know the src/dst types are both integers of differing types.
7343 // Handling growing first.
7344 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7345 if (SrcBitSize < DstBitSize) {
7346 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7348 SmallVector<SDValue, 8> Ops;
7349 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7350 i += NumInputsPerOutput) {
7351 bool isLE = TLI.isLittleEndian();
7352 APInt NewBits = APInt(DstBitSize, 0);
7353 bool EltIsUndef = true;
7354 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7355 // Shift the previously computed bits over.
7356 NewBits <<= SrcBitSize;
7357 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7358 if (Op.getOpcode() == ISD::UNDEF) continue;
7361 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7362 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7366 Ops.push_back(DAG.getUNDEF(DstEltVT));
7368 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7371 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7372 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7375 // Finally, this must be the case where we are shrinking elements: each input
7376 // turns into multiple outputs.
7377 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7378 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7379 NumOutputsPerInput*BV->getNumOperands());
7380 SmallVector<SDValue, 8> Ops;
7382 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7383 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7384 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7388 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7389 getAPIntValue().zextOrTrunc(SrcBitSize);
7391 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7392 APInt ThisVal = OpVal.trunc(DstBitSize);
7393 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7394 OpVal = OpVal.lshr(DstBitSize);
7397 // For big endian targets, swap the order of the pieces of each element.
7398 if (TLI.isBigEndian())
7399 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7402 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7405 /// Try to perform FMA combining on a given FADD node.
7406 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7407 SDValue N0 = N->getOperand(0);
7408 SDValue N1 = N->getOperand(1);
7409 EVT VT = N->getValueType(0);
7412 const TargetOptions &Options = DAG.getTarget().Options;
7413 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7414 Options.UnsafeFPMath);
7416 // Floating-point multiply-add with intermediate rounding.
7417 bool HasFMAD = (LegalOperations &&
7418 TLI.isOperationLegal(ISD::FMAD, VT));
7420 // Floating-point multiply-add without intermediate rounding.
7421 bool HasFMA = ((!LegalOperations ||
7422 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7423 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7426 // No valid opcode, do not combine.
7427 if (!HasFMAD && !HasFMA)
7430 // Always prefer FMAD to FMA for precision.
7431 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7432 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7433 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7435 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7436 if (N0.getOpcode() == ISD::FMUL &&
7437 (Aggressive || N0->hasOneUse())) {
7438 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7439 N0.getOperand(0), N0.getOperand(1), N1);
7442 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7443 // Note: Commutes FADD operands.
7444 if (N1.getOpcode() == ISD::FMUL &&
7445 (Aggressive || N1->hasOneUse())) {
7446 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7447 N1.getOperand(0), N1.getOperand(1), N0);
7450 // Look through FP_EXTEND nodes to do more combining.
7451 if (UnsafeFPMath && LookThroughFPExt) {
7452 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7453 if (N0.getOpcode() == ISD::FP_EXTEND) {
7454 SDValue N00 = N0.getOperand(0);
7455 if (N00.getOpcode() == ISD::FMUL)
7456 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7457 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7459 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7460 N00.getOperand(1)), N1);
7463 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7464 // Note: Commutes FADD operands.
7465 if (N1.getOpcode() == ISD::FP_EXTEND) {
7466 SDValue N10 = N1.getOperand(0);
7467 if (N10.getOpcode() == ISD::FMUL)
7468 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7469 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7471 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7472 N10.getOperand(1)), N0);
7476 // More folding opportunities when target permits.
7477 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7478 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7479 if (N0.getOpcode() == PreferredFusedOpcode &&
7480 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7481 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7482 N0.getOperand(0), N0.getOperand(1),
7483 DAG.getNode(PreferredFusedOpcode, SL, VT,
7484 N0.getOperand(2).getOperand(0),
7485 N0.getOperand(2).getOperand(1),
7489 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7490 if (N1->getOpcode() == PreferredFusedOpcode &&
7491 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7492 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7493 N1.getOperand(0), N1.getOperand(1),
7494 DAG.getNode(PreferredFusedOpcode, SL, VT,
7495 N1.getOperand(2).getOperand(0),
7496 N1.getOperand(2).getOperand(1),
7500 if (UnsafeFPMath && LookThroughFPExt) {
7501 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7502 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7503 auto FoldFAddFMAFPExtFMul = [&] (
7504 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7505 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7506 DAG.getNode(PreferredFusedOpcode, SL, VT,
7507 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7508 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7511 if (N0.getOpcode() == PreferredFusedOpcode) {
7512 SDValue N02 = N0.getOperand(2);
7513 if (N02.getOpcode() == ISD::FP_EXTEND) {
7514 SDValue N020 = N02.getOperand(0);
7515 if (N020.getOpcode() == ISD::FMUL)
7516 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7517 N020.getOperand(0), N020.getOperand(1),
7522 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7523 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7524 // FIXME: This turns two single-precision and one double-precision
7525 // operation into two double-precision operations, which might not be
7526 // interesting for all targets, especially GPUs.
7527 auto FoldFAddFPExtFMAFMul = [&] (
7528 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7529 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7530 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7531 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7532 DAG.getNode(PreferredFusedOpcode, SL, VT,
7533 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7534 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7537 if (N0.getOpcode() == ISD::FP_EXTEND) {
7538 SDValue N00 = N0.getOperand(0);
7539 if (N00.getOpcode() == PreferredFusedOpcode) {
7540 SDValue N002 = N00.getOperand(2);
7541 if (N002.getOpcode() == ISD::FMUL)
7542 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7543 N002.getOperand(0), N002.getOperand(1),
7548 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7549 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7550 if (N1.getOpcode() == PreferredFusedOpcode) {
7551 SDValue N12 = N1.getOperand(2);
7552 if (N12.getOpcode() == ISD::FP_EXTEND) {
7553 SDValue N120 = N12.getOperand(0);
7554 if (N120.getOpcode() == ISD::FMUL)
7555 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7556 N120.getOperand(0), N120.getOperand(1),
7561 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7562 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7563 // FIXME: This turns two single-precision and one double-precision
7564 // operation into two double-precision operations, which might not be
7565 // interesting for all targets, especially GPUs.
7566 if (N1.getOpcode() == ISD::FP_EXTEND) {
7567 SDValue N10 = N1.getOperand(0);
7568 if (N10.getOpcode() == PreferredFusedOpcode) {
7569 SDValue N102 = N10.getOperand(2);
7570 if (N102.getOpcode() == ISD::FMUL)
7571 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7572 N102.getOperand(0), N102.getOperand(1),
7582 /// Try to perform FMA combining on a given FSUB node.
7583 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7584 SDValue N0 = N->getOperand(0);
7585 SDValue N1 = N->getOperand(1);
7586 EVT VT = N->getValueType(0);
7589 const TargetOptions &Options = DAG.getTarget().Options;
7590 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7591 Options.UnsafeFPMath);
7593 // Floating-point multiply-add with intermediate rounding.
7594 bool HasFMAD = (LegalOperations &&
7595 TLI.isOperationLegal(ISD::FMAD, VT));
7597 // Floating-point multiply-add without intermediate rounding.
7598 bool HasFMA = ((!LegalOperations ||
7599 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7600 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7603 // No valid opcode, do not combine.
7604 if (!HasFMAD && !HasFMA)
7607 // Always prefer FMAD to FMA for precision.
7608 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7609 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7610 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7612 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7613 if (N0.getOpcode() == ISD::FMUL &&
7614 (Aggressive || N0->hasOneUse())) {
7615 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7616 N0.getOperand(0), N0.getOperand(1),
7617 DAG.getNode(ISD::FNEG, SL, VT, N1));
7620 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7621 // Note: Commutes FSUB operands.
7622 if (N1.getOpcode() == ISD::FMUL &&
7623 (Aggressive || N1->hasOneUse()))
7624 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7625 DAG.getNode(ISD::FNEG, SL, VT,
7627 N1.getOperand(1), N0);
7629 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7630 if (N0.getOpcode() == ISD::FNEG &&
7631 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7632 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7633 SDValue N00 = N0.getOperand(0).getOperand(0);
7634 SDValue N01 = N0.getOperand(0).getOperand(1);
7635 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7636 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7637 DAG.getNode(ISD::FNEG, SL, VT, N1));
7640 // Look through FP_EXTEND nodes to do more combining.
7641 if (UnsafeFPMath && LookThroughFPExt) {
7642 // fold (fsub (fpext (fmul x, y)), z)
7643 // -> (fma (fpext x), (fpext y), (fneg z))
7644 if (N0.getOpcode() == ISD::FP_EXTEND) {
7645 SDValue N00 = N0.getOperand(0);
7646 if (N00.getOpcode() == ISD::FMUL)
7647 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7648 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7650 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7652 DAG.getNode(ISD::FNEG, SL, VT, N1));
7655 // fold (fsub x, (fpext (fmul y, z)))
7656 // -> (fma (fneg (fpext y)), (fpext z), x)
7657 // Note: Commutes FSUB operands.
7658 if (N1.getOpcode() == ISD::FP_EXTEND) {
7659 SDValue N10 = N1.getOperand(0);
7660 if (N10.getOpcode() == ISD::FMUL)
7661 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7662 DAG.getNode(ISD::FNEG, SL, VT,
7663 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7664 N10.getOperand(0))),
7665 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7670 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7671 // -> (fneg (fma (fpext x), (fpext y), z))
7672 // Note: This could be removed with appropriate canonicalization of the
7673 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7674 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7675 // from implementing the canonicalization in visitFSUB.
7676 if (N0.getOpcode() == ISD::FP_EXTEND) {
7677 SDValue N00 = N0.getOperand(0);
7678 if (N00.getOpcode() == ISD::FNEG) {
7679 SDValue N000 = N00.getOperand(0);
7680 if (N000.getOpcode() == ISD::FMUL) {
7681 return DAG.getNode(ISD::FNEG, SL, VT,
7682 DAG.getNode(PreferredFusedOpcode, SL, VT,
7683 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7684 N000.getOperand(0)),
7685 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7686 N000.getOperand(1)),
7692 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7693 // -> (fneg (fma (fpext x)), (fpext y), z)
7694 // Note: This could be removed with appropriate canonicalization of the
7695 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7696 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7697 // from implementing the canonicalization in visitFSUB.
7698 if (N0.getOpcode() == ISD::FNEG) {
7699 SDValue N00 = N0.getOperand(0);
7700 if (N00.getOpcode() == ISD::FP_EXTEND) {
7701 SDValue N000 = N00.getOperand(0);
7702 if (N000.getOpcode() == ISD::FMUL) {
7703 return DAG.getNode(ISD::FNEG, SL, VT,
7704 DAG.getNode(PreferredFusedOpcode, SL, VT,
7705 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7706 N000.getOperand(0)),
7707 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7708 N000.getOperand(1)),
7716 // More folding opportunities when target permits.
7717 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7718 // fold (fsub (fma x, y, (fmul u, v)), z)
7719 // -> (fma x, y (fma u, v, (fneg z)))
7720 if (N0.getOpcode() == PreferredFusedOpcode &&
7721 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7722 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723 N0.getOperand(0), N0.getOperand(1),
7724 DAG.getNode(PreferredFusedOpcode, SL, VT,
7725 N0.getOperand(2).getOperand(0),
7726 N0.getOperand(2).getOperand(1),
7727 DAG.getNode(ISD::FNEG, SL, VT,
7731 // fold (fsub x, (fma y, z, (fmul u, v)))
7732 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7733 if (N1.getOpcode() == PreferredFusedOpcode &&
7734 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7735 SDValue N20 = N1.getOperand(2).getOperand(0);
7736 SDValue N21 = N1.getOperand(2).getOperand(1);
7737 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7738 DAG.getNode(ISD::FNEG, SL, VT,
7741 DAG.getNode(PreferredFusedOpcode, SL, VT,
7742 DAG.getNode(ISD::FNEG, SL, VT, N20),
7747 if (UnsafeFPMath && LookThroughFPExt) {
7748 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7749 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7750 if (N0.getOpcode() == PreferredFusedOpcode) {
7751 SDValue N02 = N0.getOperand(2);
7752 if (N02.getOpcode() == ISD::FP_EXTEND) {
7753 SDValue N020 = N02.getOperand(0);
7754 if (N020.getOpcode() == ISD::FMUL)
7755 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7756 N0.getOperand(0), N0.getOperand(1),
7757 DAG.getNode(PreferredFusedOpcode, SL, VT,
7758 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7759 N020.getOperand(0)),
7760 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761 N020.getOperand(1)),
7762 DAG.getNode(ISD::FNEG, SL, VT,
7767 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7768 // -> (fma (fpext x), (fpext y),
7769 // (fma (fpext u), (fpext v), (fneg z)))
7770 // FIXME: This turns two single-precision and one double-precision
7771 // operation into two double-precision operations, which might not be
7772 // interesting for all targets, especially GPUs.
7773 if (N0.getOpcode() == ISD::FP_EXTEND) {
7774 SDValue N00 = N0.getOperand(0);
7775 if (N00.getOpcode() == PreferredFusedOpcode) {
7776 SDValue N002 = N00.getOperand(2);
7777 if (N002.getOpcode() == ISD::FMUL)
7778 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7779 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783 DAG.getNode(PreferredFusedOpcode, SL, VT,
7784 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7785 N002.getOperand(0)),
7786 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787 N002.getOperand(1)),
7788 DAG.getNode(ISD::FNEG, SL, VT,
7793 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7794 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7795 if (N1.getOpcode() == PreferredFusedOpcode &&
7796 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7797 SDValue N120 = N1.getOperand(2).getOperand(0);
7798 if (N120.getOpcode() == ISD::FMUL) {
7799 SDValue N1200 = N120.getOperand(0);
7800 SDValue N1201 = N120.getOperand(1);
7801 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7802 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7804 DAG.getNode(PreferredFusedOpcode, SL, VT,
7805 DAG.getNode(ISD::FNEG, SL, VT,
7806 DAG.getNode(ISD::FP_EXTEND, SL,
7808 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7814 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7815 // -> (fma (fneg (fpext y)), (fpext z),
7816 // (fma (fneg (fpext u)), (fpext v), x))
7817 // FIXME: This turns two single-precision and one double-precision
7818 // operation into two double-precision operations, which might not be
7819 // interesting for all targets, especially GPUs.
7820 if (N1.getOpcode() == ISD::FP_EXTEND &&
7821 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7822 SDValue N100 = N1.getOperand(0).getOperand(0);
7823 SDValue N101 = N1.getOperand(0).getOperand(1);
7824 SDValue N102 = N1.getOperand(0).getOperand(2);
7825 if (N102.getOpcode() == ISD::FMUL) {
7826 SDValue N1020 = N102.getOperand(0);
7827 SDValue N1021 = N102.getOperand(1);
7828 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7829 DAG.getNode(ISD::FNEG, SL, VT,
7830 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7833 DAG.getNode(PreferredFusedOpcode, SL, VT,
7834 DAG.getNode(ISD::FNEG, SL, VT,
7835 DAG.getNode(ISD::FP_EXTEND, SL,
7837 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7848 SDValue DAGCombiner::visitFADD(SDNode *N) {
7849 SDValue N0 = N->getOperand(0);
7850 SDValue N1 = N->getOperand(1);
7851 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7852 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7853 EVT VT = N->getValueType(0);
7855 const TargetOptions &Options = DAG.getTarget().Options;
7859 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7862 // fold (fadd c1, c2) -> c1 + c2
7864 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7866 // canonicalize constant to RHS
7867 if (N0CFP && !N1CFP)
7868 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7870 // fold (fadd A, (fneg B)) -> (fsub A, B)
7871 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7872 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7873 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7874 GetNegatedExpression(N1, DAG, LegalOperations));
7876 // fold (fadd (fneg A), B) -> (fsub B, A)
7877 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7878 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7879 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7880 GetNegatedExpression(N0, DAG, LegalOperations));
7882 // If 'unsafe math' is enabled, fold lots of things.
7883 if (Options.UnsafeFPMath) {
7884 // No FP constant should be created after legalization as Instruction
7885 // Selection pass has a hard time dealing with FP constants.
7886 bool AllowNewConst = (Level < AfterLegalizeDAG);
7888 // fold (fadd A, 0) -> A
7889 if (N1CFP && N1CFP->isZero())
7892 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7893 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7894 isa<ConstantFPSDNode>(N0.getOperand(1)))
7895 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7896 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7898 // If allowed, fold (fadd (fneg x), x) -> 0.0
7899 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7900 return DAG.getConstantFP(0.0, DL, VT);
7902 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7903 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7904 return DAG.getConstantFP(0.0, DL, VT);
7906 // We can fold chains of FADD's of the same value into multiplications.
7907 // This transform is not safe in general because we are reducing the number
7908 // of rounding steps.
7909 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7910 if (N0.getOpcode() == ISD::FMUL) {
7911 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7912 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7914 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7915 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7916 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7917 DAG.getConstantFP(1.0, DL, VT));
7918 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7921 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7922 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7923 N1.getOperand(0) == N1.getOperand(1) &&
7924 N0.getOperand(0) == N1.getOperand(0)) {
7925 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7926 DAG.getConstantFP(2.0, DL, VT));
7927 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7931 if (N1.getOpcode() == ISD::FMUL) {
7932 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7933 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7935 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7936 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7937 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7938 DAG.getConstantFP(1.0, DL, VT));
7939 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7942 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7943 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7944 N0.getOperand(0) == N0.getOperand(1) &&
7945 N1.getOperand(0) == N0.getOperand(0)) {
7946 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7947 DAG.getConstantFP(2.0, DL, VT));
7948 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7952 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7953 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7954 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7955 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7956 (N0.getOperand(0) == N1)) {
7957 return DAG.getNode(ISD::FMUL, DL, VT,
7958 N1, DAG.getConstantFP(3.0, DL, VT));
7962 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7963 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7964 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7965 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7966 N1.getOperand(0) == N0) {
7967 return DAG.getNode(ISD::FMUL, DL, VT,
7968 N0, DAG.getConstantFP(3.0, DL, VT));
7972 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7973 if (AllowNewConst &&
7974 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7975 N0.getOperand(0) == N0.getOperand(1) &&
7976 N1.getOperand(0) == N1.getOperand(1) &&
7977 N0.getOperand(0) == N1.getOperand(0)) {
7978 return DAG.getNode(ISD::FMUL, DL, VT,
7979 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7982 } // enable-unsafe-fp-math
7984 // FADD -> FMA combines:
7985 SDValue Fused = visitFADDForFMACombine(N);
7987 AddToWorklist(Fused.getNode());
7994 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7995 SDValue N0 = N->getOperand(0);
7996 SDValue N1 = N->getOperand(1);
7997 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7998 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7999 EVT VT = N->getValueType(0);
8001 const TargetOptions &Options = DAG.getTarget().Options;
8005 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8008 // fold (fsub c1, c2) -> c1-c2
8010 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8012 // fold (fsub A, (fneg B)) -> (fadd A, B)
8013 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8014 return DAG.getNode(ISD::FADD, dl, VT, N0,
8015 GetNegatedExpression(N1, DAG, LegalOperations));
8017 // If 'unsafe math' is enabled, fold lots of things.
8018 if (Options.UnsafeFPMath) {
8020 if (N1CFP && N1CFP->isZero())
8023 // (fsub 0, B) -> -B
8024 if (N0CFP && N0CFP->isZero()) {
8025 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8026 return GetNegatedExpression(N1, DAG, LegalOperations);
8027 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8028 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8031 // (fsub x, x) -> 0.0
8033 return DAG.getConstantFP(0.0f, dl, VT);
8035 // (fsub x, (fadd x, y)) -> (fneg y)
8036 // (fsub x, (fadd y, x)) -> (fneg y)
8037 if (N1.getOpcode() == ISD::FADD) {
8038 SDValue N10 = N1->getOperand(0);
8039 SDValue N11 = N1->getOperand(1);
8041 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8042 return GetNegatedExpression(N11, DAG, LegalOperations);
8044 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8045 return GetNegatedExpression(N10, DAG, LegalOperations);
8049 // FSUB -> FMA combines:
8050 SDValue Fused = visitFSUBForFMACombine(N);
8052 AddToWorklist(Fused.getNode());
8059 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8060 SDValue N0 = N->getOperand(0);
8061 SDValue N1 = N->getOperand(1);
8062 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8063 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8064 EVT VT = N->getValueType(0);
8066 const TargetOptions &Options = DAG.getTarget().Options;
8069 if (VT.isVector()) {
8070 // This just handles C1 * C2 for vectors. Other vector folds are below.
8071 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8075 // fold (fmul c1, c2) -> c1*c2
8077 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8079 // canonicalize constant to RHS
8080 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8081 !isConstantFPBuildVectorOrConstantFP(N1))
8082 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8084 // fold (fmul A, 1.0) -> A
8085 if (N1CFP && N1CFP->isExactlyValue(1.0))
8088 if (Options.UnsafeFPMath) {
8089 // fold (fmul A, 0) -> 0
8090 if (N1CFP && N1CFP->isZero())
8093 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8094 if (N0.getOpcode() == ISD::FMUL) {
8095 // Fold scalars or any vector constants (not just splats).
8096 // This fold is done in general by InstCombine, but extra fmul insts
8097 // may have been generated during lowering.
8098 SDValue N00 = N0.getOperand(0);
8099 SDValue N01 = N0.getOperand(1);
8100 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8101 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8102 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8104 // Check 1: Make sure that the first operand of the inner multiply is NOT
8105 // a constant. Otherwise, we may induce infinite looping.
8106 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8107 // Check 2: Make sure that the second operand of the inner multiply and
8108 // the second operand of the outer multiply are constants.
8109 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8110 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8111 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8112 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8117 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8118 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8119 // during an early run of DAGCombiner can prevent folding with fmuls
8120 // inserted during lowering.
8121 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8122 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8123 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8124 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8128 // fold (fmul X, 2.0) -> (fadd X, X)
8129 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8130 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8132 // fold (fmul X, -1.0) -> (fneg X)
8133 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8134 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8135 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8137 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8138 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8139 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8140 // Both can be negated for free, check to see if at least one is cheaper
8142 if (LHSNeg == 2 || RHSNeg == 2)
8143 return DAG.getNode(ISD::FMUL, DL, VT,
8144 GetNegatedExpression(N0, DAG, LegalOperations),
8145 GetNegatedExpression(N1, DAG, LegalOperations));
8152 SDValue DAGCombiner::visitFMA(SDNode *N) {
8153 SDValue N0 = N->getOperand(0);
8154 SDValue N1 = N->getOperand(1);
8155 SDValue N2 = N->getOperand(2);
8156 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8157 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8158 EVT VT = N->getValueType(0);
8160 const TargetOptions &Options = DAG.getTarget().Options;
8162 // Constant fold FMA.
8163 if (isa<ConstantFPSDNode>(N0) &&
8164 isa<ConstantFPSDNode>(N1) &&
8165 isa<ConstantFPSDNode>(N2)) {
8166 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8169 if (Options.UnsafeFPMath) {
8170 if (N0CFP && N0CFP->isZero())
8172 if (N1CFP && N1CFP->isZero())
8175 if (N0CFP && N0CFP->isExactlyValue(1.0))
8176 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8177 if (N1CFP && N1CFP->isExactlyValue(1.0))
8178 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8180 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8181 if (N0CFP && !N1CFP)
8182 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8184 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8185 if (Options.UnsafeFPMath && N1CFP &&
8186 N2.getOpcode() == ISD::FMUL &&
8187 N0 == N2.getOperand(0) &&
8188 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8189 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8190 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8194 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8195 if (Options.UnsafeFPMath &&
8196 N0.getOpcode() == ISD::FMUL && N1CFP &&
8197 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8198 return DAG.getNode(ISD::FMA, dl, VT,
8200 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8204 // (fma x, 1, y) -> (fadd x, y)
8205 // (fma x, -1, y) -> (fadd (fneg x), y)
8207 if (N1CFP->isExactlyValue(1.0))
8208 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8210 if (N1CFP->isExactlyValue(-1.0) &&
8211 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8212 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8213 AddToWorklist(RHSNeg.getNode());
8214 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8218 // (fma x, c, x) -> (fmul x, (c+1))
8219 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8220 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8221 DAG.getNode(ISD::FADD, dl, VT,
8222 N1, DAG.getConstantFP(1.0, dl, VT)));
8224 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8225 if (Options.UnsafeFPMath && N1CFP &&
8226 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8227 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8228 DAG.getNode(ISD::FADD, dl, VT,
8229 N1, DAG.getConstantFP(-1.0, dl, VT)));
8235 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8236 SDValue N0 = N->getOperand(0);
8237 SDValue N1 = N->getOperand(1);
8238 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8239 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8240 EVT VT = N->getValueType(0);
8242 const TargetOptions &Options = DAG.getTarget().Options;
8246 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8249 // fold (fdiv c1, c2) -> c1/c2
8251 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8253 if (Options.UnsafeFPMath) {
8254 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8256 // Compute the reciprocal 1.0 / c2.
8257 APFloat N1APF = N1CFP->getValueAPF();
8258 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8259 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8260 // Only do the transform if the reciprocal is a legal fp immediate that
8261 // isn't too nasty (eg NaN, denormal, ...).
8262 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8263 (!LegalOperations ||
8264 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8265 // backend)... we should handle this gracefully after Legalize.
8266 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8267 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8268 TLI.isFPImmLegal(Recip, VT)))
8269 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8270 DAG.getConstantFP(Recip, DL, VT));
8273 // If this FDIV is part of a reciprocal square root, it may be folded
8274 // into a target-specific square root estimate instruction.
8275 if (N1.getOpcode() == ISD::FSQRT) {
8276 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8277 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8279 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8280 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8281 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8282 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8283 AddToWorklist(RV.getNode());
8284 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8286 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8287 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8288 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8289 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8290 AddToWorklist(RV.getNode());
8291 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8293 } else if (N1.getOpcode() == ISD::FMUL) {
8294 // Look through an FMUL. Even though this won't remove the FDIV directly,
8295 // it's still worthwhile to get rid of the FSQRT if possible.
8298 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8299 SqrtOp = N1.getOperand(0);
8300 OtherOp = N1.getOperand(1);
8301 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8302 SqrtOp = N1.getOperand(1);
8303 OtherOp = N1.getOperand(0);
8305 if (SqrtOp.getNode()) {
8306 // We found a FSQRT, so try to make this fold:
8307 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8308 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8309 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8310 AddToWorklist(RV.getNode());
8311 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8316 // Fold into a reciprocal estimate and multiply instead of a real divide.
8317 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8318 AddToWorklist(RV.getNode());
8319 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8323 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8324 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8325 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8326 // Both can be negated for free, check to see if at least one is cheaper
8328 if (LHSNeg == 2 || RHSNeg == 2)
8329 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8330 GetNegatedExpression(N0, DAG, LegalOperations),
8331 GetNegatedExpression(N1, DAG, LegalOperations));
8335 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8337 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8338 // Notice that this is not always beneficial. One reason is different target
8339 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8340 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8341 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8342 if (Options.UnsafeFPMath) {
8343 // Skip if current node is a reciprocal.
8344 if (N0CFP && N0CFP->isExactlyValue(1.0))
8347 SmallVector<SDNode *, 4> Users;
8348 // Find all FDIV users of the same divisor.
8349 for (auto *U : N1->uses()) {
8350 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8354 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8355 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8356 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8358 // Dividend / Divisor -> Dividend * Reciprocal
8359 for (auto *U : Users) {
8360 SDValue Dividend = U->getOperand(0);
8361 if (Dividend != FPOne) {
8362 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8364 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8374 SDValue DAGCombiner::visitFREM(SDNode *N) {
8375 SDValue N0 = N->getOperand(0);
8376 SDValue N1 = N->getOperand(1);
8377 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8378 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8379 EVT VT = N->getValueType(0);
8381 // fold (frem c1, c2) -> fmod(c1,c2)
8383 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8388 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8389 if (DAG.getTarget().Options.UnsafeFPMath &&
8390 !TLI.isFsqrtCheap()) {
8391 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8392 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8393 EVT VT = RV.getValueType();
8395 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8396 AddToWorklist(RV.getNode());
8398 // Unfortunately, RV is now NaN if the input was exactly 0.
8399 // Select out this case and force the answer to 0.
8400 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8402 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8403 N->getOperand(0), Zero, ISD::SETEQ);
8404 AddToWorklist(ZeroCmp.getNode());
8405 AddToWorklist(RV.getNode());
8407 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8408 DL, VT, ZeroCmp, Zero, RV);
8415 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8416 SDValue N0 = N->getOperand(0);
8417 SDValue N1 = N->getOperand(1);
8418 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8419 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8420 EVT VT = N->getValueType(0);
8422 if (N0CFP && N1CFP) // Constant fold
8423 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8426 const APFloat& V = N1CFP->getValueAPF();
8427 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8428 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8429 if (!V.isNegative()) {
8430 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8431 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8433 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8434 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8435 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8439 // copysign(fabs(x), y) -> copysign(x, y)
8440 // copysign(fneg(x), y) -> copysign(x, y)
8441 // copysign(copysign(x,z), y) -> copysign(x, y)
8442 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8443 N0.getOpcode() == ISD::FCOPYSIGN)
8444 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8445 N0.getOperand(0), N1);
8447 // copysign(x, abs(y)) -> abs(x)
8448 if (N1.getOpcode() == ISD::FABS)
8449 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8451 // copysign(x, copysign(y,z)) -> copysign(x, z)
8452 if (N1.getOpcode() == ISD::FCOPYSIGN)
8453 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8454 N0, N1.getOperand(1));
8456 // copysign(x, fp_extend(y)) -> copysign(x, y)
8457 // copysign(x, fp_round(y)) -> copysign(x, y)
8458 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8459 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8460 N0, N1.getOperand(0));
8465 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8466 SDValue N0 = N->getOperand(0);
8467 EVT VT = N->getValueType(0);
8468 EVT OpVT = N0.getValueType();
8470 // fold (sint_to_fp c1) -> c1fp
8471 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8472 // ...but only if the target supports immediate floating-point values
8473 (!LegalOperations ||
8474 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8475 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8477 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8478 // but UINT_TO_FP is legal on this target, try to convert.
8479 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8480 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8481 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8482 if (DAG.SignBitIsZero(N0))
8483 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8486 // The next optimizations are desirable only if SELECT_CC can be lowered.
8487 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8488 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8489 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8491 (!LegalOperations ||
8492 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8495 { N0.getOperand(0), N0.getOperand(1),
8496 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8498 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8501 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8502 // (select_cc x, y, 1.0, 0.0,, cc)
8503 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8504 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8505 (!LegalOperations ||
8506 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8509 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8510 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8511 N0.getOperand(0).getOperand(2) };
8512 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8519 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8520 SDValue N0 = N->getOperand(0);
8521 EVT VT = N->getValueType(0);
8522 EVT OpVT = N0.getValueType();
8524 // fold (uint_to_fp c1) -> c1fp
8525 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8526 // ...but only if the target supports immediate floating-point values
8527 (!LegalOperations ||
8528 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8529 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8531 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8532 // but SINT_TO_FP is legal on this target, try to convert.
8533 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8534 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8535 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8536 if (DAG.SignBitIsZero(N0))
8537 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8540 // The next optimizations are desirable only if SELECT_CC can be lowered.
8541 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8542 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8544 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8545 (!LegalOperations ||
8546 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8549 { N0.getOperand(0), N0.getOperand(1),
8550 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8552 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8559 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8560 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8561 SDValue N0 = N->getOperand(0);
8562 EVT VT = N->getValueType(0);
8564 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8567 SDValue Src = N0.getOperand(0);
8568 EVT SrcVT = Src.getValueType();
8569 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8570 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8572 // We can safely assume the conversion won't overflow the output range,
8573 // because (for example) (uint8_t)18293.f is undefined behavior.
8575 // Since we can assume the conversion won't overflow, our decision as to
8576 // whether the input will fit in the float should depend on the minimum
8577 // of the input range and output range.
8579 // This means this is also safe for a signed input and unsigned output, since
8580 // a negative input would lead to undefined behavior.
8581 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8582 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8583 unsigned ActualSize = std::min(InputSize, OutputSize);
8584 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8586 // We can only fold away the float conversion if the input range can be
8587 // represented exactly in the float range.
8588 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8589 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8590 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8592 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8594 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8595 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8598 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8603 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8604 SDValue N0 = N->getOperand(0);
8605 EVT VT = N->getValueType(0);
8607 // fold (fp_to_sint c1fp) -> c1
8608 if (isConstantFPBuildVectorOrConstantFP(N0))
8609 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8611 return FoldIntToFPToInt(N, DAG);
8614 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8615 SDValue N0 = N->getOperand(0);
8616 EVT VT = N->getValueType(0);
8618 // fold (fp_to_uint c1fp) -> c1
8619 if (isConstantFPBuildVectorOrConstantFP(N0))
8620 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8622 return FoldIntToFPToInt(N, DAG);
8625 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8626 SDValue N0 = N->getOperand(0);
8627 SDValue N1 = N->getOperand(1);
8628 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8629 EVT VT = N->getValueType(0);
8631 // fold (fp_round c1fp) -> c1fp
8633 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8635 // fold (fp_round (fp_extend x)) -> x
8636 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8637 return N0.getOperand(0);
8639 // fold (fp_round (fp_round x)) -> (fp_round x)
8640 if (N0.getOpcode() == ISD::FP_ROUND) {
8641 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8642 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8643 // If the first fp_round isn't a value preserving truncation, it might
8644 // introduce a tie in the second fp_round, that wouldn't occur in the
8645 // single-step fp_round we want to fold to.
8646 // In other words, double rounding isn't the same as rounding.
8647 // Also, this is a value preserving truncation iff both fp_round's are.
8648 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8650 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8651 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8655 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8656 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8657 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8658 N0.getOperand(0), N1);
8659 AddToWorklist(Tmp.getNode());
8660 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8661 Tmp, N0.getOperand(1));
8667 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8668 SDValue N0 = N->getOperand(0);
8669 EVT VT = N->getValueType(0);
8670 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8671 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8673 // fold (fp_round_inreg c1fp) -> c1fp
8674 if (N0CFP && isTypeLegal(EVT)) {
8676 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8677 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8683 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8684 SDValue N0 = N->getOperand(0);
8685 EVT VT = N->getValueType(0);
8687 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8688 if (N->hasOneUse() &&
8689 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8692 // fold (fp_extend c1fp) -> c1fp
8693 if (isConstantFPBuildVectorOrConstantFP(N0))
8694 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8696 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8697 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8698 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8699 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8701 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8703 if (N0.getOpcode() == ISD::FP_ROUND
8704 && N0.getNode()->getConstantOperandVal(1) == 1) {
8705 SDValue In = N0.getOperand(0);
8706 if (In.getValueType() == VT) return In;
8707 if (VT.bitsLT(In.getValueType()))
8708 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8709 In, N0.getOperand(1));
8710 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8713 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8714 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8715 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8716 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8717 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8719 LN0->getBasePtr(), N0.getValueType(),
8720 LN0->getMemOperand());
8721 CombineTo(N, ExtLoad);
8722 CombineTo(N0.getNode(),
8723 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8724 N0.getValueType(), ExtLoad,
8725 DAG.getIntPtrConstant(1, SDLoc(N0))),
8726 ExtLoad.getValue(1));
8727 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8733 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8734 SDValue N0 = N->getOperand(0);
8735 EVT VT = N->getValueType(0);
8737 // fold (fceil c1) -> fceil(c1)
8738 if (isConstantFPBuildVectorOrConstantFP(N0))
8739 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8744 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8745 SDValue N0 = N->getOperand(0);
8746 EVT VT = N->getValueType(0);
8748 // fold (ftrunc c1) -> ftrunc(c1)
8749 if (isConstantFPBuildVectorOrConstantFP(N0))
8750 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8755 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8756 SDValue N0 = N->getOperand(0);
8757 EVT VT = N->getValueType(0);
8759 // fold (ffloor c1) -> ffloor(c1)
8760 if (isConstantFPBuildVectorOrConstantFP(N0))
8761 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8766 // FIXME: FNEG and FABS have a lot in common; refactor.
8767 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8768 SDValue N0 = N->getOperand(0);
8769 EVT VT = N->getValueType(0);
8771 // Constant fold FNEG.
8772 if (isConstantFPBuildVectorOrConstantFP(N0))
8773 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8775 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8776 &DAG.getTarget().Options))
8777 return GetNegatedExpression(N0, DAG, LegalOperations);
8779 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8780 // constant pool values.
8781 if (!TLI.isFNegFree(VT) &&
8782 N0.getOpcode() == ISD::BITCAST &&
8783 N0.getNode()->hasOneUse()) {
8784 SDValue Int = N0.getOperand(0);
8785 EVT IntVT = Int.getValueType();
8786 if (IntVT.isInteger() && !IntVT.isVector()) {
8788 if (N0.getValueType().isVector()) {
8789 // For a vector, get a mask such as 0x80... per scalar element
8791 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8792 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8794 // For a scalar, just generate 0x80...
8795 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8798 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8799 DAG.getConstant(SignMask, DL0, IntVT));
8800 AddToWorklist(Int.getNode());
8801 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8805 // (fneg (fmul c, x)) -> (fmul -c, x)
8806 if (N0.getOpcode() == ISD::FMUL &&
8807 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8808 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8810 APFloat CVal = CFP1->getValueAPF();
8812 if (Level >= AfterLegalizeDAG &&
8813 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8814 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8816 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8817 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8824 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8825 SDValue N0 = N->getOperand(0);
8826 SDValue N1 = N->getOperand(1);
8827 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8828 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8830 if (N0CFP && N1CFP) {
8831 const APFloat &C0 = N0CFP->getValueAPF();
8832 const APFloat &C1 = N1CFP->getValueAPF();
8833 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8837 EVT VT = N->getValueType(0);
8838 // Canonicalize to constant on RHS.
8839 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8845 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8846 SDValue N0 = N->getOperand(0);
8847 SDValue N1 = N->getOperand(1);
8848 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8849 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8851 if (N0CFP && N1CFP) {
8852 const APFloat &C0 = N0CFP->getValueAPF();
8853 const APFloat &C1 = N1CFP->getValueAPF();
8854 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8858 EVT VT = N->getValueType(0);
8859 // Canonicalize to constant on RHS.
8860 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8866 SDValue DAGCombiner::visitFABS(SDNode *N) {
8867 SDValue N0 = N->getOperand(0);
8868 EVT VT = N->getValueType(0);
8870 // fold (fabs c1) -> fabs(c1)
8871 if (isConstantFPBuildVectorOrConstantFP(N0))
8872 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8874 // fold (fabs (fabs x)) -> (fabs x)
8875 if (N0.getOpcode() == ISD::FABS)
8876 return N->getOperand(0);
8878 // fold (fabs (fneg x)) -> (fabs x)
8879 // fold (fabs (fcopysign x, y)) -> (fabs x)
8880 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8881 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8883 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8884 // constant pool values.
8885 if (!TLI.isFAbsFree(VT) &&
8886 N0.getOpcode() == ISD::BITCAST &&
8887 N0.getNode()->hasOneUse()) {
8888 SDValue Int = N0.getOperand(0);
8889 EVT IntVT = Int.getValueType();
8890 if (IntVT.isInteger() && !IntVT.isVector()) {
8892 if (N0.getValueType().isVector()) {
8893 // For a vector, get a mask such as 0x7f... per scalar element
8895 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8896 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8898 // For a scalar, just generate 0x7f...
8899 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8902 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8903 DAG.getConstant(SignMask, DL, IntVT));
8904 AddToWorklist(Int.getNode());
8905 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8912 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8913 SDValue Chain = N->getOperand(0);
8914 SDValue N1 = N->getOperand(1);
8915 SDValue N2 = N->getOperand(2);
8917 // If N is a constant we could fold this into a fallthrough or unconditional
8918 // branch. However that doesn't happen very often in normal code, because
8919 // Instcombine/SimplifyCFG should have handled the available opportunities.
8920 // If we did this folding here, it would be necessary to update the
8921 // MachineBasicBlock CFG, which is awkward.
8923 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8925 if (N1.getOpcode() == ISD::SETCC &&
8926 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8927 N1.getOperand(0).getValueType())) {
8928 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8929 Chain, N1.getOperand(2),
8930 N1.getOperand(0), N1.getOperand(1), N2);
8933 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8934 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8935 (N1.getOperand(0).hasOneUse() &&
8936 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8937 SDNode *Trunc = nullptr;
8938 if (N1.getOpcode() == ISD::TRUNCATE) {
8939 // Look pass the truncate.
8940 Trunc = N1.getNode();
8941 N1 = N1.getOperand(0);
8944 // Match this pattern so that we can generate simpler code:
8947 // %b = and i32 %a, 2
8948 // %c = srl i32 %b, 1
8949 // brcond i32 %c ...
8954 // %b = and i32 %a, 2
8955 // %c = setcc eq %b, 0
8958 // This applies only when the AND constant value has one bit set and the
8959 // SRL constant is equal to the log2 of the AND constant. The back-end is
8960 // smart enough to convert the result into a TEST/JMP sequence.
8961 SDValue Op0 = N1.getOperand(0);
8962 SDValue Op1 = N1.getOperand(1);
8964 if (Op0.getOpcode() == ISD::AND &&
8965 Op1.getOpcode() == ISD::Constant) {
8966 SDValue AndOp1 = Op0.getOperand(1);
8968 if (AndOp1.getOpcode() == ISD::Constant) {
8969 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8971 if (AndConst.isPowerOf2() &&
8972 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8976 getSetCCResultType(Op0.getValueType()),
8977 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8980 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8981 MVT::Other, Chain, SetCC, N2);
8982 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8983 // will convert it back to (X & C1) >> C2.
8984 CombineTo(N, NewBRCond, false);
8985 // Truncate is dead.
8987 deleteAndRecombine(Trunc);
8988 // Replace the uses of SRL with SETCC
8989 WorklistRemover DeadNodes(*this);
8990 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8991 deleteAndRecombine(N1.getNode());
8992 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8998 // Restore N1 if the above transformation doesn't match.
8999 N1 = N->getOperand(1);
9002 // Transform br(xor(x, y)) -> br(x != y)
9003 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9004 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9005 SDNode *TheXor = N1.getNode();
9006 SDValue Op0 = TheXor->getOperand(0);
9007 SDValue Op1 = TheXor->getOperand(1);
9008 if (Op0.getOpcode() == Op1.getOpcode()) {
9009 // Avoid missing important xor optimizations.
9010 SDValue Tmp = visitXOR(TheXor);
9011 if (Tmp.getNode()) {
9012 if (Tmp.getNode() != TheXor) {
9013 DEBUG(dbgs() << "\nReplacing.8 ";
9015 dbgs() << "\nWith: ";
9016 Tmp.getNode()->dump(&DAG);
9018 WorklistRemover DeadNodes(*this);
9019 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9020 deleteAndRecombine(TheXor);
9021 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9022 MVT::Other, Chain, Tmp, N2);
9025 // visitXOR has changed XOR's operands or replaced the XOR completely,
9027 return SDValue(N, 0);
9031 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9033 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9034 Op0.getOpcode() == ISD::XOR) {
9035 TheXor = Op0.getNode();
9039 EVT SetCCVT = N1.getValueType();
9041 SetCCVT = getSetCCResultType(SetCCVT);
9042 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9045 Equal ? ISD::SETEQ : ISD::SETNE);
9046 // Replace the uses of XOR with SETCC
9047 WorklistRemover DeadNodes(*this);
9048 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9049 deleteAndRecombine(N1.getNode());
9050 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9051 MVT::Other, Chain, SetCC, N2);
9058 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9060 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9061 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9062 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9064 // If N is a constant we could fold this into a fallthrough or unconditional
9065 // branch. However that doesn't happen very often in normal code, because
9066 // Instcombine/SimplifyCFG should have handled the available opportunities.
9067 // If we did this folding here, it would be necessary to update the
9068 // MachineBasicBlock CFG, which is awkward.
9070 // Use SimplifySetCC to simplify SETCC's.
9071 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9072 CondLHS, CondRHS, CC->get(), SDLoc(N),
9074 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9076 // fold to a simpler setcc
9077 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9078 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9079 N->getOperand(0), Simp.getOperand(2),
9080 Simp.getOperand(0), Simp.getOperand(1),
9086 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9087 /// and that N may be folded in the load / store addressing mode.
9088 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9090 const TargetLowering &TLI) {
9094 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9095 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9097 VT = LD->getMemoryVT();
9098 AS = LD->getAddressSpace();
9099 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9100 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9102 VT = ST->getMemoryVT();
9103 AS = ST->getAddressSpace();
9107 TargetLowering::AddrMode AM;
9108 if (N->getOpcode() == ISD::ADD) {
9109 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9112 AM.BaseOffs = Offset->getSExtValue();
9116 } else if (N->getOpcode() == ISD::SUB) {
9117 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9120 AM.BaseOffs = -Offset->getSExtValue();
9127 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9130 /// Try turning a load/store into a pre-indexed load/store when the base
9131 /// pointer is an add or subtract and it has other uses besides the load/store.
9132 /// After the transformation, the new indexed load/store has effectively folded
9133 /// the add/subtract in and all of its other uses are redirected to the
9135 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9136 if (Level < AfterLegalizeDAG)
9142 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9143 if (LD->isIndexed())
9145 VT = LD->getMemoryVT();
9146 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9147 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9149 Ptr = LD->getBasePtr();
9150 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9151 if (ST->isIndexed())
9153 VT = ST->getMemoryVT();
9154 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9155 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9157 Ptr = ST->getBasePtr();
9163 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9164 // out. There is no reason to make this a preinc/predec.
9165 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9166 Ptr.getNode()->hasOneUse())
9169 // Ask the target to do addressing mode selection.
9172 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9173 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9176 // Backends without true r+i pre-indexed forms may need to pass a
9177 // constant base with a variable offset so that constant coercion
9178 // will work with the patterns in canonical form.
9179 bool Swapped = false;
9180 if (isa<ConstantSDNode>(BasePtr)) {
9181 std::swap(BasePtr, Offset);
9185 // Don't create a indexed load / store with zero offset.
9186 if (isNullConstant(Offset))
9189 // Try turning it into a pre-indexed load / store except when:
9190 // 1) The new base ptr is a frame index.
9191 // 2) If N is a store and the new base ptr is either the same as or is a
9192 // predecessor of the value being stored.
9193 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9194 // that would create a cycle.
9195 // 4) All uses are load / store ops that use it as old base ptr.
9197 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9198 // (plus the implicit offset) to a register to preinc anyway.
9199 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9204 SDValue Val = cast<StoreSDNode>(N)->getValue();
9205 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9209 // If the offset is a constant, there may be other adds of constants that
9210 // can be folded with this one. We should do this to avoid having to keep
9211 // a copy of the original base pointer.
9212 SmallVector<SDNode *, 16> OtherUses;
9213 if (isa<ConstantSDNode>(Offset))
9214 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9215 UE = BasePtr.getNode()->use_end();
9217 SDUse &Use = UI.getUse();
9218 // Skip the use that is Ptr and uses of other results from BasePtr's
9219 // node (important for nodes that return multiple results).
9220 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9223 if (Use.getUser()->isPredecessorOf(N))
9226 if (Use.getUser()->getOpcode() != ISD::ADD &&
9227 Use.getUser()->getOpcode() != ISD::SUB) {
9232 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9233 if (!isa<ConstantSDNode>(Op1)) {
9238 // FIXME: In some cases, we can be smarter about this.
9239 if (Op1.getValueType() != Offset.getValueType()) {
9244 OtherUses.push_back(Use.getUser());
9248 std::swap(BasePtr, Offset);
9250 // Now check for #3 and #4.
9251 bool RealUse = false;
9253 // Caches for hasPredecessorHelper
9254 SmallPtrSet<const SDNode *, 32> Visited;
9255 SmallVector<const SDNode *, 16> Worklist;
9257 for (SDNode *Use : Ptr.getNode()->uses()) {
9260 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9263 // If Ptr may be folded in addressing mode of other use, then it's
9264 // not profitable to do this transformation.
9265 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9274 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9275 BasePtr, Offset, AM);
9277 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9278 BasePtr, Offset, AM);
9281 DEBUG(dbgs() << "\nReplacing.4 ";
9283 dbgs() << "\nWith: ";
9284 Result.getNode()->dump(&DAG);
9286 WorklistRemover DeadNodes(*this);
9288 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9289 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9291 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9294 // Finally, since the node is now dead, remove it from the graph.
9295 deleteAndRecombine(N);
9298 std::swap(BasePtr, Offset);
9300 // Replace other uses of BasePtr that can be updated to use Ptr
9301 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9302 unsigned OffsetIdx = 1;
9303 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9305 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9306 BasePtr.getNode() && "Expected BasePtr operand");
9308 // We need to replace ptr0 in the following expression:
9309 // x0 * offset0 + y0 * ptr0 = t0
9311 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9313 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9314 // indexed load/store and the expresion that needs to be re-written.
9316 // Therefore, we have:
9317 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9319 ConstantSDNode *CN =
9320 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9322 APInt Offset0 = CN->getAPIntValue();
9323 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9325 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9326 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9327 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9328 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9330 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9332 APInt CNV = Offset0;
9333 if (X0 < 0) CNV = -CNV;
9334 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9335 else CNV = CNV - Offset1;
9337 SDLoc DL(OtherUses[i]);
9339 // We can now generate the new expression.
9340 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9341 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9343 SDValue NewUse = DAG.getNode(Opcode,
9345 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9346 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9347 deleteAndRecombine(OtherUses[i]);
9350 // Replace the uses of Ptr with uses of the updated base value.
9351 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9352 deleteAndRecombine(Ptr.getNode());
9357 /// Try to combine a load/store with a add/sub of the base pointer node into a
9358 /// post-indexed load/store. The transformation folded the add/subtract into the
9359 /// new indexed load/store effectively and all of its uses are redirected to the
9361 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9362 if (Level < AfterLegalizeDAG)
9368 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9369 if (LD->isIndexed())
9371 VT = LD->getMemoryVT();
9372 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9373 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9375 Ptr = LD->getBasePtr();
9376 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9377 if (ST->isIndexed())
9379 VT = ST->getMemoryVT();
9380 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9381 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9383 Ptr = ST->getBasePtr();
9389 if (Ptr.getNode()->hasOneUse())
9392 for (SDNode *Op : Ptr.getNode()->uses()) {
9394 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9399 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9400 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9401 // Don't create a indexed load / store with zero offset.
9402 if (isNullConstant(Offset))
9405 // Try turning it into a post-indexed load / store except when
9406 // 1) All uses are load / store ops that use it as base ptr (and
9407 // it may be folded as addressing mmode).
9408 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9409 // nor a successor of N. Otherwise, if Op is folded that would
9412 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9416 bool TryNext = false;
9417 for (SDNode *Use : BasePtr.getNode()->uses()) {
9418 if (Use == Ptr.getNode())
9421 // If all the uses are load / store addresses, then don't do the
9423 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9424 bool RealUse = false;
9425 for (SDNode *UseUse : Use->uses()) {
9426 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9441 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9442 SDValue Result = isLoad
9443 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9444 BasePtr, Offset, AM)
9445 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9446 BasePtr, Offset, AM);
9449 DEBUG(dbgs() << "\nReplacing.5 ";
9451 dbgs() << "\nWith: ";
9452 Result.getNode()->dump(&DAG);
9454 WorklistRemover DeadNodes(*this);
9456 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9457 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9462 // Finally, since the node is now dead, remove it from the graph.
9463 deleteAndRecombine(N);
9465 // Replace the uses of Use with uses of the updated base value.
9466 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9467 Result.getValue(isLoad ? 1 : 0));
9468 deleteAndRecombine(Op);
9477 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9478 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9479 ISD::MemIndexedMode AM = LD->getAddressingMode();
9480 assert(AM != ISD::UNINDEXED);
9481 SDValue BP = LD->getOperand(1);
9482 SDValue Inc = LD->getOperand(2);
9484 // Some backends use TargetConstants for load offsets, but don't expect
9485 // TargetConstants in general ADD nodes. We can convert these constants into
9486 // regular Constants (if the constant is not opaque).
9487 assert((Inc.getOpcode() != ISD::TargetConstant ||
9488 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9489 "Cannot split out indexing using opaque target constants");
9490 if (Inc.getOpcode() == ISD::TargetConstant) {
9491 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9492 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9493 ConstInc->getValueType(0));
9497 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9498 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9501 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9502 LoadSDNode *LD = cast<LoadSDNode>(N);
9503 SDValue Chain = LD->getChain();
9504 SDValue Ptr = LD->getBasePtr();
9506 // If load is not volatile and there are no uses of the loaded value (and
9507 // the updated indexed value in case of indexed loads), change uses of the
9508 // chain value into uses of the chain input (i.e. delete the dead load).
9509 if (!LD->isVolatile()) {
9510 if (N->getValueType(1) == MVT::Other) {
9512 if (!N->hasAnyUseOfValue(0)) {
9513 // It's not safe to use the two value CombineTo variant here. e.g.
9514 // v1, chain2 = load chain1, loc
9515 // v2, chain3 = load chain2, loc
9517 // Now we replace use of chain2 with chain1. This makes the second load
9518 // isomorphic to the one we are deleting, and thus makes this load live.
9519 DEBUG(dbgs() << "\nReplacing.6 ";
9521 dbgs() << "\nWith chain: ";
9522 Chain.getNode()->dump(&DAG);
9524 WorklistRemover DeadNodes(*this);
9525 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9528 deleteAndRecombine(N);
9530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9534 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9536 // If this load has an opaque TargetConstant offset, then we cannot split
9537 // the indexing into an add/sub directly (that TargetConstant may not be
9538 // valid for a different type of node, and we cannot convert an opaque
9539 // target constant into a regular constant).
9540 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9541 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9543 if (!N->hasAnyUseOfValue(0) &&
9544 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9545 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9547 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9548 Index = SplitIndexingFromLoad(LD);
9549 // Try to fold the base pointer arithmetic into subsequent loads and
9551 AddUsersToWorklist(N);
9553 Index = DAG.getUNDEF(N->getValueType(1));
9554 DEBUG(dbgs() << "\nReplacing.7 ";
9556 dbgs() << "\nWith: ";
9557 Undef.getNode()->dump(&DAG);
9558 dbgs() << " and 2 other values\n");
9559 WorklistRemover DeadNodes(*this);
9560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9562 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9563 deleteAndRecombine(N);
9564 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9569 // If this load is directly stored, replace the load value with the stored
9571 // TODO: Handle store large -> read small portion.
9572 // TODO: Handle TRUNCSTORE/LOADEXT
9573 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9574 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9575 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9576 if (PrevST->getBasePtr() == Ptr &&
9577 PrevST->getValue().getValueType() == N->getValueType(0))
9578 return CombineTo(N, Chain.getOperand(1), Chain);
9582 // Try to infer better alignment information than the load already has.
9583 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9584 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9585 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9587 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9588 LD->getValueType(0),
9589 Chain, Ptr, LD->getPointerInfo(),
9591 LD->isVolatile(), LD->isNonTemporal(),
9592 LD->isInvariant(), Align, LD->getAAInfo());
9593 if (NewLoad.getNode() != N)
9594 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9599 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9600 : DAG.getSubtarget().useAA();
9602 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9603 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9606 if (UseAA && LD->isUnindexed()) {
9607 // Walk up chain skipping non-aliasing memory nodes.
9608 SDValue BetterChain = FindBetterChain(N, Chain);
9610 // If there is a better chain.
9611 if (Chain != BetterChain) {
9614 // Replace the chain to void dependency.
9615 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9616 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9617 BetterChain, Ptr, LD->getMemOperand());
9619 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9620 LD->getValueType(0),
9621 BetterChain, Ptr, LD->getMemoryVT(),
9622 LD->getMemOperand());
9625 // Create token factor to keep old chain connected.
9626 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9627 MVT::Other, Chain, ReplLoad.getValue(1));
9629 // Make sure the new and old chains are cleaned up.
9630 AddToWorklist(Token.getNode());
9632 // Replace uses with load result and token factor. Don't add users
9634 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9638 // Try transforming N to an indexed load.
9639 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9640 return SDValue(N, 0);
9642 // Try to slice up N to more direct loads if the slices are mapped to
9643 // different register banks or pairing can take place.
9645 return SDValue(N, 0);
9651 /// \brief Helper structure used to slice a load in smaller loads.
9652 /// Basically a slice is obtained from the following sequence:
9653 /// Origin = load Ty1, Base
9654 /// Shift = srl Ty1 Origin, CstTy Amount
9655 /// Inst = trunc Shift to Ty2
9657 /// Then, it will be rewriten into:
9658 /// Slice = load SliceTy, Base + SliceOffset
9659 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9661 /// SliceTy is deduced from the number of bits that are actually used to
9663 struct LoadedSlice {
9664 /// \brief Helper structure used to compute the cost of a slice.
9666 /// Are we optimizing for code size.
9671 unsigned CrossRegisterBanksCopies;
9675 Cost(bool ForCodeSize = false)
9676 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9677 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9679 /// \brief Get the cost of one isolated slice.
9680 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9681 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9682 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9683 EVT TruncType = LS.Inst->getValueType(0);
9684 EVT LoadedType = LS.getLoadedType();
9685 if (TruncType != LoadedType &&
9686 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9690 /// \brief Account for slicing gain in the current cost.
9691 /// Slicing provide a few gains like removing a shift or a
9692 /// truncate. This method allows to grow the cost of the original
9693 /// load with the gain from this slice.
9694 void addSliceGain(const LoadedSlice &LS) {
9695 // Each slice saves a truncate.
9696 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9697 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9698 LS.Inst->getOperand(0).getValueType()))
9700 // If there is a shift amount, this slice gets rid of it.
9703 // If this slice can merge a cross register bank copy, account for it.
9704 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9705 ++CrossRegisterBanksCopies;
9708 Cost &operator+=(const Cost &RHS) {
9710 Truncates += RHS.Truncates;
9711 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9717 bool operator==(const Cost &RHS) const {
9718 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9719 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9720 ZExts == RHS.ZExts && Shift == RHS.Shift;
9723 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9725 bool operator<(const Cost &RHS) const {
9726 // Assume cross register banks copies are as expensive as loads.
9727 // FIXME: Do we want some more target hooks?
9728 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9729 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9730 // Unless we are optimizing for code size, consider the
9731 // expensive operation first.
9732 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9733 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9734 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9735 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9738 bool operator>(const Cost &RHS) const { return RHS < *this; }
9740 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9742 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9744 // The last instruction that represent the slice. This should be a
9745 // truncate instruction.
9747 // The original load instruction.
9749 // The right shift amount in bits from the original load.
9751 // The DAG from which Origin came from.
9752 // This is used to get some contextual information about legal types, etc.
9755 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9756 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9757 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9759 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9760 /// \return Result is \p BitWidth and has used bits set to 1 and
9761 /// not used bits set to 0.
9762 APInt getUsedBits() const {
9763 // Reproduce the trunc(lshr) sequence:
9764 // - Start from the truncated value.
9765 // - Zero extend to the desired bit width.
9767 assert(Origin && "No original load to compare against.");
9768 unsigned BitWidth = Origin->getValueSizeInBits(0);
9769 assert(Inst && "This slice is not bound to an instruction");
9770 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9771 "Extracted slice is bigger than the whole type!");
9772 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9773 UsedBits.setAllBits();
9774 UsedBits = UsedBits.zext(BitWidth);
9779 /// \brief Get the size of the slice to be loaded in bytes.
9780 unsigned getLoadedSize() const {
9781 unsigned SliceSize = getUsedBits().countPopulation();
9782 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9783 return SliceSize / 8;
9786 /// \brief Get the type that will be loaded for this slice.
9787 /// Note: This may not be the final type for the slice.
9788 EVT getLoadedType() const {
9789 assert(DAG && "Missing context");
9790 LLVMContext &Ctxt = *DAG->getContext();
9791 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9794 /// \brief Get the alignment of the load used for this slice.
9795 unsigned getAlignment() const {
9796 unsigned Alignment = Origin->getAlignment();
9797 unsigned Offset = getOffsetFromBase();
9799 Alignment = MinAlign(Alignment, Alignment + Offset);
9803 /// \brief Check if this slice can be rewritten with legal operations.
9804 bool isLegal() const {
9805 // An invalid slice is not legal.
9806 if (!Origin || !Inst || !DAG)
9809 // Offsets are for indexed load only, we do not handle that.
9810 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9813 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9815 // Check that the type is legal.
9816 EVT SliceType = getLoadedType();
9817 if (!TLI.isTypeLegal(SliceType))
9820 // Check that the load is legal for this type.
9821 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9824 // Check that the offset can be computed.
9825 // 1. Check its type.
9826 EVT PtrType = Origin->getBasePtr().getValueType();
9827 if (PtrType == MVT::Untyped || PtrType.isExtended())
9830 // 2. Check that it fits in the immediate.
9831 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9834 // 3. Check that the computation is legal.
9835 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9838 // Check that the zext is legal if it needs one.
9839 EVT TruncateType = Inst->getValueType(0);
9840 if (TruncateType != SliceType &&
9841 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9847 /// \brief Get the offset in bytes of this slice in the original chunk of
9849 /// \pre DAG != nullptr.
9850 uint64_t getOffsetFromBase() const {
9851 assert(DAG && "Missing context.");
9853 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9854 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9855 uint64_t Offset = Shift / 8;
9856 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9857 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9858 "The size of the original loaded type is not a multiple of a"
9860 // If Offset is bigger than TySizeInBytes, it means we are loading all
9861 // zeros. This should have been optimized before in the process.
9862 assert(TySizeInBytes > Offset &&
9863 "Invalid shift amount for given loaded size");
9865 Offset = TySizeInBytes - Offset - getLoadedSize();
9869 /// \brief Generate the sequence of instructions to load the slice
9870 /// represented by this object and redirect the uses of this slice to
9871 /// this new sequence of instructions.
9872 /// \pre this->Inst && this->Origin are valid Instructions and this
9873 /// object passed the legal check: LoadedSlice::isLegal returned true.
9874 /// \return The last instruction of the sequence used to load the slice.
9875 SDValue loadSlice() const {
9876 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9877 const SDValue &OldBaseAddr = Origin->getBasePtr();
9878 SDValue BaseAddr = OldBaseAddr;
9879 // Get the offset in that chunk of bytes w.r.t. the endianess.
9880 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9881 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9883 // BaseAddr = BaseAddr + Offset.
9884 EVT ArithType = BaseAddr.getValueType();
9886 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9887 DAG->getConstant(Offset, DL, ArithType));
9890 // Create the type of the loaded slice according to its size.
9891 EVT SliceType = getLoadedType();
9893 // Create the load for the slice.
9894 SDValue LastInst = DAG->getLoad(
9895 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9896 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9897 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9898 // If the final type is not the same as the loaded type, this means that
9899 // we have to pad with zero. Create a zero extend for that.
9900 EVT FinalType = Inst->getValueType(0);
9901 if (SliceType != FinalType)
9903 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9907 /// \brief Check if this slice can be merged with an expensive cross register
9908 /// bank copy. E.g.,
9910 /// f = bitcast i32 i to float
9911 bool canMergeExpensiveCrossRegisterBankCopy() const {
9912 if (!Inst || !Inst->hasOneUse())
9914 SDNode *Use = *Inst->use_begin();
9915 if (Use->getOpcode() != ISD::BITCAST)
9917 assert(DAG && "Missing context");
9918 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9919 EVT ResVT = Use->getValueType(0);
9920 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9921 const TargetRegisterClass *ArgRC =
9922 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9923 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9926 // At this point, we know that we perform a cross-register-bank copy.
9927 // Check if it is expensive.
9928 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9929 // Assume bitcasts are cheap, unless both register classes do not
9930 // explicitly share a common sub class.
9931 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9934 // Check if it will be merged with the load.
9935 // 1. Check the alignment constraint.
9936 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9937 ResVT.getTypeForEVT(*DAG->getContext()));
9939 if (RequiredAlignment > getAlignment())
9942 // 2. Check that the load is a legal operation for that type.
9943 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9946 // 3. Check that we do not have a zext in the way.
9947 if (Inst->getValueType(0) != getLoadedType())
9955 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9956 /// \p UsedBits looks like 0..0 1..1 0..0.
9957 static bool areUsedBitsDense(const APInt &UsedBits) {
9958 // If all the bits are one, this is dense!
9959 if (UsedBits.isAllOnesValue())
9962 // Get rid of the unused bits on the right.
9963 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9964 // Get rid of the unused bits on the left.
9965 if (NarrowedUsedBits.countLeadingZeros())
9966 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9967 // Check that the chunk of bits is completely used.
9968 return NarrowedUsedBits.isAllOnesValue();
9971 /// \brief Check whether or not \p First and \p Second are next to each other
9972 /// in memory. This means that there is no hole between the bits loaded
9973 /// by \p First and the bits loaded by \p Second.
9974 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9975 const LoadedSlice &Second) {
9976 assert(First.Origin == Second.Origin && First.Origin &&
9977 "Unable to match different memory origins.");
9978 APInt UsedBits = First.getUsedBits();
9979 assert((UsedBits & Second.getUsedBits()) == 0 &&
9980 "Slices are not supposed to overlap.");
9981 UsedBits |= Second.getUsedBits();
9982 return areUsedBitsDense(UsedBits);
9985 /// \brief Adjust the \p GlobalLSCost according to the target
9986 /// paring capabilities and the layout of the slices.
9987 /// \pre \p GlobalLSCost should account for at least as many loads as
9988 /// there is in the slices in \p LoadedSlices.
9989 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9990 LoadedSlice::Cost &GlobalLSCost) {
9991 unsigned NumberOfSlices = LoadedSlices.size();
9992 // If there is less than 2 elements, no pairing is possible.
9993 if (NumberOfSlices < 2)
9996 // Sort the slices so that elements that are likely to be next to each
9997 // other in memory are next to each other in the list.
9998 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9999 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10000 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10001 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10003 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10004 // First (resp. Second) is the first (resp. Second) potentially candidate
10005 // to be placed in a paired load.
10006 const LoadedSlice *First = nullptr;
10007 const LoadedSlice *Second = nullptr;
10008 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10009 // Set the beginning of the pair.
10012 Second = &LoadedSlices[CurrSlice];
10014 // If First is NULL, it means we start a new pair.
10015 // Get to the next slice.
10019 EVT LoadedType = First->getLoadedType();
10021 // If the types of the slices are different, we cannot pair them.
10022 if (LoadedType != Second->getLoadedType())
10025 // Check if the target supplies paired loads for this type.
10026 unsigned RequiredAlignment = 0;
10027 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10028 // move to the next pair, this type is hopeless.
10032 // Check if we meet the alignment requirement.
10033 if (RequiredAlignment > First->getAlignment())
10036 // Check that both loads are next to each other in memory.
10037 if (!areSlicesNextToEachOther(*First, *Second))
10040 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10041 --GlobalLSCost.Loads;
10042 // Move to the next pair.
10047 /// \brief Check the profitability of all involved LoadedSlice.
10048 /// Currently, it is considered profitable if there is exactly two
10049 /// involved slices (1) which are (2) next to each other in memory, and
10050 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10052 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10053 /// the elements themselves.
10055 /// FIXME: When the cost model will be mature enough, we can relax
10056 /// constraints (1) and (2).
10057 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10058 const APInt &UsedBits, bool ForCodeSize) {
10059 unsigned NumberOfSlices = LoadedSlices.size();
10060 if (StressLoadSlicing)
10061 return NumberOfSlices > 1;
10064 if (NumberOfSlices != 2)
10068 if (!areUsedBitsDense(UsedBits))
10072 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10073 // The original code has one big load.
10074 OrigCost.Loads = 1;
10075 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10076 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10077 // Accumulate the cost of all the slices.
10078 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10079 GlobalSlicingCost += SliceCost;
10081 // Account as cost in the original configuration the gain obtained
10082 // with the current slices.
10083 OrigCost.addSliceGain(LS);
10086 // If the target supports paired load, adjust the cost accordingly.
10087 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10088 return OrigCost > GlobalSlicingCost;
10091 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10092 /// operations, split it in the various pieces being extracted.
10094 /// This sort of thing is introduced by SROA.
10095 /// This slicing takes care not to insert overlapping loads.
10096 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10097 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10098 if (Level < AfterLegalizeDAG)
10101 LoadSDNode *LD = cast<LoadSDNode>(N);
10102 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10103 !LD->getValueType(0).isInteger())
10106 // Keep track of already used bits to detect overlapping values.
10107 // In that case, we will just abort the transformation.
10108 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10110 SmallVector<LoadedSlice, 4> LoadedSlices;
10112 // Check if this load is used as several smaller chunks of bits.
10113 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10114 // of computation for each trunc.
10115 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10116 UI != UIEnd; ++UI) {
10117 // Skip the uses of the chain.
10118 if (UI.getUse().getResNo() != 0)
10121 SDNode *User = *UI;
10122 unsigned Shift = 0;
10124 // Check if this is a trunc(lshr).
10125 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10126 isa<ConstantSDNode>(User->getOperand(1))) {
10127 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10128 User = *User->use_begin();
10131 // At this point, User is a Truncate, iff we encountered, trunc or
10133 if (User->getOpcode() != ISD::TRUNCATE)
10136 // The width of the type must be a power of 2 and greater than 8-bits.
10137 // Otherwise the load cannot be represented in LLVM IR.
10138 // Moreover, if we shifted with a non-8-bits multiple, the slice
10139 // will be across several bytes. We do not support that.
10140 unsigned Width = User->getValueSizeInBits(0);
10141 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10144 // Build the slice for this chain of computations.
10145 LoadedSlice LS(User, LD, Shift, &DAG);
10146 APInt CurrentUsedBits = LS.getUsedBits();
10148 // Check if this slice overlaps with another.
10149 if ((CurrentUsedBits & UsedBits) != 0)
10151 // Update the bits used globally.
10152 UsedBits |= CurrentUsedBits;
10154 // Check if the new slice would be legal.
10158 // Record the slice.
10159 LoadedSlices.push_back(LS);
10162 // Abort slicing if it does not seem to be profitable.
10163 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10168 // Rewrite each chain to use an independent load.
10169 // By construction, each chain can be represented by a unique load.
10171 // Prepare the argument for the new token factor for all the slices.
10172 SmallVector<SDValue, 8> ArgChains;
10173 for (SmallVectorImpl<LoadedSlice>::const_iterator
10174 LSIt = LoadedSlices.begin(),
10175 LSItEnd = LoadedSlices.end();
10176 LSIt != LSItEnd; ++LSIt) {
10177 SDValue SliceInst = LSIt->loadSlice();
10178 CombineTo(LSIt->Inst, SliceInst, true);
10179 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10180 SliceInst = SliceInst.getOperand(0);
10181 assert(SliceInst->getOpcode() == ISD::LOAD &&
10182 "It takes more than a zext to get to the loaded slice!!");
10183 ArgChains.push_back(SliceInst.getValue(1));
10186 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10188 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10192 /// Check to see if V is (and load (ptr), imm), where the load is having
10193 /// specific bytes cleared out. If so, return the byte size being masked out
10194 /// and the shift amount.
10195 static std::pair<unsigned, unsigned>
10196 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10197 std::pair<unsigned, unsigned> Result(0, 0);
10199 // Check for the structure we're looking for.
10200 if (V->getOpcode() != ISD::AND ||
10201 !isa<ConstantSDNode>(V->getOperand(1)) ||
10202 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10205 // Check the chain and pointer.
10206 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10207 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10209 // The store should be chained directly to the load or be an operand of a
10211 if (LD == Chain.getNode())
10213 else if (Chain->getOpcode() != ISD::TokenFactor)
10214 return Result; // Fail.
10217 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10218 if (Chain->getOperand(i).getNode() == LD) {
10222 if (!isOk) return Result;
10225 // This only handles simple types.
10226 if (V.getValueType() != MVT::i16 &&
10227 V.getValueType() != MVT::i32 &&
10228 V.getValueType() != MVT::i64)
10231 // Check the constant mask. Invert it so that the bits being masked out are
10232 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10233 // follow the sign bit for uniformity.
10234 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10235 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10236 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10237 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10238 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10239 if (NotMaskLZ == 64) return Result; // All zero mask.
10241 // See if we have a continuous run of bits. If so, we have 0*1+0*
10242 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10245 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10246 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10247 NotMaskLZ -= 64-V.getValueSizeInBits();
10249 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10250 switch (MaskedBytes) {
10254 default: return Result; // All one mask, or 5-byte mask.
10257 // Verify that the first bit starts at a multiple of mask so that the access
10258 // is aligned the same as the access width.
10259 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10261 Result.first = MaskedBytes;
10262 Result.second = NotMaskTZ/8;
10267 /// Check to see if IVal is something that provides a value as specified by
10268 /// MaskInfo. If so, replace the specified store with a narrower store of
10269 /// truncated IVal.
10271 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10272 SDValue IVal, StoreSDNode *St,
10274 unsigned NumBytes = MaskInfo.first;
10275 unsigned ByteShift = MaskInfo.second;
10276 SelectionDAG &DAG = DC->getDAG();
10278 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10279 // that uses this. If not, this is not a replacement.
10280 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10281 ByteShift*8, (ByteShift+NumBytes)*8);
10282 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10284 // Check that it is legal on the target to do this. It is legal if the new
10285 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10287 MVT VT = MVT::getIntegerVT(NumBytes*8);
10288 if (!DC->isTypeLegal(VT))
10291 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10292 // shifted by ByteShift and truncated down to NumBytes.
10295 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10296 DAG.getConstant(ByteShift*8, DL,
10297 DC->getShiftAmountTy(IVal.getValueType())));
10300 // Figure out the offset for the store and the alignment of the access.
10302 unsigned NewAlign = St->getAlignment();
10304 if (DAG.getTargetLoweringInfo().isLittleEndian())
10305 StOffset = ByteShift;
10307 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10309 SDValue Ptr = St->getBasePtr();
10312 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10313 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10314 NewAlign = MinAlign(NewAlign, StOffset);
10317 // Truncate down to the new size.
10318 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10321 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10322 St->getPointerInfo().getWithOffset(StOffset),
10323 false, false, NewAlign).getNode();
10327 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10328 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10329 /// narrowing the load and store if it would end up being a win for performance
10331 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10332 StoreSDNode *ST = cast<StoreSDNode>(N);
10333 if (ST->isVolatile())
10336 SDValue Chain = ST->getChain();
10337 SDValue Value = ST->getValue();
10338 SDValue Ptr = ST->getBasePtr();
10339 EVT VT = Value.getValueType();
10341 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10344 unsigned Opc = Value.getOpcode();
10346 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10347 // is a byte mask indicating a consecutive number of bytes, check to see if
10348 // Y is known to provide just those bytes. If so, we try to replace the
10349 // load + replace + store sequence with a single (narrower) store, which makes
10351 if (Opc == ISD::OR) {
10352 std::pair<unsigned, unsigned> MaskedLoad;
10353 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10354 if (MaskedLoad.first)
10355 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10356 Value.getOperand(1), ST,this))
10357 return SDValue(NewST, 0);
10359 // Or is commutative, so try swapping X and Y.
10360 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10361 if (MaskedLoad.first)
10362 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10363 Value.getOperand(0), ST,this))
10364 return SDValue(NewST, 0);
10367 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10368 Value.getOperand(1).getOpcode() != ISD::Constant)
10371 SDValue N0 = Value.getOperand(0);
10372 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10373 Chain == SDValue(N0.getNode(), 1)) {
10374 LoadSDNode *LD = cast<LoadSDNode>(N0);
10375 if (LD->getBasePtr() != Ptr ||
10376 LD->getPointerInfo().getAddrSpace() !=
10377 ST->getPointerInfo().getAddrSpace())
10380 // Find the type to narrow it the load / op / store to.
10381 SDValue N1 = Value.getOperand(1);
10382 unsigned BitWidth = N1.getValueSizeInBits();
10383 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10384 if (Opc == ISD::AND)
10385 Imm ^= APInt::getAllOnesValue(BitWidth);
10386 if (Imm == 0 || Imm.isAllOnesValue())
10388 unsigned ShAmt = Imm.countTrailingZeros();
10389 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10390 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10391 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10392 // The narrowing should be profitable, the load/store operation should be
10393 // legal (or custom) and the store size should be equal to the NewVT width.
10394 while (NewBW < BitWidth &&
10395 (NewVT.getStoreSizeInBits() != NewBW ||
10396 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10397 !TLI.isNarrowingProfitable(VT, NewVT))) {
10398 NewBW = NextPowerOf2(NewBW);
10399 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10401 if (NewBW >= BitWidth)
10404 // If the lsb changed does not start at the type bitwidth boundary,
10405 // start at the previous one.
10407 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10408 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10409 std::min(BitWidth, ShAmt + NewBW));
10410 if ((Imm & Mask) == Imm) {
10411 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10412 if (Opc == ISD::AND)
10413 NewImm ^= APInt::getAllOnesValue(NewBW);
10414 uint64_t PtrOff = ShAmt / 8;
10415 // For big endian targets, we need to adjust the offset to the pointer to
10416 // load the correct bytes.
10417 if (TLI.isBigEndian())
10418 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10420 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10421 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10422 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10425 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10426 Ptr.getValueType(), Ptr,
10427 DAG.getConstant(PtrOff, SDLoc(LD),
10428 Ptr.getValueType()));
10429 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10430 LD->getChain(), NewPtr,
10431 LD->getPointerInfo().getWithOffset(PtrOff),
10432 LD->isVolatile(), LD->isNonTemporal(),
10433 LD->isInvariant(), NewAlign,
10435 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10436 DAG.getConstant(NewImm, SDLoc(Value),
10438 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10440 ST->getPointerInfo().getWithOffset(PtrOff),
10441 false, false, NewAlign);
10443 AddToWorklist(NewPtr.getNode());
10444 AddToWorklist(NewLD.getNode());
10445 AddToWorklist(NewVal.getNode());
10446 WorklistRemover DeadNodes(*this);
10447 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10456 /// For a given floating point load / store pair, if the load value isn't used
10457 /// by any other operations, then consider transforming the pair to integer
10458 /// load / store operations if the target deems the transformation profitable.
10459 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10460 StoreSDNode *ST = cast<StoreSDNode>(N);
10461 SDValue Chain = ST->getChain();
10462 SDValue Value = ST->getValue();
10463 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10464 Value.hasOneUse() &&
10465 Chain == SDValue(Value.getNode(), 1)) {
10466 LoadSDNode *LD = cast<LoadSDNode>(Value);
10467 EVT VT = LD->getMemoryVT();
10468 if (!VT.isFloatingPoint() ||
10469 VT != ST->getMemoryVT() ||
10470 LD->isNonTemporal() ||
10471 ST->isNonTemporal() ||
10472 LD->getPointerInfo().getAddrSpace() != 0 ||
10473 ST->getPointerInfo().getAddrSpace() != 0)
10476 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10477 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10478 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10479 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10480 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10483 unsigned LDAlign = LD->getAlignment();
10484 unsigned STAlign = ST->getAlignment();
10485 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10486 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10487 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10490 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10491 LD->getChain(), LD->getBasePtr(),
10492 LD->getPointerInfo(),
10493 false, false, false, LDAlign);
10495 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10496 NewLD, ST->getBasePtr(),
10497 ST->getPointerInfo(),
10498 false, false, STAlign);
10500 AddToWorklist(NewLD.getNode());
10501 AddToWorklist(NewST.getNode());
10502 WorklistRemover DeadNodes(*this);
10503 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10512 /// Helper struct to parse and store a memory address as base + index + offset.
10513 /// We ignore sign extensions when it is safe to do so.
10514 /// The following two expressions are not equivalent. To differentiate we need
10515 /// to store whether there was a sign extension involved in the index
10517 /// (load (i64 add (i64 copyfromreg %c)
10518 /// (i64 signextend (add (i8 load %index)
10522 /// (load (i64 add (i64 copyfromreg %c)
10523 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10525 struct BaseIndexOffset {
10529 bool IsIndexSignExt;
10531 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10533 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10534 bool IsIndexSignExt) :
10535 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10537 bool equalBaseIndex(const BaseIndexOffset &Other) {
10538 return Other.Base == Base && Other.Index == Index &&
10539 Other.IsIndexSignExt == IsIndexSignExt;
10542 /// Parses tree in Ptr for base, index, offset addresses.
10543 static BaseIndexOffset match(SDValue Ptr) {
10544 bool IsIndexSignExt = false;
10546 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10547 // instruction, then it could be just the BASE or everything else we don't
10548 // know how to handle. Just use Ptr as BASE and give up.
10549 if (Ptr->getOpcode() != ISD::ADD)
10550 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10552 // We know that we have at least an ADD instruction. Try to pattern match
10553 // the simple case of BASE + OFFSET.
10554 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10555 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10556 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10560 // Inside a loop the current BASE pointer is calculated using an ADD and a
10561 // MUL instruction. In this case Ptr is the actual BASE pointer.
10562 // (i64 add (i64 %array_ptr)
10563 // (i64 mul (i64 %induction_var)
10564 // (i64 %element_size)))
10565 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10566 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10568 // Look at Base + Index + Offset cases.
10569 SDValue Base = Ptr->getOperand(0);
10570 SDValue IndexOffset = Ptr->getOperand(1);
10572 // Skip signextends.
10573 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10574 IndexOffset = IndexOffset->getOperand(0);
10575 IsIndexSignExt = true;
10578 // Either the case of Base + Index (no offset) or something else.
10579 if (IndexOffset->getOpcode() != ISD::ADD)
10580 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10582 // Now we have the case of Base + Index + offset.
10583 SDValue Index = IndexOffset->getOperand(0);
10584 SDValue Offset = IndexOffset->getOperand(1);
10586 if (!isa<ConstantSDNode>(Offset))
10587 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10589 // Ignore signextends.
10590 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10591 Index = Index->getOperand(0);
10592 IsIndexSignExt = true;
10593 } else IsIndexSignExt = false;
10595 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10596 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10601 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10603 ArrayRef<MemOpLink> Stores,
10605 SmallVector<SDValue, 8> BuildVector;
10607 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10608 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10610 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10613 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10614 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10615 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10616 // Make sure we have something to merge.
10620 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10621 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10622 unsigned LatestNodeUsed = 0;
10624 for (unsigned i=0; i < NumElem; ++i) {
10625 // Find a chain for the new wide-store operand. Notice that some
10626 // of the store nodes that we found may not be selected for inclusion
10627 // in the wide store. The chain we use needs to be the chain of the
10628 // latest store node which is *used* and replaced by the wide store.
10629 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10630 LatestNodeUsed = i;
10633 // The latest Node in the DAG.
10634 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10635 SDLoc DL(StoreNodes[0].MemNode);
10639 // Find a legal type for the vector store.
10640 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10641 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10642 if (IsConstantSrc) {
10643 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10645 SmallVector<SDValue, 8> Ops;
10646 for (unsigned i = 0; i < NumElem ; ++i) {
10647 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10648 SDValue Val = St->getValue();
10649 // All of the operands of a BUILD_VECTOR must have the same type.
10650 if (Val.getValueType() != MemVT)
10652 Ops.push_back(Val);
10655 // Build the extracted vector elements back into a vector.
10656 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10659 // We should always use a vector store when merging extracted vector
10660 // elements, so this path implies a store of constants.
10661 assert(IsConstantSrc && "Merged vector elements should use vector store");
10663 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10664 APInt StoreInt(StoreBW, 0);
10666 // Construct a single integer constant which is made of the smaller
10667 // constant inputs.
10668 bool IsLE = TLI.isLittleEndian();
10669 for (unsigned i = 0; i < NumElem ; ++i) {
10670 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10671 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10672 SDValue Val = St->getValue();
10673 StoreInt <<= ElementSizeBytes*8;
10674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10675 StoreInt |= C->getAPIntValue().zext(StoreBW);
10676 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10677 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10679 llvm_unreachable("Invalid constant element type");
10683 // Create the new Load and Store operations.
10684 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10685 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10688 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10689 FirstInChain->getBasePtr(),
10690 FirstInChain->getPointerInfo(),
10692 FirstInChain->getAlignment());
10694 // Replace the last store with the new store
10695 CombineTo(LatestOp, NewStore);
10696 // Erase all other stores.
10697 for (unsigned i = 0; i < NumElem ; ++i) {
10698 if (StoreNodes[i].MemNode == LatestOp)
10700 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10701 // ReplaceAllUsesWith will replace all uses that existed when it was
10702 // called, but graph optimizations may cause new ones to appear. For
10703 // example, the case in pr14333 looks like
10705 // St's chain -> St -> another store -> X
10707 // And the only difference from St to the other store is the chain.
10708 // When we change it's chain to be St's chain they become identical,
10709 // get CSEed and the net result is that X is now a use of St.
10710 // Since we know that St is redundant, just iterate.
10711 while (!St->use_empty())
10712 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10713 deleteAndRecombine(St);
10719 static bool allowableAlignment(const SelectionDAG &DAG,
10720 const TargetLowering &TLI, EVT EVTTy,
10721 unsigned AS, unsigned Align) {
10722 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10725 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10726 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10727 return (Align >= ABIAlignment);
10730 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10731 if (OptLevel == CodeGenOpt::None)
10734 EVT MemVT = St->getMemoryVT();
10735 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10736 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10737 Attribute::NoImplicitFloat);
10739 // This function cannot currently deal with non-byte-sized memory sizes.
10740 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10743 // Don't merge vectors into wider inputs.
10744 if (MemVT.isVector() || !MemVT.isSimple())
10747 // Perform an early exit check. Do not bother looking at stored values that
10748 // are not constants, loads, or extracted vector elements.
10749 SDValue StoredVal = St->getValue();
10750 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10751 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10752 isa<ConstantFPSDNode>(StoredVal);
10753 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10755 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10758 // Only look at ends of store sequences.
10759 SDValue Chain = SDValue(St, 0);
10760 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10763 // This holds the base pointer, index, and the offset in bytes from the base
10765 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10767 // We must have a base and an offset.
10768 if (!BasePtr.Base.getNode())
10771 // Do not handle stores to undef base pointers.
10772 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10775 // Save the LoadSDNodes that we find in the chain.
10776 // We need to make sure that these nodes do not interfere with
10777 // any of the store nodes.
10778 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10780 // Save the StoreSDNodes that we find in the chain.
10781 SmallVector<MemOpLink, 8> StoreNodes;
10783 // Walk up the chain and look for nodes with offsets from the same
10784 // base pointer. Stop when reaching an instruction with a different kind
10785 // or instruction which has a different base pointer.
10787 StoreSDNode *Index = St;
10789 // If the chain has more than one use, then we can't reorder the mem ops.
10790 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10793 // Find the base pointer and offset for this memory node.
10794 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10796 // Check that the base pointer is the same as the original one.
10797 if (!Ptr.equalBaseIndex(BasePtr))
10800 // The memory operands must not be volatile.
10801 if (Index->isVolatile() || Index->isIndexed())
10805 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10806 if (St->isTruncatingStore())
10809 // The stored memory type must be the same.
10810 if (Index->getMemoryVT() != MemVT)
10813 // We found a potential memory operand to merge.
10814 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10816 // Find the next memory operand in the chain. If the next operand in the
10817 // chain is a store then move up and continue the scan with the next
10818 // memory operand. If the next operand is a load save it and use alias
10819 // information to check if it interferes with anything.
10820 SDNode *NextInChain = Index->getChain().getNode();
10822 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10823 // We found a store node. Use it for the next iteration.
10826 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10827 if (Ldn->isVolatile()) {
10832 // Save the load node for later. Continue the scan.
10833 AliasLoadNodes.push_back(Ldn);
10834 NextInChain = Ldn->getChain().getNode();
10843 // Check if there is anything to merge.
10844 if (StoreNodes.size() < 2)
10847 // Sort the memory operands according to their distance from the base pointer.
10848 std::sort(StoreNodes.begin(), StoreNodes.end(),
10849 [](MemOpLink LHS, MemOpLink RHS) {
10850 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10851 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10852 LHS.SequenceNum > RHS.SequenceNum);
10855 // Scan the memory operations on the chain and find the first non-consecutive
10856 // store memory address.
10857 unsigned LastConsecutiveStore = 0;
10858 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10859 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10861 // Check that the addresses are consecutive starting from the second
10862 // element in the list of stores.
10864 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10865 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10869 bool Alias = false;
10870 // Check if this store interferes with any of the loads that we found.
10871 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10872 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10876 // We found a load that alias with this store. Stop the sequence.
10880 // Mark this node as useful.
10881 LastConsecutiveStore = i;
10884 // The node with the lowest store address.
10885 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10886 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10887 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10889 // Store the constants into memory as one consecutive store.
10890 if (IsConstantSrc) {
10891 unsigned LastLegalType = 0;
10892 unsigned LastLegalVectorType = 0;
10893 bool NonZero = false;
10894 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10895 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10896 SDValue StoredVal = St->getValue();
10898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10899 NonZero |= !C->isNullValue();
10900 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10901 NonZero |= !C->getConstantFPValue()->isNullValue();
10907 // Find a legal type for the constant store.
10908 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10909 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10910 if (TLI.isTypeLegal(StoreTy) &&
10911 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10912 FirstStoreAlign)) {
10913 LastLegalType = i+1;
10914 // Or check whether a truncstore is legal.
10915 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10916 TargetLowering::TypePromoteInteger) {
10917 EVT LegalizedStoredValueTy =
10918 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10919 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10920 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10921 FirstStoreAlign)) {
10922 LastLegalType = i + 1;
10926 // Find a legal type for the vector store.
10927 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10928 if (TLI.isTypeLegal(Ty) &&
10929 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10930 LastLegalVectorType = i + 1;
10935 // We only use vectors if the constant is known to be zero or the target
10936 // allows it and the function is not marked with the noimplicitfloat
10939 LastLegalVectorType = 0;
10940 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10941 LastLegalVectorType,
10943 LastLegalVectorType = 0;
10946 // Check if we found a legal integer type to store.
10947 if (LastLegalType == 0 && LastLegalVectorType == 0)
10950 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10951 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10953 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10957 // When extracting multiple vector elements, try to store them
10958 // in one vector store rather than a sequence of scalar stores.
10959 if (IsExtractVecEltSrc) {
10960 unsigned NumElem = 0;
10961 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10962 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10963 SDValue StoredVal = St->getValue();
10964 // This restriction could be loosened.
10965 // Bail out if any stored values are not elements extracted from a vector.
10966 // It should be possible to handle mixed sources, but load sources need
10967 // more careful handling (see the block of code below that handles
10968 // consecutive loads).
10969 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10972 // Find a legal type for the vector store.
10973 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10974 if (TLI.isTypeLegal(Ty) &&
10975 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10979 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10983 // Below we handle the case of multiple consecutive stores that
10984 // come from multiple consecutive loads. We merge them into a single
10985 // wide load and a single wide store.
10987 // Look for load nodes which are used by the stored values.
10988 SmallVector<MemOpLink, 8> LoadNodes;
10990 // Find acceptable loads. Loads need to have the same chain (token factor),
10991 // must not be zext, volatile, indexed, and they must be consecutive.
10992 BaseIndexOffset LdBasePtr;
10993 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10994 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10995 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10998 // Loads must only have one use.
10999 if (!Ld->hasNUsesOfValue(1, 0))
11002 // The memory operands must not be volatile.
11003 if (Ld->isVolatile() || Ld->isIndexed())
11006 // We do not accept ext loads.
11007 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11010 // The stored memory type must be the same.
11011 if (Ld->getMemoryVT() != MemVT)
11014 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11015 // If this is not the first ptr that we check.
11016 if (LdBasePtr.Base.getNode()) {
11017 // The base ptr must be the same.
11018 if (!LdPtr.equalBaseIndex(LdBasePtr))
11021 // Check that all other base pointers are the same as this one.
11025 // We found a potential memory operand to merge.
11026 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11029 if (LoadNodes.size() < 2)
11032 // If we have load/store pair instructions and we only have two values,
11034 unsigned RequiredAlignment;
11035 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11036 St->getAlignment() >= RequiredAlignment)
11039 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11040 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11041 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11043 // Scan the memory operations on the chain and find the first non-consecutive
11044 // load memory address. These variables hold the index in the store node
11046 unsigned LastConsecutiveLoad = 0;
11047 // This variable refers to the size and not index in the array.
11048 unsigned LastLegalVectorType = 0;
11049 unsigned LastLegalIntegerType = 0;
11050 StartAddress = LoadNodes[0].OffsetFromBase;
11051 SDValue FirstChain = FirstLoad->getChain();
11052 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11053 // All loads much share the same chain.
11054 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11057 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11058 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11060 LastConsecutiveLoad = i;
11062 // Find a legal type for the vector store.
11063 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11064 if (TLI.isTypeLegal(StoreTy) &&
11065 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11066 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11067 LastLegalVectorType = i + 1;
11070 // Find a legal type for the integer store.
11071 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11072 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11073 if (TLI.isTypeLegal(StoreTy) &&
11074 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11075 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11076 LastLegalIntegerType = i + 1;
11077 // Or check whether a truncstore and extload is legal.
11078 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11079 TargetLowering::TypePromoteInteger) {
11080 EVT LegalizedStoredValueTy =
11081 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11082 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11083 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11084 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11085 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11086 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11087 FirstStoreAlign) &&
11088 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11090 LastLegalIntegerType = i+1;
11094 // Only use vector types if the vector type is larger than the integer type.
11095 // If they are the same, use integers.
11096 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11097 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11099 // We add +1 here because the LastXXX variables refer to location while
11100 // the NumElem refers to array/index size.
11101 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11102 NumElem = std::min(LastLegalType, NumElem);
11107 // The latest Node in the DAG.
11108 unsigned LatestNodeUsed = 0;
11109 for (unsigned i=1; i<NumElem; ++i) {
11110 // Find a chain for the new wide-store operand. Notice that some
11111 // of the store nodes that we found may not be selected for inclusion
11112 // in the wide store. The chain we use needs to be the chain of the
11113 // latest store node which is *used* and replaced by the wide store.
11114 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11115 LatestNodeUsed = i;
11118 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11120 // Find if it is better to use vectors or integers to load and store
11124 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11126 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11127 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11130 SDLoc LoadDL(LoadNodes[0].MemNode);
11131 SDLoc StoreDL(StoreNodes[0].MemNode);
11133 SDValue NewLoad = DAG.getLoad(
11134 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11135 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11137 SDValue NewStore = DAG.getStore(
11138 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11139 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11141 // Replace one of the loads with the new load.
11142 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11143 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11144 SDValue(NewLoad.getNode(), 1));
11146 // Remove the rest of the load chains.
11147 for (unsigned i = 1; i < NumElem ; ++i) {
11148 // Replace all chain users of the old load nodes with the chain of the new
11150 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11151 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11154 // Replace the last store with the new store.
11155 CombineTo(LatestOp, NewStore);
11156 // Erase all other stores.
11157 for (unsigned i = 0; i < NumElem ; ++i) {
11158 // Remove all Store nodes.
11159 if (StoreNodes[i].MemNode == LatestOp)
11161 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11162 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11163 deleteAndRecombine(St);
11169 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11170 StoreSDNode *ST = cast<StoreSDNode>(N);
11171 SDValue Chain = ST->getChain();
11172 SDValue Value = ST->getValue();
11173 SDValue Ptr = ST->getBasePtr();
11175 // If this is a store of a bit convert, store the input value if the
11176 // resultant store does not need a higher alignment than the original.
11177 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11178 ST->isUnindexed()) {
11179 unsigned OrigAlign = ST->getAlignment();
11180 EVT SVT = Value.getOperand(0).getValueType();
11181 unsigned Align = TLI.getDataLayout()->
11182 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11183 if (Align <= OrigAlign &&
11184 ((!LegalOperations && !ST->isVolatile()) ||
11185 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11186 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11187 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11188 ST->isNonTemporal(), OrigAlign,
11192 // Turn 'store undef, Ptr' -> nothing.
11193 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11196 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11197 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11198 // NOTE: If the original store is volatile, this transform must not increase
11199 // the number of stores. For example, on x86-32 an f64 can be stored in one
11200 // processor operation but an i64 (which is not legal) requires two. So the
11201 // transform should not be done in this case.
11202 if (Value.getOpcode() != ISD::TargetConstantFP) {
11204 switch (CFP->getSimpleValueType(0).SimpleTy) {
11205 default: llvm_unreachable("Unknown FP type");
11206 case MVT::f16: // We don't do this for these yet.
11212 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11213 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11215 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11216 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11218 return DAG.getStore(Chain, SDLoc(N), Tmp,
11219 Ptr, ST->getMemOperand());
11223 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11224 !ST->isVolatile()) ||
11225 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11227 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11228 getZExtValue(), SDLoc(CFP), MVT::i64);
11229 return DAG.getStore(Chain, SDLoc(N), Tmp,
11230 Ptr, ST->getMemOperand());
11233 if (!ST->isVolatile() &&
11234 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11235 // Many FP stores are not made apparent until after legalize, e.g. for
11236 // argument passing. Since this is so common, custom legalize the
11237 // 64-bit integer store into two 32-bit stores.
11238 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11239 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11240 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11241 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11243 unsigned Alignment = ST->getAlignment();
11244 bool isVolatile = ST->isVolatile();
11245 bool isNonTemporal = ST->isNonTemporal();
11246 AAMDNodes AAInfo = ST->getAAInfo();
11250 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11251 Ptr, ST->getPointerInfo(),
11252 isVolatile, isNonTemporal,
11253 ST->getAlignment(), AAInfo);
11254 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11255 DAG.getConstant(4, DL, Ptr.getValueType()));
11256 Alignment = MinAlign(Alignment, 4U);
11257 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11258 Ptr, ST->getPointerInfo().getWithOffset(4),
11259 isVolatile, isNonTemporal,
11260 Alignment, AAInfo);
11261 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11270 // Try to infer better alignment information than the store already has.
11271 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11272 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11273 if (Align > ST->getAlignment()) {
11275 DAG.getTruncStore(Chain, SDLoc(N), Value,
11276 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11277 ST->isVolatile(), ST->isNonTemporal(), Align,
11279 if (NewStore.getNode() != N)
11280 return CombineTo(ST, NewStore, true);
11285 // Try transforming a pair floating point load / store ops to integer
11286 // load / store ops.
11287 SDValue NewST = TransformFPLoadStorePair(N);
11288 if (NewST.getNode())
11291 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11292 : DAG.getSubtarget().useAA();
11294 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11295 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11298 if (UseAA && ST->isUnindexed()) {
11299 // Walk up chain skipping non-aliasing memory nodes.
11300 SDValue BetterChain = FindBetterChain(N, Chain);
11302 // If there is a better chain.
11303 if (Chain != BetterChain) {
11306 // Replace the chain to avoid dependency.
11307 if (ST->isTruncatingStore()) {
11308 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11309 ST->getMemoryVT(), ST->getMemOperand());
11311 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11312 ST->getMemOperand());
11315 // Create token to keep both nodes around.
11316 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11317 MVT::Other, Chain, ReplStore);
11319 // Make sure the new and old chains are cleaned up.
11320 AddToWorklist(Token.getNode());
11322 // Don't add users to work list.
11323 return CombineTo(N, Token, false);
11327 // Try transforming N to an indexed store.
11328 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11329 return SDValue(N, 0);
11331 // FIXME: is there such a thing as a truncating indexed store?
11332 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11333 Value.getValueType().isInteger()) {
11334 // See if we can simplify the input to this truncstore with knowledge that
11335 // only the low bits are being used. For example:
11336 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11338 GetDemandedBits(Value,
11339 APInt::getLowBitsSet(
11340 Value.getValueType().getScalarType().getSizeInBits(),
11341 ST->getMemoryVT().getScalarType().getSizeInBits()));
11342 AddToWorklist(Value.getNode());
11343 if (Shorter.getNode())
11344 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11345 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11347 // Otherwise, see if we can simplify the operation with
11348 // SimplifyDemandedBits, which only works if the value has a single use.
11349 if (SimplifyDemandedBits(Value,
11350 APInt::getLowBitsSet(
11351 Value.getValueType().getScalarType().getSizeInBits(),
11352 ST->getMemoryVT().getScalarType().getSizeInBits())))
11353 return SDValue(N, 0);
11356 // If this is a load followed by a store to the same location, then the store
11358 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11359 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11360 ST->isUnindexed() && !ST->isVolatile() &&
11361 // There can't be any side effects between the load and store, such as
11362 // a call or store.
11363 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11364 // The store is dead, remove it.
11369 // If this is a store followed by a store with the same value to the same
11370 // location, then the store is dead/noop.
11371 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11372 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11373 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11374 ST1->isUnindexed() && !ST1->isVolatile()) {
11375 // The store is dead, remove it.
11380 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11381 // truncating store. We can do this even if this is already a truncstore.
11382 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11383 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11384 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11385 ST->getMemoryVT())) {
11386 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11387 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11390 // Only perform this optimization before the types are legal, because we
11391 // don't want to perform this optimization on every DAGCombine invocation.
11393 bool EverChanged = false;
11396 // There can be multiple store sequences on the same chain.
11397 // Keep trying to merge store sequences until we are unable to do so
11398 // or until we merge the last store on the chain.
11399 bool Changed = MergeConsecutiveStores(ST);
11400 EverChanged |= Changed;
11401 if (!Changed) break;
11402 } while (ST->getOpcode() != ISD::DELETED_NODE);
11405 return SDValue(N, 0);
11408 return ReduceLoadOpStoreWidth(N);
11411 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11412 SDValue InVec = N->getOperand(0);
11413 SDValue InVal = N->getOperand(1);
11414 SDValue EltNo = N->getOperand(2);
11417 // If the inserted element is an UNDEF, just use the input vector.
11418 if (InVal.getOpcode() == ISD::UNDEF)
11421 EVT VT = InVec.getValueType();
11423 // If we can't generate a legal BUILD_VECTOR, exit
11424 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11427 // Check that we know which element is being inserted
11428 if (!isa<ConstantSDNode>(EltNo))
11430 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11432 // Canonicalize insert_vector_elt dag nodes.
11434 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11435 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11437 // Do this only if the child insert_vector node has one use; also
11438 // do this only if indices are both constants and Idx1 < Idx0.
11439 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11440 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11441 unsigned OtherElt =
11442 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11443 if (Elt < OtherElt) {
11445 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11446 InVec.getOperand(0), InVal, EltNo);
11447 AddToWorklist(NewOp.getNode());
11448 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11449 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11453 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11454 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11455 // vector elements.
11456 SmallVector<SDValue, 8> Ops;
11457 // Do not combine these two vectors if the output vector will not replace
11458 // the input vector.
11459 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11460 Ops.append(InVec.getNode()->op_begin(),
11461 InVec.getNode()->op_end());
11462 } else if (InVec.getOpcode() == ISD::UNDEF) {
11463 unsigned NElts = VT.getVectorNumElements();
11464 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11469 // Insert the element
11470 if (Elt < Ops.size()) {
11471 // All the operands of BUILD_VECTOR must have the same type;
11472 // we enforce that here.
11473 EVT OpVT = Ops[0].getValueType();
11474 if (InVal.getValueType() != OpVT)
11475 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11476 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11477 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11481 // Return the new vector
11482 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11485 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11486 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11487 EVT ResultVT = EVE->getValueType(0);
11488 EVT VecEltVT = InVecVT.getVectorElementType();
11489 unsigned Align = OriginalLoad->getAlignment();
11490 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11491 VecEltVT.getTypeForEVT(*DAG.getContext()));
11493 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11498 SDValue NewPtr = OriginalLoad->getBasePtr();
11500 EVT PtrType = NewPtr.getValueType();
11501 MachinePointerInfo MPI;
11503 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11504 int Elt = ConstEltNo->getZExtValue();
11505 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11506 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11507 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11509 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11510 Offset = DAG.getNode(
11511 ISD::MUL, DL, PtrType, Offset,
11512 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11513 MPI = OriginalLoad->getPointerInfo();
11515 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11517 // The replacement we need to do here is a little tricky: we need to
11518 // replace an extractelement of a load with a load.
11519 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11520 // Note that this replacement assumes that the extractvalue is the only
11521 // use of the load; that's okay because we don't want to perform this
11522 // transformation in other cases anyway.
11525 if (ResultVT.bitsGT(VecEltVT)) {
11526 // If the result type of vextract is wider than the load, then issue an
11527 // extending load instead.
11528 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11532 Load = DAG.getExtLoad(
11533 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11534 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11535 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11536 Chain = Load.getValue(1);
11538 Load = DAG.getLoad(
11539 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11540 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11541 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11542 Chain = Load.getValue(1);
11543 if (ResultVT.bitsLT(VecEltVT))
11544 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11546 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11548 WorklistRemover DeadNodes(*this);
11549 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11550 SDValue To[] = { Load, Chain };
11551 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11552 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11553 // worklist explicitly as well.
11554 AddToWorklist(Load.getNode());
11555 AddUsersToWorklist(Load.getNode()); // Add users too
11556 // Make sure to revisit this node to clean it up; it will usually be dead.
11557 AddToWorklist(EVE);
11559 return SDValue(EVE, 0);
11562 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11563 // (vextract (scalar_to_vector val, 0) -> val
11564 SDValue InVec = N->getOperand(0);
11565 EVT VT = InVec.getValueType();
11566 EVT NVT = N->getValueType(0);
11568 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11569 // Check if the result type doesn't match the inserted element type. A
11570 // SCALAR_TO_VECTOR may truncate the inserted element and the
11571 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11572 SDValue InOp = InVec.getOperand(0);
11573 if (InOp.getValueType() != NVT) {
11574 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11575 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11580 SDValue EltNo = N->getOperand(1);
11581 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11583 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11584 // We only perform this optimization before the op legalization phase because
11585 // we may introduce new vector instructions which are not backed by TD
11586 // patterns. For example on AVX, extracting elements from a wide vector
11587 // without using extract_subvector. However, if we can find an underlying
11588 // scalar value, then we can always use that.
11589 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11591 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11592 int NumElem = VT.getVectorNumElements();
11593 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11594 // Find the new index to extract from.
11595 int OrigElt = SVOp->getMaskElt(Elt);
11597 // Extracting an undef index is undef.
11599 return DAG.getUNDEF(NVT);
11601 // Select the right vector half to extract from.
11603 if (OrigElt < NumElem) {
11604 SVInVec = InVec->getOperand(0);
11606 SVInVec = InVec->getOperand(1);
11607 OrigElt -= NumElem;
11610 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11611 SDValue InOp = SVInVec.getOperand(OrigElt);
11612 if (InOp.getValueType() != NVT) {
11613 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11614 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11620 // FIXME: We should handle recursing on other vector shuffles and
11621 // scalar_to_vector here as well.
11623 if (!LegalOperations) {
11624 EVT IndexTy = TLI.getVectorIdxTy();
11625 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11626 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11630 bool BCNumEltsChanged = false;
11631 EVT ExtVT = VT.getVectorElementType();
11634 // If the result of load has to be truncated, then it's not necessarily
11636 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11639 if (InVec.getOpcode() == ISD::BITCAST) {
11640 // Don't duplicate a load with other uses.
11641 if (!InVec.hasOneUse())
11644 EVT BCVT = InVec.getOperand(0).getValueType();
11645 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11647 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11648 BCNumEltsChanged = true;
11649 InVec = InVec.getOperand(0);
11650 ExtVT = BCVT.getVectorElementType();
11653 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11654 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11655 ISD::isNormalLoad(InVec.getNode()) &&
11656 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11657 SDValue Index = N->getOperand(1);
11658 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11659 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11663 // Perform only after legalization to ensure build_vector / vector_shuffle
11664 // optimizations have already been done.
11665 if (!LegalOperations) return SDValue();
11667 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11668 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11669 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11672 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11674 LoadSDNode *LN0 = nullptr;
11675 const ShuffleVectorSDNode *SVN = nullptr;
11676 if (ISD::isNormalLoad(InVec.getNode())) {
11677 LN0 = cast<LoadSDNode>(InVec);
11678 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11679 InVec.getOperand(0).getValueType() == ExtVT &&
11680 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11681 // Don't duplicate a load with other uses.
11682 if (!InVec.hasOneUse())
11685 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11686 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11687 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11689 // (load $addr+1*size)
11691 // Don't duplicate a load with other uses.
11692 if (!InVec.hasOneUse())
11695 // If the bit convert changed the number of elements, it is unsafe
11696 // to examine the mask.
11697 if (BCNumEltsChanged)
11700 // Select the input vector, guarding against out of range extract vector.
11701 unsigned NumElems = VT.getVectorNumElements();
11702 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11703 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11705 if (InVec.getOpcode() == ISD::BITCAST) {
11706 // Don't duplicate a load with other uses.
11707 if (!InVec.hasOneUse())
11710 InVec = InVec.getOperand(0);
11712 if (ISD::isNormalLoad(InVec.getNode())) {
11713 LN0 = cast<LoadSDNode>(InVec);
11714 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11715 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11719 // Make sure we found a non-volatile load and the extractelement is
11721 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11724 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11726 return DAG.getUNDEF(LVT);
11728 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11734 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11735 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11736 // We perform this optimization post type-legalization because
11737 // the type-legalizer often scalarizes integer-promoted vectors.
11738 // Performing this optimization before may create bit-casts which
11739 // will be type-legalized to complex code sequences.
11740 // We perform this optimization only before the operation legalizer because we
11741 // may introduce illegal operations.
11742 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11745 unsigned NumInScalars = N->getNumOperands();
11747 EVT VT = N->getValueType(0);
11749 // Check to see if this is a BUILD_VECTOR of a bunch of values
11750 // which come from any_extend or zero_extend nodes. If so, we can create
11751 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11752 // optimizations. We do not handle sign-extend because we can't fill the sign
11754 EVT SourceType = MVT::Other;
11755 bool AllAnyExt = true;
11757 for (unsigned i = 0; i != NumInScalars; ++i) {
11758 SDValue In = N->getOperand(i);
11759 // Ignore undef inputs.
11760 if (In.getOpcode() == ISD::UNDEF) continue;
11762 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11763 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11765 // Abort if the element is not an extension.
11766 if (!ZeroExt && !AnyExt) {
11767 SourceType = MVT::Other;
11771 // The input is a ZeroExt or AnyExt. Check the original type.
11772 EVT InTy = In.getOperand(0).getValueType();
11774 // Check that all of the widened source types are the same.
11775 if (SourceType == MVT::Other)
11778 else if (InTy != SourceType) {
11779 // Multiple income types. Abort.
11780 SourceType = MVT::Other;
11784 // Check if all of the extends are ANY_EXTENDs.
11785 AllAnyExt &= AnyExt;
11788 // In order to have valid types, all of the inputs must be extended from the
11789 // same source type and all of the inputs must be any or zero extend.
11790 // Scalar sizes must be a power of two.
11791 EVT OutScalarTy = VT.getScalarType();
11792 bool ValidTypes = SourceType != MVT::Other &&
11793 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11794 isPowerOf2_32(SourceType.getSizeInBits());
11796 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11797 // turn into a single shuffle instruction.
11801 bool isLE = TLI.isLittleEndian();
11802 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11803 assert(ElemRatio > 1 && "Invalid element size ratio");
11804 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11805 DAG.getConstant(0, SDLoc(N), SourceType);
11807 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11808 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11810 // Populate the new build_vector
11811 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11812 SDValue Cast = N->getOperand(i);
11813 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11814 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11815 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11817 if (Cast.getOpcode() == ISD::UNDEF)
11818 In = DAG.getUNDEF(SourceType);
11820 In = Cast->getOperand(0);
11821 unsigned Index = isLE ? (i * ElemRatio) :
11822 (i * ElemRatio + (ElemRatio - 1));
11824 assert(Index < Ops.size() && "Invalid index");
11828 // The type of the new BUILD_VECTOR node.
11829 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11830 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11831 "Invalid vector size");
11832 // Check if the new vector type is legal.
11833 if (!isTypeLegal(VecVT)) return SDValue();
11835 // Make the new BUILD_VECTOR.
11836 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11838 // The new BUILD_VECTOR node has the potential to be further optimized.
11839 AddToWorklist(BV.getNode());
11840 // Bitcast to the desired type.
11841 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11844 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11845 EVT VT = N->getValueType(0);
11847 unsigned NumInScalars = N->getNumOperands();
11850 EVT SrcVT = MVT::Other;
11851 unsigned Opcode = ISD::DELETED_NODE;
11852 unsigned NumDefs = 0;
11854 for (unsigned i = 0; i != NumInScalars; ++i) {
11855 SDValue In = N->getOperand(i);
11856 unsigned Opc = In.getOpcode();
11858 if (Opc == ISD::UNDEF)
11861 // If all scalar values are floats and converted from integers.
11862 if (Opcode == ISD::DELETED_NODE &&
11863 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11870 EVT InVT = In.getOperand(0).getValueType();
11872 // If all scalar values are typed differently, bail out. It's chosen to
11873 // simplify BUILD_VECTOR of integer types.
11874 if (SrcVT == MVT::Other)
11881 // If the vector has just one element defined, it's not worth to fold it into
11882 // a vectorized one.
11886 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11887 && "Should only handle conversion from integer to float.");
11888 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11890 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11892 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11895 // Just because the floating-point vector type is legal does not necessarily
11896 // mean that the corresponding integer vector type is.
11897 if (!isTypeLegal(NVT))
11900 SmallVector<SDValue, 8> Opnds;
11901 for (unsigned i = 0; i != NumInScalars; ++i) {
11902 SDValue In = N->getOperand(i);
11904 if (In.getOpcode() == ISD::UNDEF)
11905 Opnds.push_back(DAG.getUNDEF(SrcVT));
11907 Opnds.push_back(In.getOperand(0));
11909 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11910 AddToWorklist(BV.getNode());
11912 return DAG.getNode(Opcode, dl, VT, BV);
11915 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11916 unsigned NumInScalars = N->getNumOperands();
11918 EVT VT = N->getValueType(0);
11920 // A vector built entirely of undefs is undef.
11921 if (ISD::allOperandsUndef(N))
11922 return DAG.getUNDEF(VT);
11924 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11927 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11930 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11931 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11932 // at most two distinct vectors, turn this into a shuffle node.
11934 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11935 if (!isTypeLegal(VT))
11938 // May only combine to shuffle after legalize if shuffle is legal.
11939 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11942 SDValue VecIn1, VecIn2;
11943 bool UsesZeroVector = false;
11944 for (unsigned i = 0; i != NumInScalars; ++i) {
11945 SDValue Op = N->getOperand(i);
11946 // Ignore undef inputs.
11947 if (Op.getOpcode() == ISD::UNDEF) continue;
11949 // See if we can combine this build_vector into a blend with a zero vector.
11950 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11951 UsesZeroVector = true;
11955 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11956 // constant index, bail out.
11957 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11958 !isa<ConstantSDNode>(Op.getOperand(1))) {
11959 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11963 // We allow up to two distinct input vectors.
11964 SDValue ExtractedFromVec = Op.getOperand(0);
11965 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11968 if (!VecIn1.getNode()) {
11969 VecIn1 = ExtractedFromVec;
11970 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11971 VecIn2 = ExtractedFromVec;
11973 // Too many inputs.
11974 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11979 // If everything is good, we can make a shuffle operation.
11980 if (VecIn1.getNode()) {
11981 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11982 SmallVector<int, 8> Mask;
11983 for (unsigned i = 0; i != NumInScalars; ++i) {
11984 unsigned Opcode = N->getOperand(i).getOpcode();
11985 if (Opcode == ISD::UNDEF) {
11986 Mask.push_back(-1);
11990 // Operands can also be zero.
11991 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11992 assert(UsesZeroVector &&
11993 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11994 "Unexpected node found!");
11995 Mask.push_back(NumInScalars+i);
11999 // If extracting from the first vector, just use the index directly.
12000 SDValue Extract = N->getOperand(i);
12001 SDValue ExtVal = Extract.getOperand(1);
12002 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12003 if (Extract.getOperand(0) == VecIn1) {
12004 Mask.push_back(ExtIndex);
12008 // Otherwise, use InIdx + InputVecSize
12009 Mask.push_back(InNumElements + ExtIndex);
12012 // Avoid introducing illegal shuffles with zero.
12013 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12016 // We can't generate a shuffle node with mismatched input and output types.
12017 // Attempt to transform a single input vector to the correct type.
12018 if ((VT != VecIn1.getValueType())) {
12019 // If the input vector type has a different base type to the output
12020 // vector type, bail out.
12021 EVT VTElemType = VT.getVectorElementType();
12022 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12023 (VecIn2.getNode() &&
12024 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12027 // If the input vector is too small, widen it.
12028 // We only support widening of vectors which are half the size of the
12029 // output registers. For example XMM->YMM widening on X86 with AVX.
12030 EVT VecInT = VecIn1.getValueType();
12031 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12032 // If we only have one small input, widen it by adding undef values.
12033 if (!VecIn2.getNode())
12034 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12035 DAG.getUNDEF(VecIn1.getValueType()));
12036 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12037 // If we have two small inputs of the same type, try to concat them.
12038 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12039 VecIn2 = SDValue(nullptr, 0);
12042 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12043 // If the input vector is too large, try to split it.
12044 // We don't support having two input vectors that are too large.
12045 // If the zero vector was used, we can not split the vector,
12046 // since we'd need 3 inputs.
12047 if (UsesZeroVector || VecIn2.getNode())
12050 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12053 // Try to replace VecIn1 with two extract_subvectors
12054 // No need to update the masks, they should still be correct.
12055 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12056 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12057 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12058 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12063 if (UsesZeroVector)
12064 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12065 DAG.getConstantFP(0.0, dl, VT);
12067 // If VecIn2 is unused then change it to undef.
12068 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12070 // Check that we were able to transform all incoming values to the same
12072 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12073 VecIn1.getValueType() != VT)
12076 // Return the new VECTOR_SHUFFLE node.
12080 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12086 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12088 EVT OpVT = N->getOperand(0).getValueType();
12090 // If the operands are legal vectors, leave them alone.
12091 if (TLI.isTypeLegal(OpVT))
12095 EVT VT = N->getValueType(0);
12096 SmallVector<SDValue, 8> Ops;
12098 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12099 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12101 // Keep track of what we encounter.
12102 bool AnyInteger = false;
12103 bool AnyFP = false;
12104 for (const SDValue &Op : N->ops()) {
12105 if (ISD::BITCAST == Op.getOpcode() &&
12106 !Op.getOperand(0).getValueType().isVector())
12107 Ops.push_back(Op.getOperand(0));
12108 else if (ISD::UNDEF == Op.getOpcode())
12109 Ops.push_back(ScalarUndef);
12113 // Note whether we encounter an integer or floating point scalar.
12114 // If it's neither, bail out, it could be something weird like x86mmx.
12115 EVT LastOpVT = Ops.back().getValueType();
12116 if (LastOpVT.isFloatingPoint())
12118 else if (LastOpVT.isInteger())
12124 // If any of the operands is a floating point scalar bitcast to a vector,
12125 // use floating point types throughout, and bitcast everything.
12126 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12128 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12129 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12131 for (SDValue &Op : Ops) {
12132 if (Op.getValueType() == SVT)
12134 if (Op.getOpcode() == ISD::UNDEF)
12137 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12142 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12143 VT.getSizeInBits() / SVT.getSizeInBits());
12144 return DAG.getNode(ISD::BITCAST, DL, VT,
12145 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12148 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12149 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12150 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12151 // inputs come from at most two distinct vectors, turn this into a shuffle
12154 // If we only have one input vector, we don't need to do any concatenation.
12155 if (N->getNumOperands() == 1)
12156 return N->getOperand(0);
12158 // Check if all of the operands are undefs.
12159 EVT VT = N->getValueType(0);
12160 if (ISD::allOperandsUndef(N))
12161 return DAG.getUNDEF(VT);
12163 // Optimize concat_vectors where all but the first of the vectors are undef.
12164 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12165 return Op.getOpcode() == ISD::UNDEF;
12167 SDValue In = N->getOperand(0);
12168 assert(In.getValueType().isVector() && "Must concat vectors");
12170 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12171 if (In->getOpcode() == ISD::BITCAST &&
12172 !In->getOperand(0)->getValueType(0).isVector()) {
12173 SDValue Scalar = In->getOperand(0);
12175 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12176 // look through the trunc so we can still do the transform:
12177 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12178 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12179 !TLI.isTypeLegal(Scalar.getValueType()) &&
12180 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12181 Scalar = Scalar->getOperand(0);
12183 EVT SclTy = Scalar->getValueType(0);
12185 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12188 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12189 VT.getSizeInBits() / SclTy.getSizeInBits());
12190 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12193 SDLoc dl = SDLoc(N);
12194 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12195 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12199 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12200 // We have already tested above for an UNDEF only concatenation.
12201 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12202 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12203 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12204 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12206 bool AllBuildVectorsOrUndefs =
12207 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12208 if (AllBuildVectorsOrUndefs) {
12209 SmallVector<SDValue, 8> Opnds;
12210 EVT SVT = VT.getScalarType();
12213 if (!SVT.isFloatingPoint()) {
12214 // If BUILD_VECTOR are from built from integer, they may have different
12215 // operand types. Get the smallest type and truncate all operands to it.
12216 bool FoundMinVT = false;
12217 for (const SDValue &Op : N->ops())
12218 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12219 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12220 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12223 assert(FoundMinVT && "Concat vector type mismatch");
12226 for (const SDValue &Op : N->ops()) {
12227 EVT OpVT = Op.getValueType();
12228 unsigned NumElts = OpVT.getVectorNumElements();
12230 if (ISD::UNDEF == Op.getOpcode())
12231 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12233 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12234 if (SVT.isFloatingPoint()) {
12235 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12236 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12238 for (unsigned i = 0; i != NumElts; ++i)
12240 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12245 assert(VT.getVectorNumElements() == Opnds.size() &&
12246 "Concat vector type mismatch");
12247 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12250 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12251 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12254 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12255 // nodes often generate nop CONCAT_VECTOR nodes.
12256 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12257 // place the incoming vectors at the exact same location.
12258 SDValue SingleSource = SDValue();
12259 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12261 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12262 SDValue Op = N->getOperand(i);
12264 if (Op.getOpcode() == ISD::UNDEF)
12267 // Check if this is the identity extract:
12268 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12271 // Find the single incoming vector for the extract_subvector.
12272 if (SingleSource.getNode()) {
12273 if (Op.getOperand(0) != SingleSource)
12276 SingleSource = Op.getOperand(0);
12278 // Check the source type is the same as the type of the result.
12279 // If not, this concat may extend the vector, so we can not
12280 // optimize it away.
12281 if (SingleSource.getValueType() != N->getValueType(0))
12285 unsigned IdentityIndex = i * PartNumElem;
12286 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12287 // The extract index must be constant.
12291 // Check that we are reading from the identity index.
12292 if (CS->getZExtValue() != IdentityIndex)
12296 if (SingleSource.getNode())
12297 return SingleSource;
12302 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12303 EVT NVT = N->getValueType(0);
12304 SDValue V = N->getOperand(0);
12306 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12308 // (extract_subvec (concat V1, V2, ...), i)
12311 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12313 if (V->getOperand(0).getValueType() != NVT)
12315 unsigned Idx = N->getConstantOperandVal(1);
12316 unsigned NumElems = NVT.getVectorNumElements();
12317 assert((Idx % NumElems) == 0 &&
12318 "IDX in concat is not a multiple of the result vector length.");
12319 return V->getOperand(Idx / NumElems);
12323 if (V->getOpcode() == ISD::BITCAST)
12324 V = V.getOperand(0);
12326 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12328 // Handle only simple case where vector being inserted and vector
12329 // being extracted are of same type, and are half size of larger vectors.
12330 EVT BigVT = V->getOperand(0).getValueType();
12331 EVT SmallVT = V->getOperand(1).getValueType();
12332 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12335 // Only handle cases where both indexes are constants with the same type.
12336 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12337 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12339 if (InsIdx && ExtIdx &&
12340 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12341 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12343 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12345 // indices are equal or bit offsets are equal => V1
12346 // otherwise => (extract_subvec V1, ExtIdx)
12347 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12348 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12349 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12350 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12351 DAG.getNode(ISD::BITCAST, dl,
12352 N->getOperand(0).getValueType(),
12353 V->getOperand(0)), N->getOperand(1));
12360 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12361 SDValue V, SelectionDAG &DAG) {
12363 EVT VT = V.getValueType();
12365 switch (V.getOpcode()) {
12369 case ISD::CONCAT_VECTORS: {
12370 EVT OpVT = V->getOperand(0).getValueType();
12371 int OpSize = OpVT.getVectorNumElements();
12372 SmallBitVector OpUsedElements(OpSize, false);
12373 bool FoundSimplification = false;
12374 SmallVector<SDValue, 4> NewOps;
12375 NewOps.reserve(V->getNumOperands());
12376 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12377 SDValue Op = V->getOperand(i);
12378 bool OpUsed = false;
12379 for (int j = 0; j < OpSize; ++j)
12380 if (UsedElements[i * OpSize + j]) {
12381 OpUsedElements[j] = true;
12385 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12386 : DAG.getUNDEF(OpVT));
12387 FoundSimplification |= Op == NewOps.back();
12388 OpUsedElements.reset();
12390 if (FoundSimplification)
12391 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12395 case ISD::INSERT_SUBVECTOR: {
12396 SDValue BaseV = V->getOperand(0);
12397 SDValue SubV = V->getOperand(1);
12398 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12402 int SubSize = SubV.getValueType().getVectorNumElements();
12403 int Idx = IdxN->getZExtValue();
12404 bool SubVectorUsed = false;
12405 SmallBitVector SubUsedElements(SubSize, false);
12406 for (int i = 0; i < SubSize; ++i)
12407 if (UsedElements[i + Idx]) {
12408 SubVectorUsed = true;
12409 SubUsedElements[i] = true;
12410 UsedElements[i + Idx] = false;
12413 // Now recurse on both the base and sub vectors.
12414 SDValue SimplifiedSubV =
12416 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12417 : DAG.getUNDEF(SubV.getValueType());
12418 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12419 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12420 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12421 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12427 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12428 SDValue N1, SelectionDAG &DAG) {
12429 EVT VT = SVN->getValueType(0);
12430 int NumElts = VT.getVectorNumElements();
12431 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12432 for (int M : SVN->getMask())
12433 if (M >= 0 && M < NumElts)
12434 N0UsedElements[M] = true;
12435 else if (M >= NumElts)
12436 N1UsedElements[M - NumElts] = true;
12438 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12439 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12440 if (S0 == N0 && S1 == N1)
12443 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12446 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12447 // or turn a shuffle of a single concat into simpler shuffle then concat.
12448 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12449 EVT VT = N->getValueType(0);
12450 unsigned NumElts = VT.getVectorNumElements();
12452 SDValue N0 = N->getOperand(0);
12453 SDValue N1 = N->getOperand(1);
12454 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12456 SmallVector<SDValue, 4> Ops;
12457 EVT ConcatVT = N0.getOperand(0).getValueType();
12458 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12459 unsigned NumConcats = NumElts / NumElemsPerConcat;
12461 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12462 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12463 // half vector elements.
12464 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12465 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12466 SVN->getMask().end(), [](int i) { return i == -1; })) {
12467 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12468 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12469 N1 = DAG.getUNDEF(ConcatVT);
12470 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12473 // Look at every vector that's inserted. We're looking for exact
12474 // subvector-sized copies from a concatenated vector
12475 for (unsigned I = 0; I != NumConcats; ++I) {
12476 // Make sure we're dealing with a copy.
12477 unsigned Begin = I * NumElemsPerConcat;
12478 bool AllUndef = true, NoUndef = true;
12479 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12480 if (SVN->getMaskElt(J) >= 0)
12487 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12490 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12491 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12494 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12495 if (FirstElt < N0.getNumOperands())
12496 Ops.push_back(N0.getOperand(FirstElt));
12498 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12500 } else if (AllUndef) {
12501 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12502 } else { // Mixed with general masks and undefs, can't do optimization.
12507 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12510 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12511 EVT VT = N->getValueType(0);
12512 unsigned NumElts = VT.getVectorNumElements();
12514 SDValue N0 = N->getOperand(0);
12515 SDValue N1 = N->getOperand(1);
12517 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12519 // Canonicalize shuffle undef, undef -> undef
12520 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12521 return DAG.getUNDEF(VT);
12523 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12525 // Canonicalize shuffle v, v -> v, undef
12527 SmallVector<int, 8> NewMask;
12528 for (unsigned i = 0; i != NumElts; ++i) {
12529 int Idx = SVN->getMaskElt(i);
12530 if (Idx >= (int)NumElts) Idx -= NumElts;
12531 NewMask.push_back(Idx);
12533 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12537 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12538 if (N0.getOpcode() == ISD::UNDEF) {
12539 SmallVector<int, 8> NewMask;
12540 for (unsigned i = 0; i != NumElts; ++i) {
12541 int Idx = SVN->getMaskElt(i);
12543 if (Idx >= (int)NumElts)
12546 Idx = -1; // remove reference to lhs
12548 NewMask.push_back(Idx);
12550 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12554 // Remove references to rhs if it is undef
12555 if (N1.getOpcode() == ISD::UNDEF) {
12556 bool Changed = false;
12557 SmallVector<int, 8> NewMask;
12558 for (unsigned i = 0; i != NumElts; ++i) {
12559 int Idx = SVN->getMaskElt(i);
12560 if (Idx >= (int)NumElts) {
12564 NewMask.push_back(Idx);
12567 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12570 // If it is a splat, check if the argument vector is another splat or a
12572 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12573 SDNode *V = N0.getNode();
12575 // If this is a bit convert that changes the element type of the vector but
12576 // not the number of vector elements, look through it. Be careful not to
12577 // look though conversions that change things like v4f32 to v2f64.
12578 if (V->getOpcode() == ISD::BITCAST) {
12579 SDValue ConvInput = V->getOperand(0);
12580 if (ConvInput.getValueType().isVector() &&
12581 ConvInput.getValueType().getVectorNumElements() == NumElts)
12582 V = ConvInput.getNode();
12585 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12586 assert(V->getNumOperands() == NumElts &&
12587 "BUILD_VECTOR has wrong number of operands");
12589 bool AllSame = true;
12590 for (unsigned i = 0; i != NumElts; ++i) {
12591 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12592 Base = V->getOperand(i);
12596 // Splat of <u, u, u, u>, return <u, u, u, u>
12597 if (!Base.getNode())
12599 for (unsigned i = 0; i != NumElts; ++i) {
12600 if (V->getOperand(i) != Base) {
12605 // Splat of <x, x, x, x>, return <x, x, x, x>
12609 // Canonicalize any other splat as a build_vector.
12610 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12611 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12612 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12613 V->getValueType(0), Ops);
12615 // We may have jumped through bitcasts, so the type of the
12616 // BUILD_VECTOR may not match the type of the shuffle.
12617 if (V->getValueType(0) != VT)
12618 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12623 // There are various patterns used to build up a vector from smaller vectors,
12624 // subvectors, or elements. Scan chains of these and replace unused insertions
12625 // or components with undef.
12626 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12629 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12630 Level < AfterLegalizeVectorOps &&
12631 (N1.getOpcode() == ISD::UNDEF ||
12632 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12633 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12634 SDValue V = partitionShuffleOfConcats(N, DAG);
12640 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12641 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12642 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12643 SmallVector<SDValue, 8> Ops;
12644 for (int M : SVN->getMask()) {
12645 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12647 int Idx = M % NumElts;
12648 SDValue &S = (M < (int)NumElts ? N0 : N1);
12649 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12650 Op = S.getOperand(Idx);
12651 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12653 Op = S.getOperand(0);
12655 // Operand can't be combined - bail out.
12661 if (Ops.size() == VT.getVectorNumElements()) {
12662 // BUILD_VECTOR requires all inputs to be of the same type, find the
12663 // maximum type and extend them all.
12664 EVT SVT = VT.getScalarType();
12665 if (SVT.isInteger())
12666 for (SDValue &Op : Ops)
12667 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12668 if (SVT != VT.getScalarType())
12669 for (SDValue &Op : Ops)
12670 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12671 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12672 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12673 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12677 // If this shuffle only has a single input that is a bitcasted shuffle,
12678 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12679 // back to their original types.
12680 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12681 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12682 TLI.isTypeLegal(VT)) {
12684 // Peek through the bitcast only if there is one user.
12686 while (BC0.getOpcode() == ISD::BITCAST) {
12687 if (!BC0.hasOneUse())
12689 BC0 = BC0.getOperand(0);
12692 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12694 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12696 SmallVector<int, 8> NewMask;
12698 for (int s = 0; s != Scale; ++s)
12699 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12703 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12704 EVT SVT = VT.getScalarType();
12705 EVT InnerVT = BC0->getValueType(0);
12706 EVT InnerSVT = InnerVT.getScalarType();
12708 // Determine which shuffle works with the smaller scalar type.
12709 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12710 EVT ScaleSVT = ScaleVT.getScalarType();
12712 if (TLI.isTypeLegal(ScaleVT) &&
12713 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12714 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12716 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12717 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12719 // Scale the shuffle masks to the smaller scalar type.
12720 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12721 SmallVector<int, 8> InnerMask =
12722 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12723 SmallVector<int, 8> OuterMask =
12724 ScaleShuffleMask(SVN->getMask(), OuterScale);
12726 // Merge the shuffle masks.
12727 SmallVector<int, 8> NewMask;
12728 for (int M : OuterMask)
12729 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12731 // Test for shuffle mask legality over both commutations.
12732 SDValue SV0 = BC0->getOperand(0);
12733 SDValue SV1 = BC0->getOperand(1);
12734 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12736 std::swap(SV0, SV1);
12737 ShuffleVectorSDNode::commuteMask(NewMask);
12738 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12742 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12743 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12744 return DAG.getNode(
12745 ISD::BITCAST, SDLoc(N), VT,
12746 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12752 // Canonicalize shuffles according to rules:
12753 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12754 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12755 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12756 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12757 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12758 TLI.isTypeLegal(VT)) {
12759 // The incoming shuffle must be of the same type as the result of the
12760 // current shuffle.
12761 assert(N1->getOperand(0).getValueType() == VT &&
12762 "Shuffle types don't match");
12764 SDValue SV0 = N1->getOperand(0);
12765 SDValue SV1 = N1->getOperand(1);
12766 bool HasSameOp0 = N0 == SV0;
12767 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12768 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12769 // Commute the operands of this shuffle so that next rule
12771 return DAG.getCommutedVectorShuffle(*SVN);
12774 // Try to fold according to rules:
12775 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12776 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12777 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12778 // Don't try to fold shuffles with illegal type.
12779 // Only fold if this shuffle is the only user of the other shuffle.
12780 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12781 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12782 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12784 // The incoming shuffle must be of the same type as the result of the
12785 // current shuffle.
12786 assert(OtherSV->getOperand(0).getValueType() == VT &&
12787 "Shuffle types don't match");
12790 SmallVector<int, 4> Mask;
12791 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12792 // operand, and SV1 as the second operand.
12793 for (unsigned i = 0; i != NumElts; ++i) {
12794 int Idx = SVN->getMaskElt(i);
12796 // Propagate Undef.
12797 Mask.push_back(Idx);
12801 SDValue CurrentVec;
12802 if (Idx < (int)NumElts) {
12803 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12804 // shuffle mask to identify which vector is actually referenced.
12805 Idx = OtherSV->getMaskElt(Idx);
12807 // Propagate Undef.
12808 Mask.push_back(Idx);
12812 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12813 : OtherSV->getOperand(1);
12815 // This shuffle index references an element within N1.
12819 // Simple case where 'CurrentVec' is UNDEF.
12820 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12821 Mask.push_back(-1);
12825 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12826 // will be the first or second operand of the combined shuffle.
12827 Idx = Idx % NumElts;
12828 if (!SV0.getNode() || SV0 == CurrentVec) {
12829 // Ok. CurrentVec is the left hand side.
12830 // Update the mask accordingly.
12832 Mask.push_back(Idx);
12836 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12837 if (SV1.getNode() && SV1 != CurrentVec)
12840 // Ok. CurrentVec is the right hand side.
12841 // Update the mask accordingly.
12843 Mask.push_back(Idx + NumElts);
12846 // Check if all indices in Mask are Undef. In case, propagate Undef.
12847 bool isUndefMask = true;
12848 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12849 isUndefMask &= Mask[i] < 0;
12852 return DAG.getUNDEF(VT);
12854 if (!SV0.getNode())
12855 SV0 = DAG.getUNDEF(VT);
12856 if (!SV1.getNode())
12857 SV1 = DAG.getUNDEF(VT);
12859 // Avoid introducing shuffles with illegal mask.
12860 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12861 ShuffleVectorSDNode::commuteMask(Mask);
12863 if (!TLI.isShuffleMaskLegal(Mask, VT))
12866 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12867 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12868 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12869 std::swap(SV0, SV1);
12872 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12873 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12874 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12875 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12881 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12882 SDValue InVal = N->getOperand(0);
12883 EVT VT = N->getValueType(0);
12885 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12886 // with a VECTOR_SHUFFLE.
12887 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12888 SDValue InVec = InVal->getOperand(0);
12889 SDValue EltNo = InVal->getOperand(1);
12891 // FIXME: We could support implicit truncation if the shuffle can be
12892 // scaled to a smaller vector scalar type.
12893 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12894 if (C0 && VT == InVec.getValueType() &&
12895 VT.getScalarType() == InVal.getValueType()) {
12896 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12897 int Elt = C0->getZExtValue();
12900 if (TLI.isShuffleMaskLegal(NewMask, VT))
12901 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12909 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12910 SDValue N0 = N->getOperand(0);
12911 SDValue N2 = N->getOperand(2);
12913 // If the input vector is a concatenation, and the insert replaces
12914 // one of the halves, we can optimize into a single concat_vectors.
12915 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12916 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12917 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12918 EVT VT = N->getValueType(0);
12920 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12921 // (concat_vectors Z, Y)
12923 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12924 N->getOperand(1), N0.getOperand(1));
12926 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12927 // (concat_vectors X, Z)
12928 if (InsIdx == VT.getVectorNumElements()/2)
12929 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12930 N0.getOperand(0), N->getOperand(1));
12936 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12937 SDValue N0 = N->getOperand(0);
12939 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12940 if (N0->getOpcode() == ISD::FP16_TO_FP)
12941 return N0->getOperand(0);
12946 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12947 /// with the destination vector and a zero vector.
12948 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12949 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12950 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12951 EVT VT = N->getValueType(0);
12952 SDValue LHS = N->getOperand(0);
12953 SDValue RHS = N->getOperand(1);
12956 // Make sure we're not running after operation legalization where it
12957 // may have custom lowered the vector shuffles.
12958 if (LegalOperations)
12961 if (N->getOpcode() != ISD::AND)
12964 if (RHS.getOpcode() == ISD::BITCAST)
12965 RHS = RHS.getOperand(0);
12967 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12968 SmallVector<int, 8> Indices;
12969 unsigned NumElts = RHS.getNumOperands();
12971 for (unsigned i = 0; i != NumElts; ++i) {
12972 SDValue Elt = RHS.getOperand(i);
12973 if (isAllOnesConstant(Elt))
12974 Indices.push_back(i);
12975 else if (isNullConstant(Elt))
12976 Indices.push_back(NumElts+i);
12981 // Let's see if the target supports this vector_shuffle.
12982 EVT RVT = RHS.getValueType();
12983 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12986 // Return the new VECTOR_SHUFFLE node.
12987 EVT EltVT = RVT.getVectorElementType();
12988 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12989 DAG.getConstant(0, dl, EltVT));
12990 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12991 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12992 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12993 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12999 /// Visit a binary vector operation, like ADD.
13000 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13001 assert(N->getValueType(0).isVector() &&
13002 "SimplifyVBinOp only works on vectors!");
13004 SDValue LHS = N->getOperand(0);
13005 SDValue RHS = N->getOperand(1);
13007 if (SDValue Shuffle = XformToShuffleWithZero(N))
13010 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13012 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13013 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13014 // Check if both vectors are constants. If not bail out.
13015 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13016 cast<BuildVectorSDNode>(RHS)->isConstant()))
13019 SmallVector<SDValue, 8> Ops;
13020 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13021 SDValue LHSOp = LHS.getOperand(i);
13022 SDValue RHSOp = RHS.getOperand(i);
13024 // Can't fold divide by zero.
13025 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13026 N->getOpcode() == ISD::FDIV) {
13027 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13028 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13032 EVT VT = LHSOp.getValueType();
13033 EVT RVT = RHSOp.getValueType();
13035 // Integer BUILD_VECTOR operands may have types larger than the element
13036 // size (e.g., when the element type is not legal). Prior to type
13037 // legalization, the types may not match between the two BUILD_VECTORS.
13038 // Truncate one of the operands to make them match.
13039 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13040 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13042 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13046 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13048 if (FoldOp.getOpcode() != ISD::UNDEF &&
13049 FoldOp.getOpcode() != ISD::Constant &&
13050 FoldOp.getOpcode() != ISD::ConstantFP)
13052 Ops.push_back(FoldOp);
13053 AddToWorklist(FoldOp.getNode());
13056 if (Ops.size() == LHS.getNumOperands())
13057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13060 // Type legalization might introduce new shuffles in the DAG.
13061 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13062 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13063 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13064 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13065 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13066 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13067 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13068 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13070 if (SVN0->getMask().equals(SVN1->getMask())) {
13071 EVT VT = N->getValueType(0);
13072 SDValue UndefVector = LHS.getOperand(1);
13073 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13074 LHS.getOperand(0), RHS.getOperand(0));
13075 AddUsersToWorklist(N);
13076 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13077 &SVN0->getMask()[0]);
13084 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13085 SDValue N1, SDValue N2){
13086 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13088 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13089 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13091 // If we got a simplified select_cc node back from SimplifySelectCC, then
13092 // break it down into a new SETCC node, and a new SELECT node, and then return
13093 // the SELECT node, since we were called with a SELECT node.
13094 if (SCC.getNode()) {
13095 // Check to see if we got a select_cc back (to turn into setcc/select).
13096 // Otherwise, just return whatever node we got back, like fabs.
13097 if (SCC.getOpcode() == ISD::SELECT_CC) {
13098 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13100 SCC.getOperand(0), SCC.getOperand(1),
13101 SCC.getOperand(4));
13102 AddToWorklist(SETCC.getNode());
13103 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13104 SCC.getOperand(2), SCC.getOperand(3));
13112 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13113 /// being selected between, see if we can simplify the select. Callers of this
13114 /// should assume that TheSelect is deleted if this returns true. As such, they
13115 /// should return the appropriate thing (e.g. the node) back to the top-level of
13116 /// the DAG combiner loop to avoid it being looked at.
13117 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13120 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13121 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13122 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13123 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13124 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13125 SDValue Sqrt = RHS;
13128 const ConstantFPSDNode *NegZero = nullptr;
13130 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13131 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13132 CmpLHS = TheSelect->getOperand(0);
13133 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13135 // SELECT or VSELECT
13136 SDValue Cmp = TheSelect->getOperand(0);
13137 if (Cmp.getOpcode() == ISD::SETCC) {
13138 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13139 CmpLHS = Cmp.getOperand(0);
13140 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13143 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13144 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13145 CC == ISD::SETULT || CC == ISD::SETLT)) {
13146 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13147 CombineTo(TheSelect, Sqrt);
13152 // Cannot simplify select with vector condition
13153 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13155 // If this is a select from two identical things, try to pull the operation
13156 // through the select.
13157 if (LHS.getOpcode() != RHS.getOpcode() ||
13158 !LHS.hasOneUse() || !RHS.hasOneUse())
13161 // If this is a load and the token chain is identical, replace the select
13162 // of two loads with a load through a select of the address to load from.
13163 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13164 // constants have been dropped into the constant pool.
13165 if (LHS.getOpcode() == ISD::LOAD) {
13166 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13167 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13169 // Token chains must be identical.
13170 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13171 // Do not let this transformation reduce the number of volatile loads.
13172 LLD->isVolatile() || RLD->isVolatile() ||
13173 // FIXME: If either is a pre/post inc/dec load,
13174 // we'd need to split out the address adjustment.
13175 LLD->isIndexed() || RLD->isIndexed() ||
13176 // If this is an EXTLOAD, the VT's must match.
13177 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13178 // If this is an EXTLOAD, the kind of extension must match.
13179 (LLD->getExtensionType() != RLD->getExtensionType() &&
13180 // The only exception is if one of the extensions is anyext.
13181 LLD->getExtensionType() != ISD::EXTLOAD &&
13182 RLD->getExtensionType() != ISD::EXTLOAD) ||
13183 // FIXME: this discards src value information. This is
13184 // over-conservative. It would be beneficial to be able to remember
13185 // both potential memory locations. Since we are discarding
13186 // src value info, don't do the transformation if the memory
13187 // locations are not in the default address space.
13188 LLD->getPointerInfo().getAddrSpace() != 0 ||
13189 RLD->getPointerInfo().getAddrSpace() != 0 ||
13190 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13191 LLD->getBasePtr().getValueType()))
13194 // Check that the select condition doesn't reach either load. If so,
13195 // folding this will induce a cycle into the DAG. If not, this is safe to
13196 // xform, so create a select of the addresses.
13198 if (TheSelect->getOpcode() == ISD::SELECT) {
13199 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13200 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13201 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13203 // The loads must not depend on one another.
13204 if (LLD->isPredecessorOf(RLD) ||
13205 RLD->isPredecessorOf(LLD))
13207 Addr = DAG.getSelect(SDLoc(TheSelect),
13208 LLD->getBasePtr().getValueType(),
13209 TheSelect->getOperand(0), LLD->getBasePtr(),
13210 RLD->getBasePtr());
13211 } else { // Otherwise SELECT_CC
13212 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13213 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13215 if ((LLD->hasAnyUseOfValue(1) &&
13216 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13217 (RLD->hasAnyUseOfValue(1) &&
13218 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13221 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13222 LLD->getBasePtr().getValueType(),
13223 TheSelect->getOperand(0),
13224 TheSelect->getOperand(1),
13225 LLD->getBasePtr(), RLD->getBasePtr(),
13226 TheSelect->getOperand(4));
13230 // It is safe to replace the two loads if they have different alignments,
13231 // but the new load must be the minimum (most restrictive) alignment of the
13233 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13234 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13235 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13236 Load = DAG.getLoad(TheSelect->getValueType(0),
13238 // FIXME: Discards pointer and AA info.
13239 LLD->getChain(), Addr, MachinePointerInfo(),
13240 LLD->isVolatile(), LLD->isNonTemporal(),
13241 isInvariant, Alignment);
13243 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13244 RLD->getExtensionType() : LLD->getExtensionType(),
13246 TheSelect->getValueType(0),
13247 // FIXME: Discards pointer and AA info.
13248 LLD->getChain(), Addr, MachinePointerInfo(),
13249 LLD->getMemoryVT(), LLD->isVolatile(),
13250 LLD->isNonTemporal(), isInvariant, Alignment);
13253 // Users of the select now use the result of the load.
13254 CombineTo(TheSelect, Load);
13256 // Users of the old loads now use the new load's chain. We know the
13257 // old-load value is dead now.
13258 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13259 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13266 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13267 /// where 'cond' is the comparison specified by CC.
13268 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13269 SDValue N2, SDValue N3,
13270 ISD::CondCode CC, bool NotExtCompare) {
13271 // (x ? y : y) -> y.
13272 if (N2 == N3) return N2;
13274 EVT VT = N2.getValueType();
13275 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13276 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13278 // Determine if the condition we're dealing with is constant
13279 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13280 N0, N1, CC, DL, false);
13281 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13283 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13284 // fold select_cc true, x, y -> x
13285 // fold select_cc false, x, y -> y
13286 return !SCCC->isNullValue() ? N2 : N3;
13289 // Check to see if we can simplify the select into an fabs node
13290 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13291 // Allow either -0.0 or 0.0
13292 if (CFP->isZero()) {
13293 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13294 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13295 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13296 N2 == N3.getOperand(0))
13297 return DAG.getNode(ISD::FABS, DL, VT, N0);
13299 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13300 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13301 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13302 N2.getOperand(0) == N3)
13303 return DAG.getNode(ISD::FABS, DL, VT, N3);
13307 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13308 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13309 // in it. This is a win when the constant is not otherwise available because
13310 // it replaces two constant pool loads with one. We only do this if the FP
13311 // type is known to be legal, because if it isn't, then we are before legalize
13312 // types an we want the other legalization to happen first (e.g. to avoid
13313 // messing with soft float) and if the ConstantFP is not legal, because if
13314 // it is legal, we may not need to store the FP constant in a constant pool.
13315 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13316 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13317 if (TLI.isTypeLegal(N2.getValueType()) &&
13318 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13319 TargetLowering::Legal &&
13320 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13321 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13322 // If both constants have multiple uses, then we won't need to do an
13323 // extra load, they are likely around in registers for other users.
13324 (TV->hasOneUse() || FV->hasOneUse())) {
13325 Constant *Elts[] = {
13326 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13327 const_cast<ConstantFP*>(TV->getConstantFPValue())
13329 Type *FPTy = Elts[0]->getType();
13330 const DataLayout &TD = *TLI.getDataLayout();
13332 // Create a ConstantArray of the two constants.
13333 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13334 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13335 TD.getPrefTypeAlignment(FPTy));
13336 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13338 // Get the offsets to the 0 and 1 element of the array so that we can
13339 // select between them.
13340 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13341 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13342 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13344 SDValue Cond = DAG.getSetCC(DL,
13345 getSetCCResultType(N0.getValueType()),
13347 AddToWorklist(Cond.getNode());
13348 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13350 AddToWorklist(CstOffset.getNode());
13351 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13353 AddToWorklist(CPIdx.getNode());
13354 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13355 MachinePointerInfo::getConstantPool(), false,
13356 false, false, Alignment);
13360 // Check to see if we can perform the "gzip trick", transforming
13361 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13362 if (isNullConstant(N3) && CC == ISD::SETLT &&
13363 (isNullConstant(N1) || // (a < 0) ? b : 0
13364 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13365 EVT XType = N0.getValueType();
13366 EVT AType = N2.getValueType();
13367 if (XType.bitsGE(AType)) {
13368 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13369 // single-bit constant.
13370 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13371 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13372 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13373 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13374 getShiftAmountTy(N0.getValueType()));
13375 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13377 AddToWorklist(Shift.getNode());
13379 if (XType.bitsGT(AType)) {
13380 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13381 AddToWorklist(Shift.getNode());
13384 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13387 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13389 DAG.getConstant(XType.getSizeInBits() - 1,
13391 getShiftAmountTy(N0.getValueType())));
13392 AddToWorklist(Shift.getNode());
13394 if (XType.bitsGT(AType)) {
13395 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13396 AddToWorklist(Shift.getNode());
13399 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13403 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13404 // where y is has a single bit set.
13405 // A plaintext description would be, we can turn the SELECT_CC into an AND
13406 // when the condition can be materialized as an all-ones register. Any
13407 // single bit-test can be materialized as an all-ones register with
13408 // shift-left and shift-right-arith.
13409 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13410 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13411 SDValue AndLHS = N0->getOperand(0);
13412 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13413 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13414 // Shift the tested bit over the sign bit.
13415 APInt AndMask = ConstAndRHS->getAPIntValue();
13417 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13418 getShiftAmountTy(AndLHS.getValueType()));
13419 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13421 // Now arithmetic right shift it all the way over, so the result is either
13422 // all-ones, or zero.
13424 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13425 getShiftAmountTy(Shl.getValueType()));
13426 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13428 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13432 // fold select C, 16, 0 -> shl C, 4
13433 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13434 TLI.getBooleanContents(N0.getValueType()) ==
13435 TargetLowering::ZeroOrOneBooleanContent) {
13437 // If the caller doesn't want us to simplify this into a zext of a compare,
13439 if (NotExtCompare && N2C->isOne())
13442 // Get a SetCC of the condition
13443 // NOTE: Don't create a SETCC if it's not legal on this target.
13444 if (!LegalOperations ||
13445 TLI.isOperationLegal(ISD::SETCC,
13446 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13448 // cast from setcc result type to select result type
13450 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13452 if (N2.getValueType().bitsLT(SCC.getValueType()))
13453 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13454 N2.getValueType());
13456 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13457 N2.getValueType(), SCC);
13459 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13460 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13461 N2.getValueType(), SCC);
13464 AddToWorklist(SCC.getNode());
13465 AddToWorklist(Temp.getNode());
13470 // shl setcc result by log2 n2c
13471 return DAG.getNode(
13472 ISD::SHL, DL, N2.getValueType(), Temp,
13473 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13474 getShiftAmountTy(Temp.getValueType())));
13478 // Check to see if this is the equivalent of setcc
13479 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13480 // otherwise, go ahead with the folds.
13481 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13482 EVT XType = N0.getValueType();
13483 if (!LegalOperations ||
13484 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13485 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13486 if (Res.getValueType() != VT)
13487 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13491 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13492 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13493 (!LegalOperations ||
13494 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13495 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13496 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13497 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13499 getShiftAmountTy(Ctlz.getValueType())));
13501 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13502 if (isNullConstant(N1) && CC == ISD::SETGT) {
13504 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13505 XType, DAG.getConstant(0, DL, XType), N0);
13506 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13507 return DAG.getNode(ISD::SRL, DL, XType,
13508 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13509 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13510 getShiftAmountTy(XType)));
13512 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13513 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13515 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13516 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13517 getShiftAmountTy(N0.getValueType())));
13518 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13523 // Check to see if this is an integer abs.
13524 // select_cc setg[te] X, 0, X, -X ->
13525 // select_cc setgt X, -1, X, -X ->
13526 // select_cc setl[te] X, 0, -X, X ->
13527 // select_cc setlt X, 1, -X, X ->
13528 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13530 ConstantSDNode *SubC = nullptr;
13531 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13532 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13533 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13534 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13535 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13536 (N1C->isOne() && CC == ISD::SETLT)) &&
13537 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13538 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13540 EVT XType = N0.getValueType();
13541 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13543 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13545 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13546 getShiftAmountTy(N0.getValueType())));
13547 SDValue Add = DAG.getNode(ISD::ADD, DL,
13549 AddToWorklist(Shift.getNode());
13550 AddToWorklist(Add.getNode());
13551 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13558 /// This is a stub for TargetLowering::SimplifySetCC.
13559 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13560 SDValue N1, ISD::CondCode Cond,
13561 SDLoc DL, bool foldBooleans) {
13562 TargetLowering::DAGCombinerInfo
13563 DagCombineInfo(DAG, Level, false, this);
13564 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13567 /// Given an ISD::SDIV node expressing a divide by constant, return
13568 /// a DAG expression to select that will generate the same value by multiplying
13569 /// by a magic number.
13570 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13571 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13572 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13576 // Avoid division by zero.
13577 if (C->isNullValue())
13580 std::vector<SDNode*> Built;
13582 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13584 for (SDNode *N : Built)
13589 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13590 /// DAG expression that will generate the same value by right shifting.
13591 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13592 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13596 // Avoid division by zero.
13597 if (C->isNullValue())
13600 std::vector<SDNode *> Built;
13601 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13603 for (SDNode *N : Built)
13608 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13609 /// expression that will generate the same value by multiplying by a magic
13611 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13612 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13613 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13617 // Avoid division by zero.
13618 if (C->isNullValue())
13621 std::vector<SDNode*> Built;
13623 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13625 for (SDNode *N : Built)
13630 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13631 if (Level >= AfterLegalizeDAG)
13634 // Expose the DAG combiner to the target combiner implementations.
13635 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13637 unsigned Iterations = 0;
13638 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13640 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13641 // For the reciprocal, we need to find the zero of the function:
13642 // F(X) = A X - 1 [which has a zero at X = 1/A]
13644 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13645 // does not require additional intermediate precision]
13646 EVT VT = Op.getValueType();
13648 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13650 AddToWorklist(Est.getNode());
13652 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13653 for (unsigned i = 0; i < Iterations; ++i) {
13654 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13655 AddToWorklist(NewEst.getNode());
13657 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13658 AddToWorklist(NewEst.getNode());
13660 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13661 AddToWorklist(NewEst.getNode());
13663 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13664 AddToWorklist(Est.getNode());
13673 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13674 /// For the reciprocal sqrt, we need to find the zero of the function:
13675 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13677 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13678 /// As a result, we precompute A/2 prior to the iteration loop.
13679 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13680 unsigned Iterations) {
13681 EVT VT = Arg.getValueType();
13683 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13685 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13686 // this entire sequence requires only one FP constant.
13687 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13688 AddToWorklist(HalfArg.getNode());
13690 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13691 AddToWorklist(HalfArg.getNode());
13693 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13694 for (unsigned i = 0; i < Iterations; ++i) {
13695 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13696 AddToWorklist(NewEst.getNode());
13698 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13699 AddToWorklist(NewEst.getNode());
13701 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13702 AddToWorklist(NewEst.getNode());
13704 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13705 AddToWorklist(Est.getNode());
13710 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13711 /// For the reciprocal sqrt, we need to find the zero of the function:
13712 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13714 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13715 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13716 unsigned Iterations) {
13717 EVT VT = Arg.getValueType();
13719 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13720 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13722 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13723 for (unsigned i = 0; i < Iterations; ++i) {
13724 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13725 AddToWorklist(HalfEst.getNode());
13727 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13728 AddToWorklist(Est.getNode());
13730 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13731 AddToWorklist(Est.getNode());
13733 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13734 AddToWorklist(Est.getNode());
13736 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13737 AddToWorklist(Est.getNode());
13742 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13743 if (Level >= AfterLegalizeDAG)
13746 // Expose the DAG combiner to the target combiner implementations.
13747 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13748 unsigned Iterations = 0;
13749 bool UseOneConstNR = false;
13750 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13751 AddToWorklist(Est.getNode());
13753 Est = UseOneConstNR ?
13754 BuildRsqrtNROneConst(Op, Est, Iterations) :
13755 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13763 /// Return true if base is a frame index, which is known not to alias with
13764 /// anything but itself. Provides base object and offset as results.
13765 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13766 const GlobalValue *&GV, const void *&CV) {
13767 // Assume it is a primitive operation.
13768 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13770 // If it's an adding a simple constant then integrate the offset.
13771 if (Base.getOpcode() == ISD::ADD) {
13772 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13773 Base = Base.getOperand(0);
13774 Offset += C->getZExtValue();
13778 // Return the underlying GlobalValue, and update the Offset. Return false
13779 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13780 // by multiple nodes with different offsets.
13781 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13782 GV = G->getGlobal();
13783 Offset += G->getOffset();
13787 // Return the underlying Constant value, and update the Offset. Return false
13788 // for ConstantSDNodes since the same constant pool entry may be represented
13789 // by multiple nodes with different offsets.
13790 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13791 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13792 : (const void *)C->getConstVal();
13793 Offset += C->getOffset();
13796 // If it's any of the following then it can't alias with anything but itself.
13797 return isa<FrameIndexSDNode>(Base);
13800 /// Return true if there is any possibility that the two addresses overlap.
13801 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13802 // If they are the same then they must be aliases.
13803 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13805 // If they are both volatile then they cannot be reordered.
13806 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13808 // Gather base node and offset information.
13809 SDValue Base1, Base2;
13810 int64_t Offset1, Offset2;
13811 const GlobalValue *GV1, *GV2;
13812 const void *CV1, *CV2;
13813 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13814 Base1, Offset1, GV1, CV1);
13815 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13816 Base2, Offset2, GV2, CV2);
13818 // If they have a same base address then check to see if they overlap.
13819 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13820 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13821 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13823 // It is possible for different frame indices to alias each other, mostly
13824 // when tail call optimization reuses return address slots for arguments.
13825 // To catch this case, look up the actual index of frame indices to compute
13826 // the real alias relationship.
13827 if (isFrameIndex1 && isFrameIndex2) {
13828 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13829 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13830 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13831 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13832 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13835 // Otherwise, if we know what the bases are, and they aren't identical, then
13836 // we know they cannot alias.
13837 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13840 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13841 // compared to the size and offset of the access, we may be able to prove they
13842 // do not alias. This check is conservative for now to catch cases created by
13843 // splitting vector types.
13844 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13845 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13846 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13847 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13848 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13849 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13850 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13852 // There is no overlap between these relatively aligned accesses of similar
13853 // size, return no alias.
13854 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13855 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13859 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13861 : DAG.getSubtarget().useAA();
13863 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13864 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13868 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13869 // Use alias analysis information.
13870 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13871 Op1->getSrcValueOffset());
13872 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13873 Op0->getSrcValueOffset() - MinOffset;
13874 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13875 Op1->getSrcValueOffset() - MinOffset;
13876 AliasAnalysis::AliasResult AAResult =
13877 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13879 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13880 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13882 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13883 if (AAResult == AliasAnalysis::NoAlias)
13887 // Otherwise we have to assume they alias.
13891 /// Walk up chain skipping non-aliasing memory nodes,
13892 /// looking for aliasing nodes and adding them to the Aliases vector.
13893 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13894 SmallVectorImpl<SDValue> &Aliases) {
13895 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13896 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13898 // Get alias information for node.
13899 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13902 Chains.push_back(OriginalChain);
13903 unsigned Depth = 0;
13905 // Look at each chain and determine if it is an alias. If so, add it to the
13906 // aliases list. If not, then continue up the chain looking for the next
13908 while (!Chains.empty()) {
13909 SDValue Chain = Chains.back();
13912 // For TokenFactor nodes, look at each operand and only continue up the
13913 // chain until we find two aliases. If we've seen two aliases, assume we'll
13914 // find more and revert to original chain since the xform is unlikely to be
13917 // FIXME: The depth check could be made to return the last non-aliasing
13918 // chain we found before we hit a tokenfactor rather than the original
13920 if (Depth > 6 || Aliases.size() == 2) {
13922 Aliases.push_back(OriginalChain);
13926 // Don't bother if we've been before.
13927 if (!Visited.insert(Chain.getNode()).second)
13930 switch (Chain.getOpcode()) {
13931 case ISD::EntryToken:
13932 // Entry token is ideal chain operand, but handled in FindBetterChain.
13937 // Get alias information for Chain.
13938 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13939 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13941 // If chain is alias then stop here.
13942 if (!(IsLoad && IsOpLoad) &&
13943 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13944 Aliases.push_back(Chain);
13946 // Look further up the chain.
13947 Chains.push_back(Chain.getOperand(0));
13953 case ISD::TokenFactor:
13954 // We have to check each of the operands of the token factor for "small"
13955 // token factors, so we queue them up. Adding the operands to the queue
13956 // (stack) in reverse order maintains the original order and increases the
13957 // likelihood that getNode will find a matching token factor (CSE.)
13958 if (Chain.getNumOperands() > 16) {
13959 Aliases.push_back(Chain);
13962 for (unsigned n = Chain.getNumOperands(); n;)
13963 Chains.push_back(Chain.getOperand(--n));
13968 // For all other instructions we will just have to take what we can get.
13969 Aliases.push_back(Chain);
13974 // We need to be careful here to also search for aliases through the
13975 // value operand of a store, etc. Consider the following situation:
13977 // L1 = load Token1, %52
13978 // S1 = store Token1, L1, %51
13979 // L2 = load Token1, %52+8
13980 // S2 = store Token1, L2, %51+8
13981 // Token2 = Token(S1, S2)
13982 // L3 = load Token2, %53
13983 // S3 = store Token2, L3, %52
13984 // L4 = load Token2, %53+8
13985 // S4 = store Token2, L4, %52+8
13986 // If we search for aliases of S3 (which loads address %52), and we look
13987 // only through the chain, then we'll miss the trivial dependence on L1
13988 // (which also loads from %52). We then might change all loads and
13989 // stores to use Token1 as their chain operand, which could result in
13990 // copying %53 into %52 before copying %52 into %51 (which should
13993 // The problem is, however, that searching for such data dependencies
13994 // can become expensive, and the cost is not directly related to the
13995 // chain depth. Instead, we'll rule out such configurations here by
13996 // insisting that we've visited all chain users (except for users
13997 // of the original chain, which is not necessary). When doing this,
13998 // we need to look through nodes we don't care about (otherwise, things
13999 // like register copies will interfere with trivial cases).
14001 SmallVector<const SDNode *, 16> Worklist;
14002 for (const SDNode *N : Visited)
14003 if (N != OriginalChain.getNode())
14004 Worklist.push_back(N);
14006 while (!Worklist.empty()) {
14007 const SDNode *M = Worklist.pop_back_val();
14009 // We have already visited M, and want to make sure we've visited any uses
14010 // of M that we care about. For uses that we've not visisted, and don't
14011 // care about, queue them to the worklist.
14013 for (SDNode::use_iterator UI = M->use_begin(),
14014 UIE = M->use_end(); UI != UIE; ++UI)
14015 if (UI.getUse().getValueType() == MVT::Other &&
14016 Visited.insert(*UI).second) {
14017 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14018 // We've not visited this use, and we care about it (it could have an
14019 // ordering dependency with the original node).
14021 Aliases.push_back(OriginalChain);
14025 // We've not visited this use, but we don't care about it. Mark it as
14026 // visited and enqueue it to the worklist.
14027 Worklist.push_back(*UI);
14032 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14033 /// (aliasing node.)
14034 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14035 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14037 // Accumulate all the aliases to this node.
14038 GatherAllAliases(N, OldChain, Aliases);
14040 // If no operands then chain to entry token.
14041 if (Aliases.size() == 0)
14042 return DAG.getEntryNode();
14044 // If a single operand then chain to it. We don't need to revisit it.
14045 if (Aliases.size() == 1)
14048 // Construct a custom tailored token factor.
14049 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14052 /// This is the entry point for the file.
14053 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14054 CodeGenOpt::Level OptLevel) {
14055 /// This is the main entry point to this class.
14056 DAGCombiner(*this, AA, OptLevel).Run(Level);