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 visitCTLZ(SDNode *N);
259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTTZ(SDNode *N);
261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
264 SDValue visitVSELECT(SDNode *N);
265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
272 SDValue visitBITCAST(SDNode *N);
273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
277 SDValue visitFMA(SDNode *N);
278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
280 SDValue visitFSQRT(SDNode *N);
281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
310 SDValue visitFP_TO_FP16(SDNode *N);
312 SDValue visitFADDForFMACombine(SDNode *N);
313 SDValue visitFSUBForFMACombine(SDNode *N);
315 SDValue XformToShuffleWithZero(SDNode *N);
316 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
318 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
320 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324 SDValue N3, ISD::CondCode CC,
325 bool NotExtCompare = false);
326 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327 SDLoc DL, bool foldBooleans = true);
329 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
331 bool isOneUseSetCC(SDValue N) const;
333 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
335 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336 SDValue CombineExtLoad(SDNode *N);
337 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338 SDValue BuildSDIV(SDNode *N);
339 SDValue BuildSDIVPow2(SDNode *N);
340 SDValue BuildUDIV(SDNode *N);
341 SDValue BuildReciprocalEstimate(SDValue Op);
342 SDValue BuildRsqrtEstimate(SDValue Op);
343 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346 bool DemandHighBits = true);
347 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349 SDValue InnerPos, SDValue InnerNeg,
350 unsigned PosOpcode, unsigned NegOpcode,
352 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353 SDValue ReduceLoadWidth(SDNode *N);
354 SDValue ReduceLoadOpStoreWidth(SDNode *N);
355 SDValue TransformFPLoadStorePair(SDNode *N);
356 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
359 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
361 /// Walk up chain skipping non-aliasing memory nodes,
362 /// looking for aliasing nodes and adding them to the Aliases vector.
363 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364 SmallVectorImpl<SDValue> &Aliases);
366 /// Return true if there is any possibility that the two addresses overlap.
367 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
369 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370 /// chain (aliasing node.)
371 SDValue FindBetterChain(SDNode *N, SDValue Chain);
373 /// Holds a pointer to an LSBaseSDNode as well as information on where it
374 /// is located in a sequence of memory operations connected by a chain.
376 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378 // Ptr to the mem node.
379 LSBaseSDNode *MemNode;
380 // Offset from the base ptr.
381 int64_t OffsetFromBase;
382 // What is the sequence number of this mem node.
383 // Lowest mem operand in the DAG starts at zero.
384 unsigned SequenceNum;
387 /// This is a helper function for MergeConsecutiveStores. When the source
388 /// elements of the consecutive stores are all constants or all extracted
389 /// vector elements, try to merge them into one larger store.
390 /// \return True if a merged store was created.
391 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392 EVT MemVT, unsigned NumElem,
393 bool IsConstantSrc, bool UseVector);
395 /// Merge consecutive store operations into a wide store.
396 /// This optimization uses wide integers or vectors when possible.
397 /// \return True if some memory operations were changed.
398 bool MergeConsecutiveStores(StoreSDNode *N);
400 /// \brief Try to transform a truncation where C is a constant:
401 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
403 /// \p N needs to be a truncation and its first operand an AND. Other
404 /// requirements are checked by the function (e.g. that trunc is
405 /// single-use) and if missed an empty SDValue is returned.
406 SDValue distributeTruncateThroughAnd(SDNode *N);
409 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412 auto *F = DAG.getMachineFunction().getFunction();
413 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414 F->hasFnAttribute(Attribute::MinSize);
417 /// Runs the dag combiner on all nodes in the work list
418 void Run(CombineLevel AtLevel);
420 SelectionDAG &getDAG() const { return DAG; }
422 /// Returns a type large enough to hold any valid shift amount - before type
423 /// legalization these can be huge.
424 EVT getShiftAmountTy(EVT LHSTy) {
425 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426 if (LHSTy.isVector())
428 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429 : TLI.getPointerTy();
432 /// This method returns true if we are running before type legalization or
433 /// if the specified VT is legal.
434 bool isTypeLegal(const EVT &VT) {
435 if (!LegalTypes) return true;
436 return TLI.isTypeLegal(VT);
439 /// Convenience wrapper around TargetLowering::getSetCCResultType
440 EVT getSetCCResultType(EVT VT) const {
441 return TLI.getSetCCResultType(*DAG.getContext(), VT);
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453 explicit WorklistRemover(DAGCombiner &dc)
454 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
456 void NodeDeleted(SDNode *N, SDNode *E) override {
457 DC.removeFromWorklist(N);
462 //===----------------------------------------------------------------------===//
463 // TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467 ((DAGCombiner*)DC)->AddToWorklist(N);
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471 ((DAGCombiner*)DC)->removeFromWorklist(N);
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 //===----------------------------------------------------------------------===//
497 //===----------------------------------------------------------------------===//
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500 removeFromWorklist(N);
502 // If the operands of this node are only used by the node, they will now be
503 // dead. Make sure to re-visit them and recursively delete dead nodes.
504 for (const SDValue &Op : N->ops())
505 // For an operand generating multiple values, one of the values may
506 // become dead allowing further simplification (e.g. split index
507 // arithmetic from an indexed load).
508 if (Op->hasOneUse() || Op->getNumValues() > 1)
509 AddToWorklist(Op.getNode());
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518 const TargetLowering &TLI,
519 const TargetOptions *Options,
520 unsigned Depth = 0) {
521 // fneg is removable even if it has multiple uses.
522 if (Op.getOpcode() == ISD::FNEG) return 2;
524 // Don't allow anything with multiple uses.
525 if (!Op.hasOneUse()) return 0;
527 // Don't recurse exponentially.
528 if (Depth > 6) return 0;
530 switch (Op.getOpcode()) {
531 default: return false;
532 case ISD::ConstantFP:
533 // Don't invert constant FP values after legalize. The negated constant
534 // isn't necessarily legal.
535 return LegalOperations ? 0 : 1;
537 // FIXME: determine better conditions for this xform.
538 if (!Options->UnsafeFPMath) return 0;
540 // After operation legalization, it might not be legal to create new FSUBs.
541 if (LegalOperations &&
542 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
545 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553 // We can't turn -(A-B) into B-A when we honor signed zeros.
554 if (!Options->UnsafeFPMath) return 0;
556 // fold (fneg (fsub A, B)) -> (fsub B, A)
561 if (Options->HonorSignDependentRoundingFPMath()) return 0;
563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
574 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581 bool LegalOperations, unsigned Depth = 0) {
582 const TargetOptions &Options = DAG.getTarget().Options;
583 // fneg is removable even if it has multiple uses.
584 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
586 // Don't allow anything with multiple uses.
587 assert(Op.hasOneUse() && "Unknown reuse!");
589 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590 switch (Op.getOpcode()) {
591 default: llvm_unreachable("Unknown code");
592 case ISD::ConstantFP: {
593 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
595 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598 // FIXME: determine better conditions for this xform.
599 assert(Options.UnsafeFPMath);
601 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603 DAG.getTargetLoweringInfo(), &Options, Depth+1))
604 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605 GetNegatedExpression(Op.getOperand(0), DAG,
606 LegalOperations, Depth+1),
608 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610 GetNegatedExpression(Op.getOperand(1), DAG,
611 LegalOperations, Depth+1),
614 // We can't turn -(A-B) into B-A when we honor signed zeros.
615 assert(Options.UnsafeFPMath);
617 // fold (fneg (fsub 0, B)) -> B
618 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619 if (N0CFP->getValueAPF().isZero())
620 return Op.getOperand(1);
622 // fold (fneg (fsub A, B)) -> (fsub B, A)
623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624 Op.getOperand(1), Op.getOperand(0));
628 assert(!Options.HonorSignDependentRoundingFPMath());
630 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632 DAG.getTargetLoweringInfo(), &Options, Depth+1))
633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634 GetNegatedExpression(Op.getOperand(0), DAG,
635 LegalOperations, Depth+1),
638 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
641 GetNegatedExpression(Op.getOperand(1), DAG,
642 LegalOperations, Depth+1));
646 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(0), DAG,
648 LegalOperations, Depth+1));
650 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651 GetNegatedExpression(Op.getOperand(0), DAG,
652 LegalOperations, Depth+1),
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
664 if (N.getOpcode() == ISD::SETCC) {
665 LHS = N.getOperand(0);
666 RHS = N.getOperand(1);
667 CC = N.getOperand(2);
671 if (N.getOpcode() != ISD::SELECT_CC ||
672 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676 if (TLI.getBooleanContents(N.getValueType()) ==
677 TargetLowering::UndefinedBooleanContent)
680 LHS = N.getOperand(0);
681 RHS = N.getOperand(1);
682 CC = N.getOperand(4);
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
691 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
704 unsigned SplatBitSize;
706 EVT EltVT = N->getValueType(0).getVectorElementType();
707 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
709 EltVT.getSizeInBits() >= SplatBitSize);
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715 if (isa<ConstantSDNode>(N))
717 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725 if (isa<ConstantFPSDNode>(N))
727 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739 BitVector UndefElements;
740 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
742 // BuildVectors can truncate their operands. Ignore that case here.
743 // FIXME: We blindly ignore splats which include undef which is overly
745 if (CN && UndefElements.none() &&
746 CN->getValueType(0) == N.getValueType().getScalarType())
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760 BitVector UndefElements;
761 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
763 if (CN && UndefElements.none())
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771 SDValue N0, SDValue N1) {
772 EVT VT = N0.getValueType();
773 if (N0.getOpcode() == Opc) {
774 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
778 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781 if (N0.hasOneUse()) {
782 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
784 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785 if (!OpNode.getNode())
787 AddToWorklist(OpNode.getNode());
788 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
793 if (N1.getOpcode() == Opc) {
794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
798 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801 if (N1.hasOneUse()) {
802 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
804 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805 if (!OpNode.getNode())
807 AddToWorklist(OpNode.getNode());
808 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
818 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
820 DEBUG(dbgs() << "\nReplacing.1 ";
822 dbgs() << "\nWith: ";
823 To[0].getNode()->dump(&DAG);
824 dbgs() << " and " << NumTo-1 << " other values\n");
825 for (unsigned i = 0, e = NumTo; i != e; ++i)
826 assert((!To[i].getNode() ||
827 N->getValueType(i) == To[i].getValueType()) &&
828 "Cannot combine value to value of different type!");
830 WorklistRemover DeadNodes(*this);
831 DAG.ReplaceAllUsesWith(N, To);
833 // Push the new nodes and any users onto the worklist
834 for (unsigned i = 0, e = NumTo; i != e; ++i) {
835 if (To[i].getNode()) {
836 AddToWorklist(To[i].getNode());
837 AddUsersToWorklist(To[i].getNode());
842 // Finally, if the node is now dead, remove it from the graph. The node
843 // may not be dead if the replacement process recursively simplified to
844 // something else needing this node.
846 deleteAndRecombine(N);
847 return SDValue(N, 0);
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852 // Replace all uses. If any nodes become isomorphic to other nodes and
853 // are deleted, make sure to remove them from our worklist.
854 WorklistRemover DeadNodes(*this);
855 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
857 // Push the new node and any (possibly new) users onto the worklist.
858 AddToWorklist(TLO.New.getNode());
859 AddUsersToWorklist(TLO.New.getNode());
861 // Finally, if the node is now dead, remove it from the graph. The node
862 // may not be dead if the replacement process recursively simplified to
863 // something else needing this node.
864 if (TLO.Old.getNode()->use_empty())
865 deleteAndRecombine(TLO.Old.getNode());
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872 APInt KnownZero, KnownOne;
873 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
877 AddToWorklist(Op.getNode());
879 // Replace the old value with the new one.
881 DEBUG(dbgs() << "\nReplacing.2 ";
882 TLO.Old.getNode()->dump(&DAG);
883 dbgs() << "\nWith: ";
884 TLO.New.getNode()->dump(&DAG);
887 CommitTargetLoweringOpt(TLO);
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
893 EVT VT = Load->getValueType(0);
894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
896 DEBUG(dbgs() << "\nReplacing.9 ";
898 dbgs() << "\nWith: ";
899 Trunc.getNode()->dump(&DAG);
901 WorklistRemover DeadNodes(*this);
902 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904 deleteAndRecombine(Load);
905 AddToWorklist(Trunc.getNode());
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912 EVT MemVT = LD->getMemoryVT();
913 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
916 : LD->getExtensionType();
918 return DAG.getExtLoad(ExtType, dl, PVT,
919 LD->getChain(), LD->getBasePtr(),
920 MemVT, LD->getMemOperand());
923 unsigned Opc = Op.getOpcode();
926 case ISD::AssertSext:
927 return DAG.getNode(ISD::AssertSext, dl, PVT,
928 SExtPromoteOperand(Op.getOperand(0), PVT),
930 case ISD::AssertZext:
931 return DAG.getNode(ISD::AssertZext, dl, PVT,
932 ZExtPromoteOperand(Op.getOperand(0), PVT),
934 case ISD::Constant: {
936 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937 return DAG.getNode(ExtOpc, dl, PVT, Op);
941 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
943 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
949 EVT OldVT = Op.getValueType();
951 bool Replace = false;
952 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953 if (!NewOp.getNode())
955 AddToWorklist(NewOp.getNode());
958 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960 DAG.getValueType(OldVT));
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964 EVT OldVT = Op.getValueType();
966 bool Replace = false;
967 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968 if (!NewOp.getNode())
970 AddToWorklist(NewOp.getNode());
973 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981 if (!LegalOperations)
984 EVT VT = Op.getValueType();
985 if (VT.isVector() || !VT.isInteger())
988 // If operation type is 'undesirable', e.g. i16 on x86, consider
990 unsigned Opc = Op.getOpcode();
991 if (TLI.isTypeDesirableForOp(Opc, VT))
995 // Consult target whether it is a good idea to promote this operation and
996 // what's the right type to promote it to.
997 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998 assert(PVT != VT && "Don't know what type to promote to!");
1000 bool Replace0 = false;
1001 SDValue N0 = Op.getOperand(0);
1002 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1006 bool Replace1 = false;
1007 SDValue N1 = Op.getOperand(1);
1012 NN1 = PromoteOperand(N1, PVT, Replace1);
1017 AddToWorklist(NN0.getNode());
1019 AddToWorklist(NN1.getNode());
1022 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1024 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1026 DEBUG(dbgs() << "\nPromoting ";
1027 Op.getNode()->dump(&DAG));
1029 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039 if (!LegalOperations)
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1058 bool Replace = false;
1059 SDValue N0 = Op.getOperand(0);
1060 if (Opc == ISD::SRA)
1061 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062 else if (Opc == ISD::SRL)
1063 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1065 N0 = PromoteOperand(N0, PVT, Replace);
1069 AddToWorklist(N0.getNode());
1071 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1073 DEBUG(dbgs() << "\nPromoting ";
1074 Op.getNode()->dump(&DAG));
1076 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083 if (!LegalOperations)
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1101 // fold (aext (aext x)) -> (aext x)
1102 // fold (aext (zext x)) -> (zext x)
1103 // fold (aext (sext x)) -> (sext x)
1104 DEBUG(dbgs() << "\nPromoting ";
1105 Op.getNode()->dump(&DAG));
1106 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112 if (!LegalOperations)
1115 EVT VT = Op.getValueType();
1116 if (VT.isVector() || !VT.isInteger())
1119 // If operation type is 'undesirable', e.g. i16 on x86, consider
1121 unsigned Opc = Op.getOpcode();
1122 if (TLI.isTypeDesirableForOp(Opc, VT))
1126 // Consult target whether it is a good idea to promote this operation and
1127 // what's the right type to promote it to.
1128 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129 assert(PVT != VT && "Don't know what type to promote to!");
1132 SDNode *N = Op.getNode();
1133 LoadSDNode *LD = cast<LoadSDNode>(N);
1134 EVT MemVT = LD->getMemoryVT();
1135 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1138 : LD->getExtensionType();
1139 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140 LD->getChain(), LD->getBasePtr(),
1141 MemVT, LD->getMemOperand());
1142 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1144 DEBUG(dbgs() << "\nPromoting ";
1147 Result.getNode()->dump(&DAG);
1149 WorklistRemover DeadNodes(*this);
1150 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152 deleteAndRecombine(N);
1153 AddToWorklist(Result.getNode());
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166 if (!N->use_empty())
1169 SmallSetVector<SDNode *, 16> Nodes;
1172 N = Nodes.pop_back_val();
1176 if (N->use_empty()) {
1177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178 Nodes.insert(N->getOperand(i).getNode());
1180 removeFromWorklist(N);
1185 } while (!Nodes.empty());
1189 //===----------------------------------------------------------------------===//
1190 // Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194 // set the instance variables, so that the various visit routines may use it.
1196 LegalOperations = Level >= AfterLegalizeVectorOps;
1197 LegalTypes = Level >= AfterLegalizeTypes;
1199 // Add all the dag nodes to the worklist.
1200 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201 E = DAG.allnodes_end(); I != E; ++I)
1204 // Create a dummy node (which is not added to allnodes), that adds a reference
1205 // to the root node, preventing it from being deleted, and tracking any
1206 // changes of the root.
1207 HandleSDNode Dummy(DAG.getRoot());
1209 // while the worklist isn't empty, find a node and
1210 // try and combine it.
1211 while (!WorklistMap.empty()) {
1213 // The Worklist holds the SDNodes in order, but it may contain null entries.
1215 N = Worklist.pop_back_val();
1218 bool GoodWorklistEntry = WorklistMap.erase(N);
1219 (void)GoodWorklistEntry;
1220 assert(GoodWorklistEntry &&
1221 "Found a worklist entry without a corresponding map entry!");
1223 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1224 // N is deleted from the DAG, since they too may now be dead or may have a
1225 // reduced number of uses, allowing other xforms.
1226 if (recursivelyDeleteUnusedNodes(N))
1229 WorklistRemover DeadNodes(*this);
1231 // If this combine is running after legalizing the DAG, re-legalize any
1232 // nodes pulled off the worklist.
1233 if (Level == AfterLegalizeDAG) {
1234 SmallSetVector<SDNode *, 16> UpdatedNodes;
1235 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1237 for (SDNode *LN : UpdatedNodes) {
1239 AddUsersToWorklist(LN);
1245 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1247 // Add any operands of the new node which have not yet been combined to the
1248 // worklist as well. Because the worklist uniques things already, this
1249 // won't repeatedly process the same operand.
1250 CombinedNodes.insert(N);
1251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253 AddToWorklist(N->getOperand(i).getNode());
1255 SDValue RV = combine(N);
1262 // If we get back the same node we passed in, rather than a new node or
1263 // zero, we know that the node must have defined multiple values and
1264 // CombineTo was used. Since CombineTo takes care of the worklist
1265 // mechanics for us, we have no work to do in this case.
1266 if (RV.getNode() == N)
1269 assert(N->getOpcode() != ISD::DELETED_NODE &&
1270 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271 "Node was deleted but visit returned new node!");
1273 DEBUG(dbgs() << " ... into: ";
1274 RV.getNode()->dump(&DAG));
1276 // Transfer debug value.
1277 DAG.TransferDbgValues(SDValue(N, 0), RV);
1278 if (N->getNumValues() == RV.getNode()->getNumValues())
1279 DAG.ReplaceAllUsesWith(N, RV.getNode());
1281 assert(N->getValueType(0) == RV.getValueType() &&
1282 N->getNumValues() == 1 && "Type mismatch");
1284 DAG.ReplaceAllUsesWith(N, &OpV);
1287 // Push the new node and any users onto the worklist
1288 AddToWorklist(RV.getNode());
1289 AddUsersToWorklist(RV.getNode());
1291 // Finally, if the node is now dead, remove it from the graph. The node
1292 // may not be dead if the replacement process recursively simplified to
1293 // something else needing this node. This will also take care of adding any
1294 // operands which have lost a user to the worklist.
1295 recursivelyDeleteUnusedNodes(N);
1298 // If the root changed (e.g. it was a dead load, update the root).
1299 DAG.setRoot(Dummy.getValue());
1300 DAG.RemoveDeadNodes();
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304 switch (N->getOpcode()) {
1306 case ISD::TokenFactor: return visitTokenFactor(N);
1307 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1308 case ISD::ADD: return visitADD(N);
1309 case ISD::SUB: return visitSUB(N);
1310 case ISD::ADDC: return visitADDC(N);
1311 case ISD::SUBC: return visitSUBC(N);
1312 case ISD::ADDE: return visitADDE(N);
1313 case ISD::SUBE: return visitSUBE(N);
1314 case ISD::MUL: return visitMUL(N);
1315 case ISD::SDIV: return visitSDIV(N);
1316 case ISD::UDIV: return visitUDIV(N);
1317 case ISD::SREM: return visitSREM(N);
1318 case ISD::UREM: return visitUREM(N);
1319 case ISD::MULHU: return visitMULHU(N);
1320 case ISD::MULHS: return visitMULHS(N);
1321 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1322 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1323 case ISD::SMULO: return visitSMULO(N);
1324 case ISD::UMULO: return visitUMULO(N);
1325 case ISD::SDIVREM: return visitSDIVREM(N);
1326 case ISD::UDIVREM: return visitUDIVREM(N);
1327 case ISD::AND: return visitAND(N);
1328 case ISD::OR: return visitOR(N);
1329 case ISD::XOR: return visitXOR(N);
1330 case ISD::SHL: return visitSHL(N);
1331 case ISD::SRA: return visitSRA(N);
1332 case ISD::SRL: return visitSRL(N);
1334 case ISD::ROTL: return visitRotate(N);
1335 case ISD::CTLZ: return visitCTLZ(N);
1336 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1337 case ISD::CTTZ: return visitCTTZ(N);
1338 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1339 case ISD::CTPOP: return visitCTPOP(N);
1340 case ISD::SELECT: return visitSELECT(N);
1341 case ISD::VSELECT: return visitVSELECT(N);
1342 case ISD::SELECT_CC: return visitSELECT_CC(N);
1343 case ISD::SETCC: return visitSETCC(N);
1344 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1345 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1346 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1347 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1348 case ISD::TRUNCATE: return visitTRUNCATE(N);
1349 case ISD::BITCAST: return visitBITCAST(N);
1350 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1351 case ISD::FADD: return visitFADD(N);
1352 case ISD::FSUB: return visitFSUB(N);
1353 case ISD::FMUL: return visitFMUL(N);
1354 case ISD::FMA: return visitFMA(N);
1355 case ISD::FDIV: return visitFDIV(N);
1356 case ISD::FREM: return visitFREM(N);
1357 case ISD::FSQRT: return visitFSQRT(N);
1358 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1359 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1360 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1361 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1362 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1363 case ISD::FP_ROUND: return visitFP_ROUND(N);
1364 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1365 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1366 case ISD::FNEG: return visitFNEG(N);
1367 case ISD::FABS: return visitFABS(N);
1368 case ISD::FFLOOR: return visitFFLOOR(N);
1369 case ISD::FMINNUM: return visitFMINNUM(N);
1370 case ISD::FMAXNUM: return visitFMAXNUM(N);
1371 case ISD::FCEIL: return visitFCEIL(N);
1372 case ISD::FTRUNC: return visitFTRUNC(N);
1373 case ISD::BRCOND: return visitBRCOND(N);
1374 case ISD::BR_CC: return visitBR_CC(N);
1375 case ISD::LOAD: return visitLOAD(N);
1376 case ISD::STORE: return visitSTORE(N);
1377 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1378 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1380 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1381 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1382 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1383 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1384 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1385 case ISD::MLOAD: return visitMLOAD(N);
1386 case ISD::MSTORE: return visitMSTORE(N);
1387 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393 SDValue RV = visit(N);
1395 // If nothing happened, try a target-specific DAG combine.
1396 if (!RV.getNode()) {
1397 assert(N->getOpcode() != ISD::DELETED_NODE &&
1398 "Node was deleted but visit returned NULL!");
1400 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1403 // Expose the DAG combiner to the target combiner impls.
1404 TargetLowering::DAGCombinerInfo
1405 DagCombineInfo(DAG, Level, false, this);
1407 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1411 // If nothing happened still, try promoting the operation.
1412 if (!RV.getNode()) {
1413 switch (N->getOpcode()) {
1421 RV = PromoteIntBinOp(SDValue(N, 0));
1426 RV = PromoteIntShiftOp(SDValue(N, 0));
1428 case ISD::SIGN_EXTEND:
1429 case ISD::ZERO_EXTEND:
1430 case ISD::ANY_EXTEND:
1431 RV = PromoteExtend(SDValue(N, 0));
1434 if (PromoteLoad(SDValue(N, 0)))
1440 // If N is a commutative binary node, try commuting it to enable more
1442 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443 N->getNumValues() == 1) {
1444 SDValue N0 = N->getOperand(0);
1445 SDValue N1 = N->getOperand(1);
1447 // Constant operands are canonicalized to RHS.
1448 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449 SDValue Ops[] = {N1, N0};
1451 if (const BinaryWithFlagsSDNode *BinNode =
1452 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453 CSENode = DAG.getNodeIfExists(
1454 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1455 BinNode->hasNoSignedWrap(), BinNode->isExact());
1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1460 return SDValue(CSENode, 0);
1467 /// Given a node, return its input chain if it has one, otherwise return a null
1469 static SDValue getInputChainForNode(SDNode *N) {
1470 if (unsigned NumOps = N->getNumOperands()) {
1471 if (N->getOperand(0).getValueType() == MVT::Other)
1472 return N->getOperand(0);
1473 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1474 return N->getOperand(NumOps-1);
1475 for (unsigned i = 1; i < NumOps-1; ++i)
1476 if (N->getOperand(i).getValueType() == MVT::Other)
1477 return N->getOperand(i);
1482 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1483 // If N has two operands, where one has an input chain equal to the other,
1484 // the 'other' chain is redundant.
1485 if (N->getNumOperands() == 2) {
1486 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1487 return N->getOperand(0);
1488 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1489 return N->getOperand(1);
1492 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1493 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1494 SmallPtrSet<SDNode*, 16> SeenOps;
1495 bool Changed = false; // If we should replace this token factor.
1497 // Start out with this token factor.
1500 // Iterate through token factors. The TFs grows when new token factors are
1502 for (unsigned i = 0; i < TFs.size(); ++i) {
1503 SDNode *TF = TFs[i];
1505 // Check each of the operands.
1506 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1507 SDValue Op = TF->getOperand(i);
1509 switch (Op.getOpcode()) {
1510 case ISD::EntryToken:
1511 // Entry tokens don't need to be added to the list. They are
1516 case ISD::TokenFactor:
1517 if (Op.hasOneUse() &&
1518 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1519 // Queue up for processing.
1520 TFs.push_back(Op.getNode());
1521 // Clean up in case the token factor is removed.
1522 AddToWorklist(Op.getNode());
1529 // Only add if it isn't already in the list.
1530 if (SeenOps.insert(Op.getNode()).second)
1541 // If we've changed things around then replace token factor.
1544 // The entry token is the only possible outcome.
1545 Result = DAG.getEntryNode();
1547 // New and improved token factor.
1548 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1551 // Add users to worklist if AA is enabled, since it may introduce
1552 // a lot of new chained token factors while removing memory deps.
1553 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1554 : DAG.getSubtarget().useAA();
1555 return CombineTo(N, Result, UseAA /*add to worklist*/);
1561 /// MERGE_VALUES can always be eliminated.
1562 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1563 WorklistRemover DeadNodes(*this);
1564 // Replacing results may cause a different MERGE_VALUES to suddenly
1565 // be CSE'd with N, and carry its uses with it. Iterate until no
1566 // uses remain, to ensure that the node can be safely deleted.
1567 // First add the users of this node to the work list so that they
1568 // can be tried again once they have new operands.
1569 AddUsersToWorklist(N);
1571 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1572 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1573 } while (!N->use_empty());
1574 deleteAndRecombine(N);
1575 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1578 SDValue DAGCombiner::visitADD(SDNode *N) {
1579 SDValue N0 = N->getOperand(0);
1580 SDValue N1 = N->getOperand(1);
1581 EVT VT = N0.getValueType();
1584 if (VT.isVector()) {
1585 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1588 // fold (add x, 0) -> x, vector edition
1589 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1595 // fold (add x, undef) -> undef
1596 if (N0.getOpcode() == ISD::UNDEF)
1598 if (N1.getOpcode() == ISD::UNDEF)
1600 // fold (add c1, c2) -> c1+c2
1601 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1605 // canonicalize constant to RHS
1606 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1607 !isConstantIntBuildVectorOrConstantInt(N1))
1608 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609 // fold (add x, 0) -> x
1610 if (N1C && N1C->isNullValue())
1612 // fold (add Sym, c) -> Sym+c
1613 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615 GA->getOpcode() == ISD::GlobalAddress)
1616 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618 (uint64_t)N1C->getSExtValue());
1619 // fold ((c1-A)+c2) -> (c1+c2)-A
1620 if (N1C && N0.getOpcode() == ISD::SUB)
1621 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1623 return DAG.getNode(ISD::SUB, DL, VT,
1624 DAG.getConstant(N1C->getAPIntValue()+
1625 N0C->getAPIntValue(), DL, VT),
1629 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1631 // fold ((0-A) + B) -> B-A
1632 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1633 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1634 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1635 // fold (A + (0-B)) -> A-B
1636 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1637 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1638 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1639 // fold (A+(B-A)) -> B
1640 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1641 return N1.getOperand(0);
1642 // fold ((B-A)+A) -> B
1643 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1644 return N0.getOperand(0);
1645 // fold (A+(B-(A+C))) to (B-C)
1646 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1647 N0 == N1.getOperand(1).getOperand(0))
1648 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1649 N1.getOperand(1).getOperand(1));
1650 // fold (A+(B-(C+A))) to (B-C)
1651 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652 N0 == N1.getOperand(1).getOperand(1))
1653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654 N1.getOperand(1).getOperand(0));
1655 // fold (A+((B-A)+or-C)) to (B+or-C)
1656 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1657 N1.getOperand(0).getOpcode() == ISD::SUB &&
1658 N0 == N1.getOperand(0).getOperand(1))
1659 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1660 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1662 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1663 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1664 SDValue N00 = N0.getOperand(0);
1665 SDValue N01 = N0.getOperand(1);
1666 SDValue N10 = N1.getOperand(0);
1667 SDValue N11 = N1.getOperand(1);
1669 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1670 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1671 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1672 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1675 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1676 return SDValue(N, 0);
1678 // fold (a+b) -> (a|b) iff a and b share no bits.
1679 if (VT.isInteger() && !VT.isVector()) {
1680 APInt LHSZero, LHSOne;
1681 APInt RHSZero, RHSOne;
1682 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1684 if (LHSZero.getBoolValue()) {
1685 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1687 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1688 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1689 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1690 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1691 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1696 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1697 if (N1.getOpcode() == ISD::SHL &&
1698 N1.getOperand(0).getOpcode() == ISD::SUB)
1699 if (ConstantSDNode *C =
1700 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1701 if (C->getAPIntValue() == 0)
1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1703 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1704 N1.getOperand(0).getOperand(1),
1706 if (N0.getOpcode() == ISD::SHL &&
1707 N0.getOperand(0).getOpcode() == ISD::SUB)
1708 if (ConstantSDNode *C =
1709 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1710 if (C->getAPIntValue() == 0)
1711 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1712 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1713 N0.getOperand(0).getOperand(1),
1716 if (N1.getOpcode() == ISD::AND) {
1717 SDValue AndOp0 = N1.getOperand(0);
1718 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1719 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1720 unsigned DestBits = VT.getScalarType().getSizeInBits();
1722 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1723 // and similar xforms where the inner op is either ~0 or 0.
1724 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1726 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1730 // add (sext i1), X -> sub X, (zext i1)
1731 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1732 N0.getOperand(0).getValueType() == MVT::i1 &&
1733 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1735 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1736 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1739 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1740 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1741 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1742 if (TN->getVT() == MVT::i1) {
1744 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1745 DAG.getConstant(1, DL, VT));
1746 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1753 SDValue DAGCombiner::visitADDC(SDNode *N) {
1754 SDValue N0 = N->getOperand(0);
1755 SDValue N1 = N->getOperand(1);
1756 EVT VT = N0.getValueType();
1758 // If the flag result is dead, turn this into an ADD.
1759 if (!N->hasAnyUseOfValue(1))
1760 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1761 DAG.getNode(ISD::CARRY_FALSE,
1762 SDLoc(N), MVT::Glue));
1764 // canonicalize constant to RHS.
1765 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1766 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1768 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1770 // fold (addc x, 0) -> x + no carry out
1771 if (N1C && N1C->isNullValue())
1772 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1773 SDLoc(N), MVT::Glue));
1775 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1776 APInt LHSZero, LHSOne;
1777 APInt RHSZero, RHSOne;
1778 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1780 if (LHSZero.getBoolValue()) {
1781 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1783 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1784 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1785 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1786 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1787 DAG.getNode(ISD::CARRY_FALSE,
1788 SDLoc(N), MVT::Glue));
1794 SDValue DAGCombiner::visitADDE(SDNode *N) {
1795 SDValue N0 = N->getOperand(0);
1796 SDValue N1 = N->getOperand(1);
1797 SDValue CarryIn = N->getOperand(2);
1799 // canonicalize constant to RHS
1800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1803 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1806 // fold (adde x, y, false) -> (addc x, y)
1807 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1808 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1813 // Since it may not be valid to emit a fold to zero for vector initializers
1814 // check if we can before folding.
1815 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1817 bool LegalOperations, bool LegalTypes) {
1819 return DAG.getConstant(0, DL, VT);
1820 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1821 return DAG.getConstant(0, DL, VT);
1825 SDValue DAGCombiner::visitSUB(SDNode *N) {
1826 SDValue N0 = N->getOperand(0);
1827 SDValue N1 = N->getOperand(1);
1828 EVT VT = N0.getValueType();
1831 if (VT.isVector()) {
1832 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1835 // fold (sub x, 0) -> x, vector edition
1836 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1840 // fold (sub x, x) -> 0
1841 // FIXME: Refactor this and xor and other similar operations together.
1843 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1844 // fold (sub c1, c2) -> c1-c2
1845 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1846 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1848 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1849 // fold (sub x, c) -> (add x, -c)
1852 return DAG.getNode(ISD::ADD, DL, VT, N0,
1853 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1855 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1856 if (N0C && N0C->isAllOnesValue())
1857 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1858 // fold A-(A-B) -> B
1859 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1860 return N1.getOperand(1);
1861 // fold (A+B)-A -> B
1862 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1863 return N0.getOperand(1);
1864 // fold (A+B)-B -> A
1865 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1866 return N0.getOperand(0);
1867 // fold C2-(A+C1) -> (C2-C1)-A
1868 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1869 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1870 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1872 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1874 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1877 // fold ((A+(B+or-C))-B) -> A+or-C
1878 if (N0.getOpcode() == ISD::ADD &&
1879 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1880 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1881 N0.getOperand(1).getOperand(0) == N1)
1882 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1883 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1884 // fold ((A+(C+B))-B) -> A+C
1885 if (N0.getOpcode() == ISD::ADD &&
1886 N0.getOperand(1).getOpcode() == ISD::ADD &&
1887 N0.getOperand(1).getOperand(1) == N1)
1888 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1889 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1890 // fold ((A-(B-C))-C) -> A-B
1891 if (N0.getOpcode() == ISD::SUB &&
1892 N0.getOperand(1).getOpcode() == ISD::SUB &&
1893 N0.getOperand(1).getOperand(1) == N1)
1894 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1895 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1897 // If either operand of a sub is undef, the result is undef
1898 if (N0.getOpcode() == ISD::UNDEF)
1900 if (N1.getOpcode() == ISD::UNDEF)
1903 // If the relocation model supports it, consider symbol offsets.
1904 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1905 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1906 // fold (sub Sym, c) -> Sym-c
1907 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1908 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1910 (uint64_t)N1C->getSExtValue());
1911 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1912 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1913 if (GA->getGlobal() == GB->getGlobal())
1914 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1918 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1919 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1920 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1921 if (TN->getVT() == MVT::i1) {
1923 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1924 DAG.getConstant(1, DL, VT));
1925 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1932 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1933 SDValue N0 = N->getOperand(0);
1934 SDValue N1 = N->getOperand(1);
1935 EVT VT = N0.getValueType();
1937 // If the flag result is dead, turn this into an SUB.
1938 if (!N->hasAnyUseOfValue(1))
1939 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1940 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943 // fold (subc x, x) -> 0 + no borrow
1946 return CombineTo(N, DAG.getConstant(0, DL, VT),
1947 DAG.getNode(ISD::CARRY_FALSE, DL,
1951 // fold (subc x, 0) -> x + no borrow
1952 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1953 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1954 if (N1C && N1C->isNullValue())
1955 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1958 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1959 if (N0C && N0C->isAllOnesValue())
1960 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1961 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1967 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1968 SDValue N0 = N->getOperand(0);
1969 SDValue N1 = N->getOperand(1);
1970 SDValue CarryIn = N->getOperand(2);
1972 // fold (sube x, y, false) -> (subc x, y)
1973 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1974 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1979 SDValue DAGCombiner::visitMUL(SDNode *N) {
1980 SDValue N0 = N->getOperand(0);
1981 SDValue N1 = N->getOperand(1);
1982 EVT VT = N0.getValueType();
1984 // fold (mul x, undef) -> 0
1985 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1986 return DAG.getConstant(0, SDLoc(N), VT);
1988 bool N0IsConst = false;
1989 bool N1IsConst = false;
1990 APInt ConstValue0, ConstValue1;
1992 if (VT.isVector()) {
1993 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1996 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1997 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1999 N0IsConst = isa<ConstantSDNode>(N0);
2001 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2002 N1IsConst = isa<ConstantSDNode>(N1);
2004 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2007 // fold (mul c1, c2) -> c1*c2
2008 if (N0IsConst && N1IsConst)
2009 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2010 N0.getNode(), N1.getNode());
2012 // canonicalize constant to RHS (vector doesn't have to splat)
2013 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2014 !isConstantIntBuildVectorOrConstantInt(N1))
2015 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2016 // fold (mul x, 0) -> 0
2017 if (N1IsConst && ConstValue1 == 0)
2019 // We require a splat of the entire scalar bit width for non-contiguous
2022 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2023 // fold (mul x, 1) -> x
2024 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2026 // fold (mul x, -1) -> 0-x
2027 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2029 return DAG.getNode(ISD::SUB, DL, VT,
2030 DAG.getConstant(0, DL, VT), N0);
2032 // fold (mul x, (1 << c)) -> x << c
2033 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2035 return DAG.getNode(ISD::SHL, DL, VT, N0,
2036 DAG.getConstant(ConstValue1.logBase2(), DL,
2037 getShiftAmountTy(N0.getValueType())));
2039 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2040 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2041 unsigned Log2Val = (-ConstValue1).logBase2();
2043 // FIXME: If the input is something that is easily negated (e.g. a
2044 // single-use add), we should put the negate there.
2045 return DAG.getNode(ISD::SUB, DL, VT,
2046 DAG.getConstant(0, DL, VT),
2047 DAG.getNode(ISD::SHL, DL, VT, N0,
2048 DAG.getConstant(Log2Val, DL,
2049 getShiftAmountTy(N0.getValueType()))));
2053 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2054 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2055 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2056 isa<ConstantSDNode>(N0.getOperand(1)))) {
2057 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2058 N1, N0.getOperand(1));
2059 AddToWorklist(C3.getNode());
2060 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2061 N0.getOperand(0), C3);
2064 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2067 SDValue Sh(nullptr,0), Y(nullptr,0);
2068 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2069 if (N0.getOpcode() == ISD::SHL &&
2070 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2071 isa<ConstantSDNode>(N0.getOperand(1))) &&
2072 N0.getNode()->hasOneUse()) {
2074 } else if (N1.getOpcode() == ISD::SHL &&
2075 isa<ConstantSDNode>(N1.getOperand(1)) &&
2076 N1.getNode()->hasOneUse()) {
2081 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2082 Sh.getOperand(0), Y);
2083 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2084 Mul, Sh.getOperand(1));
2088 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2089 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2090 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2091 isa<ConstantSDNode>(N0.getOperand(1))))
2092 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2093 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2094 N0.getOperand(0), N1),
2095 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2096 N0.getOperand(1), N1));
2099 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2105 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2106 SDValue N0 = N->getOperand(0);
2107 SDValue N1 = N->getOperand(1);
2108 EVT VT = N->getValueType(0);
2112 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2115 // fold (sdiv c1, c2) -> c1/c2
2116 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2117 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2118 if (N0C && N1C && !N1C->isNullValue())
2119 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2120 // fold (sdiv X, 1) -> X
2121 if (N1C && N1C->getAPIntValue() == 1LL)
2123 // fold (sdiv X, -1) -> 0-X
2124 if (N1C && N1C->isAllOnesValue()) {
2126 return DAG.getNode(ISD::SUB, DL, VT,
2127 DAG.getConstant(0, DL, VT), N0);
2129 // If we know the sign bits of both operands are zero, strength reduce to a
2130 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2131 if (!VT.isVector()) {
2132 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2133 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2137 // fold (sdiv X, pow2) -> simple ops after legalize
2138 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2139 (-N1C->getAPIntValue()).isPowerOf2())) {
2140 // If dividing by powers of two is cheap, then don't perform the following
2142 if (TLI.isPow2SDivCheap())
2145 // Target-specific implementation of sdiv x, pow2.
2146 SDValue Res = BuildSDIVPow2(N);
2150 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2153 // Splat the sign bit into the register
2155 DAG.getNode(ISD::SRA, DL, VT, N0,
2156 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2157 getShiftAmountTy(N0.getValueType())));
2158 AddToWorklist(SGN.getNode());
2160 // Add (N0 < 0) ? abs2 - 1 : 0;
2162 DAG.getNode(ISD::SRL, DL, VT, SGN,
2163 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2164 getShiftAmountTy(SGN.getValueType())));
2165 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2166 AddToWorklist(SRL.getNode());
2167 AddToWorklist(ADD.getNode()); // Divide by pow2
2168 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2169 DAG.getConstant(lg2, DL,
2170 getShiftAmountTy(ADD.getValueType())));
2172 // If we're dividing by a positive value, we're done. Otherwise, we must
2173 // negate the result.
2174 if (N1C->getAPIntValue().isNonNegative())
2177 AddToWorklist(SRA.getNode());
2178 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2181 // If integer divide is expensive and we satisfy the requirements, emit an
2182 // alternate sequence.
2183 if (N1C && !TLI.isIntDivCheap()) {
2184 SDValue Op = BuildSDIV(N);
2185 if (Op.getNode()) return Op;
2189 if (N0.getOpcode() == ISD::UNDEF)
2190 return DAG.getConstant(0, SDLoc(N), VT);
2191 // X / undef -> undef
2192 if (N1.getOpcode() == ISD::UNDEF)
2198 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2199 SDValue N0 = N->getOperand(0);
2200 SDValue N1 = N->getOperand(1);
2201 EVT VT = N->getValueType(0);
2205 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2208 // fold (udiv c1, c2) -> c1/c2
2209 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2210 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2211 if (N0C && N1C && !N1C->isNullValue())
2212 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2213 // fold (udiv x, (1 << c)) -> x >>u c
2214 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2216 return DAG.getNode(ISD::SRL, DL, VT, N0,
2217 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2218 getShiftAmountTy(N0.getValueType())));
2220 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2221 if (N1.getOpcode() == ISD::SHL) {
2222 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2223 if (SHC->getAPIntValue().isPowerOf2()) {
2224 EVT ADDVT = N1.getOperand(1).getValueType();
2226 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2228 DAG.getConstant(SHC->getAPIntValue()
2231 AddToWorklist(Add.getNode());
2232 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2236 // fold (udiv x, c) -> alternate
2237 if (N1C && !TLI.isIntDivCheap()) {
2238 SDValue Op = BuildUDIV(N);
2239 if (Op.getNode()) return Op;
2243 if (N0.getOpcode() == ISD::UNDEF)
2244 return DAG.getConstant(0, SDLoc(N), VT);
2245 // X / undef -> undef
2246 if (N1.getOpcode() == ISD::UNDEF)
2252 SDValue DAGCombiner::visitSREM(SDNode *N) {
2253 SDValue N0 = N->getOperand(0);
2254 SDValue N1 = N->getOperand(1);
2255 EVT VT = N->getValueType(0);
2257 // fold (srem c1, c2) -> c1%c2
2258 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2259 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2260 if (N0C && N1C && !N1C->isNullValue())
2261 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2262 // If we know the sign bits of both operands are zero, strength reduce to a
2263 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2264 if (!VT.isVector()) {
2265 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2266 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2269 // If X/C can be simplified by the division-by-constant logic, lower
2270 // X%C to the equivalent of X-X/C*C.
2271 if (N1C && !N1C->isNullValue()) {
2272 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2273 AddToWorklist(Div.getNode());
2274 SDValue OptimizedDiv = combine(Div.getNode());
2275 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2276 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2279 AddToWorklist(Mul.getNode());
2285 if (N0.getOpcode() == ISD::UNDEF)
2286 return DAG.getConstant(0, SDLoc(N), VT);
2287 // X % undef -> undef
2288 if (N1.getOpcode() == ISD::UNDEF)
2294 SDValue DAGCombiner::visitUREM(SDNode *N) {
2295 SDValue N0 = N->getOperand(0);
2296 SDValue N1 = N->getOperand(1);
2297 EVT VT = N->getValueType(0);
2299 // fold (urem c1, c2) -> c1%c2
2300 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2301 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2302 if (N0C && N1C && !N1C->isNullValue())
2303 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2304 // fold (urem x, pow2) -> (and x, pow2-1)
2305 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2307 return DAG.getNode(ISD::AND, DL, VT, N0,
2308 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2310 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2311 if (N1.getOpcode() == ISD::SHL) {
2312 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2313 if (SHC->getAPIntValue().isPowerOf2()) {
2316 DAG.getNode(ISD::ADD, DL, VT, N1,
2317 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2319 AddToWorklist(Add.getNode());
2320 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2325 // If X/C can be simplified by the division-by-constant logic, lower
2326 // X%C to the equivalent of X-X/C*C.
2327 if (N1C && !N1C->isNullValue()) {
2328 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2329 AddToWorklist(Div.getNode());
2330 SDValue OptimizedDiv = combine(Div.getNode());
2331 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2332 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2334 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2335 AddToWorklist(Mul.getNode());
2341 if (N0.getOpcode() == ISD::UNDEF)
2342 return DAG.getConstant(0, SDLoc(N), VT);
2343 // X % undef -> undef
2344 if (N1.getOpcode() == ISD::UNDEF)
2350 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2351 SDValue N0 = N->getOperand(0);
2352 SDValue N1 = N->getOperand(1);
2353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2354 EVT VT = N->getValueType(0);
2357 // fold (mulhs x, 0) -> 0
2358 if (N1C && N1C->isNullValue())
2360 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2361 if (N1C && N1C->getAPIntValue() == 1) {
2363 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2364 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2366 getShiftAmountTy(N0.getValueType())));
2368 // fold (mulhs x, undef) -> 0
2369 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2370 return DAG.getConstant(0, SDLoc(N), VT);
2372 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2374 if (VT.isSimple() && !VT.isVector()) {
2375 MVT Simple = VT.getSimpleVT();
2376 unsigned SimpleSize = Simple.getSizeInBits();
2377 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2378 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2379 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2380 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2381 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2382 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2383 DAG.getConstant(SimpleSize, DL,
2384 getShiftAmountTy(N1.getValueType())));
2385 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2392 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2393 SDValue N0 = N->getOperand(0);
2394 SDValue N1 = N->getOperand(1);
2395 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2396 EVT VT = N->getValueType(0);
2399 // fold (mulhu x, 0) -> 0
2400 if (N1C && N1C->isNullValue())
2402 // fold (mulhu x, 1) -> 0
2403 if (N1C && N1C->getAPIntValue() == 1)
2404 return DAG.getConstant(0, DL, N0.getValueType());
2405 // fold (mulhu x, undef) -> 0
2406 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2407 return DAG.getConstant(0, DL, VT);
2409 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2411 if (VT.isSimple() && !VT.isVector()) {
2412 MVT Simple = VT.getSimpleVT();
2413 unsigned SimpleSize = Simple.getSizeInBits();
2414 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2415 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2416 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2417 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2418 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2419 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2420 DAG.getConstant(SimpleSize, DL,
2421 getShiftAmountTy(N1.getValueType())));
2422 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2429 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2430 /// give the opcodes for the two computations that are being performed. Return
2431 /// true if a simplification was made.
2432 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2434 // If the high half is not needed, just compute the low half.
2435 bool HiExists = N->hasAnyUseOfValue(1);
2437 (!LegalOperations ||
2438 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2439 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2440 return CombineTo(N, Res, Res);
2443 // If the low half is not needed, just compute the high half.
2444 bool LoExists = N->hasAnyUseOfValue(0);
2446 (!LegalOperations ||
2447 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2448 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2449 return CombineTo(N, Res, Res);
2452 // If both halves are used, return as it is.
2453 if (LoExists && HiExists)
2456 // If the two computed results can be simplified separately, separate them.
2458 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2459 AddToWorklist(Lo.getNode());
2460 SDValue LoOpt = combine(Lo.getNode());
2461 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2462 (!LegalOperations ||
2463 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2464 return CombineTo(N, LoOpt, LoOpt);
2468 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2469 AddToWorklist(Hi.getNode());
2470 SDValue HiOpt = combine(Hi.getNode());
2471 if (HiOpt.getNode() && HiOpt != Hi &&
2472 (!LegalOperations ||
2473 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2474 return CombineTo(N, HiOpt, HiOpt);
2480 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2481 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2482 if (Res.getNode()) return Res;
2484 EVT VT = N->getValueType(0);
2487 // If the type is twice as wide is legal, transform the mulhu to a wider
2488 // multiply plus a shift.
2489 if (VT.isSimple() && !VT.isVector()) {
2490 MVT Simple = VT.getSimpleVT();
2491 unsigned SimpleSize = Simple.getSizeInBits();
2492 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2493 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2494 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2495 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2496 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2497 // Compute the high part as N1.
2498 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2499 DAG.getConstant(SimpleSize, DL,
2500 getShiftAmountTy(Lo.getValueType())));
2501 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2502 // Compute the low part as N0.
2503 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2504 return CombineTo(N, Lo, Hi);
2511 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2512 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2513 if (Res.getNode()) return Res;
2515 EVT VT = N->getValueType(0);
2518 // If the type is twice as wide is legal, transform the mulhu to a wider
2519 // multiply plus a shift.
2520 if (VT.isSimple() && !VT.isVector()) {
2521 MVT Simple = VT.getSimpleVT();
2522 unsigned SimpleSize = Simple.getSizeInBits();
2523 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2524 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2525 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2526 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2527 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2528 // Compute the high part as N1.
2529 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2530 DAG.getConstant(SimpleSize, DL,
2531 getShiftAmountTy(Lo.getValueType())));
2532 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2533 // Compute the low part as N0.
2534 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2535 return CombineTo(N, Lo, Hi);
2542 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2543 // (smulo x, 2) -> (saddo x, x)
2544 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2545 if (C2->getAPIntValue() == 2)
2546 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2547 N->getOperand(0), N->getOperand(0));
2552 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2553 // (umulo x, 2) -> (uaddo x, x)
2554 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2555 if (C2->getAPIntValue() == 2)
2556 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2557 N->getOperand(0), N->getOperand(0));
2562 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2563 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2564 if (Res.getNode()) return Res;
2569 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2570 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2571 if (Res.getNode()) return Res;
2576 /// If this is a binary operator with two operands of the same opcode, try to
2578 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2579 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2580 EVT VT = N0.getValueType();
2581 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2583 // Bail early if none of these transforms apply.
2584 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2586 // For each of OP in AND/OR/XOR:
2587 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2588 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2589 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2590 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2591 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2593 // do not sink logical op inside of a vector extend, since it may combine
2595 EVT Op0VT = N0.getOperand(0).getValueType();
2596 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2597 N0.getOpcode() == ISD::SIGN_EXTEND ||
2598 N0.getOpcode() == ISD::BSWAP ||
2599 // Avoid infinite looping with PromoteIntBinOp.
2600 (N0.getOpcode() == ISD::ANY_EXTEND &&
2601 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2602 (N0.getOpcode() == ISD::TRUNCATE &&
2603 (!TLI.isZExtFree(VT, Op0VT) ||
2604 !TLI.isTruncateFree(Op0VT, VT)) &&
2605 TLI.isTypeLegal(Op0VT))) &&
2607 Op0VT == N1.getOperand(0).getValueType() &&
2608 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2609 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2610 N0.getOperand(0).getValueType(),
2611 N0.getOperand(0), N1.getOperand(0));
2612 AddToWorklist(ORNode.getNode());
2613 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2616 // For each of OP in SHL/SRL/SRA/AND...
2617 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2618 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2619 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2620 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2621 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2622 N0.getOperand(1) == N1.getOperand(1)) {
2623 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2624 N0.getOperand(0).getValueType(),
2625 N0.getOperand(0), N1.getOperand(0));
2626 AddToWorklist(ORNode.getNode());
2627 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2628 ORNode, N0.getOperand(1));
2631 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2632 // Only perform this optimization after type legalization and before
2633 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2634 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2635 // we don't want to undo this promotion.
2636 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2638 if ((N0.getOpcode() == ISD::BITCAST ||
2639 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2640 Level == AfterLegalizeTypes) {
2641 SDValue In0 = N0.getOperand(0);
2642 SDValue In1 = N1.getOperand(0);
2643 EVT In0Ty = In0.getValueType();
2644 EVT In1Ty = In1.getValueType();
2646 // If both incoming values are integers, and the original types are the
2648 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2649 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2650 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2651 AddToWorklist(Op.getNode());
2656 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2657 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2658 // If both shuffles use the same mask, and both shuffle within a single
2659 // vector, then it is worthwhile to move the swizzle after the operation.
2660 // The type-legalizer generates this pattern when loading illegal
2661 // vector types from memory. In many cases this allows additional shuffle
2663 // There are other cases where moving the shuffle after the xor/and/or
2664 // is profitable even if shuffles don't perform a swizzle.
2665 // If both shuffles use the same mask, and both shuffles have the same first
2666 // or second operand, then it might still be profitable to move the shuffle
2667 // after the xor/and/or operation.
2668 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2669 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2670 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2672 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2673 "Inputs to shuffles are not the same type");
2675 // Check that both shuffles use the same mask. The masks are known to be of
2676 // the same length because the result vector type is the same.
2677 // Check also that shuffles have only one use to avoid introducing extra
2679 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2680 SVN0->getMask().equals(SVN1->getMask())) {
2681 SDValue ShOp = N0->getOperand(1);
2683 // Don't try to fold this node if it requires introducing a
2684 // build vector of all zeros that might be illegal at this stage.
2685 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2687 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2692 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2693 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2694 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2695 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2696 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2697 N0->getOperand(0), N1->getOperand(0));
2698 AddToWorklist(NewNode.getNode());
2699 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2700 &SVN0->getMask()[0]);
2703 // Don't try to fold this node if it requires introducing a
2704 // build vector of all zeros that might be illegal at this stage.
2705 ShOp = N0->getOperand(0);
2706 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2708 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2713 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2714 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2715 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2716 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2717 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2718 N0->getOperand(1), N1->getOperand(1));
2719 AddToWorklist(NewNode.getNode());
2720 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2721 &SVN0->getMask()[0]);
2729 /// This contains all DAGCombine rules which reduce two values combined by
2730 /// an And operation to a single value. This makes them reusable in the context
2731 /// of visitSELECT(). Rules involving constants are not included as
2732 /// visitSELECT() already handles those cases.
2733 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2734 SDNode *LocReference) {
2735 EVT VT = N1.getValueType();
2737 // fold (and x, undef) -> 0
2738 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2739 return DAG.getConstant(0, SDLoc(LocReference), VT);
2740 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2741 SDValue LL, LR, RL, RR, CC0, CC1;
2742 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2743 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2744 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2746 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2747 LL.getValueType().isInteger()) {
2748 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2749 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2750 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2751 LR.getValueType(), LL, RL);
2752 AddToWorklist(ORNode.getNode());
2753 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2755 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2756 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2757 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2758 LR.getValueType(), LL, RL);
2759 AddToWorklist(ANDNode.getNode());
2760 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2762 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2763 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2764 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765 LR.getValueType(), LL, RL);
2766 AddToWorklist(ORNode.getNode());
2767 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2770 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2771 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2772 Op0 == Op1 && LL.getValueType().isInteger() &&
2773 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2774 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2775 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2776 cast<ConstantSDNode>(RR)->isNullValue()))) {
2778 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2779 LL, DAG.getConstant(1, DL,
2780 LL.getValueType()));
2781 AddToWorklist(ADDNode.getNode());
2782 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2783 DAG.getConstant(2, DL, LL.getValueType()),
2786 // canonicalize equivalent to ll == rl
2787 if (LL == RR && LR == RL) {
2788 Op1 = ISD::getSetCCSwappedOperands(Op1);
2791 if (LL == RL && LR == RR) {
2792 bool isInteger = LL.getValueType().isInteger();
2793 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2794 if (Result != ISD::SETCC_INVALID &&
2795 (!LegalOperations ||
2796 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797 TLI.isOperationLegal(ISD::SETCC,
2798 getSetCCResultType(N0.getSimpleValueType())))))
2799 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2804 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2805 VT.getSizeInBits() <= 64) {
2806 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2807 APInt ADDC = ADDI->getAPIntValue();
2808 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2809 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2810 // immediate for an add, but it is legal if its top c2 bits are set,
2811 // transform the ADD so the immediate doesn't need to be materialized
2813 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2814 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2815 SRLI->getZExtValue());
2816 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2818 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2821 DAG.getNode(ISD::ADD, DL, VT,
2822 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2823 CombineTo(N0.getNode(), NewAdd);
2824 // Return N so it doesn't get rechecked!
2825 return SDValue(LocReference, 0);
2836 SDValue DAGCombiner::visitAND(SDNode *N) {
2837 SDValue N0 = N->getOperand(0);
2838 SDValue N1 = N->getOperand(1);
2839 EVT VT = N1.getValueType();
2842 if (VT.isVector()) {
2843 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2846 // fold (and x, 0) -> 0, vector edition
2847 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2848 // do not return N0, because undef node may exist in N0
2849 return DAG.getConstant(
2850 APInt::getNullValue(
2851 N0.getValueType().getScalarType().getSizeInBits()),
2852 SDLoc(N), N0.getValueType());
2853 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2854 // do not return N1, because undef node may exist in N1
2855 return DAG.getConstant(
2856 APInt::getNullValue(
2857 N1.getValueType().getScalarType().getSizeInBits()),
2858 SDLoc(N), N1.getValueType());
2860 // fold (and x, -1) -> x, vector edition
2861 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2863 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2867 // fold (and c1, c2) -> c1&c2
2868 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2869 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2871 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2872 // canonicalize constant to RHS
2873 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2874 !isConstantIntBuildVectorOrConstantInt(N1))
2875 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2876 // fold (and x, -1) -> x
2877 if (N1C && N1C->isAllOnesValue())
2879 // if (and x, c) is known to be zero, return 0
2880 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2881 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2882 APInt::getAllOnesValue(BitWidth)))
2883 return DAG.getConstant(0, SDLoc(N), VT);
2885 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2887 // fold (and (or x, C), D) -> D if (C & D) == D
2888 if (N1C && N0.getOpcode() == ISD::OR)
2889 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2890 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2892 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2893 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2894 SDValue N0Op0 = N0.getOperand(0);
2895 APInt Mask = ~N1C->getAPIntValue();
2896 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2897 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2898 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2899 N0.getValueType(), N0Op0);
2901 // Replace uses of the AND with uses of the Zero extend node.
2904 // We actually want to replace all uses of the any_extend with the
2905 // zero_extend, to avoid duplicating things. This will later cause this
2906 // AND to be folded.
2907 CombineTo(N0.getNode(), Zext);
2908 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2911 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2912 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2913 // already be zero by virtue of the width of the base type of the load.
2915 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2917 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2918 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2919 N0.getOpcode() == ISD::LOAD) {
2920 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2921 N0 : N0.getOperand(0) );
2923 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2924 // This can be a pure constant or a vector splat, in which case we treat the
2925 // vector as a scalar and use the splat value.
2926 APInt Constant = APInt::getNullValue(1);
2927 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2928 Constant = C->getAPIntValue();
2929 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2930 APInt SplatValue, SplatUndef;
2931 unsigned SplatBitSize;
2933 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2934 SplatBitSize, HasAnyUndefs);
2936 // Undef bits can contribute to a possible optimisation if set, so
2938 SplatValue |= SplatUndef;
2940 // The splat value may be something like "0x00FFFFFF", which means 0 for
2941 // the first vector value and FF for the rest, repeating. We need a mask
2942 // that will apply equally to all members of the vector, so AND all the
2943 // lanes of the constant together.
2944 EVT VT = Vector->getValueType(0);
2945 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2947 // If the splat value has been compressed to a bitlength lower
2948 // than the size of the vector lane, we need to re-expand it to
2950 if (BitWidth > SplatBitSize)
2951 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2952 SplatBitSize < BitWidth;
2953 SplatBitSize = SplatBitSize * 2)
2954 SplatValue |= SplatValue.shl(SplatBitSize);
2956 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2957 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2958 if (SplatBitSize % BitWidth == 0) {
2959 Constant = APInt::getAllOnesValue(BitWidth);
2960 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2961 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2966 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2967 // actually legal and isn't going to get expanded, else this is a false
2969 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2970 Load->getValueType(0),
2971 Load->getMemoryVT());
2973 // Resize the constant to the same size as the original memory access before
2974 // extension. If it is still the AllOnesValue then this AND is completely
2977 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2980 switch (Load->getExtensionType()) {
2981 default: B = false; break;
2982 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2984 case ISD::NON_EXTLOAD: B = true; break;
2987 if (B && Constant.isAllOnesValue()) {
2988 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2989 // preserve semantics once we get rid of the AND.
2990 SDValue NewLoad(Load, 0);
2991 if (Load->getExtensionType() == ISD::EXTLOAD) {
2992 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2993 Load->getValueType(0), SDLoc(Load),
2994 Load->getChain(), Load->getBasePtr(),
2995 Load->getOffset(), Load->getMemoryVT(),
2996 Load->getMemOperand());
2997 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2998 if (Load->getNumValues() == 3) {
2999 // PRE/POST_INC loads have 3 values.
3000 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3001 NewLoad.getValue(2) };
3002 CombineTo(Load, To, 3, true);
3004 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3008 // Fold the AND away, taking care not to fold to the old load node if we
3010 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3012 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3016 // fold (and (load x), 255) -> (zextload x, i8)
3017 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3018 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3019 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3020 (N0.getOpcode() == ISD::ANY_EXTEND &&
3021 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3022 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3023 LoadSDNode *LN0 = HasAnyExt
3024 ? cast<LoadSDNode>(N0.getOperand(0))
3025 : cast<LoadSDNode>(N0);
3026 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3027 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3028 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3029 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3030 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3031 EVT LoadedVT = LN0->getMemoryVT();
3032 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3034 if (ExtVT == LoadedVT &&
3035 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3039 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3040 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3041 LN0->getMemOperand());
3043 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3044 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3047 // Do not change the width of a volatile load.
3048 // Do not generate loads of non-round integer types since these can
3049 // be expensive (and would be wrong if the type is not byte sized).
3050 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3051 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3053 EVT PtrType = LN0->getOperand(1).getValueType();
3055 unsigned Alignment = LN0->getAlignment();
3056 SDValue NewPtr = LN0->getBasePtr();
3058 // For big endian targets, we need to add an offset to the pointer
3059 // to load the correct bytes. For little endian systems, we merely
3060 // need to read fewer bytes from the same pointer.
3061 if (TLI.isBigEndian()) {
3062 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3063 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3064 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3066 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3067 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3068 Alignment = MinAlign(Alignment, PtrOff);
3071 AddToWorklist(NewPtr.getNode());
3074 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3075 LN0->getChain(), NewPtr,
3076 LN0->getPointerInfo(),
3077 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3078 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3080 CombineTo(LN0, Load, Load.getValue(1));
3081 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3087 if (SDValue Combined = visitANDLike(N0, N1, N))
3090 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3091 if (N0.getOpcode() == N1.getOpcode()) {
3092 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3093 if (Tmp.getNode()) return Tmp;
3096 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3097 // fold (and (sra)) -> (and (srl)) when possible.
3098 if (!VT.isVector() &&
3099 SimplifyDemandedBits(SDValue(N, 0)))
3100 return SDValue(N, 0);
3102 // fold (zext_inreg (extload x)) -> (zextload x)
3103 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3104 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3105 EVT MemVT = LN0->getMemoryVT();
3106 // If we zero all the possible extended bits, then we can turn this into
3107 // a zextload if we are running before legalize or the operation is legal.
3108 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3109 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3110 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3111 ((!LegalOperations && !LN0->isVolatile()) ||
3112 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3113 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3114 LN0->getChain(), LN0->getBasePtr(),
3115 MemVT, LN0->getMemOperand());
3117 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3118 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3121 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3122 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3124 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3125 EVT MemVT = LN0->getMemoryVT();
3126 // If we zero all the possible extended bits, then we can turn this into
3127 // a zextload if we are running before legalize or the operation is legal.
3128 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3129 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3130 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3131 ((!LegalOperations && !LN0->isVolatile()) ||
3132 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3133 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3134 LN0->getChain(), LN0->getBasePtr(),
3135 MemVT, LN0->getMemOperand());
3137 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3138 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3141 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3142 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3143 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3144 N0.getOperand(1), false);
3145 if (BSwap.getNode())
3152 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3153 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3154 bool DemandHighBits) {
3155 if (!LegalOperations)
3158 EVT VT = N->getValueType(0);
3159 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3161 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3164 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3165 bool LookPassAnd0 = false;
3166 bool LookPassAnd1 = false;
3167 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3169 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3171 if (N0.getOpcode() == ISD::AND) {
3172 if (!N0.getNode()->hasOneUse())
3174 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3175 if (!N01C || N01C->getZExtValue() != 0xFF00)
3177 N0 = N0.getOperand(0);
3178 LookPassAnd0 = true;
3181 if (N1.getOpcode() == ISD::AND) {
3182 if (!N1.getNode()->hasOneUse())
3184 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3185 if (!N11C || N11C->getZExtValue() != 0xFF)
3187 N1 = N1.getOperand(0);
3188 LookPassAnd1 = true;
3191 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3193 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3195 if (!N0.getNode()->hasOneUse() ||
3196 !N1.getNode()->hasOneUse())
3199 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3200 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3203 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3206 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3207 SDValue N00 = N0->getOperand(0);
3208 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3209 if (!N00.getNode()->hasOneUse())
3211 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3212 if (!N001C || N001C->getZExtValue() != 0xFF)
3214 N00 = N00.getOperand(0);
3215 LookPassAnd0 = true;
3218 SDValue N10 = N1->getOperand(0);
3219 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3220 if (!N10.getNode()->hasOneUse())
3222 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3223 if (!N101C || N101C->getZExtValue() != 0xFF00)
3225 N10 = N10.getOperand(0);
3226 LookPassAnd1 = true;
3232 // Make sure everything beyond the low halfword gets set to zero since the SRL
3233 // 16 will clear the top bits.
3234 unsigned OpSizeInBits = VT.getSizeInBits();
3235 if (DemandHighBits && OpSizeInBits > 16) {
3236 // If the left-shift isn't masked out then the only way this is a bswap is
3237 // if all bits beyond the low 8 are 0. In that case the entire pattern
3238 // reduces to a left shift anyway: leave it for other parts of the combiner.
3242 // However, if the right shift isn't masked out then it might be because
3243 // it's not needed. See if we can spot that too.
3244 if (!LookPassAnd1 &&
3245 !DAG.MaskedValueIsZero(
3246 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3250 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3251 if (OpSizeInBits > 16) {
3253 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3254 DAG.getConstant(OpSizeInBits - 16, DL,
3255 getShiftAmountTy(VT)));
3260 /// Return true if the specified node is an element that makes up a 32-bit
3261 /// packed halfword byteswap.
3262 /// ((x & 0x000000ff) << 8) |
3263 /// ((x & 0x0000ff00) >> 8) |
3264 /// ((x & 0x00ff0000) << 8) |
3265 /// ((x & 0xff000000) >> 8)
3266 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3267 if (!N.getNode()->hasOneUse())
3270 unsigned Opc = N.getOpcode();
3271 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3274 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3279 switch (N1C->getZExtValue()) {
3282 case 0xFF: Num = 0; break;
3283 case 0xFF00: Num = 1; break;
3284 case 0xFF0000: Num = 2; break;
3285 case 0xFF000000: Num = 3; break;
3288 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3289 SDValue N0 = N.getOperand(0);
3290 if (Opc == ISD::AND) {
3291 if (Num == 0 || Num == 2) {
3293 // (x >> 8) & 0xff0000
3294 if (N0.getOpcode() != ISD::SRL)
3296 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3297 if (!C || C->getZExtValue() != 8)
3300 // (x << 8) & 0xff00
3301 // (x << 8) & 0xff000000
3302 if (N0.getOpcode() != ISD::SHL)
3304 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3305 if (!C || C->getZExtValue() != 8)
3308 } else if (Opc == ISD::SHL) {
3310 // (x & 0xff0000) << 8
3311 if (Num != 0 && Num != 2)
3313 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3314 if (!C || C->getZExtValue() != 8)
3316 } else { // Opc == ISD::SRL
3317 // (x & 0xff00) >> 8
3318 // (x & 0xff000000) >> 8
3319 if (Num != 1 && Num != 3)
3321 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3322 if (!C || C->getZExtValue() != 8)
3329 Parts[Num] = N0.getOperand(0).getNode();
3333 /// Match a 32-bit packed halfword bswap. That is
3334 /// ((x & 0x000000ff) << 8) |
3335 /// ((x & 0x0000ff00) >> 8) |
3336 /// ((x & 0x00ff0000) << 8) |
3337 /// ((x & 0xff000000) >> 8)
3338 /// => (rotl (bswap x), 16)
3339 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3340 if (!LegalOperations)
3343 EVT VT = N->getValueType(0);
3346 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3350 // (or (or (and), (and)), (or (and), (and)))
3351 // (or (or (or (and), (and)), (and)), (and))
3352 if (N0.getOpcode() != ISD::OR)
3354 SDValue N00 = N0.getOperand(0);
3355 SDValue N01 = N0.getOperand(1);
3356 SDNode *Parts[4] = {};
3358 if (N1.getOpcode() == ISD::OR &&
3359 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3360 // (or (or (and), (and)), (or (and), (and)))
3361 SDValue N000 = N00.getOperand(0);
3362 if (!isBSwapHWordElement(N000, Parts))
3365 SDValue N001 = N00.getOperand(1);
3366 if (!isBSwapHWordElement(N001, Parts))
3368 SDValue N010 = N01.getOperand(0);
3369 if (!isBSwapHWordElement(N010, Parts))
3371 SDValue N011 = N01.getOperand(1);
3372 if (!isBSwapHWordElement(N011, Parts))
3375 // (or (or (or (and), (and)), (and)), (and))
3376 if (!isBSwapHWordElement(N1, Parts))
3378 if (!isBSwapHWordElement(N01, Parts))
3380 if (N00.getOpcode() != ISD::OR)
3382 SDValue N000 = N00.getOperand(0);
3383 if (!isBSwapHWordElement(N000, Parts))
3385 SDValue N001 = N00.getOperand(1);
3386 if (!isBSwapHWordElement(N001, Parts))
3390 // Make sure the parts are all coming from the same node.
3391 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3395 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3396 SDValue(Parts[0], 0));
3398 // Result of the bswap should be rotated by 16. If it's not legal, then
3399 // do (x << 16) | (x >> 16).
3400 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3401 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3402 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3403 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3404 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3405 return DAG.getNode(ISD::OR, DL, VT,
3406 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3407 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3410 /// This contains all DAGCombine rules which reduce two values combined by
3411 /// an Or operation to a single value \see visitANDLike().
3412 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3413 EVT VT = N1.getValueType();
3414 // fold (or x, undef) -> -1
3415 if (!LegalOperations &&
3416 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3417 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3418 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3419 SDLoc(LocReference), VT);
3421 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3422 SDValue LL, LR, RL, RR, CC0, CC1;
3423 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3424 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3425 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3427 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3428 LL.getValueType().isInteger()) {
3429 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3430 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3431 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3432 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3433 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3434 LR.getValueType(), LL, RL);
3435 AddToWorklist(ORNode.getNode());
3436 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3438 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3439 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3440 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3441 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3442 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3443 LR.getValueType(), LL, RL);
3444 AddToWorklist(ANDNode.getNode());
3445 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3448 // canonicalize equivalent to ll == rl
3449 if (LL == RR && LR == RL) {
3450 Op1 = ISD::getSetCCSwappedOperands(Op1);
3453 if (LL == RL && LR == RR) {
3454 bool isInteger = LL.getValueType().isInteger();
3455 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3456 if (Result != ISD::SETCC_INVALID &&
3457 (!LegalOperations ||
3458 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3459 TLI.isOperationLegal(ISD::SETCC,
3460 getSetCCResultType(N0.getValueType())))))
3461 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3466 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3467 if (N0.getOpcode() == ISD::AND &&
3468 N1.getOpcode() == ISD::AND &&
3469 N0.getOperand(1).getOpcode() == ISD::Constant &&
3470 N1.getOperand(1).getOpcode() == ISD::Constant &&
3471 // Don't increase # computations.
3472 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3473 // We can only do this xform if we know that bits from X that are set in C2
3474 // but not in C1 are already zero. Likewise for Y.
3475 const APInt &LHSMask =
3476 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3477 const APInt &RHSMask =
3478 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3480 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3481 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3482 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3483 N0.getOperand(0), N1.getOperand(0));
3484 SDLoc DL(LocReference);
3485 return DAG.getNode(ISD::AND, DL, VT, X,
3486 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3490 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3491 if (N0.getOpcode() == ISD::AND &&
3492 N1.getOpcode() == ISD::AND &&
3493 N0.getOperand(0) == N1.getOperand(0) &&
3494 // Don't increase # computations.
3495 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3496 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3497 N0.getOperand(1), N1.getOperand(1));
3498 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3504 SDValue DAGCombiner::visitOR(SDNode *N) {
3505 SDValue N0 = N->getOperand(0);
3506 SDValue N1 = N->getOperand(1);
3507 EVT VT = N1.getValueType();
3510 if (VT.isVector()) {
3511 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3514 // fold (or x, 0) -> x, vector edition
3515 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3517 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3520 // fold (or x, -1) -> -1, vector edition
3521 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3522 // do not return N0, because undef node may exist in N0
3523 return DAG.getConstant(
3524 APInt::getAllOnesValue(
3525 N0.getValueType().getScalarType().getSizeInBits()),
3526 SDLoc(N), N0.getValueType());
3527 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3528 // do not return N1, because undef node may exist in N1
3529 return DAG.getConstant(
3530 APInt::getAllOnesValue(
3531 N1.getValueType().getScalarType().getSizeInBits()),
3532 SDLoc(N), N1.getValueType());
3534 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3535 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3536 // Do this only if the resulting shuffle is legal.
3537 if (isa<ShuffleVectorSDNode>(N0) &&
3538 isa<ShuffleVectorSDNode>(N1) &&
3539 // Avoid folding a node with illegal type.
3540 TLI.isTypeLegal(VT) &&
3541 N0->getOperand(1) == N1->getOperand(1) &&
3542 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3543 bool CanFold = true;
3544 unsigned NumElts = VT.getVectorNumElements();
3545 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3546 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3547 // We construct two shuffle masks:
3548 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3549 // and N1 as the second operand.
3550 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3551 // and N0 as the second operand.
3552 // We do this because OR is commutable and therefore there might be
3553 // two ways to fold this node into a shuffle.
3554 SmallVector<int,4> Mask1;
3555 SmallVector<int,4> Mask2;
3557 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3558 int M0 = SV0->getMaskElt(i);
3559 int M1 = SV1->getMaskElt(i);
3561 // Both shuffle indexes are undef. Propagate Undef.
3562 if (M0 < 0 && M1 < 0) {
3563 Mask1.push_back(M0);
3564 Mask2.push_back(M0);
3568 if (M0 < 0 || M1 < 0 ||
3569 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3570 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3575 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3576 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3580 // Fold this sequence only if the resulting shuffle is 'legal'.
3581 if (TLI.isShuffleMaskLegal(Mask1, VT))
3582 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3583 N1->getOperand(0), &Mask1[0]);
3584 if (TLI.isShuffleMaskLegal(Mask2, VT))
3585 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3586 N0->getOperand(0), &Mask2[0]);
3591 // fold (or c1, c2) -> c1|c2
3592 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3595 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3596 // canonicalize constant to RHS
3597 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3598 !isConstantIntBuildVectorOrConstantInt(N1))
3599 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3600 // fold (or x, 0) -> x
3601 if (N1C && N1C->isNullValue())
3603 // fold (or x, -1) -> -1
3604 if (N1C && N1C->isAllOnesValue())
3606 // fold (or x, c) -> c iff (x & ~c) == 0
3607 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3610 if (SDValue Combined = visitORLike(N0, N1, N))
3613 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3614 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3615 if (BSwap.getNode())
3617 BSwap = MatchBSwapHWordLow(N, N0, N1);
3618 if (BSwap.getNode())
3622 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3624 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3625 // iff (c1 & c2) == 0.
3626 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3627 isa<ConstantSDNode>(N0.getOperand(1))) {
3628 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3629 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3630 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3633 ISD::AND, SDLoc(N), VT,
3634 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3638 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3639 if (N0.getOpcode() == N1.getOpcode()) {
3640 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3641 if (Tmp.getNode()) return Tmp;
3644 // See if this is some rotate idiom.
3645 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3646 return SDValue(Rot, 0);
3648 // Simplify the operands using demanded-bits information.
3649 if (!VT.isVector() &&
3650 SimplifyDemandedBits(SDValue(N, 0)))
3651 return SDValue(N, 0);
3656 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3657 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3658 if (Op.getOpcode() == ISD::AND) {
3659 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3660 Mask = Op.getOperand(1);
3661 Op = Op.getOperand(0);
3667 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3675 // Return true if we can prove that, whenever Neg and Pos are both in the
3676 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3677 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3679 // (or (shift1 X, Neg), (shift2 X, Pos))
3681 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3682 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3683 // to consider shift amounts with defined behavior.
3684 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3685 // If OpSize is a power of 2 then:
3687 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3688 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3690 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3691 // for the stronger condition:
3693 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3695 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3696 // we can just replace Neg with Neg' for the rest of the function.
3698 // In other cases we check for the even stronger condition:
3700 // Neg == OpSize - Pos [B]
3702 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3703 // behavior if Pos == 0 (and consequently Neg == OpSize).
3705 // We could actually use [A] whenever OpSize is a power of 2, but the
3706 // only extra cases that it would match are those uninteresting ones
3707 // where Neg and Pos are never in range at the same time. E.g. for
3708 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3709 // as well as (sub 32, Pos), but:
3711 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3713 // always invokes undefined behavior for 32-bit X.
3715 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3716 unsigned MaskLoBits = 0;
3717 if (Neg.getOpcode() == ISD::AND &&
3718 isPowerOf2_64(OpSize) &&
3719 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3720 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3721 Neg = Neg.getOperand(0);
3722 MaskLoBits = Log2_64(OpSize);
3725 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3726 if (Neg.getOpcode() != ISD::SUB)
3728 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3731 SDValue NegOp1 = Neg.getOperand(1);
3733 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3734 // Pos'. The truncation is redundant for the purpose of the equality.
3736 Pos.getOpcode() == ISD::AND &&
3737 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3738 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3739 Pos = Pos.getOperand(0);
3741 // The condition we need is now:
3743 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3745 // If NegOp1 == Pos then we need:
3747 // OpSize & Mask == NegC & Mask
3749 // (because "x & Mask" is a truncation and distributes through subtraction).
3752 Width = NegC->getAPIntValue();
3753 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3754 // Then the condition we want to prove becomes:
3756 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3758 // which, again because "x & Mask" is a truncation, becomes:
3760 // NegC & Mask == (OpSize - PosC) & Mask
3761 // OpSize & Mask == (NegC + PosC) & Mask
3762 else if (Pos.getOpcode() == ISD::ADD &&
3763 Pos.getOperand(0) == NegOp1 &&
3764 Pos.getOperand(1).getOpcode() == ISD::Constant)
3765 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3766 NegC->getAPIntValue());
3770 // Now we just need to check that OpSize & Mask == Width & Mask.
3772 // Opsize & Mask is 0 since Mask is Opsize - 1.
3773 return Width.getLoBits(MaskLoBits) == 0;
3774 return Width == OpSize;
3777 // A subroutine of MatchRotate used once we have found an OR of two opposite
3778 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3779 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3780 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3781 // Neg with outer conversions stripped away.
3782 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3783 SDValue Neg, SDValue InnerPos,
3784 SDValue InnerNeg, unsigned PosOpcode,
3785 unsigned NegOpcode, SDLoc DL) {
3786 // fold (or (shl x, (*ext y)),
3787 // (srl x, (*ext (sub 32, y)))) ->
3788 // (rotl x, y) or (rotr x, (sub 32, y))
3790 // fold (or (shl x, (*ext (sub 32, y))),
3791 // (srl x, (*ext y))) ->
3792 // (rotr x, y) or (rotl x, (sub 32, y))
3793 EVT VT = Shifted.getValueType();
3794 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3795 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3796 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3797 HasPos ? Pos : Neg).getNode();
3803 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3804 // idioms for rotate, and if the target supports rotation instructions, generate
3806 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3807 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3808 EVT VT = LHS.getValueType();
3809 if (!TLI.isTypeLegal(VT)) return nullptr;
3811 // The target must have at least one rotate flavor.
3812 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3813 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3814 if (!HasROTL && !HasROTR) return nullptr;
3816 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3817 SDValue LHSShift; // The shift.
3818 SDValue LHSMask; // AND value if any.
3819 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3820 return nullptr; // Not part of a rotate.
3822 SDValue RHSShift; // The shift.
3823 SDValue RHSMask; // AND value if any.
3824 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3825 return nullptr; // Not part of a rotate.
3827 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3828 return nullptr; // Not shifting the same value.
3830 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3831 return nullptr; // Shifts must disagree.
3833 // Canonicalize shl to left side in a shl/srl pair.
3834 if (RHSShift.getOpcode() == ISD::SHL) {
3835 std::swap(LHS, RHS);
3836 std::swap(LHSShift, RHSShift);
3837 std::swap(LHSMask , RHSMask );
3840 unsigned OpSizeInBits = VT.getSizeInBits();
3841 SDValue LHSShiftArg = LHSShift.getOperand(0);
3842 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3843 SDValue RHSShiftArg = RHSShift.getOperand(0);
3844 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3846 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3847 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3848 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3849 RHSShiftAmt.getOpcode() == ISD::Constant) {
3850 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3851 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3852 if ((LShVal + RShVal) != OpSizeInBits)
3855 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3856 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3858 // If there is an AND of either shifted operand, apply it to the result.
3859 if (LHSMask.getNode() || RHSMask.getNode()) {
3860 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3862 if (LHSMask.getNode()) {
3863 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3864 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3866 if (RHSMask.getNode()) {
3867 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3868 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3871 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3874 return Rot.getNode();
3877 // If there is a mask here, and we have a variable shift, we can't be sure
3878 // that we're masking out the right stuff.
3879 if (LHSMask.getNode() || RHSMask.getNode())
3882 // If the shift amount is sign/zext/any-extended just peel it off.
3883 SDValue LExtOp0 = LHSShiftAmt;
3884 SDValue RExtOp0 = RHSShiftAmt;
3885 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3886 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3887 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3888 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3889 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3893 LExtOp0 = LHSShiftAmt.getOperand(0);
3894 RExtOp0 = RHSShiftAmt.getOperand(0);
3897 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3898 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3902 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3903 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3910 SDValue DAGCombiner::visitXOR(SDNode *N) {
3911 SDValue N0 = N->getOperand(0);
3912 SDValue N1 = N->getOperand(1);
3913 EVT VT = N0.getValueType();
3916 if (VT.isVector()) {
3917 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3920 // fold (xor x, 0) -> x, vector edition
3921 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3923 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3927 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3928 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3929 return DAG.getConstant(0, SDLoc(N), VT);
3930 // fold (xor x, undef) -> undef
3931 if (N0.getOpcode() == ISD::UNDEF)
3933 if (N1.getOpcode() == ISD::UNDEF)
3935 // fold (xor c1, c2) -> c1^c2
3936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3939 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3940 // canonicalize constant to RHS
3941 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3942 !isConstantIntBuildVectorOrConstantInt(N1))
3943 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3944 // fold (xor x, 0) -> x
3945 if (N1C && N1C->isNullValue())
3948 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3951 // fold !(x cc y) -> (x !cc y)
3952 SDValue LHS, RHS, CC;
3953 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3954 bool isInt = LHS.getValueType().isInteger();
3955 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3958 if (!LegalOperations ||
3959 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3960 switch (N0.getOpcode()) {
3962 llvm_unreachable("Unhandled SetCC Equivalent!");
3964 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3965 case ISD::SELECT_CC:
3966 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3967 N0.getOperand(3), NotCC);
3972 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3973 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3974 N0.getNode()->hasOneUse() &&
3975 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3976 SDValue V = N0.getOperand(0);
3978 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3979 DAG.getConstant(1, DL, V.getValueType()));
3980 AddToWorklist(V.getNode());
3981 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3984 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3985 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3986 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3987 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3988 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3989 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3990 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3991 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3992 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3993 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3996 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3997 if (N1C && N1C->isAllOnesValue() &&
3998 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3999 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4000 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4001 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4002 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4003 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4004 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4005 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4008 // fold (xor (and x, y), y) -> (and (not x), y)
4009 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4010 N0->getOperand(1) == N1) {
4011 SDValue X = N0->getOperand(0);
4012 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4013 AddToWorklist(NotX.getNode());
4014 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4016 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4017 if (N1C && N0.getOpcode() == ISD::XOR) {
4018 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4019 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4022 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4023 DAG.getConstant(N1C->getAPIntValue() ^
4024 N00C->getAPIntValue(), DL, VT));
4028 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4029 DAG.getConstant(N1C->getAPIntValue() ^
4030 N01C->getAPIntValue(), DL, VT));
4033 // fold (xor x, x) -> 0
4035 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4037 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4038 // Here is a concrete example of this equivalence:
4040 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4041 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4045 // i16 ~1 == 0b1111111111111110
4046 // i16 rol(~1, 14) == 0b1011111111111111
4048 // Some additional tips to help conceptualize this transform:
4049 // - Try to see the operation as placing a single zero in a value of all ones.
4050 // - There exists no value for x which would allow the result to contain zero.
4051 // - Values of x larger than the bitwidth are undefined and do not require a
4052 // consistent result.
4053 // - Pushing the zero left requires shifting one bits in from the right.
4054 // A rotate left of ~1 is a nice way of achieving the desired result.
4055 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4056 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4057 if (N0.getOpcode() == ISD::SHL)
4058 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4059 if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4061 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4065 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4066 if (N0.getOpcode() == N1.getOpcode()) {
4067 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4068 if (Tmp.getNode()) return Tmp;
4071 // Simplify the expression using non-local knowledge.
4072 if (!VT.isVector() &&
4073 SimplifyDemandedBits(SDValue(N, 0)))
4074 return SDValue(N, 0);
4079 /// Handle transforms common to the three shifts, when the shift amount is a
4081 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4082 // We can't and shouldn't fold opaque constants.
4083 if (Amt->isOpaque())
4086 SDNode *LHS = N->getOperand(0).getNode();
4087 if (!LHS->hasOneUse()) return SDValue();
4089 // We want to pull some binops through shifts, so that we have (and (shift))
4090 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4091 // thing happens with address calculations, so it's important to canonicalize
4093 bool HighBitSet = false; // Can we transform this if the high bit is set?
4095 switch (LHS->getOpcode()) {
4096 default: return SDValue();
4099 HighBitSet = false; // We can only transform sra if the high bit is clear.
4102 HighBitSet = true; // We can only transform sra if the high bit is set.
4105 if (N->getOpcode() != ISD::SHL)
4106 return SDValue(); // only shl(add) not sr[al](add).
4107 HighBitSet = false; // We can only transform sra if the high bit is clear.
4111 // We require the RHS of the binop to be a constant and not opaque as well.
4112 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4113 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115 // FIXME: disable this unless the input to the binop is a shift by a constant.
4116 // If it is not a shift, it pessimizes some common cases like:
4118 // void foo(int *X, int i) { X[i & 1235] = 1; }
4119 // int bar(int *X, int i) { return X[i & 255]; }
4120 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4121 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4122 BinOpLHSVal->getOpcode() != ISD::SRA &&
4123 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4124 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4127 EVT VT = N->getValueType(0);
4129 // If this is a signed shift right, and the high bit is modified by the
4130 // logical operation, do not perform the transformation. The highBitSet
4131 // boolean indicates the value of the high bit of the constant which would
4132 // cause it to be modified for this operation.
4133 if (N->getOpcode() == ISD::SRA) {
4134 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4135 if (BinOpRHSSignSet != HighBitSet)
4139 if (!TLI.isDesirableToCommuteWithShift(LHS))
4142 // Fold the constants, shifting the binop RHS by the shift amount.
4143 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145 LHS->getOperand(1), N->getOperand(1));
4146 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148 // Create the new shift.
4149 SDValue NewShift = DAG.getNode(N->getOpcode(),
4150 SDLoc(LHS->getOperand(0)),
4151 VT, LHS->getOperand(0), N->getOperand(1));
4153 // Create the new binop.
4154 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4157 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4158 assert(N->getOpcode() == ISD::TRUNCATE);
4159 assert(N->getOperand(0).getOpcode() == ISD::AND);
4161 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4162 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4163 SDValue N01 = N->getOperand(0).getOperand(1);
4165 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4166 EVT TruncVT = N->getValueType(0);
4167 SDValue N00 = N->getOperand(0).getOperand(0);
4168 APInt TruncC = N01C->getAPIntValue();
4169 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4172 return DAG.getNode(ISD::AND, DL, TruncVT,
4173 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4174 DAG.getConstant(TruncC, DL, TruncVT));
4181 SDValue DAGCombiner::visitRotate(SDNode *N) {
4182 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4183 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4184 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4185 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4186 if (NewOp1.getNode())
4187 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4188 N->getOperand(0), NewOp1);
4193 SDValue DAGCombiner::visitSHL(SDNode *N) {
4194 SDValue N0 = N->getOperand(0);
4195 SDValue N1 = N->getOperand(1);
4196 EVT VT = N0.getValueType();
4197 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4201 if (VT.isVector()) {
4202 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4205 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4206 // If setcc produces all-one true value then:
4207 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4208 if (N1CV && N1CV->isConstant()) {
4209 if (N0.getOpcode() == ISD::AND) {
4210 SDValue N00 = N0->getOperand(0);
4211 SDValue N01 = N0->getOperand(1);
4212 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4215 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4216 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4217 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4222 N1C = isConstOrConstSplat(N1);
4227 // fold (shl c1, c2) -> c1<<c2
4228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4231 // fold (shl 0, x) -> 0
4232 if (N0C && N0C->isNullValue())
4234 // fold (shl x, c >= size(x)) -> undef
4235 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4236 return DAG.getUNDEF(VT);
4237 // fold (shl x, 0) -> x
4238 if (N1C && N1C->isNullValue())
4240 // fold (shl undef, x) -> 0
4241 if (N0.getOpcode() == ISD::UNDEF)
4242 return DAG.getConstant(0, SDLoc(N), VT);
4243 // if (shl x, c) is known to be zero, return 0
4244 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4245 APInt::getAllOnesValue(OpSizeInBits)))
4246 return DAG.getConstant(0, SDLoc(N), VT);
4247 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4248 if (N1.getOpcode() == ISD::TRUNCATE &&
4249 N1.getOperand(0).getOpcode() == ISD::AND) {
4250 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4251 if (NewOp1.getNode())
4252 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4255 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4256 return SDValue(N, 0);
4258 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4259 if (N1C && N0.getOpcode() == ISD::SHL) {
4260 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4261 uint64_t c1 = N0C1->getZExtValue();
4262 uint64_t c2 = N1C->getZExtValue();
4264 if (c1 + c2 >= OpSizeInBits)
4265 return DAG.getConstant(0, DL, VT);
4266 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4267 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4271 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4272 // For this to be valid, the second form must not preserve any of the bits
4273 // that are shifted out by the inner shift in the first form. This means
4274 // the outer shift size must be >= the number of bits added by the ext.
4275 // As a corollary, we don't care what kind of ext it is.
4276 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4277 N0.getOpcode() == ISD::ANY_EXTEND ||
4278 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4279 N0.getOperand(0).getOpcode() == ISD::SHL) {
4280 SDValue N0Op0 = N0.getOperand(0);
4281 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4282 uint64_t c1 = N0Op0C1->getZExtValue();
4283 uint64_t c2 = N1C->getZExtValue();
4284 EVT InnerShiftVT = N0Op0.getValueType();
4285 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4286 if (c2 >= OpSizeInBits - InnerShiftSize) {
4288 if (c1 + c2 >= OpSizeInBits)
4289 return DAG.getConstant(0, DL, VT);
4290 return DAG.getNode(ISD::SHL, DL, VT,
4291 DAG.getNode(N0.getOpcode(), DL, VT,
4292 N0Op0->getOperand(0)),
4293 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4298 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4299 // Only fold this if the inner zext has no other uses to avoid increasing
4300 // the total number of instructions.
4301 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4302 N0.getOperand(0).getOpcode() == ISD::SRL) {
4303 SDValue N0Op0 = N0.getOperand(0);
4304 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305 uint64_t c1 = N0Op0C1->getZExtValue();
4306 if (c1 < VT.getScalarSizeInBits()) {
4307 uint64_t c2 = N1C->getZExtValue();
4309 SDValue NewOp0 = N0.getOperand(0);
4310 EVT CountVT = NewOp0.getOperand(1).getValueType();
4312 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314 DAG.getConstant(c2, DL, CountVT));
4315 AddToWorklist(NewSHL.getNode());
4316 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4322 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4323 // (and (srl x, (sub c1, c2), MASK)
4324 // Only fold this if the inner shift has no other uses -- if it does, folding
4325 // this will increase the total number of instructions.
4326 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4327 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4328 uint64_t c1 = N0C1->getZExtValue();
4329 if (c1 < OpSizeInBits) {
4330 uint64_t c2 = N1C->getZExtValue();
4331 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4334 Mask = Mask.shl(c2 - c1);
4336 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4337 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339 Mask = Mask.lshr(c1 - c2);
4341 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4342 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4345 return DAG.getNode(ISD::AND, DL, VT, Shift,
4346 DAG.getConstant(Mask, DL, VT));
4350 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4351 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4352 unsigned BitSize = VT.getScalarSizeInBits();
4354 SDValue HiBitsMask =
4355 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4356 BitSize - N1C->getZExtValue()),
4358 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4362 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4363 // Variant of version done on multiply, except mul by a power of 2 is turned
4366 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4367 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4368 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4369 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4370 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4371 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4375 SDValue NewSHL = visitShiftByConstant(N, N1C);
4376 if (NewSHL.getNode())
4383 SDValue DAGCombiner::visitSRA(SDNode *N) {
4384 SDValue N0 = N->getOperand(0);
4385 SDValue N1 = N->getOperand(1);
4386 EVT VT = N0.getValueType();
4387 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4390 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4391 if (VT.isVector()) {
4392 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4395 N1C = isConstOrConstSplat(N1);
4398 // fold (sra c1, c2) -> (sra c1, c2)
4399 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4402 // fold (sra 0, x) -> 0
4403 if (N0C && N0C->isNullValue())
4405 // fold (sra -1, x) -> -1
4406 if (N0C && N0C->isAllOnesValue())
4408 // fold (sra x, (setge c, size(x))) -> undef
4409 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4410 return DAG.getUNDEF(VT);
4411 // fold (sra x, 0) -> x
4412 if (N1C && N1C->isNullValue())
4414 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4417 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4418 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4421 ExtVT, VT.getVectorNumElements());
4422 if ((!LegalOperations ||
4423 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4424 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4425 N0.getOperand(0), DAG.getValueType(ExtVT));
4428 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4429 if (N1C && N0.getOpcode() == ISD::SRA) {
4430 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4431 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4432 if (Sum >= OpSizeInBits)
4433 Sum = OpSizeInBits - 1;
4435 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4436 DAG.getConstant(Sum, DL, N1.getValueType()));
4440 // fold (sra (shl X, m), (sub result_size, n))
4441 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4442 // result_size - n != m.
4443 // If truncate is free for the target sext(shl) is likely to result in better
4445 if (N0.getOpcode() == ISD::SHL && N1C) {
4446 // Get the two constanst of the shifts, CN0 = m, CN = n.
4447 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449 LLVMContext &Ctx = *DAG.getContext();
4450 // Determine what the truncate's result bitsize and type would be.
4451 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4454 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456 // Determine the residual right-shift amount.
4457 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459 // If the shift is not a no-op (in which case this should be just a sign
4460 // extend already), the truncated to type is legal, sign_extend is legal
4461 // on that type, and the truncate to that type is both legal and free,
4462 // perform the transform.
4463 if ((ShiftAmt > 0) &&
4464 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4465 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4466 TLI.isTruncateFree(VT, TruncVT)) {
4469 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4470 getShiftAmountTy(N0.getOperand(0).getValueType()));
4471 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4472 N0.getOperand(0), Amt);
4473 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4476 N->getValueType(0), Trunc);
4481 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4482 if (N1.getOpcode() == ISD::TRUNCATE &&
4483 N1.getOperand(0).getOpcode() == ISD::AND) {
4484 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4485 if (NewOp1.getNode())
4486 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4489 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4490 // if c1 is equal to the number of bits the trunc removes
4491 if (N0.getOpcode() == ISD::TRUNCATE &&
4492 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4493 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4494 N0.getOperand(0).hasOneUse() &&
4495 N0.getOperand(0).getOperand(1).hasOneUse() &&
4497 SDValue N0Op0 = N0.getOperand(0);
4498 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4499 unsigned LargeShiftVal = LargeShift->getZExtValue();
4500 EVT LargeVT = N0Op0.getValueType();
4502 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4505 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4506 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4507 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4508 N0Op0.getOperand(0), Amt);
4509 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4514 // Simplify, based on bits shifted out of the LHS.
4515 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516 return SDValue(N, 0);
4519 // If the sign bit is known to be zero, switch this to a SRL.
4520 if (DAG.SignBitIsZero(N0))
4521 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4524 SDValue NewSRA = visitShiftByConstant(N, N1C);
4525 if (NewSRA.getNode())
4532 SDValue DAGCombiner::visitSRL(SDNode *N) {
4533 SDValue N0 = N->getOperand(0);
4534 SDValue N1 = N->getOperand(1);
4535 EVT VT = N0.getValueType();
4536 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4539 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4540 if (VT.isVector()) {
4541 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4544 N1C = isConstOrConstSplat(N1);
4547 // fold (srl c1, c2) -> c1 >>u c2
4548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4551 // fold (srl 0, x) -> 0
4552 if (N0C && N0C->isNullValue())
4554 // fold (srl x, c >= size(x)) -> undef
4555 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556 return DAG.getUNDEF(VT);
4557 // fold (srl x, 0) -> x
4558 if (N1C && N1C->isNullValue())
4560 // if (srl x, c) is known to be zero, return 0
4561 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4562 APInt::getAllOnesValue(OpSizeInBits)))
4563 return DAG.getConstant(0, SDLoc(N), VT);
4565 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4566 if (N1C && N0.getOpcode() == ISD::SRL) {
4567 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4568 uint64_t c1 = N01C->getZExtValue();
4569 uint64_t c2 = N1C->getZExtValue();
4571 if (c1 + c2 >= OpSizeInBits)
4572 return DAG.getConstant(0, DL, VT);
4573 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4574 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4578 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4579 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4580 N0.getOperand(0).getOpcode() == ISD::SRL &&
4581 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4584 uint64_t c2 = N1C->getZExtValue();
4585 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4586 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4587 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4588 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4589 if (c1 + OpSizeInBits == InnerShiftSize) {
4591 if (c1 + c2 >= InnerShiftSize)
4592 return DAG.getConstant(0, DL, VT);
4593 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4594 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4595 N0.getOperand(0)->getOperand(0),
4596 DAG.getConstant(c1 + c2, DL,
4601 // fold (srl (shl x, c), c) -> (and x, cst2)
4602 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4603 unsigned BitSize = N0.getScalarValueSizeInBits();
4604 if (BitSize <= 64) {
4605 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4608 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4612 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4613 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4614 // Shifting in all undef bits?
4615 EVT SmallVT = N0.getOperand(0).getValueType();
4616 unsigned BitSize = SmallVT.getScalarSizeInBits();
4617 if (N1C->getZExtValue() >= BitSize)
4618 return DAG.getUNDEF(VT);
4620 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4621 uint64_t ShiftAmt = N1C->getZExtValue();
4623 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625 DAG.getConstant(ShiftAmt, DL0,
4626 getShiftAmountTy(SmallVT)));
4627 AddToWorklist(SmallShift.getNode());
4628 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630 return DAG.getNode(ISD::AND, DL, VT,
4631 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4632 DAG.getConstant(Mask, DL, VT));
4636 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4637 // bit, which is unmodified by sra.
4638 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4639 if (N0.getOpcode() == ISD::SRA)
4640 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4643 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4644 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4645 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4646 APInt KnownZero, KnownOne;
4647 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649 // If any of the input bits are KnownOne, then the input couldn't be all
4650 // zeros, thus the result of the srl will always be zero.
4651 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653 // If all of the bits input the to ctlz node are known to be zero, then
4654 // the result of the ctlz is "32" and the result of the shift is one.
4655 APInt UnknownBits = ~KnownZero;
4656 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4659 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4660 // Okay, we know that only that the single bit specified by UnknownBits
4661 // could be set on input to the CTLZ node. If this bit is set, the SRL
4662 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4663 // to an SRL/XOR pair, which is likely to simplify more.
4664 unsigned ShAmt = UnknownBits.countTrailingZeros();
4665 SDValue Op = N0.getOperand(0);
4669 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4670 DAG.getConstant(ShAmt, DL,
4671 getShiftAmountTy(Op.getValueType())));
4672 AddToWorklist(Op.getNode());
4676 return DAG.getNode(ISD::XOR, DL, VT,
4677 Op, DAG.getConstant(1, DL, VT));
4681 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4682 if (N1.getOpcode() == ISD::TRUNCATE &&
4683 N1.getOperand(0).getOpcode() == ISD::AND) {
4684 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4685 if (NewOp1.getNode())
4686 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4689 // fold operands of srl based on knowledge that the low bits are not
4691 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692 return SDValue(N, 0);
4695 SDValue NewSRL = visitShiftByConstant(N, N1C);
4696 if (NewSRL.getNode())
4700 // Attempt to convert a srl of a load into a narrower zero-extending load.
4701 SDValue NarrowLoad = ReduceLoadWidth(N);
4702 if (NarrowLoad.getNode())
4705 // Here is a common situation. We want to optimize:
4708 // %b = and i32 %a, 2
4709 // %c = srl i32 %b, 1
4710 // brcond i32 %c ...
4716 // %c = setcc eq %b, 0
4719 // However when after the source operand of SRL is optimized into AND, the SRL
4720 // itself may not be optimized further. Look for it and add the BRCOND into
4722 if (N->hasOneUse()) {
4723 SDNode *Use = *N->use_begin();
4724 if (Use->getOpcode() == ISD::BRCOND)
4726 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4727 // Also look pass the truncate.
4728 Use = *Use->use_begin();
4729 if (Use->getOpcode() == ISD::BRCOND)
4737 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4738 SDValue N0 = N->getOperand(0);
4739 EVT VT = N->getValueType(0);
4741 // fold (ctlz c1) -> c2
4742 if (isa<ConstantSDNode>(N0))
4743 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4747 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4748 SDValue N0 = N->getOperand(0);
4749 EVT VT = N->getValueType(0);
4751 // fold (ctlz_zero_undef c1) -> c2
4752 if (isa<ConstantSDNode>(N0))
4753 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4757 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4758 SDValue N0 = N->getOperand(0);
4759 EVT VT = N->getValueType(0);
4761 // fold (cttz c1) -> c2
4762 if (isa<ConstantSDNode>(N0))
4763 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4767 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4768 SDValue N0 = N->getOperand(0);
4769 EVT VT = N->getValueType(0);
4771 // fold (cttz_zero_undef c1) -> c2
4772 if (isa<ConstantSDNode>(N0))
4773 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4777 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4778 SDValue N0 = N->getOperand(0);
4779 EVT VT = N->getValueType(0);
4781 // fold (ctpop c1) -> c2
4782 if (isa<ConstantSDNode>(N0))
4783 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4788 /// \brief Generate Min/Max node
4789 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4790 SDValue True, SDValue False,
4791 ISD::CondCode CC, const TargetLowering &TLI,
4792 SelectionDAG &DAG) {
4793 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4803 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4804 if (TLI.isOperationLegal(Opcode, VT))
4805 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4814 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4815 if (TLI.isOperationLegal(Opcode, VT))
4816 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4824 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4825 SDValue N0 = N->getOperand(0);
4826 SDValue N1 = N->getOperand(1);
4827 SDValue N2 = N->getOperand(2);
4828 EVT VT = N->getValueType(0);
4829 EVT VT0 = N0.getValueType();
4831 // fold (select C, X, X) -> X
4834 // fold (select true, X, Y) -> X
4835 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4836 if (N0C && !N0C->isNullValue())
4838 // fold (select false, X, Y) -> Y
4839 if (N0C && N0C->isNullValue())
4841 // fold (select C, 1, X) -> (or C, X)
4842 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4843 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4844 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4845 // fold (select C, 0, 1) -> (xor C, 1)
4846 // We can't do this reliably if integer based booleans have different contents
4847 // to floating point based booleans. This is because we can't tell whether we
4848 // have an integer-based boolean or a floating-point-based boolean unless we
4849 // can find the SETCC that produced it and inspect its operands. This is
4850 // fairly easy if C is the SETCC node, but it can potentially be
4851 // undiscoverable (or not reasonably discoverable). For example, it could be
4852 // in another basic block or it could require searching a complicated
4854 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4855 if (VT.isInteger() &&
4856 (VT0 == MVT::i1 || (VT0.isInteger() &&
4857 TLI.getBooleanContents(false, false) ==
4858 TLI.getBooleanContents(false, true) &&
4859 TLI.getBooleanContents(false, false) ==
4860 TargetLowering::ZeroOrOneBooleanContent)) &&
4861 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4865 return DAG.getNode(ISD::XOR, DL, VT0,
4866 N0, DAG.getConstant(1, DL, VT0));
4869 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4870 N0, DAG.getConstant(1, DL0, VT0));
4871 AddToWorklist(XORNode.getNode());
4873 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4874 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4876 // fold (select C, 0, X) -> (and (not C), X)
4877 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4878 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4879 AddToWorklist(NOTNode.getNode());
4880 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4882 // fold (select C, X, 1) -> (or (not C), X)
4883 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4884 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4885 AddToWorklist(NOTNode.getNode());
4886 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4888 // fold (select C, X, 0) -> (and C, X)
4889 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4890 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4891 // fold (select X, X, Y) -> (or X, Y)
4892 // fold (select X, 1, Y) -> (or X, Y)
4893 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4894 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4895 // fold (select X, Y, X) -> (and X, Y)
4896 // fold (select X, Y, 0) -> (and X, Y)
4897 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4898 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4900 // If we can fold this based on the true/false value, do so.
4901 if (SimplifySelectOps(N, N1, N2))
4902 return SDValue(N, 0); // Don't revisit N.
4904 // fold selects based on a setcc into other things, such as min/max/abs
4905 if (N0.getOpcode() == ISD::SETCC) {
4906 // select x, y (fcmp lt x, y) -> fminnum x, y
4907 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4909 // This is OK if we don't care about what happens if either operand is a
4913 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4914 // no signed zeros as well as no nans.
4915 const TargetOptions &Options = DAG.getTarget().Options;
4916 if (Options.UnsafeFPMath &&
4917 VT.isFloatingPoint() && N0.hasOneUse() &&
4918 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4919 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4922 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4923 N1, N2, CC, TLI, DAG);
4928 if ((!LegalOperations &&
4929 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4930 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4931 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4932 N0.getOperand(0), N0.getOperand(1),
4933 N1, N2, N0.getOperand(2));
4934 return SimplifySelect(SDLoc(N), N0, N1, N2);
4937 if (VT0 == MVT::i1) {
4938 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4939 // select (and Cond0, Cond1), X, Y
4940 // -> select Cond0, (select Cond1, X, Y), Y
4941 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4942 SDValue Cond0 = N0->getOperand(0);
4943 SDValue Cond1 = N0->getOperand(1);
4944 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4945 N1.getValueType(), Cond1, N1, N2);
4946 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4949 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4950 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4951 SDValue Cond0 = N0->getOperand(0);
4952 SDValue Cond1 = N0->getOperand(1);
4953 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4954 N1.getValueType(), Cond1, N1, N2);
4955 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4960 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4961 if (N1->getOpcode() == ISD::SELECT) {
4962 SDValue N1_0 = N1->getOperand(0);
4963 SDValue N1_1 = N1->getOperand(1);
4964 SDValue N1_2 = N1->getOperand(2);
4965 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4966 // Create the actual and node if we can generate good code for it.
4967 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4968 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4970 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4973 // Otherwise see if we can optimize the "and" to a better pattern.
4974 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4975 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4979 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4980 if (N2->getOpcode() == ISD::SELECT) {
4981 SDValue N2_0 = N2->getOperand(0);
4982 SDValue N2_1 = N2->getOperand(1);
4983 SDValue N2_2 = N2->getOperand(2);
4984 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4985 // Create the actual or node if we can generate good code for it.
4986 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4987 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4989 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4992 // Otherwise see if we can optimize to a better pattern.
4993 if (SDValue Combined = visitORLike(N0, N2_0, N))
4994 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5004 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5007 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5009 // Split the inputs.
5010 SDValue Lo, Hi, LL, LH, RL, RH;
5011 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5012 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5014 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5015 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5017 return std::make_pair(Lo, Hi);
5020 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5021 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5022 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5024 SDValue Cond = N->getOperand(0);
5025 SDValue LHS = N->getOperand(1);
5026 SDValue RHS = N->getOperand(2);
5027 EVT VT = N->getValueType(0);
5028 int NumElems = VT.getVectorNumElements();
5029 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5030 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5031 Cond.getOpcode() == ISD::BUILD_VECTOR);
5033 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5034 // binary ones here.
5035 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5038 // We're sure we have an even number of elements due to the
5039 // concat_vectors we have as arguments to vselect.
5040 // Skip BV elements until we find one that's not an UNDEF
5041 // After we find an UNDEF element, keep looping until we get to half the
5042 // length of the BV and see if all the non-undef nodes are the same.
5043 ConstantSDNode *BottomHalf = nullptr;
5044 for (int i = 0; i < NumElems / 2; ++i) {
5045 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5048 if (BottomHalf == nullptr)
5049 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5050 else if (Cond->getOperand(i).getNode() != BottomHalf)
5054 // Do the same for the second half of the BuildVector
5055 ConstantSDNode *TopHalf = nullptr;
5056 for (int i = NumElems / 2; i < NumElems; ++i) {
5057 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5060 if (TopHalf == nullptr)
5061 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5062 else if (Cond->getOperand(i).getNode() != TopHalf)
5066 assert(TopHalf && BottomHalf &&
5067 "One half of the selector was all UNDEFs and the other was all the "
5068 "same value. This should have been addressed before this function.");
5070 ISD::CONCAT_VECTORS, dl, VT,
5071 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5072 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5075 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5077 if (Level >= AfterLegalizeTypes)
5080 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5081 SDValue Mask = MST->getMask();
5082 SDValue Data = MST->getValue();
5085 // If the MSTORE data type requires splitting and the mask is provided by a
5086 // SETCC, then split both nodes and its operands before legalization. This
5087 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5088 // and enables future optimizations (e.g. min/max pattern matching on X86).
5089 if (Mask.getOpcode() == ISD::SETCC) {
5091 // Check if any splitting is required.
5092 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5093 TargetLowering::TypeSplitVector)
5096 SDValue MaskLo, MaskHi, Lo, Hi;
5097 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5100 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5102 SDValue Chain = MST->getChain();
5103 SDValue Ptr = MST->getBasePtr();
5105 EVT MemoryVT = MST->getMemoryVT();
5106 unsigned Alignment = MST->getOriginalAlignment();
5108 // if Alignment is equal to the vector size,
5109 // take the half of it for the second part
5110 unsigned SecondHalfAlignment =
5111 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5112 Alignment/2 : Alignment;
5114 EVT LoMemVT, HiMemVT;
5115 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5117 SDValue DataLo, DataHi;
5118 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5120 MachineMemOperand *MMO = DAG.getMachineFunction().
5121 getMachineMemOperand(MST->getPointerInfo(),
5122 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5123 Alignment, MST->getAAInfo(), MST->getRanges());
5125 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5126 MST->isTruncatingStore());
5128 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5129 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5130 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5132 MMO = DAG.getMachineFunction().
5133 getMachineMemOperand(MST->getPointerInfo(),
5134 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5135 SecondHalfAlignment, MST->getAAInfo(),
5138 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5139 MST->isTruncatingStore());
5141 AddToWorklist(Lo.getNode());
5142 AddToWorklist(Hi.getNode());
5144 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5149 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5151 if (Level >= AfterLegalizeTypes)
5154 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5155 SDValue Mask = MLD->getMask();
5158 // If the MLOAD result requires splitting and the mask is provided by a
5159 // SETCC, then split both nodes and its operands before legalization. This
5160 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5161 // and enables future optimizations (e.g. min/max pattern matching on X86).
5163 if (Mask.getOpcode() == ISD::SETCC) {
5164 EVT VT = N->getValueType(0);
5166 // Check if any splitting is required.
5167 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5168 TargetLowering::TypeSplitVector)
5171 SDValue MaskLo, MaskHi, Lo, Hi;
5172 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5174 SDValue Src0 = MLD->getSrc0();
5175 SDValue Src0Lo, Src0Hi;
5176 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5179 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5181 SDValue Chain = MLD->getChain();
5182 SDValue Ptr = MLD->getBasePtr();
5183 EVT MemoryVT = MLD->getMemoryVT();
5184 unsigned Alignment = MLD->getOriginalAlignment();
5186 // if Alignment is equal to the vector size,
5187 // take the half of it for the second part
5188 unsigned SecondHalfAlignment =
5189 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5190 Alignment/2 : Alignment;
5192 EVT LoMemVT, HiMemVT;
5193 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5195 MachineMemOperand *MMO = DAG.getMachineFunction().
5196 getMachineMemOperand(MLD->getPointerInfo(),
5197 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5198 Alignment, MLD->getAAInfo(), MLD->getRanges());
5200 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5203 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5204 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5205 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5207 MMO = DAG.getMachineFunction().
5208 getMachineMemOperand(MLD->getPointerInfo(),
5209 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5210 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5212 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5215 AddToWorklist(Lo.getNode());
5216 AddToWorklist(Hi.getNode());
5218 // Build a factor node to remember that this load is independent of the
5220 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5223 // Legalized the chain result - switch anything that used the old chain to
5225 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5227 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5229 SDValue RetOps[] = { LoadRes, Chain };
5230 return DAG.getMergeValues(RetOps, DL);
5235 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5236 SDValue N0 = N->getOperand(0);
5237 SDValue N1 = N->getOperand(1);
5238 SDValue N2 = N->getOperand(2);
5241 // Canonicalize integer abs.
5242 // vselect (setg[te] X, 0), X, -X ->
5243 // vselect (setgt X, -1), X, -X ->
5244 // vselect (setl[te] X, 0), -X, X ->
5245 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5246 if (N0.getOpcode() == ISD::SETCC) {
5247 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5248 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5250 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5252 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5253 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5254 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5255 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5256 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5257 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5258 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5261 EVT VT = LHS.getValueType();
5262 SDValue Shift = DAG.getNode(
5263 ISD::SRA, DL, VT, LHS,
5264 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5265 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5266 AddToWorklist(Shift.getNode());
5267 AddToWorklist(Add.getNode());
5268 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5272 if (SimplifySelectOps(N, N1, N2))
5273 return SDValue(N, 0); // Don't revisit N.
5275 // If the VSELECT result requires splitting and the mask is provided by a
5276 // SETCC, then split both nodes and its operands before legalization. This
5277 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5278 // and enables future optimizations (e.g. min/max pattern matching on X86).
5279 if (N0.getOpcode() == ISD::SETCC) {
5280 EVT VT = N->getValueType(0);
5282 // Check if any splitting is required.
5283 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5284 TargetLowering::TypeSplitVector)
5287 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5288 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5289 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5290 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5292 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5293 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5295 // Add the new VSELECT nodes to the work list in case they need to be split
5297 AddToWorklist(Lo.getNode());
5298 AddToWorklist(Hi.getNode());
5300 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5303 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5304 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5306 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5307 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5310 // The ConvertSelectToConcatVector function is assuming both the above
5311 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5313 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5314 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5315 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5316 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5324 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5325 SDValue N0 = N->getOperand(0);
5326 SDValue N1 = N->getOperand(1);
5327 SDValue N2 = N->getOperand(2);
5328 SDValue N3 = N->getOperand(3);
5329 SDValue N4 = N->getOperand(4);
5330 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5332 // fold select_cc lhs, rhs, x, x, cc -> x
5336 // Determine if the condition we're dealing with is constant
5337 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5338 N0, N1, CC, SDLoc(N), false);
5339 if (SCC.getNode()) {
5340 AddToWorklist(SCC.getNode());
5342 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5343 if (!SCCC->isNullValue())
5344 return N2; // cond always true -> true val
5346 return N3; // cond always false -> false val
5347 } else if (SCC->getOpcode() == ISD::UNDEF) {
5348 // When the condition is UNDEF, just return the first operand. This is
5349 // coherent the DAG creation, no setcc node is created in this case
5351 } else if (SCC.getOpcode() == ISD::SETCC) {
5352 // Fold to a simpler select_cc
5353 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5354 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5359 // If we can fold this based on the true/false value, do so.
5360 if (SimplifySelectOps(N, N2, N3))
5361 return SDValue(N, 0); // Don't revisit N.
5363 // fold select_cc into other things, such as min/max/abs
5364 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5367 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5368 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5369 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5373 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5374 // dag node into a ConstantSDNode or a build_vector of constants.
5375 // This function is called by the DAGCombiner when visiting sext/zext/aext
5376 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5377 // Vector extends are not folded if operations are legal; this is to
5378 // avoid introducing illegal build_vector dag nodes.
5379 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5380 SelectionDAG &DAG, bool LegalTypes,
5381 bool LegalOperations) {
5382 unsigned Opcode = N->getOpcode();
5383 SDValue N0 = N->getOperand(0);
5384 EVT VT = N->getValueType(0);
5386 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5387 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5389 // fold (sext c1) -> c1
5390 // fold (zext c1) -> c1
5391 // fold (aext c1) -> c1
5392 if (isa<ConstantSDNode>(N0))
5393 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5395 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5396 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5397 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5398 EVT SVT = VT.getScalarType();
5399 if (!(VT.isVector() &&
5400 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5401 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5404 // We can fold this node into a build_vector.
5405 unsigned VTBits = SVT.getSizeInBits();
5406 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5407 unsigned ShAmt = VTBits - EVTBits;
5408 SmallVector<SDValue, 8> Elts;
5409 unsigned NumElts = N0->getNumOperands();
5412 for (unsigned i=0; i != NumElts; ++i) {
5413 SDValue Op = N0->getOperand(i);
5414 if (Op->getOpcode() == ISD::UNDEF) {
5415 Elts.push_back(DAG.getUNDEF(SVT));
5420 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5421 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5422 if (Opcode == ISD::SIGN_EXTEND)
5423 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5426 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5430 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5433 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5434 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5435 // transformation. Returns true if extension are possible and the above
5436 // mentioned transformation is profitable.
5437 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5439 SmallVectorImpl<SDNode *> &ExtendNodes,
5440 const TargetLowering &TLI) {
5441 bool HasCopyToRegUses = false;
5442 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5443 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5444 UE = N0.getNode()->use_end();
5449 if (UI.getUse().getResNo() != N0.getResNo())
5451 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5452 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5453 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5454 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5455 // Sign bits will be lost after a zext.
5458 for (unsigned i = 0; i != 2; ++i) {
5459 SDValue UseOp = User->getOperand(i);
5462 if (!isa<ConstantSDNode>(UseOp))
5467 ExtendNodes.push_back(User);
5470 // If truncates aren't free and there are users we can't
5471 // extend, it isn't worthwhile.
5474 // Remember if this value is live-out.
5475 if (User->getOpcode() == ISD::CopyToReg)
5476 HasCopyToRegUses = true;
5479 if (HasCopyToRegUses) {
5480 bool BothLiveOut = false;
5481 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5483 SDUse &Use = UI.getUse();
5484 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5490 // Both unextended and extended values are live out. There had better be
5491 // a good reason for the transformation.
5492 return ExtendNodes.size();
5497 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5498 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5499 ISD::NodeType ExtType) {
5500 // Extend SetCC uses if necessary.
5501 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5502 SDNode *SetCC = SetCCs[i];
5503 SmallVector<SDValue, 4> Ops;
5505 for (unsigned j = 0; j != 2; ++j) {
5506 SDValue SOp = SetCC->getOperand(j);
5508 Ops.push_back(ExtLoad);
5510 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5513 Ops.push_back(SetCC->getOperand(2));
5514 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5518 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5519 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5520 SDValue N0 = N->getOperand(0);
5521 EVT DstVT = N->getValueType(0);
5522 EVT SrcVT = N0.getValueType();
5524 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5525 N->getOpcode() == ISD::ZERO_EXTEND) &&
5526 "Unexpected node type (not an extend)!");
5528 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5529 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5530 // (v8i32 (sext (v8i16 (load x))))
5532 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5533 // (v4i32 (sextload (x + 16)))))
5534 // Where uses of the original load, i.e.:
5536 // are replaced with:
5538 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5539 // (v4i32 (sextload (x + 16)))))))
5541 // This combine is only applicable to illegal, but splittable, vectors.
5542 // All legal types, and illegal non-vector types, are handled elsewhere.
5543 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5545 if (N0->getOpcode() != ISD::LOAD)
5548 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5550 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5551 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5552 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5555 SmallVector<SDNode *, 4> SetCCs;
5556 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5559 ISD::LoadExtType ExtType =
5560 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5562 // Try to split the vector types to get down to legal types.
5563 EVT SplitSrcVT = SrcVT;
5564 EVT SplitDstVT = DstVT;
5565 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5566 SplitSrcVT.getVectorNumElements() > 1) {
5567 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5568 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5571 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5575 const unsigned NumSplits =
5576 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5577 const unsigned Stride = SplitSrcVT.getStoreSize();
5578 SmallVector<SDValue, 4> Loads;
5579 SmallVector<SDValue, 4> Chains;
5581 SDValue BasePtr = LN0->getBasePtr();
5582 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5583 const unsigned Offset = Idx * Stride;
5584 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5586 SDValue SplitLoad = DAG.getExtLoad(
5587 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5588 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5589 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5590 Align, LN0->getAAInfo());
5592 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5593 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5595 Loads.push_back(SplitLoad.getValue(0));
5596 Chains.push_back(SplitLoad.getValue(1));
5599 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5600 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5602 CombineTo(N, NewValue);
5604 // Replace uses of the original load (before extension)
5605 // with a truncate of the concatenated sextloaded vectors.
5607 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5608 CombineTo(N0.getNode(), Trunc, NewChain);
5609 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5610 (ISD::NodeType)N->getOpcode());
5611 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5614 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5615 SDValue N0 = N->getOperand(0);
5616 EVT VT = N->getValueType(0);
5618 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5620 return SDValue(Res, 0);
5622 // fold (sext (sext x)) -> (sext x)
5623 // fold (sext (aext x)) -> (sext x)
5624 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5625 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5628 if (N0.getOpcode() == ISD::TRUNCATE) {
5629 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5630 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5631 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5632 if (NarrowLoad.getNode()) {
5633 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5634 if (NarrowLoad.getNode() != N0.getNode()) {
5635 CombineTo(N0.getNode(), NarrowLoad);
5636 // CombineTo deleted the truncate, if needed, but not what's under it.
5639 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5642 // See if the value being truncated is already sign extended. If so, just
5643 // eliminate the trunc/sext pair.
5644 SDValue Op = N0.getOperand(0);
5645 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5646 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5647 unsigned DestBits = VT.getScalarType().getSizeInBits();
5648 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5650 if (OpBits == DestBits) {
5651 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5652 // bits, it is already ready.
5653 if (NumSignBits > DestBits-MidBits)
5655 } else if (OpBits < DestBits) {
5656 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5657 // bits, just sext from i32.
5658 if (NumSignBits > OpBits-MidBits)
5659 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5661 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5662 // bits, just truncate to i32.
5663 if (NumSignBits > OpBits-MidBits)
5664 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5667 // fold (sext (truncate x)) -> (sextinreg x).
5668 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5669 N0.getValueType())) {
5670 if (OpBits < DestBits)
5671 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5672 else if (OpBits > DestBits)
5673 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5674 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5675 DAG.getValueType(N0.getValueType()));
5679 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5680 // Only generate vector extloads when 1) they're legal, and 2) they are
5681 // deemed desirable by the target.
5682 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5683 ((!LegalOperations && !VT.isVector() &&
5684 !cast<LoadSDNode>(N0)->isVolatile()) ||
5685 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5686 bool DoXform = true;
5687 SmallVector<SDNode*, 4> SetCCs;
5688 if (!N0.hasOneUse())
5689 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5691 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5693 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5694 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5696 LN0->getBasePtr(), N0.getValueType(),
5697 LN0->getMemOperand());
5698 CombineTo(N, ExtLoad);
5699 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5700 N0.getValueType(), ExtLoad);
5701 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5702 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5704 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5708 // fold (sext (load x)) to multiple smaller sextloads.
5709 // Only on illegal but splittable vectors.
5710 if (SDValue ExtLoad = CombineExtLoad(N))
5713 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5714 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5715 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5716 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5717 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5718 EVT MemVT = LN0->getMemoryVT();
5719 if ((!LegalOperations && !LN0->isVolatile()) ||
5720 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5721 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5723 LN0->getBasePtr(), MemVT,
5724 LN0->getMemOperand());
5725 CombineTo(N, ExtLoad);
5726 CombineTo(N0.getNode(),
5727 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5728 N0.getValueType(), ExtLoad),
5729 ExtLoad.getValue(1));
5730 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5734 // fold (sext (and/or/xor (load x), cst)) ->
5735 // (and/or/xor (sextload x), (sext cst))
5736 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5737 N0.getOpcode() == ISD::XOR) &&
5738 isa<LoadSDNode>(N0.getOperand(0)) &&
5739 N0.getOperand(1).getOpcode() == ISD::Constant &&
5740 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5741 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5742 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5743 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5744 bool DoXform = true;
5745 SmallVector<SDNode*, 4> SetCCs;
5746 if (!N0.hasOneUse())
5747 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5750 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5751 LN0->getChain(), LN0->getBasePtr(),
5753 LN0->getMemOperand());
5754 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5755 Mask = Mask.sext(VT.getSizeInBits());
5757 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5758 ExtLoad, DAG.getConstant(Mask, DL, VT));
5759 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5760 SDLoc(N0.getOperand(0)),
5761 N0.getOperand(0).getValueType(), ExtLoad);
5763 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5764 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5766 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5771 if (N0.getOpcode() == ISD::SETCC) {
5772 EVT N0VT = N0.getOperand(0).getValueType();
5773 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5774 // Only do this before legalize for now.
5775 if (VT.isVector() && !LegalOperations &&
5776 TLI.getBooleanContents(N0VT) ==
5777 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5778 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5779 // of the same size as the compared operands. Only optimize sext(setcc())
5780 // if this is the case.
5781 EVT SVT = getSetCCResultType(N0VT);
5783 // We know that the # elements of the results is the same as the
5784 // # elements of the compare (and the # elements of the compare result
5785 // for that matter). Check to see that they are the same size. If so,
5786 // we know that the element size of the sext'd result matches the
5787 // element size of the compare operands.
5788 if (VT.getSizeInBits() == SVT.getSizeInBits())
5789 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5791 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5793 // If the desired elements are smaller or larger than the source
5794 // elements we can use a matching integer vector type and then
5795 // truncate/sign extend
5796 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5797 if (SVT == MatchingVectorType) {
5798 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5799 N0.getOperand(0), N0.getOperand(1),
5800 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5801 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5805 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5806 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5809 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5811 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5812 NegOne, DAG.getConstant(0, DL, VT),
5813 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5814 if (SCC.getNode()) return SCC;
5816 if (!VT.isVector()) {
5817 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5818 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5820 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5821 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5822 N0.getOperand(0), N0.getOperand(1), CC);
5823 return DAG.getSelect(DL, VT, SetCC,
5824 NegOne, DAG.getConstant(0, DL, VT));
5829 // fold (sext x) -> (zext x) if the sign bit is known zero.
5830 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5831 DAG.SignBitIsZero(N0))
5832 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5837 // isTruncateOf - If N is a truncate of some other value, return true, record
5838 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5839 // This function computes KnownZero to avoid a duplicated call to
5840 // computeKnownBits in the caller.
5841 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5844 if (N->getOpcode() == ISD::TRUNCATE) {
5845 Op = N->getOperand(0);
5846 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5850 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5851 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5854 SDValue Op0 = N->getOperand(0);
5855 SDValue Op1 = N->getOperand(1);
5856 assert(Op0.getValueType() == Op1.getValueType());
5858 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5859 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5860 if (COp0 && COp0->isNullValue())
5862 else if (COp1 && COp1->isNullValue())
5867 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5869 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5875 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5876 SDValue N0 = N->getOperand(0);
5877 EVT VT = N->getValueType(0);
5879 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5881 return SDValue(Res, 0);
5883 // fold (zext (zext x)) -> (zext x)
5884 // fold (zext (aext x)) -> (zext x)
5885 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5886 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5889 // fold (zext (truncate x)) -> (zext x) or
5890 // (zext (truncate x)) -> (truncate x)
5891 // This is valid when the truncated bits of x are already zero.
5892 // FIXME: We should extend this to work for vectors too.
5895 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5896 APInt TruncatedBits =
5897 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5898 APInt(Op.getValueSizeInBits(), 0) :
5899 APInt::getBitsSet(Op.getValueSizeInBits(),
5900 N0.getValueSizeInBits(),
5901 std::min(Op.getValueSizeInBits(),
5902 VT.getSizeInBits()));
5903 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5904 if (VT.bitsGT(Op.getValueType()))
5905 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5906 if (VT.bitsLT(Op.getValueType()))
5907 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5913 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5914 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5915 if (N0.getOpcode() == ISD::TRUNCATE) {
5916 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5917 if (NarrowLoad.getNode()) {
5918 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5919 if (NarrowLoad.getNode() != N0.getNode()) {
5920 CombineTo(N0.getNode(), NarrowLoad);
5921 // CombineTo deleted the truncate, if needed, but not what's under it.
5924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5928 // fold (zext (truncate x)) -> (and x, mask)
5929 if (N0.getOpcode() == ISD::TRUNCATE &&
5930 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5932 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5933 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5934 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5935 if (NarrowLoad.getNode()) {
5936 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5937 if (NarrowLoad.getNode() != N0.getNode()) {
5938 CombineTo(N0.getNode(), NarrowLoad);
5939 // CombineTo deleted the truncate, if needed, but not what's under it.
5942 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5945 SDValue Op = N0.getOperand(0);
5946 if (Op.getValueType().bitsLT(VT)) {
5947 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5948 AddToWorklist(Op.getNode());
5949 } else if (Op.getValueType().bitsGT(VT)) {
5950 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5951 AddToWorklist(Op.getNode());
5953 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5954 N0.getValueType().getScalarType());
5957 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5958 // if either of the casts is not free.
5959 if (N0.getOpcode() == ISD::AND &&
5960 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5961 N0.getOperand(1).getOpcode() == ISD::Constant &&
5962 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5963 N0.getValueType()) ||
5964 !TLI.isZExtFree(N0.getValueType(), VT))) {
5965 SDValue X = N0.getOperand(0).getOperand(0);
5966 if (X.getValueType().bitsLT(VT)) {
5967 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5968 } else if (X.getValueType().bitsGT(VT)) {
5969 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5971 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5972 Mask = Mask.zext(VT.getSizeInBits());
5974 return DAG.getNode(ISD::AND, DL, VT,
5975 X, DAG.getConstant(Mask, DL, VT));
5978 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5979 // Only generate vector extloads when 1) they're legal, and 2) they are
5980 // deemed desirable by the target.
5981 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5982 ((!LegalOperations && !VT.isVector() &&
5983 !cast<LoadSDNode>(N0)->isVolatile()) ||
5984 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5985 bool DoXform = true;
5986 SmallVector<SDNode*, 4> SetCCs;
5987 if (!N0.hasOneUse())
5988 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5990 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5992 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5993 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5995 LN0->getBasePtr(), N0.getValueType(),
5996 LN0->getMemOperand());
5997 CombineTo(N, ExtLoad);
5998 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5999 N0.getValueType(), ExtLoad);
6000 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6002 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6004 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6008 // fold (zext (load x)) to multiple smaller zextloads.
6009 // Only on illegal but splittable vectors.
6010 if (SDValue ExtLoad = CombineExtLoad(N))
6013 // fold (zext (and/or/xor (load x), cst)) ->
6014 // (and/or/xor (zextload x), (zext cst))
6015 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6016 N0.getOpcode() == ISD::XOR) &&
6017 isa<LoadSDNode>(N0.getOperand(0)) &&
6018 N0.getOperand(1).getOpcode() == ISD::Constant &&
6019 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6020 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6021 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6022 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6023 bool DoXform = true;
6024 SmallVector<SDNode*, 4> SetCCs;
6025 if (!N0.hasOneUse())
6026 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6029 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6030 LN0->getChain(), LN0->getBasePtr(),
6032 LN0->getMemOperand());
6033 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6034 Mask = Mask.zext(VT.getSizeInBits());
6036 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6037 ExtLoad, DAG.getConstant(Mask, DL, VT));
6038 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6039 SDLoc(N0.getOperand(0)),
6040 N0.getOperand(0).getValueType(), ExtLoad);
6042 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6043 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6050 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6051 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6052 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6053 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6054 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6055 EVT MemVT = LN0->getMemoryVT();
6056 if ((!LegalOperations && !LN0->isVolatile()) ||
6057 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6058 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6060 LN0->getBasePtr(), MemVT,
6061 LN0->getMemOperand());
6062 CombineTo(N, ExtLoad);
6063 CombineTo(N0.getNode(),
6064 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6066 ExtLoad.getValue(1));
6067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6071 if (N0.getOpcode() == ISD::SETCC) {
6072 if (!LegalOperations && VT.isVector() &&
6073 N0.getValueType().getVectorElementType() == MVT::i1) {
6074 EVT N0VT = N0.getOperand(0).getValueType();
6075 if (getSetCCResultType(N0VT) == N0.getValueType())
6078 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6079 // Only do this before legalize for now.
6080 EVT EltVT = VT.getVectorElementType();
6082 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6083 DAG.getConstant(1, DL, EltVT));
6084 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6085 // We know that the # elements of the results is the same as the
6086 // # elements of the compare (and the # elements of the compare result
6087 // for that matter). Check to see that they are the same size. If so,
6088 // we know that the element size of the sext'd result matches the
6089 // element size of the compare operands.
6090 return DAG.getNode(ISD::AND, DL, VT,
6091 DAG.getSetCC(DL, VT, N0.getOperand(0),
6093 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6094 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6097 // If the desired elements are smaller or larger than the source
6098 // elements we can use a matching integer vector type and then
6099 // truncate/sign extend
6100 EVT MatchingElementType =
6101 EVT::getIntegerVT(*DAG.getContext(),
6102 N0VT.getScalarType().getSizeInBits());
6103 EVT MatchingVectorType =
6104 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6105 N0VT.getVectorNumElements());
6107 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6109 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6110 return DAG.getNode(ISD::AND, DL, VT,
6111 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6112 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6115 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6118 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6119 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6120 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6121 if (SCC.getNode()) return SCC;
6124 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6125 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6126 isa<ConstantSDNode>(N0.getOperand(1)) &&
6127 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6129 SDValue ShAmt = N0.getOperand(1);
6130 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6131 if (N0.getOpcode() == ISD::SHL) {
6132 SDValue InnerZExt = N0.getOperand(0);
6133 // If the original shl may be shifting out bits, do not perform this
6135 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6136 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6137 if (ShAmtVal > KnownZeroBits)
6143 // Ensure that the shift amount is wide enough for the shifted value.
6144 if (VT.getSizeInBits() >= 256)
6145 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6147 return DAG.getNode(N0.getOpcode(), DL, VT,
6148 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6155 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6156 SDValue N0 = N->getOperand(0);
6157 EVT VT = N->getValueType(0);
6159 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6161 return SDValue(Res, 0);
6163 // fold (aext (aext x)) -> (aext x)
6164 // fold (aext (zext x)) -> (zext x)
6165 // fold (aext (sext x)) -> (sext x)
6166 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6167 N0.getOpcode() == ISD::ZERO_EXTEND ||
6168 N0.getOpcode() == ISD::SIGN_EXTEND)
6169 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6171 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6172 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6173 if (N0.getOpcode() == ISD::TRUNCATE) {
6174 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6175 if (NarrowLoad.getNode()) {
6176 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6177 if (NarrowLoad.getNode() != N0.getNode()) {
6178 CombineTo(N0.getNode(), NarrowLoad);
6179 // CombineTo deleted the truncate, if needed, but not what's under it.
6182 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6186 // fold (aext (truncate x))
6187 if (N0.getOpcode() == ISD::TRUNCATE) {
6188 SDValue TruncOp = N0.getOperand(0);
6189 if (TruncOp.getValueType() == VT)
6190 return TruncOp; // x iff x size == zext size.
6191 if (TruncOp.getValueType().bitsGT(VT))
6192 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6193 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6196 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6197 // if the trunc is not free.
6198 if (N0.getOpcode() == ISD::AND &&
6199 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6200 N0.getOperand(1).getOpcode() == ISD::Constant &&
6201 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6202 N0.getValueType())) {
6203 SDValue X = N0.getOperand(0).getOperand(0);
6204 if (X.getValueType().bitsLT(VT)) {
6205 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6206 } else if (X.getValueType().bitsGT(VT)) {
6207 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6209 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6210 Mask = Mask.zext(VT.getSizeInBits());
6212 return DAG.getNode(ISD::AND, DL, VT,
6213 X, DAG.getConstant(Mask, DL, VT));
6216 // fold (aext (load x)) -> (aext (truncate (extload x)))
6217 // None of the supported targets knows how to perform load and any_ext
6218 // on vectors in one instruction. We only perform this transformation on
6220 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6221 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6222 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6223 bool DoXform = true;
6224 SmallVector<SDNode*, 4> SetCCs;
6225 if (!N0.hasOneUse())
6226 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6228 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6229 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6231 LN0->getBasePtr(), N0.getValueType(),
6232 LN0->getMemOperand());
6233 CombineTo(N, ExtLoad);
6234 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6235 N0.getValueType(), ExtLoad);
6236 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6237 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6239 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6243 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6244 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6245 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6246 if (N0.getOpcode() == ISD::LOAD &&
6247 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6249 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6250 ISD::LoadExtType ExtType = LN0->getExtensionType();
6251 EVT MemVT = LN0->getMemoryVT();
6252 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6253 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6254 VT, LN0->getChain(), LN0->getBasePtr(),
6255 MemVT, LN0->getMemOperand());
6256 CombineTo(N, ExtLoad);
6257 CombineTo(N0.getNode(),
6258 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6259 N0.getValueType(), ExtLoad),
6260 ExtLoad.getValue(1));
6261 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6265 if (N0.getOpcode() == ISD::SETCC) {
6267 // aext(setcc) -> vsetcc
6268 // aext(setcc) -> truncate(vsetcc)
6269 // aext(setcc) -> aext(vsetcc)
6270 // Only do this before legalize for now.
6271 if (VT.isVector() && !LegalOperations) {
6272 EVT N0VT = N0.getOperand(0).getValueType();
6273 // We know that the # elements of the results is the same as the
6274 // # elements of the compare (and the # elements of the compare result
6275 // for that matter). Check to see that they are the same size. If so,
6276 // we know that the element size of the sext'd result matches the
6277 // element size of the compare operands.
6278 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6279 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6281 cast<CondCodeSDNode>(N0.getOperand(2))->get());
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/any extend
6286 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6288 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6290 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6291 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6295 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6298 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6299 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6300 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6308 /// See if the specified operand can be simplified with the knowledge that only
6309 /// the bits specified by Mask are used. If so, return the simpler operand,
6310 /// otherwise return a null SDValue.
6311 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6312 switch (V.getOpcode()) {
6314 case ISD::Constant: {
6315 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6316 assert(CV && "Const value should be ConstSDNode.");
6317 const APInt &CVal = CV->getAPIntValue();
6318 APInt NewVal = CVal & Mask;
6320 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6325 // If the LHS or RHS don't contribute bits to the or, drop them.
6326 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6327 return V.getOperand(1);
6328 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6329 return V.getOperand(0);
6332 // Only look at single-use SRLs.
6333 if (!V.getNode()->hasOneUse())
6335 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6336 // See if we can recursively simplify the LHS.
6337 unsigned Amt = RHSC->getZExtValue();
6339 // Watch out for shift count overflow though.
6340 if (Amt >= Mask.getBitWidth()) break;
6341 APInt NewMask = Mask << Amt;
6342 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6343 if (SimplifyLHS.getNode())
6344 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6345 SimplifyLHS, V.getOperand(1));
6351 /// If the result of a wider load is shifted to right of N bits and then
6352 /// truncated to a narrower type and where N is a multiple of number of bits of
6353 /// the narrower type, transform it to a narrower load from address + N / num of
6354 /// bits of new type. If the result is to be extended, also fold the extension
6355 /// to form a extending load.
6356 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6357 unsigned Opc = N->getOpcode();
6359 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6360 SDValue N0 = N->getOperand(0);
6361 EVT VT = N->getValueType(0);
6364 // This transformation isn't valid for vector loads.
6368 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6370 if (Opc == ISD::SIGN_EXTEND_INREG) {
6371 ExtType = ISD::SEXTLOAD;
6372 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6373 } else if (Opc == ISD::SRL) {
6374 // Another special-case: SRL is basically zero-extending a narrower value.
6375 ExtType = ISD::ZEXTLOAD;
6377 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6378 if (!N01) return SDValue();
6379 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6380 VT.getSizeInBits() - N01->getZExtValue());
6382 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6385 unsigned EVTBits = ExtVT.getSizeInBits();
6387 // Do not generate loads of non-round integer types since these can
6388 // be expensive (and would be wrong if the type is not byte sized).
6389 if (!ExtVT.isRound())
6393 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6394 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6395 ShAmt = N01->getZExtValue();
6396 // Is the shift amount a multiple of size of VT?
6397 if ((ShAmt & (EVTBits-1)) == 0) {
6398 N0 = N0.getOperand(0);
6399 // Is the load width a multiple of size of VT?
6400 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6404 // At this point, we must have a load or else we can't do the transform.
6405 if (!isa<LoadSDNode>(N0)) return SDValue();
6407 // Because a SRL must be assumed to *need* to zero-extend the high bits
6408 // (as opposed to anyext the high bits), we can't combine the zextload
6409 // lowering of SRL and an sextload.
6410 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6413 // If the shift amount is larger than the input type then we're not
6414 // accessing any of the loaded bytes. If the load was a zextload/extload
6415 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6416 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6421 // If the load is shifted left (and the result isn't shifted back right),
6422 // we can fold the truncate through the shift.
6423 unsigned ShLeftAmt = 0;
6424 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6425 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6426 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6427 ShLeftAmt = N01->getZExtValue();
6428 N0 = N0.getOperand(0);
6432 // If we haven't found a load, we can't narrow it. Don't transform one with
6433 // multiple uses, this would require adding a new load.
6434 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6437 // Don't change the width of a volatile load.
6438 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6439 if (LN0->isVolatile())
6442 // Verify that we are actually reducing a load width here.
6443 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6446 // For the transform to be legal, the load must produce only two values
6447 // (the value loaded and the chain). Don't transform a pre-increment
6448 // load, for example, which produces an extra value. Otherwise the
6449 // transformation is not equivalent, and the downstream logic to replace
6450 // uses gets things wrong.
6451 if (LN0->getNumValues() > 2)
6454 // If the load that we're shrinking is an extload and we're not just
6455 // discarding the extension we can't simply shrink the load. Bail.
6456 // TODO: It would be possible to merge the extensions in some cases.
6457 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6458 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6461 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6464 EVT PtrType = N0.getOperand(1).getValueType();
6466 if (PtrType == MVT::Untyped || PtrType.isExtended())
6467 // It's not possible to generate a constant of extended or untyped type.
6470 // For big endian targets, we need to adjust the offset to the pointer to
6471 // load the correct bytes.
6472 if (TLI.isBigEndian()) {
6473 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6474 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6475 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6478 uint64_t PtrOff = ShAmt / 8;
6479 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6481 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6482 PtrType, LN0->getBasePtr(),
6483 DAG.getConstant(PtrOff, DL, PtrType));
6484 AddToWorklist(NewPtr.getNode());
6487 if (ExtType == ISD::NON_EXTLOAD)
6488 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6489 LN0->getPointerInfo().getWithOffset(PtrOff),
6490 LN0->isVolatile(), LN0->isNonTemporal(),
6491 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6493 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6494 LN0->getPointerInfo().getWithOffset(PtrOff),
6495 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6496 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6498 // Replace the old load's chain with the new load's chain.
6499 WorklistRemover DeadNodes(*this);
6500 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6502 // Shift the result left, if we've swallowed a left shift.
6503 SDValue Result = Load;
6504 if (ShLeftAmt != 0) {
6505 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6506 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6508 // If the shift amount is as large as the result size (but, presumably,
6509 // no larger than the source) then the useful bits of the result are
6510 // zero; we can't simply return the shortened shift, because the result
6511 // of that operation is undefined.
6513 if (ShLeftAmt >= VT.getSizeInBits())
6514 Result = DAG.getConstant(0, DL, VT);
6516 Result = DAG.getNode(ISD::SHL, DL, VT,
6517 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6520 // Return the new loaded value.
6524 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6525 SDValue N0 = N->getOperand(0);
6526 SDValue N1 = N->getOperand(1);
6527 EVT VT = N->getValueType(0);
6528 EVT EVT = cast<VTSDNode>(N1)->getVT();
6529 unsigned VTBits = VT.getScalarType().getSizeInBits();
6530 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6532 // fold (sext_in_reg c1) -> c1
6533 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6534 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6536 // If the input is already sign extended, just drop the extension.
6537 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6540 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6541 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6542 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6543 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6544 N0.getOperand(0), N1);
6546 // fold (sext_in_reg (sext x)) -> (sext x)
6547 // fold (sext_in_reg (aext x)) -> (sext x)
6548 // if x is small enough.
6549 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6550 SDValue N00 = N0.getOperand(0);
6551 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6552 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6553 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6556 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6557 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6558 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6560 // fold operands of sext_in_reg based on knowledge that the top bits are not
6562 if (SimplifyDemandedBits(SDValue(N, 0)))
6563 return SDValue(N, 0);
6565 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6566 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6567 SDValue NarrowLoad = ReduceLoadWidth(N);
6568 if (NarrowLoad.getNode())
6571 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6572 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6573 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6574 if (N0.getOpcode() == ISD::SRL) {
6575 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6576 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6577 // We can turn this into an SRA iff the input to the SRL is already sign
6579 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6580 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6581 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6582 N0.getOperand(0), N0.getOperand(1));
6586 // fold (sext_inreg (extload x)) -> (sextload x)
6587 if (ISD::isEXTLoad(N0.getNode()) &&
6588 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6589 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6590 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6591 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6592 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6593 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6595 LN0->getBasePtr(), EVT,
6596 LN0->getMemOperand());
6597 CombineTo(N, ExtLoad);
6598 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6599 AddToWorklist(ExtLoad.getNode());
6600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6602 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6603 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6605 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6606 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6607 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6608 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6609 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6611 LN0->getBasePtr(), EVT,
6612 LN0->getMemOperand());
6613 CombineTo(N, ExtLoad);
6614 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6615 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6618 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6619 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6620 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6621 N0.getOperand(1), false);
6622 if (BSwap.getNode())
6623 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6627 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6628 // into a build_vector.
6629 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6630 SmallVector<SDValue, 8> Elts;
6631 unsigned NumElts = N0->getNumOperands();
6632 unsigned ShAmt = VTBits - EVTBits;
6634 for (unsigned i = 0; i != NumElts; ++i) {
6635 SDValue Op = N0->getOperand(i);
6636 if (Op->getOpcode() == ISD::UNDEF) {
6641 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6642 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6643 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6644 SDLoc(Op), Op.getValueType()));
6647 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6653 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6654 SDValue N0 = N->getOperand(0);
6655 EVT VT = N->getValueType(0);
6656 bool isLE = TLI.isLittleEndian();
6659 if (N0.getValueType() == N->getValueType(0))
6661 // fold (truncate c1) -> c1
6662 if (isConstantIntBuildVectorOrConstantInt(N0))
6663 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6664 // fold (truncate (truncate x)) -> (truncate x)
6665 if (N0.getOpcode() == ISD::TRUNCATE)
6666 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6667 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6668 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6669 N0.getOpcode() == ISD::SIGN_EXTEND ||
6670 N0.getOpcode() == ISD::ANY_EXTEND) {
6671 if (N0.getOperand(0).getValueType().bitsLT(VT))
6672 // if the source is smaller than the dest, we still need an extend
6673 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6675 if (N0.getOperand(0).getValueType().bitsGT(VT))
6676 // if the source is larger than the dest, than we just need the truncate
6677 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6678 // if the source and dest are the same type, we can drop both the extend
6679 // and the truncate.
6680 return N0.getOperand(0);
6683 // Fold extract-and-trunc into a narrow extract. For example:
6684 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6685 // i32 y = TRUNCATE(i64 x)
6687 // v16i8 b = BITCAST (v2i64 val)
6688 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6690 // Note: We only run this optimization after type legalization (which often
6691 // creates this pattern) and before operation legalization after which
6692 // we need to be more careful about the vector instructions that we generate.
6693 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6694 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6696 EVT VecTy = N0.getOperand(0).getValueType();
6697 EVT ExTy = N0.getValueType();
6698 EVT TrTy = N->getValueType(0);
6700 unsigned NumElem = VecTy.getVectorNumElements();
6701 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6703 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6704 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6706 SDValue EltNo = N0->getOperand(1);
6707 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6708 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6709 EVT IndexTy = TLI.getVectorIdxTy();
6710 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6712 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6713 NVT, N0.getOperand(0));
6716 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6718 DAG.getConstant(Index, DL, IndexTy));
6722 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6723 if (N0.getOpcode() == ISD::SELECT) {
6724 EVT SrcVT = N0.getValueType();
6725 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6726 TLI.isTruncateFree(SrcVT, VT)) {
6728 SDValue Cond = N0.getOperand(0);
6729 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6730 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6731 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6735 // Fold a series of buildvector, bitcast, and truncate if possible.
6737 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6738 // (2xi32 (buildvector x, y)).
6739 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6740 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6741 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6742 N0.getOperand(0).hasOneUse()) {
6744 SDValue BuildVect = N0.getOperand(0);
6745 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6746 EVT TruncVecEltTy = VT.getVectorElementType();
6748 // Check that the element types match.
6749 if (BuildVectEltTy == TruncVecEltTy) {
6750 // Now we only need to compute the offset of the truncated elements.
6751 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6752 unsigned TruncVecNumElts = VT.getVectorNumElements();
6753 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6755 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6756 "Invalid number of elements");
6758 SmallVector<SDValue, 8> Opnds;
6759 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6760 Opnds.push_back(BuildVect.getOperand(i));
6762 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6766 // See if we can simplify the input to this truncate through knowledge that
6767 // only the low bits are being used.
6768 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6769 // Currently we only perform this optimization on scalars because vectors
6770 // may have different active low bits.
6771 if (!VT.isVector()) {
6773 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6774 VT.getSizeInBits()));
6775 if (Shorter.getNode())
6776 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6778 // fold (truncate (load x)) -> (smaller load x)
6779 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6780 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6781 SDValue Reduced = ReduceLoadWidth(N);
6782 if (Reduced.getNode())
6784 // Handle the case where the load remains an extending load even
6785 // after truncation.
6786 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6787 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6788 if (!LN0->isVolatile() &&
6789 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6790 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6791 VT, LN0->getChain(), LN0->getBasePtr(),
6793 LN0->getMemOperand());
6794 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6799 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6800 // where ... are all 'undef'.
6801 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6802 SmallVector<EVT, 8> VTs;
6805 unsigned NumDefs = 0;
6807 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6808 SDValue X = N0.getOperand(i);
6809 if (X.getOpcode() != ISD::UNDEF) {
6814 // Stop if more than one members are non-undef.
6817 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6818 VT.getVectorElementType(),
6819 X.getValueType().getVectorNumElements()));
6823 return DAG.getUNDEF(VT);
6826 assert(V.getNode() && "The single defined operand is empty!");
6827 SmallVector<SDValue, 8> Opnds;
6828 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6830 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6833 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6834 AddToWorklist(NV.getNode());
6835 Opnds.push_back(NV);
6837 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6841 // Simplify the operands using demanded-bits information.
6842 if (!VT.isVector() &&
6843 SimplifyDemandedBits(SDValue(N, 0)))
6844 return SDValue(N, 0);
6849 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6850 SDValue Elt = N->getOperand(i);
6851 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6852 return Elt.getNode();
6853 return Elt.getOperand(Elt.getResNo()).getNode();
6856 /// build_pair (load, load) -> load
6857 /// if load locations are consecutive.
6858 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6859 assert(N->getOpcode() == ISD::BUILD_PAIR);
6861 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6862 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6863 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6864 LD1->getAddressSpace() != LD2->getAddressSpace())
6866 EVT LD1VT = LD1->getValueType(0);
6868 if (ISD::isNON_EXTLoad(LD2) &&
6870 // If both are volatile this would reduce the number of volatile loads.
6871 // If one is volatile it might be ok, but play conservative and bail out.
6872 !LD1->isVolatile() &&
6873 !LD2->isVolatile() &&
6874 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6875 unsigned Align = LD1->getAlignment();
6876 unsigned NewAlign = TLI.getDataLayout()->
6877 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6879 if (NewAlign <= Align &&
6880 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6881 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6882 LD1->getBasePtr(), LD1->getPointerInfo(),
6883 false, false, false, Align);
6889 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6890 SDValue N0 = N->getOperand(0);
6891 EVT VT = N->getValueType(0);
6893 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6894 // Only do this before legalize, since afterward the target may be depending
6895 // on the bitconvert.
6896 // First check to see if this is all constant.
6898 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6900 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6902 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6903 assert(!DestEltVT.isVector() &&
6904 "Element type of vector ValueType must not be vector!");
6906 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6909 // If the input is a constant, let getNode fold it.
6910 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6911 // If we can't allow illegal operations, we need to check that this is just
6912 // a fp -> int or int -> conversion and that the resulting operation will
6914 if (!LegalOperations ||
6915 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6916 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6917 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6918 TLI.isOperationLegal(ISD::Constant, VT)))
6919 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6922 // (conv (conv x, t1), t2) -> (conv x, t2)
6923 if (N0.getOpcode() == ISD::BITCAST)
6924 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6927 // fold (conv (load x)) -> (load (conv*)x)
6928 // If the resultant load doesn't need a higher alignment than the original!
6929 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6930 // Do not change the width of a volatile load.
6931 !cast<LoadSDNode>(N0)->isVolatile() &&
6932 // Do not remove the cast if the types differ in endian layout.
6933 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6934 TLI.hasBigEndianPartOrdering(VT) &&
6935 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6936 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6938 unsigned Align = TLI.getDataLayout()->
6939 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6940 unsigned OrigAlign = LN0->getAlignment();
6942 if (Align <= OrigAlign) {
6943 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6944 LN0->getBasePtr(), LN0->getPointerInfo(),
6945 LN0->isVolatile(), LN0->isNonTemporal(),
6946 LN0->isInvariant(), OrigAlign,
6948 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6953 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6954 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6955 // This often reduces constant pool loads.
6956 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6957 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6958 N0.getNode()->hasOneUse() && VT.isInteger() &&
6959 !VT.isVector() && !N0.getValueType().isVector()) {
6960 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6962 AddToWorklist(NewConv.getNode());
6965 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6966 if (N0.getOpcode() == ISD::FNEG)
6967 return DAG.getNode(ISD::XOR, DL, VT,
6968 NewConv, DAG.getConstant(SignBit, DL, VT));
6969 assert(N0.getOpcode() == ISD::FABS);
6970 return DAG.getNode(ISD::AND, DL, VT,
6971 NewConv, DAG.getConstant(~SignBit, DL, VT));
6974 // fold (bitconvert (fcopysign cst, x)) ->
6975 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6976 // Note that we don't handle (copysign x, cst) because this can always be
6977 // folded to an fneg or fabs.
6978 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6979 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6980 VT.isInteger() && !VT.isVector()) {
6981 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6982 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6983 if (isTypeLegal(IntXVT)) {
6984 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6985 IntXVT, N0.getOperand(1));
6986 AddToWorklist(X.getNode());
6988 // If X has a different width than the result/lhs, sext it or truncate it.
6989 unsigned VTWidth = VT.getSizeInBits();
6990 if (OrigXWidth < VTWidth) {
6991 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6992 AddToWorklist(X.getNode());
6993 } else if (OrigXWidth > VTWidth) {
6994 // To get the sign bit in the right place, we have to shift it right
6995 // before truncating.
6997 X = DAG.getNode(ISD::SRL, DL,
6998 X.getValueType(), X,
6999 DAG.getConstant(OrigXWidth-VTWidth, DL,
7001 AddToWorklist(X.getNode());
7002 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7003 AddToWorklist(X.getNode());
7006 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7007 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7008 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7009 AddToWorklist(X.getNode());
7011 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7012 VT, N0.getOperand(0));
7013 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7014 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7015 AddToWorklist(Cst.getNode());
7017 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7021 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7022 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7023 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7024 if (CombineLD.getNode())
7028 // Remove double bitcasts from shuffles - this is often a legacy of
7029 // XformToShuffleWithZero being used to combine bitmaskings (of
7030 // float vectors bitcast to integer vectors) into shuffles.
7031 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7032 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7033 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7034 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7035 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7036 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7038 // If operands are a bitcast, peek through if it casts the original VT.
7039 // If operands are a UNDEF or constant, just bitcast back to original VT.
7040 auto PeekThroughBitcast = [&](SDValue Op) {
7041 if (Op.getOpcode() == ISD::BITCAST &&
7042 Op.getOperand(0)->getValueType(0) == VT)
7043 return SDValue(Op.getOperand(0));
7044 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7045 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7046 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7050 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7051 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7056 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7057 SmallVector<int, 8> NewMask;
7058 for (int M : SVN->getMask())
7059 for (int i = 0; i != MaskScale; ++i)
7060 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7062 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7064 std::swap(SV0, SV1);
7065 ShuffleVectorSDNode::commuteMask(NewMask);
7066 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7070 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7076 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7077 EVT VT = N->getValueType(0);
7078 return CombineConsecutiveLoads(N, VT);
7081 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7082 /// operands. DstEltVT indicates the destination element value type.
7083 SDValue DAGCombiner::
7084 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7085 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7087 // If this is already the right type, we're done.
7088 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7090 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7091 unsigned DstBitSize = DstEltVT.getSizeInBits();
7093 // If this is a conversion of N elements of one type to N elements of another
7094 // type, convert each element. This handles FP<->INT cases.
7095 if (SrcBitSize == DstBitSize) {
7096 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7097 BV->getValueType(0).getVectorNumElements());
7099 // Due to the FP element handling below calling this routine recursively,
7100 // we can end up with a scalar-to-vector node here.
7101 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7102 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7103 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7104 DstEltVT, BV->getOperand(0)));
7106 SmallVector<SDValue, 8> Ops;
7107 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7108 SDValue Op = BV->getOperand(i);
7109 // If the vector element type is not legal, the BUILD_VECTOR operands
7110 // are promoted and implicitly truncated. Make that explicit here.
7111 if (Op.getValueType() != SrcEltVT)
7112 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7113 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7115 AddToWorklist(Ops.back().getNode());
7117 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7120 // Otherwise, we're growing or shrinking the elements. To avoid having to
7121 // handle annoying details of growing/shrinking FP values, we convert them to
7123 if (SrcEltVT.isFloatingPoint()) {
7124 // Convert the input float vector to a int vector where the elements are the
7126 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7127 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7131 // Now we know the input is an integer vector. If the output is a FP type,
7132 // convert to integer first, then to FP of the right size.
7133 if (DstEltVT.isFloatingPoint()) {
7134 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7135 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7137 // Next, convert to FP elements of the same size.
7138 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7143 // Okay, we know the src/dst types are both integers of differing types.
7144 // Handling growing first.
7145 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7146 if (SrcBitSize < DstBitSize) {
7147 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7149 SmallVector<SDValue, 8> Ops;
7150 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7151 i += NumInputsPerOutput) {
7152 bool isLE = TLI.isLittleEndian();
7153 APInt NewBits = APInt(DstBitSize, 0);
7154 bool EltIsUndef = true;
7155 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7156 // Shift the previously computed bits over.
7157 NewBits <<= SrcBitSize;
7158 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7159 if (Op.getOpcode() == ISD::UNDEF) continue;
7162 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7163 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7167 Ops.push_back(DAG.getUNDEF(DstEltVT));
7169 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7172 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7173 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7176 // Finally, this must be the case where we are shrinking elements: each input
7177 // turns into multiple outputs.
7178 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7179 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7180 NumOutputsPerInput*BV->getNumOperands());
7181 SmallVector<SDValue, 8> Ops;
7183 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7184 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7185 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7189 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7190 getAPIntValue().zextOrTrunc(SrcBitSize);
7192 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7193 APInt ThisVal = OpVal.trunc(DstBitSize);
7194 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7195 OpVal = OpVal.lshr(DstBitSize);
7198 // For big endian targets, swap the order of the pieces of each element.
7199 if (TLI.isBigEndian())
7200 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7203 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7206 /// Try to perform FMA combining on a given FADD node.
7207 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7212 SDValue N0 = N->getOperand(0);
7213 SDValue N1 = N->getOperand(1);
7214 EVT VT = N->getValueType(0);
7217 const TargetOptions &Options = DAG.getTarget().Options;
7218 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7219 Options.UnsafeFPMath);
7221 // Floating-point multiply-add with intermediate rounding.
7222 bool HasFMAD = (LegalOperations &&
7223 TLI.isOperationLegal(ISD::FMAD, VT));
7225 // Floating-point multiply-add without intermediate rounding.
7226 bool HasFMA = ((!LegalOperations ||
7227 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7228 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7231 // No valid opcode, do not combine.
7232 if (!HasFMAD && !HasFMA)
7235 // Always prefer FMAD to FMA for precision.
7236 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7237 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7238 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7240 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7241 if (N0.getOpcode() == ISD::FMUL &&
7242 (Aggressive || N0->hasOneUse())) {
7243 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7244 N0.getOperand(0), N0.getOperand(1), N1);
7247 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7248 // Note: Commutes FADD operands.
7249 if (N1.getOpcode() == ISD::FMUL &&
7250 (Aggressive || N1->hasOneUse())) {
7251 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7252 N1.getOperand(0), N1.getOperand(1), N0);
7255 // Look through FP_EXTEND nodes to do more combining.
7256 if (UnsafeFPMath && LookThroughFPExt) {
7257 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7258 if (N0.getOpcode() == ISD::FP_EXTEND) {
7259 SDValue N00 = N0.getOperand(0);
7260 if (N00.getOpcode() == ISD::FMUL)
7261 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7262 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7264 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7265 N00.getOperand(1)), N1);
7268 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7269 // Note: Commutes FADD operands.
7270 if (N1.getOpcode() == ISD::FP_EXTEND) {
7271 SDValue N10 = N1.getOperand(0);
7272 if (N10.getOpcode() == ISD::FMUL)
7273 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7274 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7276 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7277 N10.getOperand(1)), N0);
7281 // More folding opportunities when target permits.
7282 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7283 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7284 if (N0.getOpcode() == PreferredFusedOpcode &&
7285 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7286 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7287 N0.getOperand(0), N0.getOperand(1),
7288 DAG.getNode(PreferredFusedOpcode, SL, VT,
7289 N0.getOperand(2).getOperand(0),
7290 N0.getOperand(2).getOperand(1),
7294 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7295 if (N1->getOpcode() == PreferredFusedOpcode &&
7296 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7297 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7298 N1.getOperand(0), N1.getOperand(1),
7299 DAG.getNode(PreferredFusedOpcode, SL, VT,
7300 N1.getOperand(2).getOperand(0),
7301 N1.getOperand(2).getOperand(1),
7305 if (UnsafeFPMath && LookThroughFPExt) {
7306 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7307 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7308 auto FoldFAddFMAFPExtFMul = [&] (
7309 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7310 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7311 DAG.getNode(PreferredFusedOpcode, SL, VT,
7312 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7313 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7316 if (N0.getOpcode() == PreferredFusedOpcode) {
7317 SDValue N02 = N0.getOperand(2);
7318 if (N02.getOpcode() == ISD::FP_EXTEND) {
7319 SDValue N020 = N02.getOperand(0);
7320 if (N020.getOpcode() == ISD::FMUL)
7321 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7322 N020.getOperand(0), N020.getOperand(1),
7327 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7328 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7329 // FIXME: This turns two single-precision and one double-precision
7330 // operation into two double-precision operations, which might not be
7331 // interesting for all targets, especially GPUs.
7332 auto FoldFAddFPExtFMAFMul = [&] (
7333 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7334 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7335 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7336 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7337 DAG.getNode(PreferredFusedOpcode, SL, VT,
7338 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7339 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7342 if (N0.getOpcode() == ISD::FP_EXTEND) {
7343 SDValue N00 = N0.getOperand(0);
7344 if (N00.getOpcode() == PreferredFusedOpcode) {
7345 SDValue N002 = N00.getOperand(2);
7346 if (N002.getOpcode() == ISD::FMUL)
7347 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7348 N002.getOperand(0), N002.getOperand(1),
7353 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7354 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7355 if (N1.getOpcode() == PreferredFusedOpcode) {
7356 SDValue N12 = N1.getOperand(2);
7357 if (N12.getOpcode() == ISD::FP_EXTEND) {
7358 SDValue N120 = N12.getOperand(0);
7359 if (N120.getOpcode() == ISD::FMUL)
7360 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7361 N120.getOperand(0), N120.getOperand(1),
7366 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7367 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7368 // FIXME: This turns two single-precision and one double-precision
7369 // operation into two double-precision operations, which might not be
7370 // interesting for all targets, especially GPUs.
7371 if (N1.getOpcode() == ISD::FP_EXTEND) {
7372 SDValue N10 = N1.getOperand(0);
7373 if (N10.getOpcode() == PreferredFusedOpcode) {
7374 SDValue N102 = N10.getOperand(2);
7375 if (N102.getOpcode() == ISD::FMUL)
7376 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7377 N102.getOperand(0), N102.getOperand(1),
7387 /// Try to perform FMA combining on a given FSUB node.
7388 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7392 SDValue N0 = N->getOperand(0);
7393 SDValue N1 = N->getOperand(1);
7394 EVT VT = N->getValueType(0);
7398 const TargetOptions &Options = DAG.getTarget().Options;
7399 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7400 Options.UnsafeFPMath);
7402 // Floating-point multiply-add with intermediate rounding.
7403 bool HasFMAD = (LegalOperations &&
7404 TLI.isOperationLegal(ISD::FMAD, VT));
7406 // Floating-point multiply-add without intermediate rounding.
7407 bool HasFMA = ((!LegalOperations ||
7408 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7409 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7412 // No valid opcode, do not combine.
7413 if (!HasFMAD && !HasFMA)
7416 // Always prefer FMAD to FMA for precision.
7417 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7418 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7419 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7421 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7422 if (N0.getOpcode() == ISD::FMUL &&
7423 (Aggressive || N0->hasOneUse())) {
7424 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7425 N0.getOperand(0), N0.getOperand(1),
7426 DAG.getNode(ISD::FNEG, SL, VT, N1));
7429 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7430 // Note: Commutes FSUB operands.
7431 if (N1.getOpcode() == ISD::FMUL &&
7432 (Aggressive || N1->hasOneUse()))
7433 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7434 DAG.getNode(ISD::FNEG, SL, VT,
7436 N1.getOperand(1), N0);
7438 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7439 if (N0.getOpcode() == ISD::FNEG &&
7440 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7441 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7442 SDValue N00 = N0.getOperand(0).getOperand(0);
7443 SDValue N01 = N0.getOperand(0).getOperand(1);
7444 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7445 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7446 DAG.getNode(ISD::FNEG, SL, VT, N1));
7449 // Look through FP_EXTEND nodes to do more combining.
7450 if (UnsafeFPMath && LookThroughFPExt) {
7451 // fold (fsub (fpext (fmul x, y)), z)
7452 // -> (fma (fpext x), (fpext y), (fneg 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,
7461 DAG.getNode(ISD::FNEG, SL, VT, N1));
7464 // fold (fsub x, (fpext (fmul y, z)))
7465 // -> (fma (fneg (fpext y)), (fpext z), x)
7466 // Note: Commutes FSUB operands.
7467 if (N1.getOpcode() == ISD::FP_EXTEND) {
7468 SDValue N10 = N1.getOperand(0);
7469 if (N10.getOpcode() == ISD::FMUL)
7470 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471 DAG.getNode(ISD::FNEG, SL, VT,
7472 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7473 N10.getOperand(0))),
7474 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7479 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7480 // -> (fneg (fma (fpext x), (fpext y), z))
7481 // Note: This could be removed with appropriate canonicalization of the
7482 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7483 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7484 // from implementing the canonicalization in visitFSUB.
7485 if (N0.getOpcode() == ISD::FP_EXTEND) {
7486 SDValue N00 = N0.getOperand(0);
7487 if (N00.getOpcode() == ISD::FNEG) {
7488 SDValue N000 = N00.getOperand(0);
7489 if (N000.getOpcode() == ISD::FMUL) {
7490 return DAG.getNode(ISD::FNEG, SL, VT,
7491 DAG.getNode(PreferredFusedOpcode, SL, VT,
7492 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7493 N000.getOperand(0)),
7494 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7495 N000.getOperand(1)),
7501 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7502 // -> (fneg (fma (fpext x)), (fpext y), z)
7503 // Note: This could be removed with appropriate canonicalization of the
7504 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7505 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7506 // from implementing the canonicalization in visitFSUB.
7507 if (N0.getOpcode() == ISD::FNEG) {
7508 SDValue N00 = N0.getOperand(0);
7509 if (N00.getOpcode() == ISD::FP_EXTEND) {
7510 SDValue N000 = N00.getOperand(0);
7511 if (N000.getOpcode() == ISD::FMUL) {
7512 return DAG.getNode(ISD::FNEG, SL, VT,
7513 DAG.getNode(PreferredFusedOpcode, SL, VT,
7514 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7515 N000.getOperand(0)),
7516 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7517 N000.getOperand(1)),
7525 // More folding opportunities when target permits.
7526 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7527 // fold (fsub (fma x, y, (fmul u, v)), z)
7528 // -> (fma x, y (fma u, v, (fneg z)))
7529 if (N0.getOpcode() == PreferredFusedOpcode &&
7530 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7531 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7532 N0.getOperand(0), N0.getOperand(1),
7533 DAG.getNode(PreferredFusedOpcode, SL, VT,
7534 N0.getOperand(2).getOperand(0),
7535 N0.getOperand(2).getOperand(1),
7536 DAG.getNode(ISD::FNEG, SL, VT,
7540 // fold (fsub x, (fma y, z, (fmul u, v)))
7541 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7542 if (N1.getOpcode() == PreferredFusedOpcode &&
7543 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7544 SDValue N20 = N1.getOperand(2).getOperand(0);
7545 SDValue N21 = N1.getOperand(2).getOperand(1);
7546 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547 DAG.getNode(ISD::FNEG, SL, VT,
7550 DAG.getNode(PreferredFusedOpcode, SL, VT,
7551 DAG.getNode(ISD::FNEG, SL, VT, N20),
7556 if (UnsafeFPMath && LookThroughFPExt) {
7557 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7558 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7559 if (N0.getOpcode() == PreferredFusedOpcode) {
7560 SDValue N02 = N0.getOperand(2);
7561 if (N02.getOpcode() == ISD::FP_EXTEND) {
7562 SDValue N020 = N02.getOperand(0);
7563 if (N020.getOpcode() == ISD::FMUL)
7564 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7565 N0.getOperand(0), N0.getOperand(1),
7566 DAG.getNode(PreferredFusedOpcode, SL, VT,
7567 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7568 N020.getOperand(0)),
7569 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7570 N020.getOperand(1)),
7571 DAG.getNode(ISD::FNEG, SL, VT,
7576 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7577 // -> (fma (fpext x), (fpext y),
7578 // (fma (fpext u), (fpext v), (fneg z)))
7579 // FIXME: This turns two single-precision and one double-precision
7580 // operation into two double-precision operations, which might not be
7581 // interesting for all targets, especially GPUs.
7582 if (N0.getOpcode() == ISD::FP_EXTEND) {
7583 SDValue N00 = N0.getOperand(0);
7584 if (N00.getOpcode() == PreferredFusedOpcode) {
7585 SDValue N002 = N00.getOperand(2);
7586 if (N002.getOpcode() == ISD::FMUL)
7587 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7588 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7590 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7592 DAG.getNode(PreferredFusedOpcode, SL, VT,
7593 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7594 N002.getOperand(0)),
7595 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7596 N002.getOperand(1)),
7597 DAG.getNode(ISD::FNEG, SL, VT,
7602 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7603 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7604 if (N1.getOpcode() == PreferredFusedOpcode &&
7605 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7606 SDValue N120 = N1.getOperand(2).getOperand(0);
7607 if (N120.getOpcode() == ISD::FMUL) {
7608 SDValue N1200 = N120.getOperand(0);
7609 SDValue N1201 = N120.getOperand(1);
7610 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7611 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7613 DAG.getNode(PreferredFusedOpcode, SL, VT,
7614 DAG.getNode(ISD::FNEG, SL, VT,
7615 DAG.getNode(ISD::FP_EXTEND, SL,
7617 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7623 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7624 // -> (fma (fneg (fpext y)), (fpext z),
7625 // (fma (fneg (fpext u)), (fpext v), x))
7626 // FIXME: This turns two single-precision and one double-precision
7627 // operation into two double-precision operations, which might not be
7628 // interesting for all targets, especially GPUs.
7629 if (N1.getOpcode() == ISD::FP_EXTEND &&
7630 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7631 SDValue N100 = N1.getOperand(0).getOperand(0);
7632 SDValue N101 = N1.getOperand(0).getOperand(1);
7633 SDValue N102 = N1.getOperand(0).getOperand(2);
7634 if (N102.getOpcode() == ISD::FMUL) {
7635 SDValue N1020 = N102.getOperand(0);
7636 SDValue N1021 = N102.getOperand(1);
7637 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638 DAG.getNode(ISD::FNEG, SL, VT,
7639 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7642 DAG.getNode(PreferredFusedOpcode, SL, VT,
7643 DAG.getNode(ISD::FNEG, SL, VT,
7644 DAG.getNode(ISD::FP_EXTEND, SL,
7646 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7657 SDValue DAGCombiner::visitFADD(SDNode *N) {
7658 SDValue N0 = N->getOperand(0);
7659 SDValue N1 = N->getOperand(1);
7660 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7661 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7662 EVT VT = N->getValueType(0);
7663 const TargetOptions &Options = DAG.getTarget().Options;
7667 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7670 // fold (fadd c1, c2) -> c1 + c2
7672 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7674 // canonicalize constant to RHS
7675 if (N0CFP && !N1CFP)
7676 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7678 // fold (fadd A, (fneg B)) -> (fsub A, B)
7679 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7680 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7681 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7682 GetNegatedExpression(N1, DAG, LegalOperations));
7684 // fold (fadd (fneg A), B) -> (fsub B, A)
7685 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7686 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7687 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7688 GetNegatedExpression(N0, DAG, LegalOperations));
7690 // If 'unsafe math' is enabled, fold lots of things.
7691 if (Options.UnsafeFPMath) {
7692 // No FP constant should be created after legalization as Instruction
7693 // Selection pass has a hard time dealing with FP constants.
7694 bool AllowNewConst = (Level < AfterLegalizeDAG);
7696 // fold (fadd A, 0) -> A
7697 if (N1CFP && N1CFP->getValueAPF().isZero())
7700 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7701 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7702 isa<ConstantFPSDNode>(N0.getOperand(1)))
7703 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7704 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7705 N0.getOperand(1), N1));
7707 // If allowed, fold (fadd (fneg x), x) -> 0.0
7708 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7709 return DAG.getConstantFP(0.0, SDLoc(N), VT);
7711 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7712 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7713 return DAG.getConstantFP(0.0, SDLoc(N), VT);
7715 // We can fold chains of FADD's of the same value into multiplications.
7716 // This transform is not safe in general because we are reducing the number
7717 // of rounding steps.
7718 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7719 if (N0.getOpcode() == ISD::FMUL) {
7720 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7721 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7723 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7724 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7726 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7728 DAG.getConstantFP(1.0, DL, VT));
7729 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7732 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7733 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7734 N1.getOperand(0) == N1.getOperand(1) &&
7735 N0.getOperand(0) == N1.getOperand(0)) {
7737 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7739 DAG.getConstantFP(2.0, DL, VT));
7740 return DAG.getNode(ISD::FMUL, DL, VT,
7741 N0.getOperand(0), NewCFP);
7745 if (N1.getOpcode() == ISD::FMUL) {
7746 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7747 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7749 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7750 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7752 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7754 DAG.getConstantFP(1.0, DL, VT));
7755 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7758 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7759 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7760 N0.getOperand(0) == N0.getOperand(1) &&
7761 N1.getOperand(0) == N0.getOperand(0)) {
7763 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7765 DAG.getConstantFP(2.0, DL, VT));
7766 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7770 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7771 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7772 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7773 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7774 (N0.getOperand(0) == N1)) {
7776 return DAG.getNode(ISD::FMUL, DL, VT,
7777 N1, DAG.getConstantFP(3.0, DL, VT));
7781 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7782 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7783 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7784 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7785 N1.getOperand(0) == N0) {
7787 return DAG.getNode(ISD::FMUL, DL, VT,
7788 N0, DAG.getConstantFP(3.0, DL, VT));
7792 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7793 if (AllowNewConst &&
7794 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7795 N0.getOperand(0) == N0.getOperand(1) &&
7796 N1.getOperand(0) == N1.getOperand(1) &&
7797 N0.getOperand(0) == N1.getOperand(0)) {
7799 return DAG.getNode(ISD::FMUL, DL, VT,
7800 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7803 } // enable-unsafe-fp-math
7805 // FADD -> FMA combines:
7806 SDValue Fused = visitFADDForFMACombine(N);
7808 AddToWorklist(Fused.getNode());
7815 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7816 SDValue N0 = N->getOperand(0);
7817 SDValue N1 = N->getOperand(1);
7818 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7819 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7820 EVT VT = N->getValueType(0);
7822 const TargetOptions &Options = DAG.getTarget().Options;
7826 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7829 // fold (fsub c1, c2) -> c1-c2
7831 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7833 // fold (fsub A, (fneg B)) -> (fadd A, B)
7834 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7835 return DAG.getNode(ISD::FADD, dl, VT, N0,
7836 GetNegatedExpression(N1, DAG, LegalOperations));
7838 // If 'unsafe math' is enabled, fold lots of things.
7839 if (Options.UnsafeFPMath) {
7841 if (N1CFP && N1CFP->getValueAPF().isZero())
7844 // (fsub 0, B) -> -B
7845 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7846 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7847 return GetNegatedExpression(N1, DAG, LegalOperations);
7848 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7849 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7852 // (fsub x, x) -> 0.0
7854 return DAG.getConstantFP(0.0f, dl, VT);
7856 // (fsub x, (fadd x, y)) -> (fneg y)
7857 // (fsub x, (fadd y, x)) -> (fneg y)
7858 if (N1.getOpcode() == ISD::FADD) {
7859 SDValue N10 = N1->getOperand(0);
7860 SDValue N11 = N1->getOperand(1);
7862 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7863 return GetNegatedExpression(N11, DAG, LegalOperations);
7865 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7866 return GetNegatedExpression(N10, DAG, LegalOperations);
7870 // FSUB -> FMA combines:
7871 SDValue Fused = visitFSUBForFMACombine(N);
7873 AddToWorklist(Fused.getNode());
7880 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7881 SDValue N0 = N->getOperand(0);
7882 SDValue N1 = N->getOperand(1);
7883 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7884 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7885 EVT VT = N->getValueType(0);
7886 const TargetOptions &Options = DAG.getTarget().Options;
7889 if (VT.isVector()) {
7890 // This just handles C1 * C2 for vectors. Other vector folds are below.
7891 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7895 // fold (fmul c1, c2) -> c1*c2
7897 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7899 // canonicalize constant to RHS
7900 if (isConstantFPBuildVectorOrConstantFP(N0) &&
7901 !isConstantFPBuildVectorOrConstantFP(N1))
7902 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7904 // fold (fmul A, 1.0) -> A
7905 if (N1CFP && N1CFP->isExactlyValue(1.0))
7908 if (Options.UnsafeFPMath) {
7909 // fold (fmul A, 0) -> 0
7910 if (N1CFP && N1CFP->getValueAPF().isZero())
7913 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7914 if (N0.getOpcode() == ISD::FMUL) {
7915 // Fold scalars or any vector constants (not just splats).
7916 // This fold is done in general by InstCombine, but extra fmul insts
7917 // may have been generated during lowering.
7918 SDValue N00 = N0.getOperand(0);
7919 SDValue N01 = N0.getOperand(1);
7920 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7921 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7922 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7924 // Check 1: Make sure that the first operand of the inner multiply is NOT
7925 // a constant. Otherwise, we may induce infinite looping.
7926 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7927 // Check 2: Make sure that the second operand of the inner multiply and
7928 // the second operand of the outer multiply are constants.
7929 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7930 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7932 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7933 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7938 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7939 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7940 // during an early run of DAGCombiner can prevent folding with fmuls
7941 // inserted during lowering.
7942 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7944 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7945 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7946 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7950 // fold (fmul X, 2.0) -> (fadd X, X)
7951 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7952 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7954 // fold (fmul X, -1.0) -> (fneg X)
7955 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7956 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7957 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7959 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7960 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7961 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7962 // Both can be negated for free, check to see if at least one is cheaper
7964 if (LHSNeg == 2 || RHSNeg == 2)
7965 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7966 GetNegatedExpression(N0, DAG, LegalOperations),
7967 GetNegatedExpression(N1, DAG, LegalOperations));
7974 SDValue DAGCombiner::visitFMA(SDNode *N) {
7975 SDValue N0 = N->getOperand(0);
7976 SDValue N1 = N->getOperand(1);
7977 SDValue N2 = N->getOperand(2);
7978 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7979 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7980 EVT VT = N->getValueType(0);
7982 const TargetOptions &Options = DAG.getTarget().Options;
7984 // Constant fold FMA.
7985 if (isa<ConstantFPSDNode>(N0) &&
7986 isa<ConstantFPSDNode>(N1) &&
7987 isa<ConstantFPSDNode>(N2)) {
7988 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7991 if (Options.UnsafeFPMath) {
7992 if (N0CFP && N0CFP->isZero())
7994 if (N1CFP && N1CFP->isZero())
7997 if (N0CFP && N0CFP->isExactlyValue(1.0))
7998 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7999 if (N1CFP && N1CFP->isExactlyValue(1.0))
8000 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8002 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8003 if (N0CFP && !N1CFP)
8004 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8006 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8007 if (Options.UnsafeFPMath && N1CFP &&
8008 N2.getOpcode() == ISD::FMUL &&
8009 N0 == N2.getOperand(0) &&
8010 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8011 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8012 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8016 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8017 if (Options.UnsafeFPMath &&
8018 N0.getOpcode() == ISD::FMUL && N1CFP &&
8019 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8020 return DAG.getNode(ISD::FMA, dl, VT,
8022 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8026 // (fma x, 1, y) -> (fadd x, y)
8027 // (fma x, -1, y) -> (fadd (fneg x), y)
8029 if (N1CFP->isExactlyValue(1.0))
8030 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8032 if (N1CFP->isExactlyValue(-1.0) &&
8033 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8034 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8035 AddToWorklist(RHSNeg.getNode());
8036 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8040 // (fma x, c, x) -> (fmul x, (c+1))
8041 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8042 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8043 DAG.getNode(ISD::FADD, dl, VT,
8044 N1, DAG.getConstantFP(1.0, dl, VT)));
8046 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8047 if (Options.UnsafeFPMath && N1CFP &&
8048 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8049 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8050 DAG.getNode(ISD::FADD, dl, VT,
8051 N1, DAG.getConstantFP(-1.0, dl, VT)));
8057 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8058 SDValue N0 = N->getOperand(0);
8059 SDValue N1 = N->getOperand(1);
8060 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8061 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8062 EVT VT = N->getValueType(0);
8064 const TargetOptions &Options = DAG.getTarget().Options;
8068 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8071 // fold (fdiv c1, c2) -> c1/c2
8073 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8075 if (Options.UnsafeFPMath) {
8076 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8078 // Compute the reciprocal 1.0 / c2.
8079 APFloat N1APF = N1CFP->getValueAPF();
8080 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8081 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8082 // Only do the transform if the reciprocal is a legal fp immediate that
8083 // isn't too nasty (eg NaN, denormal, ...).
8084 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8085 (!LegalOperations ||
8086 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8087 // backend)... we should handle this gracefully after Legalize.
8088 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8089 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8090 TLI.isFPImmLegal(Recip, VT)))
8091 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8092 DAG.getConstantFP(Recip, DL, VT));
8095 // If this FDIV is part of a reciprocal square root, it may be folded
8096 // into a target-specific square root estimate instruction.
8097 if (N1.getOpcode() == ISD::FSQRT) {
8098 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8099 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8101 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8102 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8103 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8104 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8105 AddToWorklist(RV.getNode());
8106 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8108 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8109 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8110 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8111 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8112 AddToWorklist(RV.getNode());
8113 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8115 } else if (N1.getOpcode() == ISD::FMUL) {
8116 // Look through an FMUL. Even though this won't remove the FDIV directly,
8117 // it's still worthwhile to get rid of the FSQRT if possible.
8120 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8121 SqrtOp = N1.getOperand(0);
8122 OtherOp = N1.getOperand(1);
8123 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8124 SqrtOp = N1.getOperand(1);
8125 OtherOp = N1.getOperand(0);
8127 if (SqrtOp.getNode()) {
8128 // We found a FSQRT, so try to make this fold:
8129 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8130 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8131 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8132 AddToWorklist(RV.getNode());
8133 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8138 // Fold into a reciprocal estimate and multiply instead of a real divide.
8139 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8140 AddToWorklist(RV.getNode());
8141 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8145 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8146 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8147 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8148 // Both can be negated for free, check to see if at least one is cheaper
8150 if (LHSNeg == 2 || RHSNeg == 2)
8151 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8152 GetNegatedExpression(N0, DAG, LegalOperations),
8153 GetNegatedExpression(N1, DAG, LegalOperations));
8157 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8159 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8160 // Notice that this is not always beneficial. One reason is different target
8161 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8162 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8163 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8164 if (Options.UnsafeFPMath) {
8165 // Skip if current node is a reciprocal.
8166 if (N0CFP && N0CFP->isExactlyValue(1.0))
8169 SmallVector<SDNode *, 4> Users;
8170 // Find all FDIV users of the same divisor.
8171 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8172 UE = N1.getNode()->use_end();
8174 SDNode *User = UI.getUse().getUser();
8175 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8176 Users.push_back(User);
8179 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8181 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8182 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8184 // Dividend / Divisor -> Dividend * Reciprocal
8185 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8186 if ((*I)->getOperand(0) != FPOne) {
8187 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8188 (*I)->getOperand(0), Reciprocal);
8189 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8199 SDValue DAGCombiner::visitFREM(SDNode *N) {
8200 SDValue N0 = N->getOperand(0);
8201 SDValue N1 = N->getOperand(1);
8202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8203 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8204 EVT VT = N->getValueType(0);
8206 // fold (frem c1, c2) -> fmod(c1,c2)
8208 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8213 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8214 if (DAG.getTarget().Options.UnsafeFPMath &&
8215 !TLI.isFsqrtCheap()) {
8216 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8217 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8218 EVT VT = RV.getValueType();
8220 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8221 AddToWorklist(RV.getNode());
8223 // Unfortunately, RV is now NaN if the input was exactly 0.
8224 // Select out this case and force the answer to 0.
8225 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8227 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8228 N->getOperand(0), Zero, ISD::SETEQ);
8229 AddToWorklist(ZeroCmp.getNode());
8230 AddToWorklist(RV.getNode());
8232 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8233 DL, VT, ZeroCmp, Zero, RV);
8240 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8241 SDValue N0 = N->getOperand(0);
8242 SDValue N1 = N->getOperand(1);
8243 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8244 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8245 EVT VT = N->getValueType(0);
8247 if (N0CFP && N1CFP) // Constant fold
8248 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8251 const APFloat& V = N1CFP->getValueAPF();
8252 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8253 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8254 if (!V.isNegative()) {
8255 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8256 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8258 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8259 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8260 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8264 // copysign(fabs(x), y) -> copysign(x, y)
8265 // copysign(fneg(x), y) -> copysign(x, y)
8266 // copysign(copysign(x,z), y) -> copysign(x, y)
8267 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8268 N0.getOpcode() == ISD::FCOPYSIGN)
8269 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8270 N0.getOperand(0), N1);
8272 // copysign(x, abs(y)) -> abs(x)
8273 if (N1.getOpcode() == ISD::FABS)
8274 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8276 // copysign(x, copysign(y,z)) -> copysign(x, z)
8277 if (N1.getOpcode() == ISD::FCOPYSIGN)
8278 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8279 N0, N1.getOperand(1));
8281 // copysign(x, fp_extend(y)) -> copysign(x, y)
8282 // copysign(x, fp_round(y)) -> copysign(x, y)
8283 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8284 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8285 N0, N1.getOperand(0));
8290 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8291 SDValue N0 = N->getOperand(0);
8292 EVT VT = N->getValueType(0);
8293 EVT OpVT = N0.getValueType();
8295 // fold (sint_to_fp c1) -> c1fp
8296 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8297 // ...but only if the target supports immediate floating-point values
8298 (!LegalOperations ||
8299 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8300 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8302 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8303 // but UINT_TO_FP is legal on this target, try to convert.
8304 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8305 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8306 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8307 if (DAG.SignBitIsZero(N0))
8308 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8311 // The next optimizations are desirable only if SELECT_CC can be lowered.
8312 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8313 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8314 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8316 (!LegalOperations ||
8317 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8320 { N0.getOperand(0), N0.getOperand(1),
8321 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8323 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8326 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8327 // (select_cc x, y, 1.0, 0.0,, cc)
8328 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8329 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8330 (!LegalOperations ||
8331 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8334 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8335 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8336 N0.getOperand(0).getOperand(2) };
8337 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8344 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8345 SDValue N0 = N->getOperand(0);
8346 EVT VT = N->getValueType(0);
8347 EVT OpVT = N0.getValueType();
8349 // fold (uint_to_fp c1) -> c1fp
8350 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8351 // ...but only if the target supports immediate floating-point values
8352 (!LegalOperations ||
8353 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8354 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8356 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8357 // but SINT_TO_FP is legal on this target, try to convert.
8358 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8359 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8360 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8361 if (DAG.SignBitIsZero(N0))
8362 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8365 // The next optimizations are desirable only if SELECT_CC can be lowered.
8366 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8367 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8369 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8370 (!LegalOperations ||
8371 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8374 { N0.getOperand(0), N0.getOperand(1),
8375 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8377 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8384 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8385 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8386 SDValue N0 = N->getOperand(0);
8387 EVT VT = N->getValueType(0);
8389 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8392 SDValue Src = N0.getOperand(0);
8393 EVT SrcVT = Src.getValueType();
8394 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8395 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8397 // We can safely assume the conversion won't overflow the output range,
8398 // because (for example) (uint8_t)18293.f is undefined behavior.
8400 // Since we can assume the conversion won't overflow, our decision as to
8401 // whether the input will fit in the float should depend on the minimum
8402 // of the input range and output range.
8404 // This means this is also safe for a signed input and unsigned output, since
8405 // a negative input would lead to undefined behavior.
8406 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8407 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8408 unsigned ActualSize = std::min(InputSize, OutputSize);
8409 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8411 // We can only fold away the float conversion if the input range can be
8412 // represented exactly in the float range.
8413 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8414 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8415 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8417 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8419 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8420 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8423 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8428 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8429 SDValue N0 = N->getOperand(0);
8430 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8431 EVT VT = N->getValueType(0);
8433 // fold (fp_to_sint c1fp) -> c1
8435 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8437 return FoldIntToFPToInt(N, DAG);
8440 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8441 SDValue N0 = N->getOperand(0);
8442 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8443 EVT VT = N->getValueType(0);
8445 // fold (fp_to_uint c1fp) -> c1
8447 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8449 return FoldIntToFPToInt(N, DAG);
8452 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8453 SDValue N0 = N->getOperand(0);
8454 SDValue N1 = N->getOperand(1);
8455 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8456 EVT VT = N->getValueType(0);
8458 // fold (fp_round c1fp) -> c1fp
8460 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8462 // fold (fp_round (fp_extend x)) -> x
8463 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8464 return N0.getOperand(0);
8466 // fold (fp_round (fp_round x)) -> (fp_round x)
8467 if (N0.getOpcode() == ISD::FP_ROUND) {
8468 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8469 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8470 // If the first fp_round isn't a value preserving truncation, it might
8471 // introduce a tie in the second fp_round, that wouldn't occur in the
8472 // single-step fp_round we want to fold to.
8473 // In other words, double rounding isn't the same as rounding.
8474 // Also, this is a value preserving truncation iff both fp_round's are.
8475 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8477 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8478 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8482 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8483 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8484 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8485 N0.getOperand(0), N1);
8486 AddToWorklist(Tmp.getNode());
8487 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8488 Tmp, N0.getOperand(1));
8494 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8495 SDValue N0 = N->getOperand(0);
8496 EVT VT = N->getValueType(0);
8497 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8498 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8500 // fold (fp_round_inreg c1fp) -> c1fp
8501 if (N0CFP && isTypeLegal(EVT)) {
8503 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8504 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8510 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8511 SDValue N0 = N->getOperand(0);
8512 EVT VT = N->getValueType(0);
8514 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8515 if (N->hasOneUse() &&
8516 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8519 // fold (fp_extend c1fp) -> c1fp
8520 if (isConstantFPBuildVectorOrConstantFP(N0))
8521 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8523 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8524 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8525 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8526 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8528 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8530 if (N0.getOpcode() == ISD::FP_ROUND
8531 && N0.getNode()->getConstantOperandVal(1) == 1) {
8532 SDValue In = N0.getOperand(0);
8533 if (In.getValueType() == VT) return In;
8534 if (VT.bitsLT(In.getValueType()))
8535 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8536 In, N0.getOperand(1));
8537 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8540 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8541 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8542 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8543 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8544 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8546 LN0->getBasePtr(), N0.getValueType(),
8547 LN0->getMemOperand());
8548 CombineTo(N, ExtLoad);
8549 CombineTo(N0.getNode(),
8550 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8551 N0.getValueType(), ExtLoad,
8552 DAG.getIntPtrConstant(1, SDLoc(N0))),
8553 ExtLoad.getValue(1));
8554 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8560 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8561 SDValue N0 = N->getOperand(0);
8562 EVT VT = N->getValueType(0);
8564 // fold (fceil c1) -> fceil(c1)
8565 if (isConstantFPBuildVectorOrConstantFP(N0))
8566 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8571 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8572 SDValue N0 = N->getOperand(0);
8573 EVT VT = N->getValueType(0);
8575 // fold (ftrunc c1) -> ftrunc(c1)
8576 if (isConstantFPBuildVectorOrConstantFP(N0))
8577 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8582 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8583 SDValue N0 = N->getOperand(0);
8584 EVT VT = N->getValueType(0);
8586 // fold (ffloor c1) -> ffloor(c1)
8587 if (isConstantFPBuildVectorOrConstantFP(N0))
8588 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8593 // FIXME: FNEG and FABS have a lot in common; refactor.
8594 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8595 SDValue N0 = N->getOperand(0);
8596 EVT VT = N->getValueType(0);
8598 // Constant fold FNEG.
8599 if (isConstantFPBuildVectorOrConstantFP(N0))
8600 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8602 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8603 &DAG.getTarget().Options))
8604 return GetNegatedExpression(N0, DAG, LegalOperations);
8606 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8607 // constant pool values.
8608 if (!TLI.isFNegFree(VT) &&
8609 N0.getOpcode() == ISD::BITCAST &&
8610 N0.getNode()->hasOneUse()) {
8611 SDValue Int = N0.getOperand(0);
8612 EVT IntVT = Int.getValueType();
8613 if (IntVT.isInteger() && !IntVT.isVector()) {
8615 if (N0.getValueType().isVector()) {
8616 // For a vector, get a mask such as 0x80... per scalar element
8618 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8619 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8621 // For a scalar, just generate 0x80...
8622 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8625 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8626 DAG.getConstant(SignMask, DL0, IntVT));
8627 AddToWorklist(Int.getNode());
8628 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8632 // (fneg (fmul c, x)) -> (fmul -c, x)
8633 if (N0.getOpcode() == ISD::FMUL) {
8634 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8636 APFloat CVal = CFP1->getValueAPF();
8638 if (Level >= AfterLegalizeDAG &&
8639 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8640 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8642 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8643 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8650 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8651 SDValue N0 = N->getOperand(0);
8652 SDValue N1 = N->getOperand(1);
8653 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8654 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8656 if (N0CFP && N1CFP) {
8657 const APFloat &C0 = N0CFP->getValueAPF();
8658 const APFloat &C1 = N1CFP->getValueAPF();
8659 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8663 EVT VT = N->getValueType(0);
8664 // Canonicalize to constant on RHS.
8665 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8671 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8672 SDValue N0 = N->getOperand(0);
8673 SDValue N1 = N->getOperand(1);
8674 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8675 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8677 if (N0CFP && N1CFP) {
8678 const APFloat &C0 = N0CFP->getValueAPF();
8679 const APFloat &C1 = N1CFP->getValueAPF();
8680 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8684 EVT VT = N->getValueType(0);
8685 // Canonicalize to constant on RHS.
8686 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8692 SDValue DAGCombiner::visitFABS(SDNode *N) {
8693 SDValue N0 = N->getOperand(0);
8694 EVT VT = N->getValueType(0);
8696 // fold (fabs c1) -> fabs(c1)
8697 if (isConstantFPBuildVectorOrConstantFP(N0))
8698 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8700 // fold (fabs (fabs x)) -> (fabs x)
8701 if (N0.getOpcode() == ISD::FABS)
8702 return N->getOperand(0);
8704 // fold (fabs (fneg x)) -> (fabs x)
8705 // fold (fabs (fcopysign x, y)) -> (fabs x)
8706 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8707 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8709 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8710 // constant pool values.
8711 if (!TLI.isFAbsFree(VT) &&
8712 N0.getOpcode() == ISD::BITCAST &&
8713 N0.getNode()->hasOneUse()) {
8714 SDValue Int = N0.getOperand(0);
8715 EVT IntVT = Int.getValueType();
8716 if (IntVT.isInteger() && !IntVT.isVector()) {
8718 if (N0.getValueType().isVector()) {
8719 // For a vector, get a mask such as 0x7f... per scalar element
8721 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8722 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8724 // For a scalar, just generate 0x7f...
8725 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8728 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8729 DAG.getConstant(SignMask, DL, IntVT));
8730 AddToWorklist(Int.getNode());
8731 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8738 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8739 SDValue Chain = N->getOperand(0);
8740 SDValue N1 = N->getOperand(1);
8741 SDValue N2 = N->getOperand(2);
8743 // If N is a constant we could fold this into a fallthrough or unconditional
8744 // branch. However that doesn't happen very often in normal code, because
8745 // Instcombine/SimplifyCFG should have handled the available opportunities.
8746 // If we did this folding here, it would be necessary to update the
8747 // MachineBasicBlock CFG, which is awkward.
8749 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8751 if (N1.getOpcode() == ISD::SETCC &&
8752 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8753 N1.getOperand(0).getValueType())) {
8754 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8755 Chain, N1.getOperand(2),
8756 N1.getOperand(0), N1.getOperand(1), N2);
8759 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8760 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8761 (N1.getOperand(0).hasOneUse() &&
8762 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8763 SDNode *Trunc = nullptr;
8764 if (N1.getOpcode() == ISD::TRUNCATE) {
8765 // Look pass the truncate.
8766 Trunc = N1.getNode();
8767 N1 = N1.getOperand(0);
8770 // Match this pattern so that we can generate simpler code:
8773 // %b = and i32 %a, 2
8774 // %c = srl i32 %b, 1
8775 // brcond i32 %c ...
8780 // %b = and i32 %a, 2
8781 // %c = setcc eq %b, 0
8784 // This applies only when the AND constant value has one bit set and the
8785 // SRL constant is equal to the log2 of the AND constant. The back-end is
8786 // smart enough to convert the result into a TEST/JMP sequence.
8787 SDValue Op0 = N1.getOperand(0);
8788 SDValue Op1 = N1.getOperand(1);
8790 if (Op0.getOpcode() == ISD::AND &&
8791 Op1.getOpcode() == ISD::Constant) {
8792 SDValue AndOp1 = Op0.getOperand(1);
8794 if (AndOp1.getOpcode() == ISD::Constant) {
8795 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8797 if (AndConst.isPowerOf2() &&
8798 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8802 getSetCCResultType(Op0.getValueType()),
8803 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8806 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8807 MVT::Other, Chain, SetCC, N2);
8808 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8809 // will convert it back to (X & C1) >> C2.
8810 CombineTo(N, NewBRCond, false);
8811 // Truncate is dead.
8813 deleteAndRecombine(Trunc);
8814 // Replace the uses of SRL with SETCC
8815 WorklistRemover DeadNodes(*this);
8816 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8817 deleteAndRecombine(N1.getNode());
8818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8824 // Restore N1 if the above transformation doesn't match.
8825 N1 = N->getOperand(1);
8828 // Transform br(xor(x, y)) -> br(x != y)
8829 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8830 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8831 SDNode *TheXor = N1.getNode();
8832 SDValue Op0 = TheXor->getOperand(0);
8833 SDValue Op1 = TheXor->getOperand(1);
8834 if (Op0.getOpcode() == Op1.getOpcode()) {
8835 // Avoid missing important xor optimizations.
8836 SDValue Tmp = visitXOR(TheXor);
8837 if (Tmp.getNode()) {
8838 if (Tmp.getNode() != TheXor) {
8839 DEBUG(dbgs() << "\nReplacing.8 ";
8841 dbgs() << "\nWith: ";
8842 Tmp.getNode()->dump(&DAG);
8844 WorklistRemover DeadNodes(*this);
8845 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8846 deleteAndRecombine(TheXor);
8847 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8848 MVT::Other, Chain, Tmp, N2);
8851 // visitXOR has changed XOR's operands or replaced the XOR completely,
8853 return SDValue(N, 0);
8857 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8859 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8860 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8861 Op0.getOpcode() == ISD::XOR) {
8862 TheXor = Op0.getNode();
8866 EVT SetCCVT = N1.getValueType();
8868 SetCCVT = getSetCCResultType(SetCCVT);
8869 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8872 Equal ? ISD::SETEQ : ISD::SETNE);
8873 // Replace the uses of XOR with SETCC
8874 WorklistRemover DeadNodes(*this);
8875 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8876 deleteAndRecombine(N1.getNode());
8877 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8878 MVT::Other, Chain, SetCC, N2);
8885 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8887 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8888 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8889 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8891 // If N is a constant we could fold this into a fallthrough or unconditional
8892 // branch. However that doesn't happen very often in normal code, because
8893 // Instcombine/SimplifyCFG should have handled the available opportunities.
8894 // If we did this folding here, it would be necessary to update the
8895 // MachineBasicBlock CFG, which is awkward.
8897 // Use SimplifySetCC to simplify SETCC's.
8898 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8899 CondLHS, CondRHS, CC->get(), SDLoc(N),
8901 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8903 // fold to a simpler setcc
8904 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8905 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8906 N->getOperand(0), Simp.getOperand(2),
8907 Simp.getOperand(0), Simp.getOperand(1),
8913 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8914 /// and that N may be folded in the load / store addressing mode.
8915 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8917 const TargetLowering &TLI) {
8919 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8920 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8922 VT = LD->getMemoryVT();
8923 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8924 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8926 VT = ST->getMemoryVT();
8930 TargetLowering::AddrMode AM;
8931 if (N->getOpcode() == ISD::ADD) {
8932 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8935 AM.BaseOffs = Offset->getSExtValue();
8939 } else if (N->getOpcode() == ISD::SUB) {
8940 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8943 AM.BaseOffs = -Offset->getSExtValue();
8950 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8953 /// Try turning a load/store into a pre-indexed load/store when the base
8954 /// pointer is an add or subtract and it has other uses besides the load/store.
8955 /// After the transformation, the new indexed load/store has effectively folded
8956 /// the add/subtract in and all of its other uses are redirected to the
8958 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8959 if (Level < AfterLegalizeDAG)
8965 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8966 if (LD->isIndexed())
8968 VT = LD->getMemoryVT();
8969 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8970 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8972 Ptr = LD->getBasePtr();
8973 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8974 if (ST->isIndexed())
8976 VT = ST->getMemoryVT();
8977 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8978 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8980 Ptr = ST->getBasePtr();
8986 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8987 // out. There is no reason to make this a preinc/predec.
8988 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8989 Ptr.getNode()->hasOneUse())
8992 // Ask the target to do addressing mode selection.
8995 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8996 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8999 // Backends without true r+i pre-indexed forms may need to pass a
9000 // constant base with a variable offset so that constant coercion
9001 // will work with the patterns in canonical form.
9002 bool Swapped = false;
9003 if (isa<ConstantSDNode>(BasePtr)) {
9004 std::swap(BasePtr, Offset);
9008 // Don't create a indexed load / store with zero offset.
9009 if (isa<ConstantSDNode>(Offset) &&
9010 cast<ConstantSDNode>(Offset)->isNullValue())
9013 // Try turning it into a pre-indexed load / store except when:
9014 // 1) The new base ptr is a frame index.
9015 // 2) If N is a store and the new base ptr is either the same as or is a
9016 // predecessor of the value being stored.
9017 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9018 // that would create a cycle.
9019 // 4) All uses are load / store ops that use it as old base ptr.
9021 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9022 // (plus the implicit offset) to a register to preinc anyway.
9023 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9028 SDValue Val = cast<StoreSDNode>(N)->getValue();
9029 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9033 // If the offset is a constant, there may be other adds of constants that
9034 // can be folded with this one. We should do this to avoid having to keep
9035 // a copy of the original base pointer.
9036 SmallVector<SDNode *, 16> OtherUses;
9037 if (isa<ConstantSDNode>(Offset))
9038 for (SDNode *Use : BasePtr.getNode()->uses()) {
9039 if (Use == Ptr.getNode())
9042 if (Use->isPredecessorOf(N))
9045 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9050 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9051 if (Op1.getNode() == BasePtr.getNode())
9052 std::swap(Op0, Op1);
9053 assert(Op0.getNode() == BasePtr.getNode() &&
9054 "Use of ADD/SUB but not an operand");
9056 if (!isa<ConstantSDNode>(Op1)) {
9061 // FIXME: In some cases, we can be smarter about this.
9062 if (Op1.getValueType() != Offset.getValueType()) {
9067 OtherUses.push_back(Use);
9071 std::swap(BasePtr, Offset);
9073 // Now check for #3 and #4.
9074 bool RealUse = false;
9076 // Caches for hasPredecessorHelper
9077 SmallPtrSet<const SDNode *, 32> Visited;
9078 SmallVector<const SDNode *, 16> Worklist;
9080 for (SDNode *Use : Ptr.getNode()->uses()) {
9083 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9086 // If Ptr may be folded in addressing mode of other use, then it's
9087 // not profitable to do this transformation.
9088 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9097 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9098 BasePtr, Offset, AM);
9100 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9101 BasePtr, Offset, AM);
9104 DEBUG(dbgs() << "\nReplacing.4 ";
9106 dbgs() << "\nWith: ";
9107 Result.getNode()->dump(&DAG);
9109 WorklistRemover DeadNodes(*this);
9111 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9112 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9114 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9117 // Finally, since the node is now dead, remove it from the graph.
9118 deleteAndRecombine(N);
9121 std::swap(BasePtr, Offset);
9123 // Replace other uses of BasePtr that can be updated to use Ptr
9124 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9125 unsigned OffsetIdx = 1;
9126 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9128 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9129 BasePtr.getNode() && "Expected BasePtr operand");
9131 // We need to replace ptr0 in the following expression:
9132 // x0 * offset0 + y0 * ptr0 = t0
9134 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9136 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9137 // indexed load/store and the expresion that needs to be re-written.
9139 // Therefore, we have:
9140 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9142 ConstantSDNode *CN =
9143 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9145 APInt Offset0 = CN->getAPIntValue();
9146 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9148 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9149 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9150 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9151 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9153 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9155 APInt CNV = Offset0;
9156 if (X0 < 0) CNV = -CNV;
9157 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9158 else CNV = CNV - Offset1;
9160 SDLoc DL(OtherUses[i]);
9162 // We can now generate the new expression.
9163 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9164 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9166 SDValue NewUse = DAG.getNode(Opcode,
9168 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9169 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9170 deleteAndRecombine(OtherUses[i]);
9173 // Replace the uses of Ptr with uses of the updated base value.
9174 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9175 deleteAndRecombine(Ptr.getNode());
9180 /// Try to combine a load/store with a add/sub of the base pointer node into a
9181 /// post-indexed load/store. The transformation folded the add/subtract into the
9182 /// new indexed load/store effectively and all of its uses are redirected to the
9184 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9185 if (Level < AfterLegalizeDAG)
9191 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9192 if (LD->isIndexed())
9194 VT = LD->getMemoryVT();
9195 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9196 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9198 Ptr = LD->getBasePtr();
9199 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9200 if (ST->isIndexed())
9202 VT = ST->getMemoryVT();
9203 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9204 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9206 Ptr = ST->getBasePtr();
9212 if (Ptr.getNode()->hasOneUse())
9215 for (SDNode *Op : Ptr.getNode()->uses()) {
9217 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9222 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9223 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9224 // Don't create a indexed load / store with zero offset.
9225 if (isa<ConstantSDNode>(Offset) &&
9226 cast<ConstantSDNode>(Offset)->isNullValue())
9229 // Try turning it into a post-indexed load / store except when
9230 // 1) All uses are load / store ops that use it as base ptr (and
9231 // it may be folded as addressing mmode).
9232 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9233 // nor a successor of N. Otherwise, if Op is folded that would
9236 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9240 bool TryNext = false;
9241 for (SDNode *Use : BasePtr.getNode()->uses()) {
9242 if (Use == Ptr.getNode())
9245 // If all the uses are load / store addresses, then don't do the
9247 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9248 bool RealUse = false;
9249 for (SDNode *UseUse : Use->uses()) {
9250 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9265 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9266 SDValue Result = isLoad
9267 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9268 BasePtr, Offset, AM)
9269 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9270 BasePtr, Offset, AM);
9273 DEBUG(dbgs() << "\nReplacing.5 ";
9275 dbgs() << "\nWith: ";
9276 Result.getNode()->dump(&DAG);
9278 WorklistRemover DeadNodes(*this);
9280 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9281 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9283 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9286 // Finally, since the node is now dead, remove it from the graph.
9287 deleteAndRecombine(N);
9289 // Replace the uses of Use with uses of the updated base value.
9290 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9291 Result.getValue(isLoad ? 1 : 0));
9292 deleteAndRecombine(Op);
9301 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9302 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9303 ISD::MemIndexedMode AM = LD->getAddressingMode();
9304 assert(AM != ISD::UNINDEXED);
9305 SDValue BP = LD->getOperand(1);
9306 SDValue Inc = LD->getOperand(2);
9308 // Some backends use TargetConstants for load offsets, but don't expect
9309 // TargetConstants in general ADD nodes. We can convert these constants into
9310 // regular Constants (if the constant is not opaque).
9311 assert((Inc.getOpcode() != ISD::TargetConstant ||
9312 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9313 "Cannot split out indexing using opaque target constants");
9314 if (Inc.getOpcode() == ISD::TargetConstant) {
9315 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9316 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9317 ConstInc->getValueType(0));
9321 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9322 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9325 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9326 LoadSDNode *LD = cast<LoadSDNode>(N);
9327 SDValue Chain = LD->getChain();
9328 SDValue Ptr = LD->getBasePtr();
9330 // If load is not volatile and there are no uses of the loaded value (and
9331 // the updated indexed value in case of indexed loads), change uses of the
9332 // chain value into uses of the chain input (i.e. delete the dead load).
9333 if (!LD->isVolatile()) {
9334 if (N->getValueType(1) == MVT::Other) {
9336 if (!N->hasAnyUseOfValue(0)) {
9337 // It's not safe to use the two value CombineTo variant here. e.g.
9338 // v1, chain2 = load chain1, loc
9339 // v2, chain3 = load chain2, loc
9341 // Now we replace use of chain2 with chain1. This makes the second load
9342 // isomorphic to the one we are deleting, and thus makes this load live.
9343 DEBUG(dbgs() << "\nReplacing.6 ";
9345 dbgs() << "\nWith chain: ";
9346 Chain.getNode()->dump(&DAG);
9348 WorklistRemover DeadNodes(*this);
9349 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9352 deleteAndRecombine(N);
9354 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9358 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9360 // If this load has an opaque TargetConstant offset, then we cannot split
9361 // the indexing into an add/sub directly (that TargetConstant may not be
9362 // valid for a different type of node, and we cannot convert an opaque
9363 // target constant into a regular constant).
9364 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9365 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9367 if (!N->hasAnyUseOfValue(0) &&
9368 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9369 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9371 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9372 Index = SplitIndexingFromLoad(LD);
9373 // Try to fold the base pointer arithmetic into subsequent loads and
9375 AddUsersToWorklist(N);
9377 Index = DAG.getUNDEF(N->getValueType(1));
9378 DEBUG(dbgs() << "\nReplacing.7 ";
9380 dbgs() << "\nWith: ";
9381 Undef.getNode()->dump(&DAG);
9382 dbgs() << " and 2 other values\n");
9383 WorklistRemover DeadNodes(*this);
9384 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9387 deleteAndRecombine(N);
9388 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9393 // If this load is directly stored, replace the load value with the stored
9395 // TODO: Handle store large -> read small portion.
9396 // TODO: Handle TRUNCSTORE/LOADEXT
9397 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9398 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9399 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9400 if (PrevST->getBasePtr() == Ptr &&
9401 PrevST->getValue().getValueType() == N->getValueType(0))
9402 return CombineTo(N, Chain.getOperand(1), Chain);
9406 // Try to infer better alignment information than the load already has.
9407 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9408 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9409 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9411 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9412 LD->getValueType(0),
9413 Chain, Ptr, LD->getPointerInfo(),
9415 LD->isVolatile(), LD->isNonTemporal(),
9416 LD->isInvariant(), Align, LD->getAAInfo());
9417 if (NewLoad.getNode() != N)
9418 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9423 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9424 : DAG.getSubtarget().useAA();
9426 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9427 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9430 if (UseAA && LD->isUnindexed()) {
9431 // Walk up chain skipping non-aliasing memory nodes.
9432 SDValue BetterChain = FindBetterChain(N, Chain);
9434 // If there is a better chain.
9435 if (Chain != BetterChain) {
9438 // Replace the chain to void dependency.
9439 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9440 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9441 BetterChain, Ptr, LD->getMemOperand());
9443 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9444 LD->getValueType(0),
9445 BetterChain, Ptr, LD->getMemoryVT(),
9446 LD->getMemOperand());
9449 // Create token factor to keep old chain connected.
9450 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9451 MVT::Other, Chain, ReplLoad.getValue(1));
9453 // Make sure the new and old chains are cleaned up.
9454 AddToWorklist(Token.getNode());
9456 // Replace uses with load result and token factor. Don't add users
9458 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9462 // Try transforming N to an indexed load.
9463 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9464 return SDValue(N, 0);
9466 // Try to slice up N to more direct loads if the slices are mapped to
9467 // different register banks or pairing can take place.
9469 return SDValue(N, 0);
9475 /// \brief Helper structure used to slice a load in smaller loads.
9476 /// Basically a slice is obtained from the following sequence:
9477 /// Origin = load Ty1, Base
9478 /// Shift = srl Ty1 Origin, CstTy Amount
9479 /// Inst = trunc Shift to Ty2
9481 /// Then, it will be rewriten into:
9482 /// Slice = load SliceTy, Base + SliceOffset
9483 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9485 /// SliceTy is deduced from the number of bits that are actually used to
9487 struct LoadedSlice {
9488 /// \brief Helper structure used to compute the cost of a slice.
9490 /// Are we optimizing for code size.
9495 unsigned CrossRegisterBanksCopies;
9499 Cost(bool ForCodeSize = false)
9500 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9501 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9503 /// \brief Get the cost of one isolated slice.
9504 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9505 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9506 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9507 EVT TruncType = LS.Inst->getValueType(0);
9508 EVT LoadedType = LS.getLoadedType();
9509 if (TruncType != LoadedType &&
9510 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9514 /// \brief Account for slicing gain in the current cost.
9515 /// Slicing provide a few gains like removing a shift or a
9516 /// truncate. This method allows to grow the cost of the original
9517 /// load with the gain from this slice.
9518 void addSliceGain(const LoadedSlice &LS) {
9519 // Each slice saves a truncate.
9520 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9521 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9522 LS.Inst->getOperand(0).getValueType()))
9524 // If there is a shift amount, this slice gets rid of it.
9527 // If this slice can merge a cross register bank copy, account for it.
9528 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9529 ++CrossRegisterBanksCopies;
9532 Cost &operator+=(const Cost &RHS) {
9534 Truncates += RHS.Truncates;
9535 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9541 bool operator==(const Cost &RHS) const {
9542 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9543 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9544 ZExts == RHS.ZExts && Shift == RHS.Shift;
9547 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9549 bool operator<(const Cost &RHS) const {
9550 // Assume cross register banks copies are as expensive as loads.
9551 // FIXME: Do we want some more target hooks?
9552 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9553 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9554 // Unless we are optimizing for code size, consider the
9555 // expensive operation first.
9556 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9557 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9558 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9559 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9562 bool operator>(const Cost &RHS) const { return RHS < *this; }
9564 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9566 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9568 // The last instruction that represent the slice. This should be a
9569 // truncate instruction.
9571 // The original load instruction.
9573 // The right shift amount in bits from the original load.
9575 // The DAG from which Origin came from.
9576 // This is used to get some contextual information about legal types, etc.
9579 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9580 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9581 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9583 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9584 /// \return Result is \p BitWidth and has used bits set to 1 and
9585 /// not used bits set to 0.
9586 APInt getUsedBits() const {
9587 // Reproduce the trunc(lshr) sequence:
9588 // - Start from the truncated value.
9589 // - Zero extend to the desired bit width.
9591 assert(Origin && "No original load to compare against.");
9592 unsigned BitWidth = Origin->getValueSizeInBits(0);
9593 assert(Inst && "This slice is not bound to an instruction");
9594 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9595 "Extracted slice is bigger than the whole type!");
9596 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9597 UsedBits.setAllBits();
9598 UsedBits = UsedBits.zext(BitWidth);
9603 /// \brief Get the size of the slice to be loaded in bytes.
9604 unsigned getLoadedSize() const {
9605 unsigned SliceSize = getUsedBits().countPopulation();
9606 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9607 return SliceSize / 8;
9610 /// \brief Get the type that will be loaded for this slice.
9611 /// Note: This may not be the final type for the slice.
9612 EVT getLoadedType() const {
9613 assert(DAG && "Missing context");
9614 LLVMContext &Ctxt = *DAG->getContext();
9615 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9618 /// \brief Get the alignment of the load used for this slice.
9619 unsigned getAlignment() const {
9620 unsigned Alignment = Origin->getAlignment();
9621 unsigned Offset = getOffsetFromBase();
9623 Alignment = MinAlign(Alignment, Alignment + Offset);
9627 /// \brief Check if this slice can be rewritten with legal operations.
9628 bool isLegal() const {
9629 // An invalid slice is not legal.
9630 if (!Origin || !Inst || !DAG)
9633 // Offsets are for indexed load only, we do not handle that.
9634 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9637 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9639 // Check that the type is legal.
9640 EVT SliceType = getLoadedType();
9641 if (!TLI.isTypeLegal(SliceType))
9644 // Check that the load is legal for this type.
9645 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9648 // Check that the offset can be computed.
9649 // 1. Check its type.
9650 EVT PtrType = Origin->getBasePtr().getValueType();
9651 if (PtrType == MVT::Untyped || PtrType.isExtended())
9654 // 2. Check that it fits in the immediate.
9655 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9658 // 3. Check that the computation is legal.
9659 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9662 // Check that the zext is legal if it needs one.
9663 EVT TruncateType = Inst->getValueType(0);
9664 if (TruncateType != SliceType &&
9665 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9671 /// \brief Get the offset in bytes of this slice in the original chunk of
9673 /// \pre DAG != nullptr.
9674 uint64_t getOffsetFromBase() const {
9675 assert(DAG && "Missing context.");
9677 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9678 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9679 uint64_t Offset = Shift / 8;
9680 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9681 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9682 "The size of the original loaded type is not a multiple of a"
9684 // If Offset is bigger than TySizeInBytes, it means we are loading all
9685 // zeros. This should have been optimized before in the process.
9686 assert(TySizeInBytes > Offset &&
9687 "Invalid shift amount for given loaded size");
9689 Offset = TySizeInBytes - Offset - getLoadedSize();
9693 /// \brief Generate the sequence of instructions to load the slice
9694 /// represented by this object and redirect the uses of this slice to
9695 /// this new sequence of instructions.
9696 /// \pre this->Inst && this->Origin are valid Instructions and this
9697 /// object passed the legal check: LoadedSlice::isLegal returned true.
9698 /// \return The last instruction of the sequence used to load the slice.
9699 SDValue loadSlice() const {
9700 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9701 const SDValue &OldBaseAddr = Origin->getBasePtr();
9702 SDValue BaseAddr = OldBaseAddr;
9703 // Get the offset in that chunk of bytes w.r.t. the endianess.
9704 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9705 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9707 // BaseAddr = BaseAddr + Offset.
9708 EVT ArithType = BaseAddr.getValueType();
9710 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9711 DAG->getConstant(Offset, DL, ArithType));
9714 // Create the type of the loaded slice according to its size.
9715 EVT SliceType = getLoadedType();
9717 // Create the load for the slice.
9718 SDValue LastInst = DAG->getLoad(
9719 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9720 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9721 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9722 // If the final type is not the same as the loaded type, this means that
9723 // we have to pad with zero. Create a zero extend for that.
9724 EVT FinalType = Inst->getValueType(0);
9725 if (SliceType != FinalType)
9727 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9731 /// \brief Check if this slice can be merged with an expensive cross register
9732 /// bank copy. E.g.,
9734 /// f = bitcast i32 i to float
9735 bool canMergeExpensiveCrossRegisterBankCopy() const {
9736 if (!Inst || !Inst->hasOneUse())
9738 SDNode *Use = *Inst->use_begin();
9739 if (Use->getOpcode() != ISD::BITCAST)
9741 assert(DAG && "Missing context");
9742 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9743 EVT ResVT = Use->getValueType(0);
9744 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9745 const TargetRegisterClass *ArgRC =
9746 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9747 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9750 // At this point, we know that we perform a cross-register-bank copy.
9751 // Check if it is expensive.
9752 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9753 // Assume bitcasts are cheap, unless both register classes do not
9754 // explicitly share a common sub class.
9755 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9758 // Check if it will be merged with the load.
9759 // 1. Check the alignment constraint.
9760 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9761 ResVT.getTypeForEVT(*DAG->getContext()));
9763 if (RequiredAlignment > getAlignment())
9766 // 2. Check that the load is a legal operation for that type.
9767 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9770 // 3. Check that we do not have a zext in the way.
9771 if (Inst->getValueType(0) != getLoadedType())
9779 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9780 /// \p UsedBits looks like 0..0 1..1 0..0.
9781 static bool areUsedBitsDense(const APInt &UsedBits) {
9782 // If all the bits are one, this is dense!
9783 if (UsedBits.isAllOnesValue())
9786 // Get rid of the unused bits on the right.
9787 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9788 // Get rid of the unused bits on the left.
9789 if (NarrowedUsedBits.countLeadingZeros())
9790 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9791 // Check that the chunk of bits is completely used.
9792 return NarrowedUsedBits.isAllOnesValue();
9795 /// \brief Check whether or not \p First and \p Second are next to each other
9796 /// in memory. This means that there is no hole between the bits loaded
9797 /// by \p First and the bits loaded by \p Second.
9798 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9799 const LoadedSlice &Second) {
9800 assert(First.Origin == Second.Origin && First.Origin &&
9801 "Unable to match different memory origins.");
9802 APInt UsedBits = First.getUsedBits();
9803 assert((UsedBits & Second.getUsedBits()) == 0 &&
9804 "Slices are not supposed to overlap.");
9805 UsedBits |= Second.getUsedBits();
9806 return areUsedBitsDense(UsedBits);
9809 /// \brief Adjust the \p GlobalLSCost according to the target
9810 /// paring capabilities and the layout of the slices.
9811 /// \pre \p GlobalLSCost should account for at least as many loads as
9812 /// there is in the slices in \p LoadedSlices.
9813 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9814 LoadedSlice::Cost &GlobalLSCost) {
9815 unsigned NumberOfSlices = LoadedSlices.size();
9816 // If there is less than 2 elements, no pairing is possible.
9817 if (NumberOfSlices < 2)
9820 // Sort the slices so that elements that are likely to be next to each
9821 // other in memory are next to each other in the list.
9822 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9823 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9824 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9825 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9827 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9828 // First (resp. Second) is the first (resp. Second) potentially candidate
9829 // to be placed in a paired load.
9830 const LoadedSlice *First = nullptr;
9831 const LoadedSlice *Second = nullptr;
9832 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9833 // Set the beginning of the pair.
9836 Second = &LoadedSlices[CurrSlice];
9838 // If First is NULL, it means we start a new pair.
9839 // Get to the next slice.
9843 EVT LoadedType = First->getLoadedType();
9845 // If the types of the slices are different, we cannot pair them.
9846 if (LoadedType != Second->getLoadedType())
9849 // Check if the target supplies paired loads for this type.
9850 unsigned RequiredAlignment = 0;
9851 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9852 // move to the next pair, this type is hopeless.
9856 // Check if we meet the alignment requirement.
9857 if (RequiredAlignment > First->getAlignment())
9860 // Check that both loads are next to each other in memory.
9861 if (!areSlicesNextToEachOther(*First, *Second))
9864 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9865 --GlobalLSCost.Loads;
9866 // Move to the next pair.
9871 /// \brief Check the profitability of all involved LoadedSlice.
9872 /// Currently, it is considered profitable if there is exactly two
9873 /// involved slices (1) which are (2) next to each other in memory, and
9874 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9876 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9877 /// the elements themselves.
9879 /// FIXME: When the cost model will be mature enough, we can relax
9880 /// constraints (1) and (2).
9881 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9882 const APInt &UsedBits, bool ForCodeSize) {
9883 unsigned NumberOfSlices = LoadedSlices.size();
9884 if (StressLoadSlicing)
9885 return NumberOfSlices > 1;
9888 if (NumberOfSlices != 2)
9892 if (!areUsedBitsDense(UsedBits))
9896 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9897 // The original code has one big load.
9899 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9900 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9901 // Accumulate the cost of all the slices.
9902 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9903 GlobalSlicingCost += SliceCost;
9905 // Account as cost in the original configuration the gain obtained
9906 // with the current slices.
9907 OrigCost.addSliceGain(LS);
9910 // If the target supports paired load, adjust the cost accordingly.
9911 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9912 return OrigCost > GlobalSlicingCost;
9915 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9916 /// operations, split it in the various pieces being extracted.
9918 /// This sort of thing is introduced by SROA.
9919 /// This slicing takes care not to insert overlapping loads.
9920 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9921 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9922 if (Level < AfterLegalizeDAG)
9925 LoadSDNode *LD = cast<LoadSDNode>(N);
9926 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9927 !LD->getValueType(0).isInteger())
9930 // Keep track of already used bits to detect overlapping values.
9931 // In that case, we will just abort the transformation.
9932 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9934 SmallVector<LoadedSlice, 4> LoadedSlices;
9936 // Check if this load is used as several smaller chunks of bits.
9937 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9938 // of computation for each trunc.
9939 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9940 UI != UIEnd; ++UI) {
9941 // Skip the uses of the chain.
9942 if (UI.getUse().getResNo() != 0)
9948 // Check if this is a trunc(lshr).
9949 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9950 isa<ConstantSDNode>(User->getOperand(1))) {
9951 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9952 User = *User->use_begin();
9955 // At this point, User is a Truncate, iff we encountered, trunc or
9957 if (User->getOpcode() != ISD::TRUNCATE)
9960 // The width of the type must be a power of 2 and greater than 8-bits.
9961 // Otherwise the load cannot be represented in LLVM IR.
9962 // Moreover, if we shifted with a non-8-bits multiple, the slice
9963 // will be across several bytes. We do not support that.
9964 unsigned Width = User->getValueSizeInBits(0);
9965 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9968 // Build the slice for this chain of computations.
9969 LoadedSlice LS(User, LD, Shift, &DAG);
9970 APInt CurrentUsedBits = LS.getUsedBits();
9972 // Check if this slice overlaps with another.
9973 if ((CurrentUsedBits & UsedBits) != 0)
9975 // Update the bits used globally.
9976 UsedBits |= CurrentUsedBits;
9978 // Check if the new slice would be legal.
9982 // Record the slice.
9983 LoadedSlices.push_back(LS);
9986 // Abort slicing if it does not seem to be profitable.
9987 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9992 // Rewrite each chain to use an independent load.
9993 // By construction, each chain can be represented by a unique load.
9995 // Prepare the argument for the new token factor for all the slices.
9996 SmallVector<SDValue, 8> ArgChains;
9997 for (SmallVectorImpl<LoadedSlice>::const_iterator
9998 LSIt = LoadedSlices.begin(),
9999 LSItEnd = LoadedSlices.end();
10000 LSIt != LSItEnd; ++LSIt) {
10001 SDValue SliceInst = LSIt->loadSlice();
10002 CombineTo(LSIt->Inst, SliceInst, true);
10003 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10004 SliceInst = SliceInst.getOperand(0);
10005 assert(SliceInst->getOpcode() == ISD::LOAD &&
10006 "It takes more than a zext to get to the loaded slice!!");
10007 ArgChains.push_back(SliceInst.getValue(1));
10010 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10012 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10016 /// Check to see if V is (and load (ptr), imm), where the load is having
10017 /// specific bytes cleared out. If so, return the byte size being masked out
10018 /// and the shift amount.
10019 static std::pair<unsigned, unsigned>
10020 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10021 std::pair<unsigned, unsigned> Result(0, 0);
10023 // Check for the structure we're looking for.
10024 if (V->getOpcode() != ISD::AND ||
10025 !isa<ConstantSDNode>(V->getOperand(1)) ||
10026 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10029 // Check the chain and pointer.
10030 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10031 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10033 // The store should be chained directly to the load or be an operand of a
10035 if (LD == Chain.getNode())
10037 else if (Chain->getOpcode() != ISD::TokenFactor)
10038 return Result; // Fail.
10041 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10042 if (Chain->getOperand(i).getNode() == LD) {
10046 if (!isOk) return Result;
10049 // This only handles simple types.
10050 if (V.getValueType() != MVT::i16 &&
10051 V.getValueType() != MVT::i32 &&
10052 V.getValueType() != MVT::i64)
10055 // Check the constant mask. Invert it so that the bits being masked out are
10056 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10057 // follow the sign bit for uniformity.
10058 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10059 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10060 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10061 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10062 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10063 if (NotMaskLZ == 64) return Result; // All zero mask.
10065 // See if we have a continuous run of bits. If so, we have 0*1+0*
10066 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10069 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10070 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10071 NotMaskLZ -= 64-V.getValueSizeInBits();
10073 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10074 switch (MaskedBytes) {
10078 default: return Result; // All one mask, or 5-byte mask.
10081 // Verify that the first bit starts at a multiple of mask so that the access
10082 // is aligned the same as the access width.
10083 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10085 Result.first = MaskedBytes;
10086 Result.second = NotMaskTZ/8;
10091 /// Check to see if IVal is something that provides a value as specified by
10092 /// MaskInfo. If so, replace the specified store with a narrower store of
10093 /// truncated IVal.
10095 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10096 SDValue IVal, StoreSDNode *St,
10098 unsigned NumBytes = MaskInfo.first;
10099 unsigned ByteShift = MaskInfo.second;
10100 SelectionDAG &DAG = DC->getDAG();
10102 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10103 // that uses this. If not, this is not a replacement.
10104 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10105 ByteShift*8, (ByteShift+NumBytes)*8);
10106 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10108 // Check that it is legal on the target to do this. It is legal if the new
10109 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10111 MVT VT = MVT::getIntegerVT(NumBytes*8);
10112 if (!DC->isTypeLegal(VT))
10115 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10116 // shifted by ByteShift and truncated down to NumBytes.
10119 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10120 DAG.getConstant(ByteShift*8, DL,
10121 DC->getShiftAmountTy(IVal.getValueType())));
10124 // Figure out the offset for the store and the alignment of the access.
10126 unsigned NewAlign = St->getAlignment();
10128 if (DAG.getTargetLoweringInfo().isLittleEndian())
10129 StOffset = ByteShift;
10131 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10133 SDValue Ptr = St->getBasePtr();
10136 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10137 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10138 NewAlign = MinAlign(NewAlign, StOffset);
10141 // Truncate down to the new size.
10142 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10145 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10146 St->getPointerInfo().getWithOffset(StOffset),
10147 false, false, NewAlign).getNode();
10151 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10152 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10153 /// narrowing the load and store if it would end up being a win for performance
10155 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10156 StoreSDNode *ST = cast<StoreSDNode>(N);
10157 if (ST->isVolatile())
10160 SDValue Chain = ST->getChain();
10161 SDValue Value = ST->getValue();
10162 SDValue Ptr = ST->getBasePtr();
10163 EVT VT = Value.getValueType();
10165 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10168 unsigned Opc = Value.getOpcode();
10170 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10171 // is a byte mask indicating a consecutive number of bytes, check to see if
10172 // Y is known to provide just those bytes. If so, we try to replace the
10173 // load + replace + store sequence with a single (narrower) store, which makes
10175 if (Opc == ISD::OR) {
10176 std::pair<unsigned, unsigned> MaskedLoad;
10177 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10178 if (MaskedLoad.first)
10179 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10180 Value.getOperand(1), ST,this))
10181 return SDValue(NewST, 0);
10183 // Or is commutative, so try swapping X and Y.
10184 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10185 if (MaskedLoad.first)
10186 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10187 Value.getOperand(0), ST,this))
10188 return SDValue(NewST, 0);
10191 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10192 Value.getOperand(1).getOpcode() != ISD::Constant)
10195 SDValue N0 = Value.getOperand(0);
10196 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10197 Chain == SDValue(N0.getNode(), 1)) {
10198 LoadSDNode *LD = cast<LoadSDNode>(N0);
10199 if (LD->getBasePtr() != Ptr ||
10200 LD->getPointerInfo().getAddrSpace() !=
10201 ST->getPointerInfo().getAddrSpace())
10204 // Find the type to narrow it the load / op / store to.
10205 SDValue N1 = Value.getOperand(1);
10206 unsigned BitWidth = N1.getValueSizeInBits();
10207 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10208 if (Opc == ISD::AND)
10209 Imm ^= APInt::getAllOnesValue(BitWidth);
10210 if (Imm == 0 || Imm.isAllOnesValue())
10212 unsigned ShAmt = Imm.countTrailingZeros();
10213 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10214 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10215 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10216 // The narrowing should be profitable, the load/store operation should be
10217 // legal (or custom) and the store size should be equal to the NewVT width.
10218 while (NewBW < BitWidth &&
10219 (NewVT.getStoreSizeInBits() != NewBW ||
10220 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10221 !TLI.isNarrowingProfitable(VT, NewVT))) {
10222 NewBW = NextPowerOf2(NewBW);
10223 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10225 if (NewBW >= BitWidth)
10228 // If the lsb changed does not start at the type bitwidth boundary,
10229 // start at the previous one.
10231 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10232 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10233 std::min(BitWidth, ShAmt + NewBW));
10234 if ((Imm & Mask) == Imm) {
10235 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10236 if (Opc == ISD::AND)
10237 NewImm ^= APInt::getAllOnesValue(NewBW);
10238 uint64_t PtrOff = ShAmt / 8;
10239 // For big endian targets, we need to adjust the offset to the pointer to
10240 // load the correct bytes.
10241 if (TLI.isBigEndian())
10242 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10244 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10245 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10246 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10249 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10250 Ptr.getValueType(), Ptr,
10251 DAG.getConstant(PtrOff, SDLoc(LD),
10252 Ptr.getValueType()));
10253 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10254 LD->getChain(), NewPtr,
10255 LD->getPointerInfo().getWithOffset(PtrOff),
10256 LD->isVolatile(), LD->isNonTemporal(),
10257 LD->isInvariant(), NewAlign,
10259 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10260 DAG.getConstant(NewImm, SDLoc(Value),
10262 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10264 ST->getPointerInfo().getWithOffset(PtrOff),
10265 false, false, NewAlign);
10267 AddToWorklist(NewPtr.getNode());
10268 AddToWorklist(NewLD.getNode());
10269 AddToWorklist(NewVal.getNode());
10270 WorklistRemover DeadNodes(*this);
10271 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10280 /// For a given floating point load / store pair, if the load value isn't used
10281 /// by any other operations, then consider transforming the pair to integer
10282 /// load / store operations if the target deems the transformation profitable.
10283 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10284 StoreSDNode *ST = cast<StoreSDNode>(N);
10285 SDValue Chain = ST->getChain();
10286 SDValue Value = ST->getValue();
10287 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10288 Value.hasOneUse() &&
10289 Chain == SDValue(Value.getNode(), 1)) {
10290 LoadSDNode *LD = cast<LoadSDNode>(Value);
10291 EVT VT = LD->getMemoryVT();
10292 if (!VT.isFloatingPoint() ||
10293 VT != ST->getMemoryVT() ||
10294 LD->isNonTemporal() ||
10295 ST->isNonTemporal() ||
10296 LD->getPointerInfo().getAddrSpace() != 0 ||
10297 ST->getPointerInfo().getAddrSpace() != 0)
10300 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10301 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10302 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10303 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10304 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10307 unsigned LDAlign = LD->getAlignment();
10308 unsigned STAlign = ST->getAlignment();
10309 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10310 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10311 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10314 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10315 LD->getChain(), LD->getBasePtr(),
10316 LD->getPointerInfo(),
10317 false, false, false, LDAlign);
10319 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10320 NewLD, ST->getBasePtr(),
10321 ST->getPointerInfo(),
10322 false, false, STAlign);
10324 AddToWorklist(NewLD.getNode());
10325 AddToWorklist(NewST.getNode());
10326 WorklistRemover DeadNodes(*this);
10327 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10336 /// Helper struct to parse and store a memory address as base + index + offset.
10337 /// We ignore sign extensions when it is safe to do so.
10338 /// The following two expressions are not equivalent. To differentiate we need
10339 /// to store whether there was a sign extension involved in the index
10341 /// (load (i64 add (i64 copyfromreg %c)
10342 /// (i64 signextend (add (i8 load %index)
10346 /// (load (i64 add (i64 copyfromreg %c)
10347 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10349 struct BaseIndexOffset {
10353 bool IsIndexSignExt;
10355 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10357 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10358 bool IsIndexSignExt) :
10359 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10361 bool equalBaseIndex(const BaseIndexOffset &Other) {
10362 return Other.Base == Base && Other.Index == Index &&
10363 Other.IsIndexSignExt == IsIndexSignExt;
10366 /// Parses tree in Ptr for base, index, offset addresses.
10367 static BaseIndexOffset match(SDValue Ptr) {
10368 bool IsIndexSignExt = false;
10370 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10371 // instruction, then it could be just the BASE or everything else we don't
10372 // know how to handle. Just use Ptr as BASE and give up.
10373 if (Ptr->getOpcode() != ISD::ADD)
10374 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10376 // We know that we have at least an ADD instruction. Try to pattern match
10377 // the simple case of BASE + OFFSET.
10378 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10379 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10380 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10384 // Inside a loop the current BASE pointer is calculated using an ADD and a
10385 // MUL instruction. In this case Ptr is the actual BASE pointer.
10386 // (i64 add (i64 %array_ptr)
10387 // (i64 mul (i64 %induction_var)
10388 // (i64 %element_size)))
10389 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10390 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10392 // Look at Base + Index + Offset cases.
10393 SDValue Base = Ptr->getOperand(0);
10394 SDValue IndexOffset = Ptr->getOperand(1);
10396 // Skip signextends.
10397 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10398 IndexOffset = IndexOffset->getOperand(0);
10399 IsIndexSignExt = true;
10402 // Either the case of Base + Index (no offset) or something else.
10403 if (IndexOffset->getOpcode() != ISD::ADD)
10404 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10406 // Now we have the case of Base + Index + offset.
10407 SDValue Index = IndexOffset->getOperand(0);
10408 SDValue Offset = IndexOffset->getOperand(1);
10410 if (!isa<ConstantSDNode>(Offset))
10411 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10413 // Ignore signextends.
10414 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10415 Index = Index->getOperand(0);
10416 IsIndexSignExt = true;
10417 } else IsIndexSignExt = false;
10419 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10420 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10425 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10426 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10427 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10428 // Make sure we have something to merge.
10432 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10433 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10434 unsigned LatestNodeUsed = 0;
10436 for (unsigned i=0; i < NumElem; ++i) {
10437 // Find a chain for the new wide-store operand. Notice that some
10438 // of the store nodes that we found may not be selected for inclusion
10439 // in the wide store. The chain we use needs to be the chain of the
10440 // latest store node which is *used* and replaced by the wide store.
10441 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10442 LatestNodeUsed = i;
10445 // The latest Node in the DAG.
10446 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10447 SDLoc DL(StoreNodes[0].MemNode);
10451 // Find a legal type for the vector store.
10452 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10453 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10454 if (IsConstantSrc) {
10455 // A vector store with a constant source implies that the constant is
10456 // zero; we only handle merging stores of constant zeros because the zero
10457 // can be materialized without a load.
10458 // It may be beneficial to loosen this restriction to allow non-zero
10460 StoredVal = DAG.getConstant(0, DL, Ty);
10462 SmallVector<SDValue, 8> Ops;
10463 for (unsigned i = 0; i < NumElem ; ++i) {
10464 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10465 SDValue Val = St->getValue();
10466 // All of the operands of a BUILD_VECTOR must have the same type.
10467 if (Val.getValueType() != MemVT)
10469 Ops.push_back(Val);
10472 // Build the extracted vector elements back into a vector.
10473 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10476 // We should always use a vector store when merging extracted vector
10477 // elements, so this path implies a store of constants.
10478 assert(IsConstantSrc && "Merged vector elements should use vector store");
10480 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10481 APInt StoreInt(StoreBW, 0);
10483 // Construct a single integer constant which is made of the smaller
10484 // constant inputs.
10485 bool IsLE = TLI.isLittleEndian();
10486 for (unsigned i = 0; i < NumElem ; ++i) {
10487 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10488 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10489 SDValue Val = St->getValue();
10490 StoreInt <<= ElementSizeBytes*8;
10491 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10492 StoreInt |= C->getAPIntValue().zext(StoreBW);
10493 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10494 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10496 llvm_unreachable("Invalid constant element type");
10500 // Create the new Load and Store operations.
10501 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10502 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10505 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10506 FirstInChain->getBasePtr(),
10507 FirstInChain->getPointerInfo(),
10509 FirstInChain->getAlignment());
10511 // Replace the last store with the new store
10512 CombineTo(LatestOp, NewStore);
10513 // Erase all other stores.
10514 for (unsigned i = 0; i < NumElem ; ++i) {
10515 if (StoreNodes[i].MemNode == LatestOp)
10517 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10518 // ReplaceAllUsesWith will replace all uses that existed when it was
10519 // called, but graph optimizations may cause new ones to appear. For
10520 // example, the case in pr14333 looks like
10522 // St's chain -> St -> another store -> X
10524 // And the only difference from St to the other store is the chain.
10525 // When we change it's chain to be St's chain they become identical,
10526 // get CSEed and the net result is that X is now a use of St.
10527 // Since we know that St is redundant, just iterate.
10528 while (!St->use_empty())
10529 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10530 deleteAndRecombine(St);
10536 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10537 if (OptLevel == CodeGenOpt::None)
10540 EVT MemVT = St->getMemoryVT();
10541 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10542 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10543 Attribute::NoImplicitFloat);
10545 // Don't merge vectors into wider inputs.
10546 if (MemVT.isVector() || !MemVT.isSimple())
10549 // Perform an early exit check. Do not bother looking at stored values that
10550 // are not constants, loads, or extracted vector elements.
10551 SDValue StoredVal = St->getValue();
10552 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10553 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10554 isa<ConstantFPSDNode>(StoredVal);
10555 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10557 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10560 // Only look at ends of store sequences.
10561 SDValue Chain = SDValue(St, 0);
10562 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10565 // This holds the base pointer, index, and the offset in bytes from the base
10567 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10569 // We must have a base and an offset.
10570 if (!BasePtr.Base.getNode())
10573 // Do not handle stores to undef base pointers.
10574 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10577 // Save the LoadSDNodes that we find in the chain.
10578 // We need to make sure that these nodes do not interfere with
10579 // any of the store nodes.
10580 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10582 // Save the StoreSDNodes that we find in the chain.
10583 SmallVector<MemOpLink, 8> StoreNodes;
10585 // Walk up the chain and look for nodes with offsets from the same
10586 // base pointer. Stop when reaching an instruction with a different kind
10587 // or instruction which has a different base pointer.
10589 StoreSDNode *Index = St;
10591 // If the chain has more than one use, then we can't reorder the mem ops.
10592 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10595 // Find the base pointer and offset for this memory node.
10596 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10598 // Check that the base pointer is the same as the original one.
10599 if (!Ptr.equalBaseIndex(BasePtr))
10602 // Check that the alignment is the same.
10603 if (Index->getAlignment() != St->getAlignment())
10606 // The memory operands must not be volatile.
10607 if (Index->isVolatile() || Index->isIndexed())
10611 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10612 if (St->isTruncatingStore())
10615 // The stored memory type must be the same.
10616 if (Index->getMemoryVT() != MemVT)
10619 // We do not allow unaligned stores because we want to prevent overriding
10621 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10624 // We found a potential memory operand to merge.
10625 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10627 // Find the next memory operand in the chain. If the next operand in the
10628 // chain is a store then move up and continue the scan with the next
10629 // memory operand. If the next operand is a load save it and use alias
10630 // information to check if it interferes with anything.
10631 SDNode *NextInChain = Index->getChain().getNode();
10633 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10634 // We found a store node. Use it for the next iteration.
10637 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10638 if (Ldn->isVolatile()) {
10643 // Save the load node for later. Continue the scan.
10644 AliasLoadNodes.push_back(Ldn);
10645 NextInChain = Ldn->getChain().getNode();
10654 // Check if there is anything to merge.
10655 if (StoreNodes.size() < 2)
10658 // Sort the memory operands according to their distance from the base pointer.
10659 std::sort(StoreNodes.begin(), StoreNodes.end(),
10660 [](MemOpLink LHS, MemOpLink RHS) {
10661 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10662 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10663 LHS.SequenceNum > RHS.SequenceNum);
10666 // Scan the memory operations on the chain and find the first non-consecutive
10667 // store memory address.
10668 unsigned LastConsecutiveStore = 0;
10669 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10670 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10672 // Check that the addresses are consecutive starting from the second
10673 // element in the list of stores.
10675 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10676 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10680 bool Alias = false;
10681 // Check if this store interferes with any of the loads that we found.
10682 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10683 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10687 // We found a load that alias with this store. Stop the sequence.
10691 // Mark this node as useful.
10692 LastConsecutiveStore = i;
10695 // The node with the lowest store address.
10696 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10698 // Store the constants into memory as one consecutive store.
10699 if (IsConstantSrc) {
10700 unsigned LastLegalType = 0;
10701 unsigned LastLegalVectorType = 0;
10702 bool NonZero = false;
10703 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10704 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10705 SDValue StoredVal = St->getValue();
10707 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10708 NonZero |= !C->isNullValue();
10709 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10710 NonZero |= !C->getConstantFPValue()->isNullValue();
10716 // Find a legal type for the constant store.
10717 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10718 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10719 if (TLI.isTypeLegal(StoreTy))
10720 LastLegalType = i+1;
10721 // Or check whether a truncstore is legal.
10722 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10723 TargetLowering::TypePromoteInteger) {
10724 EVT LegalizedStoredValueTy =
10725 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10726 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10727 LastLegalType = i+1;
10730 // Find a legal type for the vector store.
10731 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10732 if (TLI.isTypeLegal(Ty))
10733 LastLegalVectorType = i + 1;
10736 // We only use vectors if the constant is known to be zero and the
10737 // function is not marked with the noimplicitfloat attribute.
10738 if (NonZero || NoVectors)
10739 LastLegalVectorType = 0;
10741 // Check if we found a legal integer type to store.
10742 if (LastLegalType == 0 && LastLegalVectorType == 0)
10745 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10746 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10748 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10752 // When extracting multiple vector elements, try to store them
10753 // in one vector store rather than a sequence of scalar stores.
10754 if (IsExtractVecEltSrc) {
10755 unsigned NumElem = 0;
10756 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10757 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10758 SDValue StoredVal = St->getValue();
10759 // This restriction could be loosened.
10760 // Bail out if any stored values are not elements extracted from a vector.
10761 // It should be possible to handle mixed sources, but load sources need
10762 // more careful handling (see the block of code below that handles
10763 // consecutive loads).
10764 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10767 // Find a legal type for the vector store.
10768 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10769 if (TLI.isTypeLegal(Ty))
10773 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10777 // Below we handle the case of multiple consecutive stores that
10778 // come from multiple consecutive loads. We merge them into a single
10779 // wide load and a single wide store.
10781 // Look for load nodes which are used by the stored values.
10782 SmallVector<MemOpLink, 8> LoadNodes;
10784 // Find acceptable loads. Loads need to have the same chain (token factor),
10785 // must not be zext, volatile, indexed, and they must be consecutive.
10786 BaseIndexOffset LdBasePtr;
10787 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10788 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10789 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10792 // Loads must only have one use.
10793 if (!Ld->hasNUsesOfValue(1, 0))
10796 // Check that the alignment is the same as the stores.
10797 if (Ld->getAlignment() != St->getAlignment())
10800 // The memory operands must not be volatile.
10801 if (Ld->isVolatile() || Ld->isIndexed())
10804 // We do not accept ext loads.
10805 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10808 // The stored memory type must be the same.
10809 if (Ld->getMemoryVT() != MemVT)
10812 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10813 // If this is not the first ptr that we check.
10814 if (LdBasePtr.Base.getNode()) {
10815 // The base ptr must be the same.
10816 if (!LdPtr.equalBaseIndex(LdBasePtr))
10819 // Check that all other base pointers are the same as this one.
10823 // We found a potential memory operand to merge.
10824 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10827 if (LoadNodes.size() < 2)
10830 // If we have load/store pair instructions and we only have two values,
10832 unsigned RequiredAlignment;
10833 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10834 St->getAlignment() >= RequiredAlignment)
10837 // Scan the memory operations on the chain and find the first non-consecutive
10838 // load memory address. These variables hold the index in the store node
10840 unsigned LastConsecutiveLoad = 0;
10841 // This variable refers to the size and not index in the array.
10842 unsigned LastLegalVectorType = 0;
10843 unsigned LastLegalIntegerType = 0;
10844 StartAddress = LoadNodes[0].OffsetFromBase;
10845 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10846 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10847 // All loads much share the same chain.
10848 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10851 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10852 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10854 LastConsecutiveLoad = i;
10856 // Find a legal type for the vector store.
10857 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10858 if (TLI.isTypeLegal(StoreTy))
10859 LastLegalVectorType = i + 1;
10861 // Find a legal type for the integer store.
10862 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10863 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10864 if (TLI.isTypeLegal(StoreTy))
10865 LastLegalIntegerType = i + 1;
10866 // Or check whether a truncstore and extload is legal.
10867 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10868 TargetLowering::TypePromoteInteger) {
10869 EVT LegalizedStoredValueTy =
10870 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10871 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10872 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10873 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10874 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10875 LastLegalIntegerType = i+1;
10879 // Only use vector types if the vector type is larger than the integer type.
10880 // If they are the same, use integers.
10881 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10882 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10884 // We add +1 here because the LastXXX variables refer to location while
10885 // the NumElem refers to array/index size.
10886 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10887 NumElem = std::min(LastLegalType, NumElem);
10892 // The latest Node in the DAG.
10893 unsigned LatestNodeUsed = 0;
10894 for (unsigned i=1; i<NumElem; ++i) {
10895 // Find a chain for the new wide-store operand. Notice that some
10896 // of the store nodes that we found may not be selected for inclusion
10897 // in the wide store. The chain we use needs to be the chain of the
10898 // latest store node which is *used* and replaced by the wide store.
10899 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10900 LatestNodeUsed = i;
10903 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10905 // Find if it is better to use vectors or integers to load and store
10909 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10911 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10912 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10915 SDLoc LoadDL(LoadNodes[0].MemNode);
10916 SDLoc StoreDL(StoreNodes[0].MemNode);
10918 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10919 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10920 FirstLoad->getChain(),
10921 FirstLoad->getBasePtr(),
10922 FirstLoad->getPointerInfo(),
10923 false, false, false,
10924 FirstLoad->getAlignment());
10926 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10927 FirstInChain->getBasePtr(),
10928 FirstInChain->getPointerInfo(), false, false,
10929 FirstInChain->getAlignment());
10931 // Replace one of the loads with the new load.
10932 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10933 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10934 SDValue(NewLoad.getNode(), 1));
10936 // Remove the rest of the load chains.
10937 for (unsigned i = 1; i < NumElem ; ++i) {
10938 // Replace all chain users of the old load nodes with the chain of the new
10940 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10941 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10944 // Replace the last store with the new store.
10945 CombineTo(LatestOp, NewStore);
10946 // Erase all other stores.
10947 for (unsigned i = 0; i < NumElem ; ++i) {
10948 // Remove all Store nodes.
10949 if (StoreNodes[i].MemNode == LatestOp)
10951 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10952 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10953 deleteAndRecombine(St);
10959 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10960 StoreSDNode *ST = cast<StoreSDNode>(N);
10961 SDValue Chain = ST->getChain();
10962 SDValue Value = ST->getValue();
10963 SDValue Ptr = ST->getBasePtr();
10965 // If this is a store of a bit convert, store the input value if the
10966 // resultant store does not need a higher alignment than the original.
10967 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10968 ST->isUnindexed()) {
10969 unsigned OrigAlign = ST->getAlignment();
10970 EVT SVT = Value.getOperand(0).getValueType();
10971 unsigned Align = TLI.getDataLayout()->
10972 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10973 if (Align <= OrigAlign &&
10974 ((!LegalOperations && !ST->isVolatile()) ||
10975 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10976 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10977 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10978 ST->isNonTemporal(), OrigAlign,
10982 // Turn 'store undef, Ptr' -> nothing.
10983 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10986 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10987 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10988 // NOTE: If the original store is volatile, this transform must not increase
10989 // the number of stores. For example, on x86-32 an f64 can be stored in one
10990 // processor operation but an i64 (which is not legal) requires two. So the
10991 // transform should not be done in this case.
10992 if (Value.getOpcode() != ISD::TargetConstantFP) {
10994 switch (CFP->getSimpleValueType(0).SimpleTy) {
10995 default: llvm_unreachable("Unknown FP type");
10996 case MVT::f16: // We don't do this for these yet.
11002 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11003 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11005 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11006 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11008 return DAG.getStore(Chain, SDLoc(N), Tmp,
11009 Ptr, ST->getMemOperand());
11013 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11014 !ST->isVolatile()) ||
11015 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11017 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11018 getZExtValue(), SDLoc(CFP), MVT::i64);
11019 return DAG.getStore(Chain, SDLoc(N), Tmp,
11020 Ptr, ST->getMemOperand());
11023 if (!ST->isVolatile() &&
11024 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11025 // Many FP stores are not made apparent until after legalize, e.g. for
11026 // argument passing. Since this is so common, custom legalize the
11027 // 64-bit integer store into two 32-bit stores.
11028 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11029 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11030 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11031 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11033 unsigned Alignment = ST->getAlignment();
11034 bool isVolatile = ST->isVolatile();
11035 bool isNonTemporal = ST->isNonTemporal();
11036 AAMDNodes AAInfo = ST->getAAInfo();
11040 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11041 Ptr, ST->getPointerInfo(),
11042 isVolatile, isNonTemporal,
11043 ST->getAlignment(), AAInfo);
11044 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11045 DAG.getConstant(4, DL, Ptr.getValueType()));
11046 Alignment = MinAlign(Alignment, 4U);
11047 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11048 Ptr, ST->getPointerInfo().getWithOffset(4),
11049 isVolatile, isNonTemporal,
11050 Alignment, AAInfo);
11051 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11060 // Try to infer better alignment information than the store already has.
11061 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11062 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11063 if (Align > ST->getAlignment()) {
11065 DAG.getTruncStore(Chain, SDLoc(N), Value,
11066 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11067 ST->isVolatile(), ST->isNonTemporal(), Align,
11069 if (NewStore.getNode() != N)
11070 return CombineTo(ST, NewStore, true);
11075 // Try transforming a pair floating point load / store ops to integer
11076 // load / store ops.
11077 SDValue NewST = TransformFPLoadStorePair(N);
11078 if (NewST.getNode())
11081 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11082 : DAG.getSubtarget().useAA();
11084 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11085 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11088 if (UseAA && ST->isUnindexed()) {
11089 // Walk up chain skipping non-aliasing memory nodes.
11090 SDValue BetterChain = FindBetterChain(N, Chain);
11092 // If there is a better chain.
11093 if (Chain != BetterChain) {
11096 // Replace the chain to avoid dependency.
11097 if (ST->isTruncatingStore()) {
11098 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11099 ST->getMemoryVT(), ST->getMemOperand());
11101 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11102 ST->getMemOperand());
11105 // Create token to keep both nodes around.
11106 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11107 MVT::Other, Chain, ReplStore);
11109 // Make sure the new and old chains are cleaned up.
11110 AddToWorklist(Token.getNode());
11112 // Don't add users to work list.
11113 return CombineTo(N, Token, false);
11117 // Try transforming N to an indexed store.
11118 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11119 return SDValue(N, 0);
11121 // FIXME: is there such a thing as a truncating indexed store?
11122 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11123 Value.getValueType().isInteger()) {
11124 // See if we can simplify the input to this truncstore with knowledge that
11125 // only the low bits are being used. For example:
11126 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11128 GetDemandedBits(Value,
11129 APInt::getLowBitsSet(
11130 Value.getValueType().getScalarType().getSizeInBits(),
11131 ST->getMemoryVT().getScalarType().getSizeInBits()));
11132 AddToWorklist(Value.getNode());
11133 if (Shorter.getNode())
11134 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11135 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11137 // Otherwise, see if we can simplify the operation with
11138 // SimplifyDemandedBits, which only works if the value has a single use.
11139 if (SimplifyDemandedBits(Value,
11140 APInt::getLowBitsSet(
11141 Value.getValueType().getScalarType().getSizeInBits(),
11142 ST->getMemoryVT().getScalarType().getSizeInBits())))
11143 return SDValue(N, 0);
11146 // If this is a load followed by a store to the same location, then the store
11148 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11149 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11150 ST->isUnindexed() && !ST->isVolatile() &&
11151 // There can't be any side effects between the load and store, such as
11152 // a call or store.
11153 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11154 // The store is dead, remove it.
11159 // If this is a store followed by a store with the same value to the same
11160 // location, then the store is dead/noop.
11161 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11162 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11163 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11164 ST1->isUnindexed() && !ST1->isVolatile()) {
11165 // The store is dead, remove it.
11170 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11171 // truncating store. We can do this even if this is already a truncstore.
11172 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11173 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11174 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11175 ST->getMemoryVT())) {
11176 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11177 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11180 // Only perform this optimization before the types are legal, because we
11181 // don't want to perform this optimization on every DAGCombine invocation.
11183 bool EverChanged = false;
11186 // There can be multiple store sequences on the same chain.
11187 // Keep trying to merge store sequences until we are unable to do so
11188 // or until we merge the last store on the chain.
11189 bool Changed = MergeConsecutiveStores(ST);
11190 EverChanged |= Changed;
11191 if (!Changed) break;
11192 } while (ST->getOpcode() != ISD::DELETED_NODE);
11195 return SDValue(N, 0);
11198 return ReduceLoadOpStoreWidth(N);
11201 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11202 SDValue InVec = N->getOperand(0);
11203 SDValue InVal = N->getOperand(1);
11204 SDValue EltNo = N->getOperand(2);
11207 // If the inserted element is an UNDEF, just use the input vector.
11208 if (InVal.getOpcode() == ISD::UNDEF)
11211 EVT VT = InVec.getValueType();
11213 // If we can't generate a legal BUILD_VECTOR, exit
11214 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11217 // Check that we know which element is being inserted
11218 if (!isa<ConstantSDNode>(EltNo))
11220 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11222 // Canonicalize insert_vector_elt dag nodes.
11224 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11225 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11227 // Do this only if the child insert_vector node has one use; also
11228 // do this only if indices are both constants and Idx1 < Idx0.
11229 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11230 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11231 unsigned OtherElt =
11232 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11233 if (Elt < OtherElt) {
11235 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11236 InVec.getOperand(0), InVal, EltNo);
11237 AddToWorklist(NewOp.getNode());
11238 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11239 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11243 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11244 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11245 // vector elements.
11246 SmallVector<SDValue, 8> Ops;
11247 // Do not combine these two vectors if the output vector will not replace
11248 // the input vector.
11249 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11250 Ops.append(InVec.getNode()->op_begin(),
11251 InVec.getNode()->op_end());
11252 } else if (InVec.getOpcode() == ISD::UNDEF) {
11253 unsigned NElts = VT.getVectorNumElements();
11254 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11259 // Insert the element
11260 if (Elt < Ops.size()) {
11261 // All the operands of BUILD_VECTOR must have the same type;
11262 // we enforce that here.
11263 EVT OpVT = Ops[0].getValueType();
11264 if (InVal.getValueType() != OpVT)
11265 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11266 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11267 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11271 // Return the new vector
11272 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11275 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11276 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11277 EVT ResultVT = EVE->getValueType(0);
11278 EVT VecEltVT = InVecVT.getVectorElementType();
11279 unsigned Align = OriginalLoad->getAlignment();
11280 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11281 VecEltVT.getTypeForEVT(*DAG.getContext()));
11283 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11288 SDValue NewPtr = OriginalLoad->getBasePtr();
11290 EVT PtrType = NewPtr.getValueType();
11291 MachinePointerInfo MPI;
11293 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11294 int Elt = ConstEltNo->getZExtValue();
11295 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11296 if (TLI.isBigEndian())
11297 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11298 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11299 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11301 Offset = DAG.getNode(
11302 ISD::MUL, DL, EltNo.getValueType(), EltNo,
11303 DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11304 if (TLI.isBigEndian())
11305 Offset = DAG.getNode(
11306 ISD::SUB, DL, EltNo.getValueType(),
11307 DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11309 MPI = OriginalLoad->getPointerInfo();
11311 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11313 // The replacement we need to do here is a little tricky: we need to
11314 // replace an extractelement of a load with a load.
11315 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11316 // Note that this replacement assumes that the extractvalue is the only
11317 // use of the load; that's okay because we don't want to perform this
11318 // transformation in other cases anyway.
11321 if (ResultVT.bitsGT(VecEltVT)) {
11322 // If the result type of vextract is wider than the load, then issue an
11323 // extending load instead.
11324 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11328 Load = DAG.getExtLoad(
11329 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11330 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11331 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11332 Chain = Load.getValue(1);
11334 Load = DAG.getLoad(
11335 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11336 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11337 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11338 Chain = Load.getValue(1);
11339 if (ResultVT.bitsLT(VecEltVT))
11340 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11342 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11344 WorklistRemover DeadNodes(*this);
11345 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11346 SDValue To[] = { Load, Chain };
11347 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11348 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11349 // worklist explicitly as well.
11350 AddToWorklist(Load.getNode());
11351 AddUsersToWorklist(Load.getNode()); // Add users too
11352 // Make sure to revisit this node to clean it up; it will usually be dead.
11353 AddToWorklist(EVE);
11355 return SDValue(EVE, 0);
11358 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11359 // (vextract (scalar_to_vector val, 0) -> val
11360 SDValue InVec = N->getOperand(0);
11361 EVT VT = InVec.getValueType();
11362 EVT NVT = N->getValueType(0);
11364 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11365 // Check if the result type doesn't match the inserted element type. A
11366 // SCALAR_TO_VECTOR may truncate the inserted element and the
11367 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11368 SDValue InOp = InVec.getOperand(0);
11369 if (InOp.getValueType() != NVT) {
11370 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11371 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11376 SDValue EltNo = N->getOperand(1);
11377 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11379 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11380 // We only perform this optimization before the op legalization phase because
11381 // we may introduce new vector instructions which are not backed by TD
11382 // patterns. For example on AVX, extracting elements from a wide vector
11383 // without using extract_subvector. However, if we can find an underlying
11384 // scalar value, then we can always use that.
11385 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11387 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11388 int NumElem = VT.getVectorNumElements();
11389 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11390 // Find the new index to extract from.
11391 int OrigElt = SVOp->getMaskElt(Elt);
11393 // Extracting an undef index is undef.
11395 return DAG.getUNDEF(NVT);
11397 // Select the right vector half to extract from.
11399 if (OrigElt < NumElem) {
11400 SVInVec = InVec->getOperand(0);
11402 SVInVec = InVec->getOperand(1);
11403 OrigElt -= NumElem;
11406 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11407 SDValue InOp = SVInVec.getOperand(OrigElt);
11408 if (InOp.getValueType() != NVT) {
11409 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11410 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11416 // FIXME: We should handle recursing on other vector shuffles and
11417 // scalar_to_vector here as well.
11419 if (!LegalOperations) {
11420 EVT IndexTy = TLI.getVectorIdxTy();
11421 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11422 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11426 bool BCNumEltsChanged = false;
11427 EVT ExtVT = VT.getVectorElementType();
11430 // If the result of load has to be truncated, then it's not necessarily
11432 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11435 if (InVec.getOpcode() == ISD::BITCAST) {
11436 // Don't duplicate a load with other uses.
11437 if (!InVec.hasOneUse())
11440 EVT BCVT = InVec.getOperand(0).getValueType();
11441 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11443 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11444 BCNumEltsChanged = true;
11445 InVec = InVec.getOperand(0);
11446 ExtVT = BCVT.getVectorElementType();
11449 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11450 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11451 ISD::isNormalLoad(InVec.getNode()) &&
11452 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11453 SDValue Index = N->getOperand(1);
11454 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11455 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11459 // Perform only after legalization to ensure build_vector / vector_shuffle
11460 // optimizations have already been done.
11461 if (!LegalOperations) return SDValue();
11463 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11464 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11465 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11468 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11470 LoadSDNode *LN0 = nullptr;
11471 const ShuffleVectorSDNode *SVN = nullptr;
11472 if (ISD::isNormalLoad(InVec.getNode())) {
11473 LN0 = cast<LoadSDNode>(InVec);
11474 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11475 InVec.getOperand(0).getValueType() == ExtVT &&
11476 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11477 // Don't duplicate a load with other uses.
11478 if (!InVec.hasOneUse())
11481 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11482 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11483 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11485 // (load $addr+1*size)
11487 // Don't duplicate a load with other uses.
11488 if (!InVec.hasOneUse())
11491 // If the bit convert changed the number of elements, it is unsafe
11492 // to examine the mask.
11493 if (BCNumEltsChanged)
11496 // Select the input vector, guarding against out of range extract vector.
11497 unsigned NumElems = VT.getVectorNumElements();
11498 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11499 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11501 if (InVec.getOpcode() == ISD::BITCAST) {
11502 // Don't duplicate a load with other uses.
11503 if (!InVec.hasOneUse())
11506 InVec = InVec.getOperand(0);
11508 if (ISD::isNormalLoad(InVec.getNode())) {
11509 LN0 = cast<LoadSDNode>(InVec);
11510 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11511 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11515 // Make sure we found a non-volatile load and the extractelement is
11517 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11520 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11522 return DAG.getUNDEF(LVT);
11524 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11530 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11531 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11532 // We perform this optimization post type-legalization because
11533 // the type-legalizer often scalarizes integer-promoted vectors.
11534 // Performing this optimization before may create bit-casts which
11535 // will be type-legalized to complex code sequences.
11536 // We perform this optimization only before the operation legalizer because we
11537 // may introduce illegal operations.
11538 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11541 unsigned NumInScalars = N->getNumOperands();
11543 EVT VT = N->getValueType(0);
11545 // Check to see if this is a BUILD_VECTOR of a bunch of values
11546 // which come from any_extend or zero_extend nodes. If so, we can create
11547 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11548 // optimizations. We do not handle sign-extend because we can't fill the sign
11550 EVT SourceType = MVT::Other;
11551 bool AllAnyExt = true;
11553 for (unsigned i = 0; i != NumInScalars; ++i) {
11554 SDValue In = N->getOperand(i);
11555 // Ignore undef inputs.
11556 if (In.getOpcode() == ISD::UNDEF) continue;
11558 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11559 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11561 // Abort if the element is not an extension.
11562 if (!ZeroExt && !AnyExt) {
11563 SourceType = MVT::Other;
11567 // The input is a ZeroExt or AnyExt. Check the original type.
11568 EVT InTy = In.getOperand(0).getValueType();
11570 // Check that all of the widened source types are the same.
11571 if (SourceType == MVT::Other)
11574 else if (InTy != SourceType) {
11575 // Multiple income types. Abort.
11576 SourceType = MVT::Other;
11580 // Check if all of the extends are ANY_EXTENDs.
11581 AllAnyExt &= AnyExt;
11584 // In order to have valid types, all of the inputs must be extended from the
11585 // same source type and all of the inputs must be any or zero extend.
11586 // Scalar sizes must be a power of two.
11587 EVT OutScalarTy = VT.getScalarType();
11588 bool ValidTypes = SourceType != MVT::Other &&
11589 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11590 isPowerOf2_32(SourceType.getSizeInBits());
11592 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11593 // turn into a single shuffle instruction.
11597 bool isLE = TLI.isLittleEndian();
11598 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11599 assert(ElemRatio > 1 && "Invalid element size ratio");
11600 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11601 DAG.getConstant(0, SDLoc(N), SourceType);
11603 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11604 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11606 // Populate the new build_vector
11607 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11608 SDValue Cast = N->getOperand(i);
11609 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11610 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11611 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11613 if (Cast.getOpcode() == ISD::UNDEF)
11614 In = DAG.getUNDEF(SourceType);
11616 In = Cast->getOperand(0);
11617 unsigned Index = isLE ? (i * ElemRatio) :
11618 (i * ElemRatio + (ElemRatio - 1));
11620 assert(Index < Ops.size() && "Invalid index");
11624 // The type of the new BUILD_VECTOR node.
11625 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11626 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11627 "Invalid vector size");
11628 // Check if the new vector type is legal.
11629 if (!isTypeLegal(VecVT)) return SDValue();
11631 // Make the new BUILD_VECTOR.
11632 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11634 // The new BUILD_VECTOR node has the potential to be further optimized.
11635 AddToWorklist(BV.getNode());
11636 // Bitcast to the desired type.
11637 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11640 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11641 EVT VT = N->getValueType(0);
11643 unsigned NumInScalars = N->getNumOperands();
11646 EVT SrcVT = MVT::Other;
11647 unsigned Opcode = ISD::DELETED_NODE;
11648 unsigned NumDefs = 0;
11650 for (unsigned i = 0; i != NumInScalars; ++i) {
11651 SDValue In = N->getOperand(i);
11652 unsigned Opc = In.getOpcode();
11654 if (Opc == ISD::UNDEF)
11657 // If all scalar values are floats and converted from integers.
11658 if (Opcode == ISD::DELETED_NODE &&
11659 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11666 EVT InVT = In.getOperand(0).getValueType();
11668 // If all scalar values are typed differently, bail out. It's chosen to
11669 // simplify BUILD_VECTOR of integer types.
11670 if (SrcVT == MVT::Other)
11677 // If the vector has just one element defined, it's not worth to fold it into
11678 // a vectorized one.
11682 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11683 && "Should only handle conversion from integer to float.");
11684 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11686 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11688 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11691 // Just because the floating-point vector type is legal does not necessarily
11692 // mean that the corresponding integer vector type is.
11693 if (!isTypeLegal(NVT))
11696 SmallVector<SDValue, 8> Opnds;
11697 for (unsigned i = 0; i != NumInScalars; ++i) {
11698 SDValue In = N->getOperand(i);
11700 if (In.getOpcode() == ISD::UNDEF)
11701 Opnds.push_back(DAG.getUNDEF(SrcVT));
11703 Opnds.push_back(In.getOperand(0));
11705 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11706 AddToWorklist(BV.getNode());
11708 return DAG.getNode(Opcode, dl, VT, BV);
11711 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11712 unsigned NumInScalars = N->getNumOperands();
11714 EVT VT = N->getValueType(0);
11716 // A vector built entirely of undefs is undef.
11717 if (ISD::allOperandsUndef(N))
11718 return DAG.getUNDEF(VT);
11720 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11723 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11726 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11727 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11728 // at most two distinct vectors, turn this into a shuffle node.
11730 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11731 if (!isTypeLegal(VT))
11734 // May only combine to shuffle after legalize if shuffle is legal.
11735 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11738 SDValue VecIn1, VecIn2;
11739 bool UsesZeroVector = false;
11740 for (unsigned i = 0; i != NumInScalars; ++i) {
11741 SDValue Op = N->getOperand(i);
11742 // Ignore undef inputs.
11743 if (Op.getOpcode() == ISD::UNDEF) continue;
11745 // See if we can combine this build_vector into a blend with a zero vector.
11746 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11747 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11748 (Op.getOpcode() == ISD::ConstantFP &&
11749 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11750 UsesZeroVector = true;
11754 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11755 // constant index, bail out.
11756 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11757 !isa<ConstantSDNode>(Op.getOperand(1))) {
11758 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11762 // We allow up to two distinct input vectors.
11763 SDValue ExtractedFromVec = Op.getOperand(0);
11764 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11767 if (!VecIn1.getNode()) {
11768 VecIn1 = ExtractedFromVec;
11769 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11770 VecIn2 = ExtractedFromVec;
11772 // Too many inputs.
11773 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11778 // If everything is good, we can make a shuffle operation.
11779 if (VecIn1.getNode()) {
11780 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11781 SmallVector<int, 8> Mask;
11782 for (unsigned i = 0; i != NumInScalars; ++i) {
11783 unsigned Opcode = N->getOperand(i).getOpcode();
11784 if (Opcode == ISD::UNDEF) {
11785 Mask.push_back(-1);
11789 // Operands can also be zero.
11790 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11791 assert(UsesZeroVector &&
11792 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11793 "Unexpected node found!");
11794 Mask.push_back(NumInScalars+i);
11798 // If extracting from the first vector, just use the index directly.
11799 SDValue Extract = N->getOperand(i);
11800 SDValue ExtVal = Extract.getOperand(1);
11801 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11802 if (Extract.getOperand(0) == VecIn1) {
11803 Mask.push_back(ExtIndex);
11807 // Otherwise, use InIdx + InputVecSize
11808 Mask.push_back(InNumElements + ExtIndex);
11811 // Avoid introducing illegal shuffles with zero.
11812 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11815 // We can't generate a shuffle node with mismatched input and output types.
11816 // Attempt to transform a single input vector to the correct type.
11817 if ((VT != VecIn1.getValueType())) {
11818 // If the input vector type has a different base type to the output
11819 // vector type, bail out.
11820 EVT VTElemType = VT.getVectorElementType();
11821 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11822 (VecIn2.getNode() &&
11823 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11826 // If the input vector is too small, widen it.
11827 // We only support widening of vectors which are half the size of the
11828 // output registers. For example XMM->YMM widening on X86 with AVX.
11829 EVT VecInT = VecIn1.getValueType();
11830 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11831 // If we only have one small input, widen it by adding undef values.
11832 if (!VecIn2.getNode())
11833 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11834 DAG.getUNDEF(VecIn1.getValueType()));
11835 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11836 // If we have two small inputs of the same type, try to concat them.
11837 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11838 VecIn2 = SDValue(nullptr, 0);
11841 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11842 // If the input vector is too large, try to split it.
11843 // We don't support having two input vectors that are too large.
11844 // If the zero vector was used, we can not split the vector,
11845 // since we'd need 3 inputs.
11846 if (UsesZeroVector || VecIn2.getNode())
11849 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11852 // Try to replace VecIn1 with two extract_subvectors
11853 // No need to update the masks, they should still be correct.
11854 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11855 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11856 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11857 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11862 if (UsesZeroVector)
11863 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11864 DAG.getConstantFP(0.0, dl, VT);
11866 // If VecIn2 is unused then change it to undef.
11867 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11869 // Check that we were able to transform all incoming values to the same
11871 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11872 VecIn1.getValueType() != VT)
11875 // Return the new VECTOR_SHUFFLE node.
11879 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11885 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11887 EVT OpVT = N->getOperand(0).getValueType();
11889 // If the operands are legal vectors, leave them alone.
11890 if (TLI.isTypeLegal(OpVT))
11894 EVT VT = N->getValueType(0);
11895 SmallVector<SDValue, 8> Ops;
11897 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11898 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11900 // Keep track of what we encounter.
11901 bool AnyInteger = false;
11902 bool AnyFP = false;
11903 for (const SDValue &Op : N->ops()) {
11904 if (ISD::BITCAST == Op.getOpcode() &&
11905 !Op.getOperand(0).getValueType().isVector())
11906 Ops.push_back(Op.getOperand(0));
11907 else if (ISD::UNDEF == Op.getOpcode())
11908 Ops.push_back(ScalarUndef);
11912 // Note whether we encounter an integer or floating point scalar.
11913 // If it's neither, bail out, it could be something weird like x86mmx.
11914 EVT LastOpVT = Ops.back().getValueType();
11915 if (LastOpVT.isFloatingPoint())
11917 else if (LastOpVT.isInteger())
11923 // If any of the operands is a floating point scalar bitcast to a vector,
11924 // use floating point types throughout, and bitcast everything.
11925 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11927 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11928 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11930 for (SDValue &Op : Ops) {
11931 if (Op.getValueType() == SVT)
11933 if (Op.getOpcode() == ISD::UNDEF)
11936 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11941 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11942 VT.getSizeInBits() / SVT.getSizeInBits());
11943 return DAG.getNode(ISD::BITCAST, DL, VT,
11944 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11947 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11948 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11949 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11950 // inputs come from at most two distinct vectors, turn this into a shuffle
11953 // If we only have one input vector, we don't need to do any concatenation.
11954 if (N->getNumOperands() == 1)
11955 return N->getOperand(0);
11957 // Check if all of the operands are undefs.
11958 EVT VT = N->getValueType(0);
11959 if (ISD::allOperandsUndef(N))
11960 return DAG.getUNDEF(VT);
11962 // Optimize concat_vectors where all but the first of the vectors are undef.
11963 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11964 return Op.getOpcode() == ISD::UNDEF;
11966 SDValue In = N->getOperand(0);
11967 assert(In.getValueType().isVector() && "Must concat vectors");
11969 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11970 if (In->getOpcode() == ISD::BITCAST &&
11971 !In->getOperand(0)->getValueType(0).isVector()) {
11972 SDValue Scalar = In->getOperand(0);
11974 // If the bitcast type isn't legal, it might be a trunc of a legal type;
11975 // look through the trunc so we can still do the transform:
11976 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11977 if (Scalar->getOpcode() == ISD::TRUNCATE &&
11978 !TLI.isTypeLegal(Scalar.getValueType()) &&
11979 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11980 Scalar = Scalar->getOperand(0);
11982 EVT SclTy = Scalar->getValueType(0);
11984 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11987 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11988 VT.getSizeInBits() / SclTy.getSizeInBits());
11989 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11992 SDLoc dl = SDLoc(N);
11993 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11994 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11998 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11999 // We have already tested above for an UNDEF only concatenation.
12000 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12001 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12002 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12003 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12005 bool AllBuildVectorsOrUndefs =
12006 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12007 if (AllBuildVectorsOrUndefs) {
12008 SmallVector<SDValue, 8> Opnds;
12009 EVT SVT = VT.getScalarType();
12012 if (!SVT.isFloatingPoint()) {
12013 // If BUILD_VECTOR are from built from integer, they may have different
12014 // operand types. Get the smallest type and truncate all operands to it.
12015 bool FoundMinVT = false;
12016 for (const SDValue &Op : N->ops())
12017 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12018 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12019 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12022 assert(FoundMinVT && "Concat vector type mismatch");
12025 for (const SDValue &Op : N->ops()) {
12026 EVT OpVT = Op.getValueType();
12027 unsigned NumElts = OpVT.getVectorNumElements();
12029 if (ISD::UNDEF == Op.getOpcode())
12030 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12032 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12033 if (SVT.isFloatingPoint()) {
12034 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12035 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12037 for (unsigned i = 0; i != NumElts; ++i)
12039 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12044 assert(VT.getVectorNumElements() == Opnds.size() &&
12045 "Concat vector type mismatch");
12046 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12049 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12050 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12053 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12054 // nodes often generate nop CONCAT_VECTOR nodes.
12055 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12056 // place the incoming vectors at the exact same location.
12057 SDValue SingleSource = SDValue();
12058 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12060 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12061 SDValue Op = N->getOperand(i);
12063 if (Op.getOpcode() == ISD::UNDEF)
12066 // Check if this is the identity extract:
12067 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12070 // Find the single incoming vector for the extract_subvector.
12071 if (SingleSource.getNode()) {
12072 if (Op.getOperand(0) != SingleSource)
12075 SingleSource = Op.getOperand(0);
12077 // Check the source type is the same as the type of the result.
12078 // If not, this concat may extend the vector, so we can not
12079 // optimize it away.
12080 if (SingleSource.getValueType() != N->getValueType(0))
12084 unsigned IdentityIndex = i * PartNumElem;
12085 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12086 // The extract index must be constant.
12090 // Check that we are reading from the identity index.
12091 if (CS->getZExtValue() != IdentityIndex)
12095 if (SingleSource.getNode())
12096 return SingleSource;
12101 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12102 EVT NVT = N->getValueType(0);
12103 SDValue V = N->getOperand(0);
12105 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12107 // (extract_subvec (concat V1, V2, ...), i)
12110 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12112 if (V->getOperand(0).getValueType() != NVT)
12114 unsigned Idx = N->getConstantOperandVal(1);
12115 unsigned NumElems = NVT.getVectorNumElements();
12116 assert((Idx % NumElems) == 0 &&
12117 "IDX in concat is not a multiple of the result vector length.");
12118 return V->getOperand(Idx / NumElems);
12122 if (V->getOpcode() == ISD::BITCAST)
12123 V = V.getOperand(0);
12125 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12127 // Handle only simple case where vector being inserted and vector
12128 // being extracted are of same type, and are half size of larger vectors.
12129 EVT BigVT = V->getOperand(0).getValueType();
12130 EVT SmallVT = V->getOperand(1).getValueType();
12131 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12134 // Only handle cases where both indexes are constants with the same type.
12135 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12136 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12138 if (InsIdx && ExtIdx &&
12139 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12140 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12142 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12144 // indices are equal or bit offsets are equal => V1
12145 // otherwise => (extract_subvec V1, ExtIdx)
12146 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12147 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12148 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12149 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12150 DAG.getNode(ISD::BITCAST, dl,
12151 N->getOperand(0).getValueType(),
12152 V->getOperand(0)), N->getOperand(1));
12159 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12160 SDValue V, SelectionDAG &DAG) {
12162 EVT VT = V.getValueType();
12164 switch (V.getOpcode()) {
12168 case ISD::CONCAT_VECTORS: {
12169 EVT OpVT = V->getOperand(0).getValueType();
12170 int OpSize = OpVT.getVectorNumElements();
12171 SmallBitVector OpUsedElements(OpSize, false);
12172 bool FoundSimplification = false;
12173 SmallVector<SDValue, 4> NewOps;
12174 NewOps.reserve(V->getNumOperands());
12175 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12176 SDValue Op = V->getOperand(i);
12177 bool OpUsed = false;
12178 for (int j = 0; j < OpSize; ++j)
12179 if (UsedElements[i * OpSize + j]) {
12180 OpUsedElements[j] = true;
12184 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12185 : DAG.getUNDEF(OpVT));
12186 FoundSimplification |= Op == NewOps.back();
12187 OpUsedElements.reset();
12189 if (FoundSimplification)
12190 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12194 case ISD::INSERT_SUBVECTOR: {
12195 SDValue BaseV = V->getOperand(0);
12196 SDValue SubV = V->getOperand(1);
12197 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12201 int SubSize = SubV.getValueType().getVectorNumElements();
12202 int Idx = IdxN->getZExtValue();
12203 bool SubVectorUsed = false;
12204 SmallBitVector SubUsedElements(SubSize, false);
12205 for (int i = 0; i < SubSize; ++i)
12206 if (UsedElements[i + Idx]) {
12207 SubVectorUsed = true;
12208 SubUsedElements[i] = true;
12209 UsedElements[i + Idx] = false;
12212 // Now recurse on both the base and sub vectors.
12213 SDValue SimplifiedSubV =
12215 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12216 : DAG.getUNDEF(SubV.getValueType());
12217 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12218 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12219 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12220 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12226 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12227 SDValue N1, SelectionDAG &DAG) {
12228 EVT VT = SVN->getValueType(0);
12229 int NumElts = VT.getVectorNumElements();
12230 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12231 for (int M : SVN->getMask())
12232 if (M >= 0 && M < NumElts)
12233 N0UsedElements[M] = true;
12234 else if (M >= NumElts)
12235 N1UsedElements[M - NumElts] = true;
12237 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12238 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12239 if (S0 == N0 && S1 == N1)
12242 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12245 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12246 // or turn a shuffle of a single concat into simpler shuffle then concat.
12247 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12248 EVT VT = N->getValueType(0);
12249 unsigned NumElts = VT.getVectorNumElements();
12251 SDValue N0 = N->getOperand(0);
12252 SDValue N1 = N->getOperand(1);
12253 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12255 SmallVector<SDValue, 4> Ops;
12256 EVT ConcatVT = N0.getOperand(0).getValueType();
12257 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12258 unsigned NumConcats = NumElts / NumElemsPerConcat;
12260 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12261 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12262 // half vector elements.
12263 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12264 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12265 SVN->getMask().end(), [](int i) { return i == -1; })) {
12266 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12267 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12268 N1 = DAG.getUNDEF(ConcatVT);
12269 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12272 // Look at every vector that's inserted. We're looking for exact
12273 // subvector-sized copies from a concatenated vector
12274 for (unsigned I = 0; I != NumConcats; ++I) {
12275 // Make sure we're dealing with a copy.
12276 unsigned Begin = I * NumElemsPerConcat;
12277 bool AllUndef = true, NoUndef = true;
12278 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12279 if (SVN->getMaskElt(J) >= 0)
12286 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12289 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12290 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12293 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12294 if (FirstElt < N0.getNumOperands())
12295 Ops.push_back(N0.getOperand(FirstElt));
12297 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12299 } else if (AllUndef) {
12300 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12301 } else { // Mixed with general masks and undefs, can't do optimization.
12306 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12309 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12310 EVT VT = N->getValueType(0);
12311 unsigned NumElts = VT.getVectorNumElements();
12313 SDValue N0 = N->getOperand(0);
12314 SDValue N1 = N->getOperand(1);
12316 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12318 // Canonicalize shuffle undef, undef -> undef
12319 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12320 return DAG.getUNDEF(VT);
12322 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12324 // Canonicalize shuffle v, v -> v, undef
12326 SmallVector<int, 8> NewMask;
12327 for (unsigned i = 0; i != NumElts; ++i) {
12328 int Idx = SVN->getMaskElt(i);
12329 if (Idx >= (int)NumElts) Idx -= NumElts;
12330 NewMask.push_back(Idx);
12332 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12336 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12337 if (N0.getOpcode() == ISD::UNDEF) {
12338 SmallVector<int, 8> NewMask;
12339 for (unsigned i = 0; i != NumElts; ++i) {
12340 int Idx = SVN->getMaskElt(i);
12342 if (Idx >= (int)NumElts)
12345 Idx = -1; // remove reference to lhs
12347 NewMask.push_back(Idx);
12349 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12353 // Remove references to rhs if it is undef
12354 if (N1.getOpcode() == ISD::UNDEF) {
12355 bool Changed = false;
12356 SmallVector<int, 8> NewMask;
12357 for (unsigned i = 0; i != NumElts; ++i) {
12358 int Idx = SVN->getMaskElt(i);
12359 if (Idx >= (int)NumElts) {
12363 NewMask.push_back(Idx);
12366 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12369 // If it is a splat, check if the argument vector is another splat or a
12371 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12372 SDNode *V = N0.getNode();
12374 // If this is a bit convert that changes the element type of the vector but
12375 // not the number of vector elements, look through it. Be careful not to
12376 // look though conversions that change things like v4f32 to v2f64.
12377 if (V->getOpcode() == ISD::BITCAST) {
12378 SDValue ConvInput = V->getOperand(0);
12379 if (ConvInput.getValueType().isVector() &&
12380 ConvInput.getValueType().getVectorNumElements() == NumElts)
12381 V = ConvInput.getNode();
12384 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12385 assert(V->getNumOperands() == NumElts &&
12386 "BUILD_VECTOR has wrong number of operands");
12388 bool AllSame = true;
12389 for (unsigned i = 0; i != NumElts; ++i) {
12390 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12391 Base = V->getOperand(i);
12395 // Splat of <u, u, u, u>, return <u, u, u, u>
12396 if (!Base.getNode())
12398 for (unsigned i = 0; i != NumElts; ++i) {
12399 if (V->getOperand(i) != Base) {
12404 // Splat of <x, x, x, x>, return <x, x, x, x>
12408 // Canonicalize any other splat as a build_vector.
12409 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12410 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12411 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12412 V->getValueType(0), Ops);
12414 // We may have jumped through bitcasts, so the type of the
12415 // BUILD_VECTOR may not match the type of the shuffle.
12416 if (V->getValueType(0) != VT)
12417 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12422 // There are various patterns used to build up a vector from smaller vectors,
12423 // subvectors, or elements. Scan chains of these and replace unused insertions
12424 // or components with undef.
12425 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12428 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12429 Level < AfterLegalizeVectorOps &&
12430 (N1.getOpcode() == ISD::UNDEF ||
12431 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12432 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12433 SDValue V = partitionShuffleOfConcats(N, DAG);
12439 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12440 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12441 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12442 SmallVector<SDValue, 8> Ops;
12443 for (int M : SVN->getMask()) {
12444 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12446 int Idx = M % NumElts;
12447 SDValue &S = (M < (int)NumElts ? N0 : N1);
12448 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12449 Op = S.getOperand(Idx);
12450 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12452 Op = S.getOperand(0);
12454 // Operand can't be combined - bail out.
12460 if (Ops.size() == VT.getVectorNumElements()) {
12461 // BUILD_VECTOR requires all inputs to be of the same type, find the
12462 // maximum type and extend them all.
12463 EVT SVT = VT.getScalarType();
12464 if (SVT.isInteger())
12465 for (SDValue &Op : Ops)
12466 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12467 if (SVT != VT.getScalarType())
12468 for (SDValue &Op : Ops)
12469 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12470 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12471 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12472 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12476 // If this shuffle only has a single input that is a bitcasted shuffle,
12477 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12478 // back to their original types.
12479 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12480 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12481 TLI.isTypeLegal(VT)) {
12483 // Peek through the bitcast only if there is one user.
12485 while (BC0.getOpcode() == ISD::BITCAST) {
12486 if (!BC0.hasOneUse())
12488 BC0 = BC0.getOperand(0);
12491 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12493 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12495 SmallVector<int, 8> NewMask;
12497 for (int s = 0; s != Scale; ++s)
12498 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12502 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12503 EVT SVT = VT.getScalarType();
12504 EVT InnerVT = BC0->getValueType(0);
12505 EVT InnerSVT = InnerVT.getScalarType();
12507 // Determine which shuffle works with the smaller scalar type.
12508 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12509 EVT ScaleSVT = ScaleVT.getScalarType();
12511 if (TLI.isTypeLegal(ScaleVT) &&
12512 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12513 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12515 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12516 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12518 // Scale the shuffle masks to the smaller scalar type.
12519 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12520 SmallVector<int, 8> InnerMask =
12521 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12522 SmallVector<int, 8> OuterMask =
12523 ScaleShuffleMask(SVN->getMask(), OuterScale);
12525 // Merge the shuffle masks.
12526 SmallVector<int, 8> NewMask;
12527 for (int M : OuterMask)
12528 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12530 // Test for shuffle mask legality over both commutations.
12531 SDValue SV0 = BC0->getOperand(0);
12532 SDValue SV1 = BC0->getOperand(1);
12533 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12535 std::swap(SV0, SV1);
12536 ShuffleVectorSDNode::commuteMask(NewMask);
12537 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12541 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12542 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12543 return DAG.getNode(
12544 ISD::BITCAST, SDLoc(N), VT,
12545 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12551 // Canonicalize shuffles according to rules:
12552 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12553 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12554 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12555 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12556 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12557 TLI.isTypeLegal(VT)) {
12558 // The incoming shuffle must be of the same type as the result of the
12559 // current shuffle.
12560 assert(N1->getOperand(0).getValueType() == VT &&
12561 "Shuffle types don't match");
12563 SDValue SV0 = N1->getOperand(0);
12564 SDValue SV1 = N1->getOperand(1);
12565 bool HasSameOp0 = N0 == SV0;
12566 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12567 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12568 // Commute the operands of this shuffle so that next rule
12570 return DAG.getCommutedVectorShuffle(*SVN);
12573 // Try to fold according to rules:
12574 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12575 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12576 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12577 // Don't try to fold shuffles with illegal type.
12578 // Only fold if this shuffle is the only user of the other shuffle.
12579 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12580 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12581 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12583 // The incoming shuffle must be of the same type as the result of the
12584 // current shuffle.
12585 assert(OtherSV->getOperand(0).getValueType() == VT &&
12586 "Shuffle types don't match");
12589 SmallVector<int, 4> Mask;
12590 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12591 // operand, and SV1 as the second operand.
12592 for (unsigned i = 0; i != NumElts; ++i) {
12593 int Idx = SVN->getMaskElt(i);
12595 // Propagate Undef.
12596 Mask.push_back(Idx);
12600 SDValue CurrentVec;
12601 if (Idx < (int)NumElts) {
12602 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12603 // shuffle mask to identify which vector is actually referenced.
12604 Idx = OtherSV->getMaskElt(Idx);
12606 // Propagate Undef.
12607 Mask.push_back(Idx);
12611 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12612 : OtherSV->getOperand(1);
12614 // This shuffle index references an element within N1.
12618 // Simple case where 'CurrentVec' is UNDEF.
12619 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12620 Mask.push_back(-1);
12624 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12625 // will be the first or second operand of the combined shuffle.
12626 Idx = Idx % NumElts;
12627 if (!SV0.getNode() || SV0 == CurrentVec) {
12628 // Ok. CurrentVec is the left hand side.
12629 // Update the mask accordingly.
12631 Mask.push_back(Idx);
12635 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12636 if (SV1.getNode() && SV1 != CurrentVec)
12639 // Ok. CurrentVec is the right hand side.
12640 // Update the mask accordingly.
12642 Mask.push_back(Idx + NumElts);
12645 // Check if all indices in Mask are Undef. In case, propagate Undef.
12646 bool isUndefMask = true;
12647 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12648 isUndefMask &= Mask[i] < 0;
12651 return DAG.getUNDEF(VT);
12653 if (!SV0.getNode())
12654 SV0 = DAG.getUNDEF(VT);
12655 if (!SV1.getNode())
12656 SV1 = DAG.getUNDEF(VT);
12658 // Avoid introducing shuffles with illegal mask.
12659 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12660 ShuffleVectorSDNode::commuteMask(Mask);
12662 if (!TLI.isShuffleMaskLegal(Mask, VT))
12665 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12666 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12667 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12668 std::swap(SV0, SV1);
12671 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12672 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12673 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12674 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12680 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12681 SDValue InVal = N->getOperand(0);
12682 EVT VT = N->getValueType(0);
12684 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12685 // with a VECTOR_SHUFFLE.
12686 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12687 SDValue InVec = InVal->getOperand(0);
12688 SDValue EltNo = InVal->getOperand(1);
12690 // FIXME: We could support implicit truncation if the shuffle can be
12691 // scaled to a smaller vector scalar type.
12692 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12693 if (C0 && VT == InVec.getValueType() &&
12694 VT.getScalarType() == InVal.getValueType()) {
12695 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12696 int Elt = C0->getZExtValue();
12699 if (TLI.isShuffleMaskLegal(NewMask, VT))
12700 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12708 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12709 SDValue N0 = N->getOperand(0);
12710 SDValue N2 = N->getOperand(2);
12712 // If the input vector is a concatenation, and the insert replaces
12713 // one of the halves, we can optimize into a single concat_vectors.
12714 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12715 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12716 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12717 EVT VT = N->getValueType(0);
12719 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12720 // (concat_vectors Z, Y)
12722 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12723 N->getOperand(1), N0.getOperand(1));
12725 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12726 // (concat_vectors X, Z)
12727 if (InsIdx == VT.getVectorNumElements()/2)
12728 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12729 N0.getOperand(0), N->getOperand(1));
12735 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12736 SDValue N0 = N->getOperand(0);
12738 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12739 if (N0->getOpcode() == ISD::FP16_TO_FP)
12740 return N0->getOperand(0);
12745 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12746 /// with the destination vector and a zero vector.
12747 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12748 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12749 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12750 EVT VT = N->getValueType(0);
12751 SDValue LHS = N->getOperand(0);
12752 SDValue RHS = N->getOperand(1);
12755 // Make sure we're not running after operation legalization where it
12756 // may have custom lowered the vector shuffles.
12757 if (LegalOperations)
12760 if (N->getOpcode() != ISD::AND)
12763 if (RHS.getOpcode() == ISD::BITCAST)
12764 RHS = RHS.getOperand(0);
12766 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12767 SmallVector<int, 8> Indices;
12768 unsigned NumElts = RHS.getNumOperands();
12770 for (unsigned i = 0; i != NumElts; ++i) {
12771 SDValue Elt = RHS.getOperand(i);
12772 if (!isa<ConstantSDNode>(Elt))
12775 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12776 Indices.push_back(i);
12777 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12778 Indices.push_back(NumElts+i);
12783 // Let's see if the target supports this vector_shuffle.
12784 EVT RVT = RHS.getValueType();
12785 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12788 // Return the new VECTOR_SHUFFLE node.
12789 EVT EltVT = RVT.getVectorElementType();
12790 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12791 DAG.getConstant(0, dl, EltVT));
12792 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12793 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12794 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12795 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12801 /// Visit a binary vector operation, like ADD.
12802 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12803 assert(N->getValueType(0).isVector() &&
12804 "SimplifyVBinOp only works on vectors!");
12806 SDValue LHS = N->getOperand(0);
12807 SDValue RHS = N->getOperand(1);
12809 if (SDValue Shuffle = XformToShuffleWithZero(N))
12812 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12814 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12815 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12816 // Check if both vectors are constants. If not bail out.
12817 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12818 cast<BuildVectorSDNode>(RHS)->isConstant()))
12821 SmallVector<SDValue, 8> Ops;
12822 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12823 SDValue LHSOp = LHS.getOperand(i);
12824 SDValue RHSOp = RHS.getOperand(i);
12826 // Can't fold divide by zero.
12827 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12828 N->getOpcode() == ISD::FDIV) {
12829 if ((RHSOp.getOpcode() == ISD::Constant &&
12830 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12831 (RHSOp.getOpcode() == ISD::ConstantFP &&
12832 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12836 EVT VT = LHSOp.getValueType();
12837 EVT RVT = RHSOp.getValueType();
12839 // Integer BUILD_VECTOR operands may have types larger than the element
12840 // size (e.g., when the element type is not legal). Prior to type
12841 // legalization, the types may not match between the two BUILD_VECTORS.
12842 // Truncate one of the operands to make them match.
12843 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12844 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12846 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12850 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12852 if (FoldOp.getOpcode() != ISD::UNDEF &&
12853 FoldOp.getOpcode() != ISD::Constant &&
12854 FoldOp.getOpcode() != ISD::ConstantFP)
12856 Ops.push_back(FoldOp);
12857 AddToWorklist(FoldOp.getNode());
12860 if (Ops.size() == LHS.getNumOperands())
12861 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12864 // Type legalization might introduce new shuffles in the DAG.
12865 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12866 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12867 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12868 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12869 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12870 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12871 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12872 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12874 if (SVN0->getMask().equals(SVN1->getMask())) {
12875 EVT VT = N->getValueType(0);
12876 SDValue UndefVector = LHS.getOperand(1);
12877 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12878 LHS.getOperand(0), RHS.getOperand(0));
12879 AddUsersToWorklist(N);
12880 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12881 &SVN0->getMask()[0]);
12888 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12889 SDValue N1, SDValue N2){
12890 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12892 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12893 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12895 // If we got a simplified select_cc node back from SimplifySelectCC, then
12896 // break it down into a new SETCC node, and a new SELECT node, and then return
12897 // the SELECT node, since we were called with a SELECT node.
12898 if (SCC.getNode()) {
12899 // Check to see if we got a select_cc back (to turn into setcc/select).
12900 // Otherwise, just return whatever node we got back, like fabs.
12901 if (SCC.getOpcode() == ISD::SELECT_CC) {
12902 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12904 SCC.getOperand(0), SCC.getOperand(1),
12905 SCC.getOperand(4));
12906 AddToWorklist(SETCC.getNode());
12907 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12908 SCC.getOperand(2), SCC.getOperand(3));
12916 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12917 /// being selected between, see if we can simplify the select. Callers of this
12918 /// should assume that TheSelect is deleted if this returns true. As such, they
12919 /// should return the appropriate thing (e.g. the node) back to the top-level of
12920 /// the DAG combiner loop to avoid it being looked at.
12921 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12924 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12925 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12926 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12927 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12928 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12929 SDValue Sqrt = RHS;
12932 const ConstantFPSDNode *NegZero = nullptr;
12934 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12935 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12936 CmpLHS = TheSelect->getOperand(0);
12937 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12939 // SELECT or VSELECT
12940 SDValue Cmp = TheSelect->getOperand(0);
12941 if (Cmp.getOpcode() == ISD::SETCC) {
12942 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12943 CmpLHS = Cmp.getOperand(0);
12944 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12947 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12948 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12949 CC == ISD::SETULT || CC == ISD::SETLT)) {
12950 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12951 CombineTo(TheSelect, Sqrt);
12956 // Cannot simplify select with vector condition
12957 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12959 // If this is a select from two identical things, try to pull the operation
12960 // through the select.
12961 if (LHS.getOpcode() != RHS.getOpcode() ||
12962 !LHS.hasOneUse() || !RHS.hasOneUse())
12965 // If this is a load and the token chain is identical, replace the select
12966 // of two loads with a load through a select of the address to load from.
12967 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12968 // constants have been dropped into the constant pool.
12969 if (LHS.getOpcode() == ISD::LOAD) {
12970 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12971 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12973 // Token chains must be identical.
12974 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12975 // Do not let this transformation reduce the number of volatile loads.
12976 LLD->isVolatile() || RLD->isVolatile() ||
12977 // FIXME: If either is a pre/post inc/dec load,
12978 // we'd need to split out the address adjustment.
12979 LLD->isIndexed() || RLD->isIndexed() ||
12980 // If this is an EXTLOAD, the VT's must match.
12981 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12982 // If this is an EXTLOAD, the kind of extension must match.
12983 (LLD->getExtensionType() != RLD->getExtensionType() &&
12984 // The only exception is if one of the extensions is anyext.
12985 LLD->getExtensionType() != ISD::EXTLOAD &&
12986 RLD->getExtensionType() != ISD::EXTLOAD) ||
12987 // FIXME: this discards src value information. This is
12988 // over-conservative. It would be beneficial to be able to remember
12989 // both potential memory locations. Since we are discarding
12990 // src value info, don't do the transformation if the memory
12991 // locations are not in the default address space.
12992 LLD->getPointerInfo().getAddrSpace() != 0 ||
12993 RLD->getPointerInfo().getAddrSpace() != 0 ||
12994 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12995 LLD->getBasePtr().getValueType()))
12998 // Check that the select condition doesn't reach either load. If so,
12999 // folding this will induce a cycle into the DAG. If not, this is safe to
13000 // xform, so create a select of the addresses.
13002 if (TheSelect->getOpcode() == ISD::SELECT) {
13003 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13004 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13005 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13007 // The loads must not depend on one another.
13008 if (LLD->isPredecessorOf(RLD) ||
13009 RLD->isPredecessorOf(LLD))
13011 Addr = DAG.getSelect(SDLoc(TheSelect),
13012 LLD->getBasePtr().getValueType(),
13013 TheSelect->getOperand(0), LLD->getBasePtr(),
13014 RLD->getBasePtr());
13015 } else { // Otherwise SELECT_CC
13016 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13017 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13019 if ((LLD->hasAnyUseOfValue(1) &&
13020 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13021 (RLD->hasAnyUseOfValue(1) &&
13022 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13025 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13026 LLD->getBasePtr().getValueType(),
13027 TheSelect->getOperand(0),
13028 TheSelect->getOperand(1),
13029 LLD->getBasePtr(), RLD->getBasePtr(),
13030 TheSelect->getOperand(4));
13034 // It is safe to replace the two loads if they have different alignments,
13035 // but the new load must be the minimum (most restrictive) alignment of the
13037 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13038 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13039 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13040 Load = DAG.getLoad(TheSelect->getValueType(0),
13042 // FIXME: Discards pointer and AA info.
13043 LLD->getChain(), Addr, MachinePointerInfo(),
13044 LLD->isVolatile(), LLD->isNonTemporal(),
13045 isInvariant, Alignment);
13047 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13048 RLD->getExtensionType() : LLD->getExtensionType(),
13050 TheSelect->getValueType(0),
13051 // FIXME: Discards pointer and AA info.
13052 LLD->getChain(), Addr, MachinePointerInfo(),
13053 LLD->getMemoryVT(), LLD->isVolatile(),
13054 LLD->isNonTemporal(), isInvariant, Alignment);
13057 // Users of the select now use the result of the load.
13058 CombineTo(TheSelect, Load);
13060 // Users of the old loads now use the new load's chain. We know the
13061 // old-load value is dead now.
13062 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13063 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13070 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13071 /// where 'cond' is the comparison specified by CC.
13072 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13073 SDValue N2, SDValue N3,
13074 ISD::CondCode CC, bool NotExtCompare) {
13075 // (x ? y : y) -> y.
13076 if (N2 == N3) return N2;
13078 EVT VT = N2.getValueType();
13079 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13080 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13081 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13083 // Determine if the condition we're dealing with is constant
13084 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13085 N0, N1, CC, DL, false);
13086 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13087 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13089 // fold select_cc true, x, y -> x
13090 if (SCCC && !SCCC->isNullValue())
13092 // fold select_cc false, x, y -> y
13093 if (SCCC && SCCC->isNullValue())
13096 // Check to see if we can simplify the select into an fabs node
13097 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13098 // Allow either -0.0 or 0.0
13099 if (CFP->getValueAPF().isZero()) {
13100 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13101 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13102 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13103 N2 == N3.getOperand(0))
13104 return DAG.getNode(ISD::FABS, DL, VT, N0);
13106 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13107 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13108 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13109 N2.getOperand(0) == N3)
13110 return DAG.getNode(ISD::FABS, DL, VT, N3);
13114 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13115 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13116 // in it. This is a win when the constant is not otherwise available because
13117 // it replaces two constant pool loads with one. We only do this if the FP
13118 // type is known to be legal, because if it isn't, then we are before legalize
13119 // types an we want the other legalization to happen first (e.g. to avoid
13120 // messing with soft float) and if the ConstantFP is not legal, because if
13121 // it is legal, we may not need to store the FP constant in a constant pool.
13122 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13123 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13124 if (TLI.isTypeLegal(N2.getValueType()) &&
13125 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13126 TargetLowering::Legal &&
13127 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13128 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13129 // If both constants have multiple uses, then we won't need to do an
13130 // extra load, they are likely around in registers for other users.
13131 (TV->hasOneUse() || FV->hasOneUse())) {
13132 Constant *Elts[] = {
13133 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13134 const_cast<ConstantFP*>(TV->getConstantFPValue())
13136 Type *FPTy = Elts[0]->getType();
13137 const DataLayout &TD = *TLI.getDataLayout();
13139 // Create a ConstantArray of the two constants.
13140 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13141 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13142 TD.getPrefTypeAlignment(FPTy));
13143 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13145 // Get the offsets to the 0 and 1 element of the array so that we can
13146 // select between them.
13147 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13148 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13149 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13151 SDValue Cond = DAG.getSetCC(DL,
13152 getSetCCResultType(N0.getValueType()),
13154 AddToWorklist(Cond.getNode());
13155 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13157 AddToWorklist(CstOffset.getNode());
13158 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13160 AddToWorklist(CPIdx.getNode());
13161 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13162 MachinePointerInfo::getConstantPool(), false,
13163 false, false, Alignment);
13167 // Check to see if we can perform the "gzip trick", transforming
13168 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13169 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13170 (N1C->isNullValue() || // (a < 0) ? b : 0
13171 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
13172 EVT XType = N0.getValueType();
13173 EVT AType = N2.getValueType();
13174 if (XType.bitsGE(AType)) {
13175 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13176 // single-bit constant.
13177 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13178 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13179 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13180 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13181 getShiftAmountTy(N0.getValueType()));
13182 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13184 AddToWorklist(Shift.getNode());
13186 if (XType.bitsGT(AType)) {
13187 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13188 AddToWorklist(Shift.getNode());
13191 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13194 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13196 DAG.getConstant(XType.getSizeInBits() - 1,
13198 getShiftAmountTy(N0.getValueType())));
13199 AddToWorklist(Shift.getNode());
13201 if (XType.bitsGT(AType)) {
13202 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13203 AddToWorklist(Shift.getNode());
13206 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13210 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13211 // where y is has a single bit set.
13212 // A plaintext description would be, we can turn the SELECT_CC into an AND
13213 // when the condition can be materialized as an all-ones register. Any
13214 // single bit-test can be materialized as an all-ones register with
13215 // shift-left and shift-right-arith.
13216 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13217 N0->getValueType(0) == VT &&
13218 N1C && N1C->isNullValue() &&
13219 N2C && N2C->isNullValue()) {
13220 SDValue AndLHS = N0->getOperand(0);
13221 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13222 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13223 // Shift the tested bit over the sign bit.
13224 APInt AndMask = ConstAndRHS->getAPIntValue();
13226 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13227 getShiftAmountTy(AndLHS.getValueType()));
13228 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13230 // Now arithmetic right shift it all the way over, so the result is either
13231 // all-ones, or zero.
13233 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13234 getShiftAmountTy(Shl.getValueType()));
13235 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13237 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13241 // fold select C, 16, 0 -> shl C, 4
13242 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13243 TLI.getBooleanContents(N0.getValueType()) ==
13244 TargetLowering::ZeroOrOneBooleanContent) {
13246 // If the caller doesn't want us to simplify this into a zext of a compare,
13248 if (NotExtCompare && N2C->getAPIntValue() == 1)
13251 // Get a SetCC of the condition
13252 // NOTE: Don't create a SETCC if it's not legal on this target.
13253 if (!LegalOperations ||
13254 TLI.isOperationLegal(ISD::SETCC,
13255 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13257 // cast from setcc result type to select result type
13259 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13261 if (N2.getValueType().bitsLT(SCC.getValueType()))
13262 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13263 N2.getValueType());
13265 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13266 N2.getValueType(), SCC);
13268 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13269 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13270 N2.getValueType(), SCC);
13273 AddToWorklist(SCC.getNode());
13274 AddToWorklist(Temp.getNode());
13276 if (N2C->getAPIntValue() == 1)
13279 // shl setcc result by log2 n2c
13280 return DAG.getNode(
13281 ISD::SHL, DL, N2.getValueType(), Temp,
13282 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13283 getShiftAmountTy(Temp.getValueType())));
13287 // Check to see if this is the equivalent of setcc
13288 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13289 // otherwise, go ahead with the folds.
13290 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13291 EVT XType = N0.getValueType();
13292 if (!LegalOperations ||
13293 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13294 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13295 if (Res.getValueType() != VT)
13296 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13300 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13301 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13302 (!LegalOperations ||
13303 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13304 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13305 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13306 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13308 getShiftAmountTy(Ctlz.getValueType())));
13310 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13311 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13313 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13314 XType, DAG.getConstant(0, DL, XType), N0);
13315 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13316 return DAG.getNode(ISD::SRL, DL, XType,
13317 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13318 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13319 getShiftAmountTy(XType)));
13321 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13322 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13324 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13325 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13326 getShiftAmountTy(N0.getValueType())));
13327 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13332 // Check to see if this is an integer abs.
13333 // select_cc setg[te] X, 0, X, -X ->
13334 // select_cc setgt X, -1, X, -X ->
13335 // select_cc setl[te] X, 0, -X, X ->
13336 // select_cc setlt X, 1, -X, X ->
13337 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13339 ConstantSDNode *SubC = nullptr;
13340 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13341 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13342 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13343 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13344 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13345 (N1C->isOne() && CC == ISD::SETLT)) &&
13346 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13347 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13349 EVT XType = N0.getValueType();
13350 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13352 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13354 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13355 getShiftAmountTy(N0.getValueType())));
13356 SDValue Add = DAG.getNode(ISD::ADD, DL,
13358 AddToWorklist(Shift.getNode());
13359 AddToWorklist(Add.getNode());
13360 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13367 /// This is a stub for TargetLowering::SimplifySetCC.
13368 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13369 SDValue N1, ISD::CondCode Cond,
13370 SDLoc DL, bool foldBooleans) {
13371 TargetLowering::DAGCombinerInfo
13372 DagCombineInfo(DAG, Level, false, this);
13373 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13376 /// Given an ISD::SDIV node expressing a divide by constant, return
13377 /// a DAG expression to select that will generate the same value by multiplying
13378 /// by a magic number.
13379 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13380 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13381 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13385 // Avoid division by zero.
13386 if (!C->getAPIntValue())
13389 std::vector<SDNode*> Built;
13391 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13393 for (SDNode *N : Built)
13398 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13399 /// DAG expression that will generate the same value by right shifting.
13400 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13401 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13405 // Avoid division by zero.
13406 if (!C->getAPIntValue())
13409 std::vector<SDNode *> Built;
13410 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13412 for (SDNode *N : Built)
13417 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13418 /// expression that will generate the same value by multiplying by a magic
13420 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13421 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13422 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13426 // Avoid division by zero.
13427 if (!C->getAPIntValue())
13430 std::vector<SDNode*> Built;
13432 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13434 for (SDNode *N : Built)
13439 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13440 if (Level >= AfterLegalizeDAG)
13443 // Expose the DAG combiner to the target combiner implementations.
13444 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13446 unsigned Iterations = 0;
13447 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13449 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13450 // For the reciprocal, we need to find the zero of the function:
13451 // F(X) = A X - 1 [which has a zero at X = 1/A]
13453 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13454 // does not require additional intermediate precision]
13455 EVT VT = Op.getValueType();
13457 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13459 AddToWorklist(Est.getNode());
13461 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13462 for (unsigned i = 0; i < Iterations; ++i) {
13463 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13464 AddToWorklist(NewEst.getNode());
13466 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13467 AddToWorklist(NewEst.getNode());
13469 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13470 AddToWorklist(NewEst.getNode());
13472 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13473 AddToWorklist(Est.getNode());
13482 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13483 /// For the reciprocal sqrt, we need to find the zero of the function:
13484 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13486 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13487 /// As a result, we precompute A/2 prior to the iteration loop.
13488 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13489 unsigned Iterations) {
13490 EVT VT = Arg.getValueType();
13492 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13494 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13495 // this entire sequence requires only one FP constant.
13496 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13497 AddToWorklist(HalfArg.getNode());
13499 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13500 AddToWorklist(HalfArg.getNode());
13502 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13503 for (unsigned i = 0; i < Iterations; ++i) {
13504 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13505 AddToWorklist(NewEst.getNode());
13507 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13508 AddToWorklist(NewEst.getNode());
13510 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13511 AddToWorklist(NewEst.getNode());
13513 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13514 AddToWorklist(Est.getNode());
13519 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13520 /// For the reciprocal sqrt, we need to find the zero of the function:
13521 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13523 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13524 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13525 unsigned Iterations) {
13526 EVT VT = Arg.getValueType();
13528 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13529 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13531 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13532 for (unsigned i = 0; i < Iterations; ++i) {
13533 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13534 AddToWorklist(HalfEst.getNode());
13536 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13537 AddToWorklist(Est.getNode());
13539 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13540 AddToWorklist(Est.getNode());
13542 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13543 AddToWorklist(Est.getNode());
13545 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13546 AddToWorklist(Est.getNode());
13551 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13552 if (Level >= AfterLegalizeDAG)
13555 // Expose the DAG combiner to the target combiner implementations.
13556 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13557 unsigned Iterations = 0;
13558 bool UseOneConstNR = false;
13559 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13560 AddToWorklist(Est.getNode());
13562 Est = UseOneConstNR ?
13563 BuildRsqrtNROneConst(Op, Est, Iterations) :
13564 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13572 /// Return true if base is a frame index, which is known not to alias with
13573 /// anything but itself. Provides base object and offset as results.
13574 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13575 const GlobalValue *&GV, const void *&CV) {
13576 // Assume it is a primitive operation.
13577 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13579 // If it's an adding a simple constant then integrate the offset.
13580 if (Base.getOpcode() == ISD::ADD) {
13581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13582 Base = Base.getOperand(0);
13583 Offset += C->getZExtValue();
13587 // Return the underlying GlobalValue, and update the Offset. Return false
13588 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13589 // by multiple nodes with different offsets.
13590 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13591 GV = G->getGlobal();
13592 Offset += G->getOffset();
13596 // Return the underlying Constant value, and update the Offset. Return false
13597 // for ConstantSDNodes since the same constant pool entry may be represented
13598 // by multiple nodes with different offsets.
13599 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13600 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13601 : (const void *)C->getConstVal();
13602 Offset += C->getOffset();
13605 // If it's any of the following then it can't alias with anything but itself.
13606 return isa<FrameIndexSDNode>(Base);
13609 /// Return true if there is any possibility that the two addresses overlap.
13610 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13611 // If they are the same then they must be aliases.
13612 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13614 // If they are both volatile then they cannot be reordered.
13615 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13617 // Gather base node and offset information.
13618 SDValue Base1, Base2;
13619 int64_t Offset1, Offset2;
13620 const GlobalValue *GV1, *GV2;
13621 const void *CV1, *CV2;
13622 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13623 Base1, Offset1, GV1, CV1);
13624 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13625 Base2, Offset2, GV2, CV2);
13627 // If they have a same base address then check to see if they overlap.
13628 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13629 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13630 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13632 // It is possible for different frame indices to alias each other, mostly
13633 // when tail call optimization reuses return address slots for arguments.
13634 // To catch this case, look up the actual index of frame indices to compute
13635 // the real alias relationship.
13636 if (isFrameIndex1 && isFrameIndex2) {
13637 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13638 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13639 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13640 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13641 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13644 // Otherwise, if we know what the bases are, and they aren't identical, then
13645 // we know they cannot alias.
13646 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13649 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13650 // compared to the size and offset of the access, we may be able to prove they
13651 // do not alias. This check is conservative for now to catch cases created by
13652 // splitting vector types.
13653 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13654 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13655 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13656 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13657 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13658 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13659 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13661 // There is no overlap between these relatively aligned accesses of similar
13662 // size, return no alias.
13663 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13664 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13668 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13670 : DAG.getSubtarget().useAA();
13672 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13673 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13677 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13678 // Use alias analysis information.
13679 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13680 Op1->getSrcValueOffset());
13681 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13682 Op0->getSrcValueOffset() - MinOffset;
13683 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13684 Op1->getSrcValueOffset() - MinOffset;
13685 AliasAnalysis::AliasResult AAResult =
13686 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13688 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13689 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13691 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13692 if (AAResult == AliasAnalysis::NoAlias)
13696 // Otherwise we have to assume they alias.
13700 /// Walk up chain skipping non-aliasing memory nodes,
13701 /// looking for aliasing nodes and adding them to the Aliases vector.
13702 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13703 SmallVectorImpl<SDValue> &Aliases) {
13704 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13705 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13707 // Get alias information for node.
13708 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13711 Chains.push_back(OriginalChain);
13712 unsigned Depth = 0;
13714 // Look at each chain and determine if it is an alias. If so, add it to the
13715 // aliases list. If not, then continue up the chain looking for the next
13717 while (!Chains.empty()) {
13718 SDValue Chain = Chains.back();
13721 // For TokenFactor nodes, look at each operand and only continue up the
13722 // chain until we find two aliases. If we've seen two aliases, assume we'll
13723 // find more and revert to original chain since the xform is unlikely to be
13726 // FIXME: The depth check could be made to return the last non-aliasing
13727 // chain we found before we hit a tokenfactor rather than the original
13729 if (Depth > 6 || Aliases.size() == 2) {
13731 Aliases.push_back(OriginalChain);
13735 // Don't bother if we've been before.
13736 if (!Visited.insert(Chain.getNode()).second)
13739 switch (Chain.getOpcode()) {
13740 case ISD::EntryToken:
13741 // Entry token is ideal chain operand, but handled in FindBetterChain.
13746 // Get alias information for Chain.
13747 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13748 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13750 // If chain is alias then stop here.
13751 if (!(IsLoad && IsOpLoad) &&
13752 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13753 Aliases.push_back(Chain);
13755 // Look further up the chain.
13756 Chains.push_back(Chain.getOperand(0));
13762 case ISD::TokenFactor:
13763 // We have to check each of the operands of the token factor for "small"
13764 // token factors, so we queue them up. Adding the operands to the queue
13765 // (stack) in reverse order maintains the original order and increases the
13766 // likelihood that getNode will find a matching token factor (CSE.)
13767 if (Chain.getNumOperands() > 16) {
13768 Aliases.push_back(Chain);
13771 for (unsigned n = Chain.getNumOperands(); n;)
13772 Chains.push_back(Chain.getOperand(--n));
13777 // For all other instructions we will just have to take what we can get.
13778 Aliases.push_back(Chain);
13783 // We need to be careful here to also search for aliases through the
13784 // value operand of a store, etc. Consider the following situation:
13786 // L1 = load Token1, %52
13787 // S1 = store Token1, L1, %51
13788 // L2 = load Token1, %52+8
13789 // S2 = store Token1, L2, %51+8
13790 // Token2 = Token(S1, S2)
13791 // L3 = load Token2, %53
13792 // S3 = store Token2, L3, %52
13793 // L4 = load Token2, %53+8
13794 // S4 = store Token2, L4, %52+8
13795 // If we search for aliases of S3 (which loads address %52), and we look
13796 // only through the chain, then we'll miss the trivial dependence on L1
13797 // (which also loads from %52). We then might change all loads and
13798 // stores to use Token1 as their chain operand, which could result in
13799 // copying %53 into %52 before copying %52 into %51 (which should
13802 // The problem is, however, that searching for such data dependencies
13803 // can become expensive, and the cost is not directly related to the
13804 // chain depth. Instead, we'll rule out such configurations here by
13805 // insisting that we've visited all chain users (except for users
13806 // of the original chain, which is not necessary). When doing this,
13807 // we need to look through nodes we don't care about (otherwise, things
13808 // like register copies will interfere with trivial cases).
13810 SmallVector<const SDNode *, 16> Worklist;
13811 for (const SDNode *N : Visited)
13812 if (N != OriginalChain.getNode())
13813 Worklist.push_back(N);
13815 while (!Worklist.empty()) {
13816 const SDNode *M = Worklist.pop_back_val();
13818 // We have already visited M, and want to make sure we've visited any uses
13819 // of M that we care about. For uses that we've not visisted, and don't
13820 // care about, queue them to the worklist.
13822 for (SDNode::use_iterator UI = M->use_begin(),
13823 UIE = M->use_end(); UI != UIE; ++UI)
13824 if (UI.getUse().getValueType() == MVT::Other &&
13825 Visited.insert(*UI).second) {
13826 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13827 // We've not visited this use, and we care about it (it could have an
13828 // ordering dependency with the original node).
13830 Aliases.push_back(OriginalChain);
13834 // We've not visited this use, but we don't care about it. Mark it as
13835 // visited and enqueue it to the worklist.
13836 Worklist.push_back(*UI);
13841 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13842 /// (aliasing node.)
13843 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13844 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13846 // Accumulate all the aliases to this node.
13847 GatherAllAliases(N, OldChain, Aliases);
13849 // If no operands then chain to entry token.
13850 if (Aliases.size() == 0)
13851 return DAG.getEntryNode();
13853 // If a single operand then chain to it. We don't need to revisit it.
13854 if (Aliases.size() == 1)
13857 // Construct a custom tailored token factor.
13858 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13861 /// This is the entry point for the file.
13862 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13863 CodeGenOpt::Level OptLevel) {
13864 /// This is the main entry point to this class.
13865 DAGCombiner(*this, AA, OptLevel).Run(Level);